body
stringlengths
25
86.7k
comments
list
answers
list
meta_data
dict
question_id
stringlengths
1
6
<p>So I got this query from another analyst here and I'm a little stumped as to why a cursor was used instead of just joins. Could I please have some help trying to refactor it? I am using MSSQL 2008.</p> <pre><code>SET NOCOUNT ON; DECLARE @myCur AS CURSOR; DECLARE @totalCdes AS INT; DECLARE @SysOjb AS SMALLINT; DECLARE @prinOjb AS SMALLINT; DECLARE @JobClass AS VARCHAR (25); DECLARE @JobNo AS INT; DECLARE @JobType AS VARCHAR (2); DECLARE @JobDescr AS VARCHAR (30); DECLARE @JobComplCde AS VARCHAR (18); DECLARE @OrderNo AS VARCHAR (16); DECLARE @SchedDate AS DATETIME; DECLARE @JobResolution AS VARCHAR (200); DECLARE @startingRow AS INT; CREATE TABLE #JobsFixCodes ( SYS_OJB BIGINT , PRIN_OJB SMALLINT , JOB_NO INT , ORDER_NO BIGINT , JOB_CLASS VARCHAR (25) , JOB_TYPE VARCHAR (30) , JOB_RESOLUTION VARCHAR (200), SCHED_DATE DATE ); SET @myCur = CURSOR FOR SELECT [SYS_OJB], [PRIN_OJB], CASE [JOB_CLASS_OJB] WHEN 'C' THEN 'New Connect' WHEN 'D' THEN 'Disco' WHEN 'R' THEN 'Restart' WHEN 'S' THEN 'Service Change' WHEN 'T' THEN 'Trouble Call' WHEN 'Z' THEN 'Special Request' ELSE 'Unknown' END AS JobClass, [JOB_NO_OJB], [JOB_TYP_OJB], COALESCE (cagent.DESCR_CTD, cprin.DESCR_CTD, csys.DESCR_CTD, 'Unknown') AS Job_Descr, COMPL_CDE_OJB, [ORDER_NO_OJB], [SCHED_DTE_OJB] FROM [ExternalUser].[Vantage].[OJB_JOBS] AS j LEFT OUTER JOIN [ExternalUser].[Vantage].[CTD_DISPLAY] AS cagent ON cagent.SYS_CTD = j.SYS_OJB AND cagent.PRIN_CTD = j.PRIN_OJB AND cagent.AGNT_CTD = j.AGNT_OJB AND cagent.CDE_TBL_NO_CTD = '32' AND cagent.CDE_VALUE_CTD = j.JOB_TYP_OJB AND cagent.SPA_FLG_CTD = 'A' LEFT OUTER JOIN [ExternalUser].[Vantage].[CTD_DISPLAY] AS cprin ON cprin.SYS_CTD = j.SYS_OJB AND cprin.PRIN_CTD = j.PRIN_OJB AND cprin.CDE_TBL_NO_CTD = '32' AND cprin.CDE_VALUE_CTD = j.JOB_TYP_OJB AND cprin.SPA_FLG_CTD = 'P' LEFT OUTER JOIN [ExternalUser].[Vantage].[CTD_DISPLAY] AS csys ON csys.SYS_CTD = j.SYS_OJB AND csys.CDE_TBL_NO_CTD = '32' AND csys.CDE_VALUE_CTD = j.JOB_TYP_OJB AND csys.SPA_FLG_CTD = 'S' WHERE JOB_STAT_OJB = 'C' AND SYS_OJB = '8155' --and SCHED_DTE_OJB = @DateParm AND SCHED_DTE_OJB = CONVERT (VARCHAR (20), GETDATE()-3, 101); /*Use this to run 3 days in arrears*/ --and JOB_CLASS_OJB in (@JobClassParm) **Keep this commented out if you want *all* job classes OPEN @myCur; FETCH NEXT FROM @myCur INTO @SysOjb, @prinOjb, @JobClass, @JobNo, @JobType, @JobDescr, @JobComplCde, @OrderNo, @SchedDate; WHILE @@FETCH_STATUS = 0 BEGIN SET @totalCdes = len(@JobComplCde); --if @totalCdes is = 0 then don't loop IF @totalCdes &gt; 0 BEGIN IF @totalCdes = 3 OR @totalCdes = 6 OR @totalCdes = 9 OR @totalCdes = 12 OR @totalCdes = 15 OR @totalCdes = 18 SET @totalCdes = @totalCdes / 3; --this is the true loop count ELSE SET @totalCdes = @totalCdes / 2; END ELSE GOTO QuitMe; -- print 'Total job resolutions for order (: ' + convert(varchar(16), @OrderNo) + '): ' + convert(varchar(10), @totalCdes) IF @JobClass = 'Service Change' OR @JobClass = 'Special Request' WHILE @totalCdes &gt; 0 BEGIN SET @startingRow = (@totalCdes * 3) - 2; -- print 'Service Change in prin ' + convert(varchar(4),@prinOjb) + ' found with order: ' + convert(varchar(16), @OrderNo) + ' with ' + convert(varchar(16), @totalCdes) + ' resolutions of ' + @JobComplCde -- print 'starting row is ' + convert(varchar(4),@startingRow) SET @JobResolution = (SELECT descr_ctd FROM [ExternalUser].[Vantage].[CTD_DISPLAY] WHERE CDE_TBL_NO_CTD = '19' AND CDE_VALUE_CTD = SUBSTRING(@JobComplCde, @startingRow, 3) AND SYS_CTD = '8155'); INSERT INTO #JobsFixCodes VALUES (@SysOjb, @prinOjb, @JobNo, @OrderNo, @JobClass, @JobDescr, @JobResolution, @SchedDate); SET @totalCdes = @totalCdes - 1; END IF @JobClass = 'Trouble Call' WHILE @totalCdes &gt; 0 BEGIN SET @startingRow = (@totalCdes * 3) - 2; -- print 'Service Change in prin ' + convert(varchar(4),@prinOjb) + ' found with order: ' + convert(varchar(16), @OrderNo) + ' with ' + convert(varchar(16), @totalCdes) + ' resolutions of ' + @JobComplCde -- print 'starting row is ' + convert(varchar(4),@startingRow) SET @JobResolution = (SELECT descr_ctd FROM [ExternalUser].[Vantage].[CTD_DISPLAY] WHERE CDE_TBL_NO_CTD = '08' AND CDE_VALUE_CTD = SUBSTRING(@JobComplCde, @startingRow, 3) AND SYS_CTD = '8155'); INSERT INTO #JobsFixCodes VALUES (@SysOjb, @prinOjb, @JobNo, @OrderNo, @JobClass, @JobDescr, @JobResolution, @SchedDate); SET @totalCdes = @totalCdes - 1; END QuitMe: FETCH NEXT FROM @myCur INTO @SysOjb, @prinOjb, @JobClass, @JobNo, @JobType, @JobDescr, @JobComplCde, @OrderNo, @SchedDate; END CLOSE @myCur; DEALLOCATE @myCur; SELECT * FROM #JobsFixCodes AS f ORDER BY f.JOB_CLASS, f.ORDER_NO, f.SCHED_DATE; DROP TABLE #JobsFixCodes; </code></pre>
[ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-05-08T22:35:59.850", "Id": "18637", "Score": "0", "body": "Check out Jeff Atwood's post on Rubber Duck problem solving:\nhttp://www.codinghorror.com/blog/2012/03/rubber-duck-problem-solving.html" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-05-09T01:27:13.263", "Id": "18638", "Score": "0", "body": "Refactoring complex Cursor procedures into proper SQL queries is ***Hard***. That's why so many people here would rather not have to think about it. Take a look at this series of article ([There Must Be 50 Ways to Lose Your Cursors](http://www.sqlservercentral.com/articles/T-SQL/66097/)), written explicitly to help developers refactor thier Cursors into good SQL queries. Sadly, the notoriously opinionated author never finished the series, but these first two article should be perfect for helping you to get started with the refactoring process." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-05-09T20:04:21.630", "Id": "18671", "Score": "0", "body": "So, the question was migrated here, ***after*** and answer was already posted, and then my answer was turned into a comment and I was never notified? Nice. Sadly, this is the type of classless, high-handed behavior I have come to expect from StackExchange." } ]
[ { "body": "<p>Refactoring complex cursor procedures into proper SQL queries is Hard. That's why so many people here would rather not have to think about it. Take a look at this series of article (<a href=\"http://www.sqlservercentral.com/articles/T-SQL/66097/\" rel=\"nofollow\">There Must Be 15 Ways to Lose Your Cursors</a>), written explicitly to help developers refactor their cursors into good SQL queries. Sadly, the notoriously opinionated author never finished the series, but these first two article should be perfect for helping you to get started with the refactoring process.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-05-10T13:38:28.837", "Id": "26029", "ParentId": "11616", "Score": "2" } }, { "body": "<p>Back in the dark ages, when I was a newbie at SQL 2000, I had a mentor who coached me on cursors. As a result I created a template which will run as fast as possible for a simple cursor. This template is designed to run the looping process as fast as possible. This simple cursor rivals the newer forms for speed.</p>\n\n<pre><code>DECLARE @Name1 VARCHAR(50), @Name2 VARCHAR(50), @Name3 VARCHAR(50)\nDECLARE CurName CURSOR FAST_FORWARD READ_ONLY FOR\nSELECT statement\n\nOPEN CurName\nFETCH NEXT FROM CurName INTO @Name1, @Name2, @Name3\nWHILE @@FETCH_STATUS = 0 BEGIN\n\n -- Do Something\n\n FETCH NEXT FROM CurName INTO @Name1, @Name2, @Name3\nEND\nCLOSE CurName\nDEALLOCATE CurName\n</code></pre>\n\n<p>The part that makes it fast is the \"FAST_FORWARD READ_ONLY\" portion. It only works for the simple style. (I never update in a cursor. Too slow.)</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-10-29T18:55:00.100", "Id": "33477", "ParentId": "11616", "Score": "1" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "3", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-05-08T21:39:40.870", "Id": "11616", "Score": "1", "Tags": [ "sql", "sql-server" ], "Title": "Is there a way to refactor this Cursor?" }
11616
<p>I have created the value type below to represent the desired size for an image. The <code>Size.Default</code> is used in situations where the image is required in the size it was supplied in, i.e. the image shouldn't be resized.</p> <p>Is this a good implementation of a value type, especially regarding the <code>IEquatable&lt;T&gt;</code> implementation?</p> <p>What are your thoughts on the use of the private constructor to create the <code>Default</code> instance?</p> <pre><code>using System; public struct Size : IEquatable&lt;Size&gt; { private readonly int _height; private readonly int _width; private readonly bool _default; public static readonly Size Default = new Size(true); public int Height { get { return _height; } } public int Width { get { return _width; } } public bool IsDefault { get { return _default; } } private Size(bool isDefault) { _height = 0; _width = 0; _default = isDefault; } public Size(int width, int height) { _height = height; _width = width; _default = false; } public override bool Equals(object obj) { return this.Equals((Size)obj); } public bool Equals(Size other) { if (this._default &amp;&amp; other._default) return true; if (this._default &amp;&amp; !other._default) return false; if (!this._default &amp;&amp; other._default) return false; return this.Width == other.Width &amp;&amp; this.Height == other.Height; } public static bool operator ==(Size left, Size right) { return left.Equals(right); } public static bool operator !=(Size left, Size right) { return !left.Equals(right); } public static Size Parse(string input) { var parts = input.Split(new[] { ',' }, StringSplitOptions.RemoveEmptyEntries); if (parts.Length != 2) throw new FormatException("Input string was not in a correct format."); var x = int.Parse(parts[0]); var y = int.Parse(parts[1]); return new Size(y, x); } } </code></pre>
[ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-05-09T12:45:54.990", "Id": "18641", "Score": "0", "body": "What's wrong with [this](http://msdn.microsoft.com/en-us/library/system.drawing.size.aspx) or [this](http://msdn.microsoft.com/en-us/library/System.Windows.Size.aspx)?" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-05-09T13:14:58.293", "Id": "18645", "Score": "0", "body": "@JeffMercado Nothing, but I'm trying to learn something and get some feedback on the code I've written. Thanks." } ]
[ { "body": "<p>Other than needing to override <code>GetHashCode()</code>, it looks pretty darn tip-top (adapted from <a href=\"https://stackoverflow.com/a/263416/3312\">Jon Skeet</a>):</p>\n<pre><code>public override int GetHashCode()\n{\n // Overflow is fine, just wrap.\n unchecked\n {\n var hash = 17;\n\n // Suitable nullity checks etc., of course :)\n hash = (hash * 23) + this._height.GetHashCode();\n hash = (hash * 31) + this._width.GetHashCode();\n hash = (hash * 41) + this._default.GetHashCode();\n\n return hash;\n }\n}\n</code></pre>\n<p>As a matter of style, I'm not a fan of making fields <code>public</code>, no matter how <code>static</code> or <code>readonly</code> they are, so I'd prefer to do this:</p>\n<pre><code>private static readonly Size _defaultSize = new Size(true);\n\npublic static Size Default\n{\n get { return _defaultSize; }\n}\n</code></pre>\n<p>Lastly, you might want to override <code>ToString()</code> to provide the &quot;reverse&quot; of what <code>Parse()</code> does; that is, a string of height and width separated by a comma.</p>\n<p><strong>ETA: Welcome to 2021 where <code>DefaultSize</code> listed above may now be simplified to</strong></p>\n<pre><code>public static Size Default { get; } = new Size(true);\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-05-09T15:55:11.907", "Id": "18654", "Score": "0", "body": "Thanks for your comments, with regard the formula of `GetHashCode`, where do the 17,23,31 and 41 come from? Are they purely arbitrary values or is there some thought behind those choices?" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-05-09T16:00:42.120", "Id": "18658", "Score": "0", "body": "They come from a book called \"Effective Java\". They're prime numbers, which makes their inclusion in multiplication operations yield a better distribution of hash values within a given set (in this case, the set represented by the range of the `int` type)." } ], "meta_data": { "CommentCount": "2", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2012-05-09T13:57:06.497", "Id": "11620", "ParentId": "11617", "Score": "3" } }, { "body": "<p>I'm not sure what the point is for making a distinction between a size and the default size. But you shouldn't expose the default value as a field, use a property. That will give you much more flexibility should you decide to do other things when getting the value. No need for a backing field, it's a value type and it isn't all that complex.</p>\n\n<pre><code>public static Size Default\n{\n get { return new Size(true); }\n}\n</code></pre>\n\n<p>Consider renaming <code>_default</code> to something that would indicate it is a <code>bool</code>. I'd usually go with something like <code>_isDefault</code>. You already did that for the constructor parameter and property, I don't know why you didn't do the same for the field.</p>\n\n<p>Your <code>Equals()</code> method should not ever throw exceptions. What would happen if you passed in something that was not a <code>Size</code>?</p>\n\n<pre><code>public override bool Equals(object other)\n{\n if (other is Size)\n return Equals((Size)other);\n return false;\n}\n</code></pre>\n\n<p>Your <code>Equals(Size)</code> method is a little unusual. You can merge the second and third conditions into a single <code>this._isDefault != other._isDefault</code>. It might make more sense to combine that test with the tests for width and heights. And personally, I wouldn't mix accessing fields and properties within a single method, I'd choose one or the other unless the properties had other logic that I needed to be fired.</p>\n\n<pre><code>public bool Equals(Size other)\n{\n if (this._isDefault &amp;&amp; other._isDefault)\n return true;\n\n return this._isDefault == other._isDefault &amp;&amp;\n this._width == other._width &amp;&amp;\n this._height == other._height;\n}\n</code></pre>\n\n<p>Any time you override the equals method, you <em>must</em> override the <code>GetHashCode()</code> method too. Use an implementation something like this:</p>\n\n<pre><code>public override int GetHashCode()\n{\n unchecked\n {\n var hashCode = 79;\n hashCode = hashCode * 97 + _isDefault.GetHashCode();\n hashCode = hashCode * 97 + _width.GetHashCode();\n hashCode = hashCode * 97 + _height.GetHashCode();\n return hashCode;\n }\n}\n</code></pre>\n\n<p>While we're on the subject of overriding methods, you should consider overriding the <code>ToString()</code> method as well to return something reasonable.</p>\n\n<p>Your <code>Parse()</code> method should do more validation than that IMHO. You make the assumption that the input will be a comma separated pair of values. You check if you have a pair which is good, but you should explicit perform checks to make sure the values are integer numbers (i.e., digits). It's not as useful receiving a generic format exception coming from the <code>int.Parse()</code> method than if it came from <em>your</em> <code>Parse()</code> method. On a minor note, use <code>width</code> and <code>height</code> for the local variables and not <code>x</code> and <code>y</code>... that's not what they're representing.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-05-09T14:28:20.773", "Id": "18651", "Score": "0", "body": "Since you mention shortening Boolean tests in `Equals(Size)`, you can also shorten the test in `Equals(object)` with `return (other is Size) && this.Equals((Size)other);`" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-05-09T14:31:12.963", "Id": "18652", "Score": "1", "body": "True, though for that particular case, I would leave it as-is. I'd rather leave type-checking as separate steps." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-05-09T15:53:18.163", "Id": "18653", "Score": "0", "body": "I agree with Jeff, their is better readability with two separate statements." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-05-09T15:56:01.653", "Id": "18655", "Score": "0", "body": "Thanks Jeff with regard the formula of `GetHashCode`, are the 79 and 97s purely arbitrary values or is there some thought behind those choices?" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-05-09T15:57:15.850", "Id": "18656", "Score": "0", "body": "I like your point about using fields or properties only, and the `is Size` for `Equals(object)` is a good, if not obvious catch. Thanks again" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-05-09T16:26:57.217", "Id": "18660", "Score": "0", "body": "The numbers chosen in the `GetHashCode()` method should be prime numbers. I generally use those two because they mirror each other." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-02-01T16:40:35.903", "Id": "504070", "Score": "0", "body": "The code for `GetHashCode` is very verbose. Doesn't C# offer something like Java's `Objects.hash(...)`, which you can then call as `Objects.hash(_isDefault, _width, _height)`? This would avoid the question about where the numbers 79 and 97 come from." } ], "meta_data": { "CommentCount": "7", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-05-09T14:22:23.177", "Id": "11621", "ParentId": "11617", "Score": "5" } }, { "body": "<p>If you provide a <code>Parse</code> method you <a href=\"https://docs.microsoft.com/en-us/archive/blogs/ericlippert/vexing-exceptions\" rel=\"nofollow noreferrer\">should supply a corresponding <code>TryParse</code> method</a> as well (and it makes sense to implement the former in terms of the latter).</p>\n<p>Other than that, and the comments already mentioned, this is a very clean implementation.</p>\n<p>One potential gripe that I have is that <code>Default</code> and width/height are mutually exclusive so it might not make sense to provide them in the same interface. Other languages (Haskell …) would implement this cleanly as a <a href=\"https://en.wikipedia.org/wiki/Tagged_union\" rel=\"nofollow noreferrer\">discriminate union</a> (that is, a type that is <em>either</em> a default size <em>or</em> provides a custom width and height).</p>\n<p>In .NET you could use subclassing (with <code>DefaultSize</code> and <code>CustomSize</code> having a common base class <code>AbstractSize</code>) but I guess at that point we have rightly concluded that this is over-engineering and your solution is both simpler and more efficient.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-04-08T11:00:31.463", "Id": "38376", "Score": "0", "body": "+1 for tagged union. Languages like Nemerle make this kind of data structure a dream `variant Size { | Default | Other { width : int, height : int } }`" } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2012-05-09T16:12:28.017", "Id": "11625", "ParentId": "11617", "Score": "3" } }, { "body": "<p>Overall, the code is good on a technical level. This answer addresses the design philosophy behind it, because I think you've overthought the default size approach to the point of generating more work and complexity without actually adding value. We've all been there :-)</p>\n<blockquote>\n<p>The Size.Default is used in situations where the image is required in the size it was supplied in, i.e. the image shouldn't be resized.</p>\n</blockquote>\n<p>I think you've inverted the logic here. The <code>Size</code> struct is immutable. It can never change its values (i.e. &quot;resize&quot;) regardless of which initial size you picked.</p>\n<p>You cannot force your consumer to choose a default size. The consumer picks what they want, i.e. whether they fall back on a default or not. Whether that choice is correct is not the responsibility of the <code>Size</code> class, similar to how a hammer is not responsible for you using it to kill someone with it.</p>\n<p>The <code>Size</code> class cannot be held responsible for allowing resizing or not. At best, your <code>Size</code> object can prevent <em>itself</em> to be modified post-construction, but a consumer can always discard a <code>Size</code> object and create a new one, or resize images without even using your <code>Size</code> object to begin with.</p>\n<p>What I want to get at here is that there's nothing wrong with defining a default size to make your consumer's life easier, but you shouldn't expect this to be able to control your consumer's behavior.</p>\n<p>Defining a default size is fine:</p>\n<pre><code>public static readonly Size Default = new Size(true);\n</code></pre>\n<p>Though a slight improvement would be to generate a new <code>Size</code> object every time it is accessed, to avoid nasty interactions (unless you blindly trust your ability to keep this struct immutable):</p>\n<pre><code>public static Size Default =&gt; new Size(true);\n</code></pre>\n<p><em>Ignore the constructor arguments for now, I'll address this later on.</em></p>\n<p>However, the part where you pass the &quot;default&quot; boolean into the constructor, and what you do with <code>_default</code> afterwards, is unnecessary and leads to some complex and clumsy juggling. I think the intention was good but you stuck with the design when it got hairy, instead of redesigning it.</p>\n<p>One of the reasons that leads me to this suggestion is the realization that your current setup distinguishes between two size objects with the same width and height, based on whether they were explicitly set or fell back on using the default values. That makes no sense. A size of 3x3 is the same as a size of 3x3, regardless of how you decided to use those dimensions. A $100 bill is worth the same regardless of how you came to acquire it.</p>\n<p>It would be better to not track <code>_default</code> in any way, since you're better off not using it anyway. As I see it, you are using it for two things:</p>\n<ul>\n<li><code>_default</code> is used to check for equality</li>\n</ul>\n<p>But as I established above, that's actually counterproductive. Two sizes with the same dimensions are equal, regardless of how those dimensions were decided. This drastically simplifies the equality logic:</p>\n<pre><code>public bool Equals(object other)\n{\n return other is Size otherSize // Are we comparing Size objects?\n &amp;&amp; this.Width == otherSize.Width // Same width?\n &amp;&amp; this.Height == otherSize.Height; // Same height?\n}\n</code></pre>\n<ul>\n<li><code>_default</code> provides the value for the <code>IsDefault</code> property</li>\n</ul>\n<p>But you can do it without needing <code>_default</code>, if you check it on the fly. Remember that you can access your static <code>Default</code> for this. Also remember how we just refactored your <code>Equals</code> logic. That leads us to the neat implementation of:</p>\n<pre><code>public bool IsDefault =&gt; this.Equals(Default);\n</code></pre>\n<p>Now you get an accurate reading on whether a size matches the default size or not.</p>\n<blockquote>\n<p>What are your thoughts on the use of the private constructor to create the Default instance?</p>\n</blockquote>\n<p>Forgetting context for a while, you've used a private constructor correctly on a technical level. This is the general kind of use case that a private constructor is designed for.</p>\n<p>Based on my previous suggestion, I wouldn't use the private constructor here though, because when you do not track <code>_default</code>, your object ceases to need this distinction between constructors.</p>\n<p>Instead, you can just use the public one, and input whatever values you with to have as default values:</p>\n<pre><code>public static Size Default =&gt; new Size(0, 0);\n</code></pre>\n<p>Intuitively, it makes more sense that the <code>Default</code> is now grouped together with the actual <em>default</em> values themselves. In your code, the default values were off on their own in a constructor.</p>\n<p>Note that if you so choose, you can use constant values here. I don't consider it necessary in this case, but others prefer this as a default style:</p>\n<pre><code>public const int DefaultWidth = 0;\npublic const int DefaultHeight = 0;\npublic static Size Default =&gt; new Size(DefaultWidth , DefaultHeight );\n</code></pre>\n<hr />\n<p>One more mention, always think about your consumer. I noticed that in your <code>Parse</code> method, you invert the order of the arguments:</p>\n<pre><code>var x = int.Parse(parts[0]);\nvar y = int.Parse(parts[1]);\n\nreturn new Size(y, x);\n</code></pre>\n<p>This means that for your consumer, there are two different orders. This object:</p>\n<pre><code>new Size(123, 456);\n</code></pre>\n<p>is not the same as this object:</p>\n<pre><code>Size.Parse(&quot;123,456&quot;);\n</code></pre>\n<p>but it is the same as this object:</p>\n<pre><code>Size.Parse(&quot;456,123&quot;);\n</code></pre>\n<p>That's really counterintuitive and is going to lead to your consumer making mistakes. I suggest sticking to one specific order for the parameters so that your consumer doesn't need to keep guessing which order it is.</p>\n<p>By far the most common is <code>width,height</code> due to the established x/y axes convention in mathematics.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-02-01T12:34:08.807", "Id": "255465", "ParentId": "11617", "Score": "2" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "2", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-05-09T12:37:44.160", "Id": "11617", "Score": "5", "Tags": [ "c#", ".net", "reinventing-the-wheel" ], "Title": "Is this a good implementation of a simple \"Size\" value type" }
11617
<p>I am creating a step-by-step form (it only shows in step-by-step and is not a multi state form) and the parts slide in and out (similar to GitHub but without the browser's back buttons). I have written the following code to implement this. Could you please review my code and suggest flaws:</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>$(document).ready(function(){ // when the div with text next is clicked $('.nextButton').click(function(){ // remove the class from div that is visible at present, add it the class for divs on the left side and move it to the left side // and remove from the next div, the class assigned divs lying to the right and add bring it in the visible area and assign visible class to it $('.visible').removeClass('visible').addClass('onLeft').animate({left:'-980px'}).next('div').removeClass('onRight').animate({left:'0px'}).addClass('visible'); //fade in the div with title previous $('.prevButton').fadeIn(); //if there are no div left on the right side remove the class for next button and add the class for done button and modify the HTML to done if($('.onRight').length==0) { $(this).removeClass('nextButton').addClass('doneButton').html('Done'); } }); //when the div with text previous is clicked $('.prevButton').click(function(){ //if the div with class 'doneButton' exists, i.e we are at the last step, then remove the class and assign the div class for next button and text next if($('.doneButton').length) { $('.doneButton').removeClass('doneButton').addClass('nextButton').html('Next'); } //if there is just 1 div left towards left, i.e. we are on the 2nd step, remove the div with title previous if($('.onLeft').length==1) { $(this).fadeOut(); } //remove the class from div that is visible at present, add to it the class for divs on right side and move it to the right side, remove //the class assigned to divs on the left from the left div and add visible class to the div and bring it in the visible section $('.visible').removeClass('visible').addClass('onRight').animate({left:'980px'}).prev('div').removeClass('onLeft').animate({left:'0px'}).addClass('visible'); }); });</code></pre> <pre class="snippet-code-html lang-html prettyprint-override"><code>&lt;script src="https://ajax.googleapis.com/ajax/libs/jquery/1.7.2/jquery.min.js"&gt;&lt;/script&gt; &lt;div class="formContent" style="width:980px;height:100px;float:left;overflow:hidden;position:relative;"&gt; &lt;div class="visible bt" style="width:980px;float:left;position:absolute;"&gt;Part1&lt;/div&gt; &lt;div class="onRight bt" style="width:980px;float:left;position:absolute;left:980px;"&gt;Part2&lt;/div&gt; &lt;div class="onRight bt" style="width:980px;float:left;position:absolute;left:980px;"&gt;Part3&lt;/div&gt; &lt;div class="onRight bt" style="width:980px;float:left;position:absolute;left:980px;"&gt;Part4&lt;/div&gt; &lt;/div&gt; &lt;div class="formButtons" style="width:980px;height:50px;float:left;"&gt; &lt;div class="nextButton" style="float:right"&gt;Next&lt;/div&gt; &lt;div class="prevButton" style="float:right;margin-right:20px;display:none;"&gt;Previous&lt;/div&gt; &lt;/div&gt;</code></pre> </div> </div> </p> <p>(Note that the "Next" button is quite far to the right in this demo.)</p>
[ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-05-09T13:54:07.720", "Id": "18649", "Score": "0", "body": "The code is working fine BTW :) But still, I feel that using so many methods in just a single statement shouldn't be the right approach, because I have never seen anyone use it so far." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-05-09T15:57:36.207", "Id": "18657", "Score": "0", "body": "Use the second context parameter to the jquery function. Its almost always the right move, it will hugely speed up your code and help prevent bugs due to naming conflicts. In this case it seems like your context should be the above form or at least `$('div.formContent')`" } ]
[ { "body": "<p>jQuery was designed so you can chain function calls together like that. If you're worried about readability, then break them up into logical parts. You can either use variables, or keep the chaining and use whitespace to split them up. Instead of:</p>\n\n<pre><code>$('.visible').removeClass('visible').addClass('onLeft').animate({left:'-980px'}).next('div').removeClass('onRight').animate({left:'0px'}).addClass('visible');\n</code></pre>\n\n<p>you could do something like this:</p>\n\n<pre><code>$('.visible')\n .removeClass('visible')\n .addClass('onLeft')\n .animate({left:'-980px'})\n.next('div')\n .removeClass('onRight')\n .animate({left:'0px'})\n .addClass('visible');\n</code></pre>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-05-09T14:39:15.107", "Id": "11622", "ParentId": "11618", "Score": "3" } }, { "body": "<p>Did some mods with the HTML. You should separate classes for targetting and classes for state. You can use <code>data-*</code> to keep states also, just so you know. But for this one, I used <code>leftButton</code> and <code>rightButton</code> classes for targetting and left <code>prevButton</code>, <code>nextButton</code> and <code>doneButton</code> for the state.</p>\n\n<pre><code>&lt;div class=\"formButtons\" style=\"width:980px;height:50px;float:left;\"&gt;\n &lt;div class=\"nextButton rightButton\" style=\"float:right\"&gt;Next&lt;/div&gt;\n &lt;div class=\"prevButton leftButton\" style=\"float:right;margin-right:20px;display:none;\"&gt;Previous&lt;/div&gt;\n&lt;/div&gt;​\n</code></pre>\n\n<p>As for the JS, it's pretty much commented. And jQuery was designed to be chained. However, you have to <a href=\"https://stackoverflow.com/a/10515103/575527\">know what is returned in the previous call</a> so that you can optimize the chain.</p>\n\n<pre><code>//shortened doc ready\n$(function() {\n\n //cache the buttons. they never go away so set them statically\n //added an additional class for targetting, instead of the \n //prev, next and done states\n var rightButton = $('.rightButton');\n var leftButton = $('.leftButton');\n\n //delegation using on()\n $('.formContent').on('click', '.rightButton', function() {\n\n //use the value as boolean\n if (!$('.onRight').length) {\n $(this) //you can get away with $(this) \n .removeClass('nextButton') //because it's only used once\n .addClass('doneButton')\n .text('Done'); //use text if you are only putting text \n }\n\n leftButton.fadeIn();\n\n $('.visible') //i usually newline and indent\n .removeClass('visible') //anything that pertains to the current selection\n .addClass('onLeft') //moved addClass up for readability only if it's for state.\n .animate({ //if it's used for style\n left: '-980px' //move it back below animate\n }) \n .next() //you can omit the \"div\" since they are all divs\n .removeClass('onRight') //indentation again\n .addClass('visible')\n .animate({\n left: '0px'\n });\n\n\n }) //chain the next handler\n .on('click', '.leftButton', function() {\n\n //cache donebutton since it's used twice\n var doneButton = $('.doneButton');\n\n if (doneButton.length) {\n doneButton.removeClass('doneButton')\n .addClass('nextButton')\n .text('Next'); //use text if you are only putting text\n }\n\n //use the value as boolean\n if ($('.onLeft').length) {\n $(this).fadeOut();\n }\n\n $('.visible')\n .removeClass('visible')\n .addClass('onRight')\n .animate({\n left: '980px'\n })\n .prev() //same as before, omit the div\n .removeClass('onLeft')\n .addClass('visible')\n .animate({\n left: '0px'\n });\n });\n});​\n</code></pre>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-05-11T03:30:23.313", "Id": "11674", "ParentId": "11618", "Score": "1" } } ]
{ "AcceptedAnswerId": "11674", "CommentCount": "2", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-05-09T13:50:00.767", "Id": "11618", "Score": "2", "Tags": [ "javascript", "jquery", "html", "form" ], "Title": "Step-by-step form" }
11618
<p>I'm wondering if it is possible or if it is correct to proceed in such a way: </p> <pre><code>var initiate_shop = function(shop_navigation, shop_container_id, items_per_page) { return $(shop_navigation).jPages({ containerID : shop_container_id, first : false, previous : false, next : false, last : false, midRange : 15, perPage : items_per_page, animation : "fadeInUp", links : "blank", keyBrowse : true, scrollBrowse : false, callback : function(pages){ current_page = pages.current; total_pages = pages.count; } }); }; </code></pre> <p>If the above isn't correct what could be a better way to write it?</p>
[]
[ { "body": "<p>Looks good to me, if you always want those 3 params and never want to send anything else.</p>\n\n<p>Otherwise, you could improve it by receiving the non-mandatory params in an options object:</p>\n\n<pre><code>\"use strict\";\nvar initiate_shop = function(container_id, options) {\n var default_settings = {\n containerID : container_id,\n first : false,\n perPage : 5,\n '...' : '...',\n callback : function(pages){\n current_page = pages.current;\n total_pages = pages.count;\n }\n },\n settings = $.extend(default_settings, options);\n return $(shop_navigation).jPages(settings);\n};\n// ...\ninitiate_shop('outputCell', {\n perPage: 10,\n first: true\n});\n</code></pre>\n\n<p>Related (hows 3 ways to assign default values to parameters):<br>\n<a href=\"https://stackoverflow.com/a/3672142/148412\">https://stackoverflow.com/a/3672142/148412</a></p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-05-10T08:59:56.357", "Id": "18695", "Score": "0", "body": "Yeah, this seems to be more suitable, since I may have other options I could change, even the callback function might change. The example looks great :)" } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-05-09T20:48:01.133", "Id": "11634", "ParentId": "11623", "Score": "3" } } ]
{ "AcceptedAnswerId": "11634", "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-05-09T14:43:26.807", "Id": "11623", "Score": "3", "Tags": [ "javascript", "jquery" ], "Title": "Can I return an object on which a function is applied?" }
11623
<p>I have some simple tests written, however, the names are not good...I think, any suggestions on better names? I'm not really sure how these tests should be named.</p> <p>I'm looking for a format or pattern I can follow.</p> <pre><code>[TestClass] public class DoorTests { [TestMethod] public void DoorIsNotVirtualIfNameStartsWithLetterOtherThanV() { var door = new Door {Name = "R143"}; Assert.IsFalse(door.IsVirtual); } [TestMethod] public void DoorIsVirtualIfNameStartsWithLetterV() { var door = new Door {Name = "V001"}; Assert.IsTrue(door.IsVirtual); } } </code></pre>
[]
[ { "body": "<p>I find that <a href=\"http://osherove.com/blog/2005/4/3/naming-standards-for-unit-tests.html\">Roy Osherove's test naming convention</a> is easy to apply and provides suggestive names for the test methods.</p>\n\n<p>Roy proposes that the test method names should be composed of three parts:</p>\n\n<ul>\n<li>MethodName (or PropertyName, as in our case)</li>\n<li>StateUnderTest (a brief description of the scenario being tested)</li>\n<li>ExpectedBehavior</li>\n</ul>\n\n<p>Following this convention, the methods in the <code>DoorTest</code> class could be named:</p>\n\n<ul>\n<li>IsVirtual_NameStartsWithLetterOtherThanV_ReturnsFalse</li>\n<li>IsVirtual_NameStartsWithLetterV_ReturnsTrue</li>\n</ul>\n\n<p>Following a convention like this can provides consistency and makes it easy to use and maintain the test code.</p>\n\n<p>Also, having the three elements delimited by underscores provides good readability: In case a test fails, with only a glance, you are easily able to grasp all relevant information about the failure: what component failed? what was the failure scenario? what is the expectancy that was not met?</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-05-10T10:52:36.043", "Id": "18698", "Score": "0", "body": "Thank you for introducing me to a great convention. Would you agree that for cases like this, it is suitable to break general naming conventions for the language the tests are expressed in? Some people get very precious about these things.." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-05-10T12:00:06.900", "Id": "18700", "Score": "0", "body": "@obfuscation - of course, it's OK to break or adapt the convention when there's a good enough reason. After all, it's a convention, not a hard rule." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-05-10T15:32:17.527", "Id": "18705", "Score": "0", "body": "I like the names, and, despite requesting the unblocking of Osherove's site last week, it's still blocked...no clue why it's blocked in the first place. Some days ... *grrr*" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-05-11T07:01:16.680", "Id": "18724", "Score": "0", "body": "@Chad Is it blocked because of office policies? That's weird..." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-05-11T13:46:22.547", "Id": "18737", "Score": "0", "body": "@w0lf, I think some automated tool saw too many banners, since the reason given on the page is (web banners). But, it's sad how long it takes to get stuff unlocked...considering I know it can be a quick process." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-05-14T13:31:29.190", "Id": "18840", "Score": "1", "body": "@Chad Is this not where proxies, tunneling, mobile internet or home internet come into play :)?" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-05-14T13:46:50.923", "Id": "18843", "Score": "0", "body": "@obfuscation, the playbook does get broken out for use on occasion. Proxies, and tunneling, are tricky. It's tough to get things on/off the computer here. Can't even stick in a USB stick." } ], "meta_data": { "CommentCount": "7", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-05-09T21:29:45.887", "Id": "11638", "ParentId": "11635", "Score": "15" } }, { "body": "<p>In my opinion, the names of your tests are fine. The explain in a way so everyone understands what they do and what they test. The problem I find with your tests are the CamelCases.</p>\n\n<p>Even though I don't care if using CamelCase or underscores in production code, I find tests a lot easier to read by have all small letter and using underscores to separate. The reason I feel this is good in tests is that test names are often much longer than production code names, as they are only typed once. The Roy Osherove's test naming convention also seems descriptive though, but don't really see the need for it if you can read the name of your test as a plain English sentence and understand what we are after.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-05-11T11:51:26.180", "Id": "18731", "Score": "0", "body": "Plus 1 for this. Instead of `DoorIsNotVirtualIfNameStartsWithLetterOtherThanV` name the method `door_is_not_virtual_if_name_starts_with_letter_other_than_v`. This describes the test, is easy to read, and, as an added bonus, visually clearly separates from the CamelCase methods used in production code." } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-05-10T08:28:49.497", "Id": "11653", "ParentId": "11635", "Score": "3" } }, { "body": "<p>I find these test names cumbersome to the point of being confusing; method names are not camelcased sentences. </p>\n\n<p>If you want to go with \"readable\" test method names - try to make it easier to read the method name than the code (which is what a 12 word method name is likely to make a reader do). Here are some suggestions for DoorIsNotVirtualIfNameStartsWithLetterOtherThanV -</p>\n\n<ul>\n<li>The class is testing the class door - all methods in this test case will test something in the door class - the word door is not necessary.</li>\n</ul>\n\n<blockquote>\n <p>IsNotVirtualIfNameStartsWithLetterOtherThanV</p>\n</blockquote>\n\n<ul>\n<li>Remove words that don't add meaning</li>\n</ul>\n\n<blockquote>\n <p>notVirtualIfNameStartsLetterOtherThanV</p>\n</blockquote>\n\n<ul>\n<li>Use a simpler vocabulary</li>\n</ul>\n\n<blockquote>\n <p>notVirtualIfNameFirstCharNotV</p>\n</blockquote>\n\n<ul>\n<li>Double negatives are confusing</li>\n</ul>\n\n<blockquote>\n <p>notVirtualIfNameFirstCharR</p>\n</blockquote>\n\n<p><strong>But</strong>. What's wrong with</p>\n\n<pre><code>[TestClass]\npublic class DoorTests\n{\n [TestMethod]\n /**\n * Virtual doors only start with V\n */\n public void testIsVirtual()\n {\n var door = new Door {Name = \"V001\"};\n Assert.IsTrue(door.IsVirtual, \"Door $door$ is not virtual but was expected to be\");\n }\n\n [TestMethod]\n /**\n * Real doors don't start with V, and usually start with R\n */\n public void testIsVirtualFalse()\n {\n var door = new Door {Name = \"R143\"};\n Assert.IsFalse(door.IsVirtual, \"Door $door$ isVirtual, but was expected not to be\");\n }\n}\n</code></pre>\n\n<p>If you have more permutations of similar tests - use a (short) suffix. Just ensure the message when an assert fails gives all the detail you'd want to know what the failure means, or the docs for the failing test clearly guide the developer to understand the error. Replacing docs and error messages with \"meaningful method names\" just makes code tiresome to read.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-05-10T15:33:25.747", "Id": "18706", "Score": "0", "body": "The names aren't bad, but I really don't like comments to describe anything...they end up being forgotten, and eventually fall out of date and loose accuracy." } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-05-10T09:06:52.273", "Id": "11655", "ParentId": "11635", "Score": "3" } }, { "body": "<p>I like to use something very similar to what is here referred to as Roy Osherove's test naming convention, the difference being the order of the parts:</p>\n\n<ul>\n<li>IsVirtual_ReturnsFalse_IfNameStartsWithLetterOtherThanV</li>\n<li>IsVirtual_ReturnsTrue_IfNameStartsWithLetterV</li>\n</ul>\n\n<p>Also, I tend to use \"When\" instead of \"If\" (but that's just a matter of taste, I guess):</p>\n\n<ul>\n<li>IsVirtual_ReturnsFalse_WhenNameStartsWithLetterOtherThanV</li>\n<li>IsVirtual_ReturnsTrue_WhenNameStartsWithLetterV</li>\n</ul>\n\n<p>The main reason for this reordering of the parts is readability of the test names; I think it reads more naturally when in this order. Try comparing these two variations of naming the same test by reading their names out loud:</p>\n\n<ul>\n<li>IsVirtual_NameStartsWithLetterOtherThanV_ReturnsFalse</li>\n<li>IsVirtual_ReturnsFalse_WhenNameStartsWithLetterOtherThanV</li>\n</ul>\n\n<p>Which one would you prefer?</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-05-10T11:26:33.963", "Id": "11657", "ParentId": "11635", "Score": "7" } }, { "body": "<p>I like the tests layout, described here: <a href=\"http://zendeveloper.blogspot.com/2012/01/structuring-unit-tests.html\" rel=\"nofollow\">http://zendeveloper.blogspot.com/2012/01/structuring-unit-tests.html</a></p>\n\n<p>In summary, all tests for a given methods or property are grouped in their own \"sub-fixture\", and then I use more descriptive names for the test cases. Also, check <a href=\"http://fluentassertions.codeplex.com/documentation\" rel=\"nofollow\">FluentAssertions</a>, they are very good to describe the \"assert\" part in more natural language.</p>\n\n<pre><code>[TestFixture]\npublic class DoorTests\n{\n [TestFixture]\n public class IsVirtualProperty\n {\n [Test]\n public void Should_be_false_if_Name_does_not_start_with_letter_V()\n {\n var door = new Door {Name = \"R123\"};\n door.IsVirtual.Should().Be.False;\n }\n [Test]\n public void Should_be_true_if_Name_start_with_letter_V()\n {\n var door = new Door {Name = \"V123\"};\n door.IsVirtual.Should().Be.True;\n }\n }\n}\n</code></pre>\n\n<p>As an addition, the first test does not cover all the possibilities, it just verifies that if the name starts with R, IsVirtual is false :)</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-05-22T14:33:37.533", "Id": "11971", "ParentId": "11635", "Score": "0" } }, { "body": "<p>I like the BDD style test structure.</p>\n\n<p><code>GivenAnObject</code>\n<code>WhenIPerformAnAction</code>\n<code>ThenIGetTheseResults</code></p>\n\n<p>In C# this translates nicely to a namespace structure:</p>\n\n<pre><code>namespace GivenAnObject\n{\n [TestFixture]\n class WhenIPerformAnAction\n {\n private MyObject result;\n\n [SetUp]\n public void GivenAnObject()\n {\n // CreateMyObject();\n When();\n }\n\n public void When()\n {\n result = MyObject.ExecuteAction();\n }\n\n [Test]\n public void ThenIGetAResult()\n {\n Assert.AreEqual(ExpectedResult, result);\n }\n }\n}\n</code></pre>\n\n<p>When run in nunit tests that follow this paradigm will display very nicely as a well grouped set of tests which are testing the behaviour of the various parts of your program.</p>\n\n<p>In your case these tests would be:</p>\n\n<p><code>GivenADoor</code>\n<code>WhenTheDoorStartsWithV</code>\n<code>ThenTheDoorIsVirtual</code></p>\n\n<p><code>GivenADoor</code>\n<code>WhenTheDoorDoesNotStartWithV</code>\n<code>ThenTheDoorIsNotVirtual</code></p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-03-12T04:41:05.010", "Id": "76404", "Score": "0", "body": "This is actually what I've been doing bite for a while, I find it works very well." } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-03-12T04:32:32.610", "Id": "44122", "ParentId": "11635", "Score": "3" } } ]
{ "AcceptedAnswerId": "44122", "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-05-09T20:58:38.733", "Id": "11635", "Score": "11", "Tags": [ "c#", "unit-testing" ], "Title": "Better test names" }
11635
<p>I have a <code>getValue</code> function which just grabs some numbers from an HTML page.</p> <p>How can I access those variables in later functions without passing them down the entire chain of functions? As they sit within a function they are not global?</p> <p>When I call the addition function, it will need to access the variables in the <code>getValue</code> function.</p> <p>In Java, I would have used a separate class with a normal getter and setter pattern but unsure how to replicate something similar.</p> <p>I feel like I am missing a key JavaScript concept here.</p> <pre><code> function getValue() { var decimal = parseInt(parent.document.getElementById('CF_9813416').value); var a = parseFloat(parent.document.getElementById('CF_9814331').value); var b = parseFloat(parent.document.getElementById('CF_9814407').value); var c = parseFloat(parent.document.getElementById('CF_9814615').value); } function radioButtons() { for (var i = 0; i &lt; parent.document.Form1.CF_9813571.length; i++) { if (parent.document.Form1.CF_9813571[i].checked) { var sign = parent.document.Form1.CF_9813571[i].value; } } radioResult(sign); } function radioResult(sign) { if (sign == '9813524') { addition(); } else if (sign == '9813527') { subtraction(); } else if (sign == '9813530') { multiplication(); } else devision(); } function addition() { result = a + b + c; writeValue(result, decimal); } function subtraction() { result = a - b - c; writeValue(result, decimal); } function multiplication() { result = a * b * c; writeValue(result, decimal); } function devision() { result = a / b / c; writeValue(result, decimal); } function writeValue(result, decimal) { parent.document.getElementById('CF_9814616').value = result.toFixed(0); parent.document.getElementById('CF_9814617').value = result.toFixed(decimal); } &lt;/script&gt; </code></pre>
[]
[ { "body": "<p>Yes, you are right, <code>decimal</code>, <code>a</code>, <code>b</code> and <code>c</code> are not accessible by other functions because they are local to getValue(). To make them global, you need to declare them outside of your function, like this: </p>\n\n<p><strong>Solution #1</strong></p>\n\n<pre><code>var decimal; \nvar a;\nvar b;\nvar c;\n\nfunction getValue(){\n decimal = // assign decimal\n a = // assign a\n // assign rest of the variables\n}\n\nfunction useVariables(){ \n return a + b + c;\n}\n</code></pre>\n\n<p>Using global variables, however, is considered a bad practice so I would move onto another solution. </p>\n\n<p><strong>Solution #2</strong></p>\n\n<p>Have 'getter functions' for each of your variables. Instead of having <code>getValue()</code>, have <code>getDecimal()</code>, <code>getA()</code>, <code>getB()</code> and <code>getC()</code> functions (you might consider giving these variables more meaningful names). Your code would turn into something like this: </p>\n\n<pre><code>function getA(){\n return parseFloat(parent.document.getElementById('CF_9814331').value);\n}\n\n// functions for getB() and getC()\n\nfunction useVariables(){\n return getA() + getB() + getC();\n}\n</code></pre>\n\n<p>This is a more acceptable solution because you delay getting the variables until you need them and you also do not have global variables. If the values change you get the updated values as well without having to call <code>getValue()</code> again to 'refresh' your data. </p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-05-10T00:15:46.077", "Id": "18682", "Score": "0", "body": "Awesome, thank you very much for the response. Solution #2 was what I was thinking of doing prior to posting. Unsure why I decided not to in the first place, since you are correct and it does make the most sense ;)" } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-05-09T23:42:44.613", "Id": "11642", "ParentId": "11637", "Score": "4" } }, { "body": "<p>To improve on c_maker's answer, you should enclose the entire thing in a closure to avoid cluttering the global namespace:</p>\n\n<pre><code>(function (wnd, undefined) {\n var decimal; \n var a;\n var b;\n var c;\n\n function getValue(){\n decimal = // assign decimal\n a = // assign a\n // assign rest of the variables\n }\n\n function useVariables(){ \n return a + b + c;\n }\n\n // Anything that needs to be in scope outside of the closure can be\n // assigned to wnd.\n wnd.getValues = getValues;\n\n} (window));\n</code></pre>\n\n<p>This type of construct is known as an <a href=\"http://benalman.com/news/2010/11/immediately-invoked-function-expression/\" rel=\"nofollow\">IIFE</a></p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-05-10T19:49:51.593", "Id": "11666", "ParentId": "11637", "Score": "4" } }, { "body": "<p>You really miss some JavaScript keypoints. JavaScript just has function scope and doesn't has any other block scope.</p>\n\n<pre><code>function radioButtons() {\n\n for (var i = 0; i &lt; parent.document.Form1.CF_9813571.length; i++) {\n if (parent.document.Form1.CF_9813571[i].checked) {\n var sign = parent.document.Form1.CF_9813571[i].value;\n }\n }\n radioResult(sign);\n}\n</code></pre>\n\n<p>Check your function. You try to define variable 'sign' in the <code>if</code> block, then you use it. That is really bad practice. When I saw this code, I had no idea why the variable can be used even it was out of the scope. So the best practice is put all variable defines at the top of the function.</p>\n\n<p>Don't use global variables; there are lots of ways to ignore it.</p>\n\n<ul>\n<li>Use anonymous functions</li>\n<li>Arrange your function to object</li>\n</ul>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-05-25T06:56:40.627", "Id": "12056", "ParentId": "11637", "Score": "1" } } ]
{ "AcceptedAnswerId": "11642", "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-05-09T21:09:12.567", "Id": "11637", "Score": "6", "Tags": [ "javascript" ], "Title": "JavaScript functions and global variables" }
11637
<p>Do you have any suggestions to improve or extend this script? Any ideas for removing or adding comments/docstrings?</p> <pre><code>import dbm import subprocess import time subprocess.call("clear") try: # Tries to import cPickle, a faster implementation of pickle. import cPickle as pickle except ImportError: import pickle class PickleDB: def open_db(self): """Gets and opens the database""" self.db_name = input("Enter a database name\n") # Makes sure the database name is compatible db_parts = self.db_name.split(".") self.db_name = db_parts[0] self.db = dbm.open(self.db_name, "n") def get_data(self): """Gets data to write into the database""" subprocess.call("clear") self.raw_data = input("Enter your raw data\n") # Pickles data self.pickled_data = pickle.dumps(self.raw_data) def write_to_db(self): """Writes data into database""" # Logs time self.start = time.time() # Creates keys self.db["raw"] = self.raw_data self.db["pickled"] = self.pickled_data def close_db(self): """Closes database""" self.db.close() # Logs end time self.end = time.time() def info(self): """Prints out info about the database""" subprocess.call("clear") print("Load data from database using dbm") print("Keys: raw\tpickled") # Prints total time print("Speed:", self.end - self.start, "seconds") # Function calls pickled_db = PickleDB() pickled_db.open_db() pickled_db.get_data() pickled_db.write_to_db() pickled_db.close_db() pickled_db.info() </code></pre>
[]
[ { "body": "<pre><code>import dbm\nimport subprocess\nimport time\nsubprocess.call(\"clear\")\n</code></pre>\n\n<p>This isn't cross-platform. Sadly, there isn't really a cross-platform alternative</p>\n\n<pre><code>try:\n # Tries to import cPickle, a faster implementation of pickle.\n import cPickle as pickle\nexcept ImportError:\n import pickle\n\nclass PickleDB:\n def open_db(self):\n \"\"\"Gets and opens the database\"\"\"\n self.db_name = input(\"Enter a database name\\n\")\n</code></pre>\n\n<p>You really shouldn't call <code>input</code> inside of a work class. The code responsible for User I/O should be separate from that doing any actual work.</p>\n\n<pre><code> # Makes sure the database name is compatible\n db_parts = self.db_name.split(\".\")\n self.db_name = db_parts[0]\n</code></pre>\n\n<p>Ok, why are you ignoring part of the name if its not good? Shouldn't you complain to the user and ask for a new name? Also, I'd avoid assigning to <code>self.db_name</code> only the replace it again a bit later. Since you don't use it outside this function, I'd probably just have a local variable</p>\n\n<pre><code> self.db = dbm.open(self.db_name, \"n\")\n\n def get_data(self):\n \"\"\"Gets data to write into the database\"\"\"\n subprocess.call(\"clear\")\n self.raw_data = input(\"Enter your raw data\\n\")\n # Pickles data\n</code></pre>\n\n<p>This comment is a little obvious, I'd delete it</p>\n\n<pre><code> self.pickled_data = pickle.dumps(self.raw_data)\n</code></pre>\n\n<p>I'd expect a function that <code>gets</code> data to return it to the caller. Generally, functions that drop state onto the class is a sign of poor design. Methods should usually communicate by parameters and return values not object storage.</p>\n\n<pre><code> def write_to_db(self):\n \"\"\"Writes data into database\"\"\"\n # Logs time\n self.start = time.time()\n</code></pre>\n\n<p>Collecting timing information isn't something that's usually part of the actual class doing the work. Usually you'd time the class from the outside.</p>\n\n<pre><code> # Creates keys\n self.db[\"raw\"] = self.raw_data\n self.db[\"pickled\"] = self.pickled_data\n\n def close_db(self):\n \"\"\"Closes database\"\"\"\n self.db.close()\n # Logs end time\n self.end = time.time()\n\n\n def info(self):\n \"\"\"Prints out info about the database\"\"\"\n subprocess.call(\"clear\")\n print(\"Load data from database using dbm\")\n print(\"Keys: raw\\tpickled\")\n # Prints total time\n print(\"Speed:\", self.end - self.start, \"seconds\")\n</code></pre>\n\n<p>As noted, output and timing is usually something you want to do outside of the work class itself. </p>\n\n<pre><code># Function calls\npickled_db = PickleDB()\npickled_db.open_db()\npickled_db.get_data()\npickled_db.write_to_db()\npickled_db.close_db()\npickled_db.info()\n</code></pre>\n\n<p>Here's the overall thing about your code. You are using a class as a group of functions and treating the object storage like a place to put global variables. You aren't making effective use of the class. In this case, you'd be better off to use a collection of functions than a class. </p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-05-10T04:47:56.673", "Id": "11650", "ParentId": "11641", "Score": "3" } }, { "body": "<p>I think Winston Ewert summed up quite well what is wrong with the code. You should replace all that is after the line <code># Function calls</code> by</p>\n\n<pre><code>if __name__ == \"__main__\":\n pickle_db = PickleDB(input(\"Enter a database name\\n\"))\n pickle_db.write(input(\"Enter your raw data\\n\"))\n pickle_db.close()\n print(\"Speed:{0} seconds\".format(pickle_db.get_total_time())\n</code></pre>\n\n<p>and build your class from that snippet of code (put the open function in the init, for example)</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-05-16T11:22:39.300", "Id": "11802", "ParentId": "11641", "Score": "1" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-05-09T22:49:27.703", "Id": "11641", "Score": "0", "Tags": [ "python", "optimization", "database" ], "Title": "How to Improve This Program, Add Comments, etc.?" }
11641
<p>Here is my window tiling script for rio window manager in Plan 9. It fetches the current screen size and calculates the locations based on the layout given. How can I improve this program? Am I missing any idioms in rc?</p> <pre><code>#!/bin/rc # Usage: # First save the current windows # ./tile.rc save &gt;saved.s # Next switch to tall # ./tile.rc tall |tee tall.s |rc # Can go back if you want # cat saved.s |rc # get the position from the image input fn winpos { dd -bs 1 -skip 20 -count 40 -quiet 1 } # get just width and height fn winsize { winpos | awk '{print ($3-$1),($4-$2)}' } # of the screen fn screen { cat /mnt/wsys/screen | winsize } # get the width of the current windo. We use this # for wall - where the width of current window # is kept unchanged. fn getwidth { w=`{cat /mnt/wsys/window | winsize} echo $w(1) } # generate a move command for the input # move -r minx miny maxx maxy does not seem # to work. (see save cmd). So until then fn movcmd { mx=`{echo $2 $4 + p|dc} my=`{echo $3 $5 + p|dc} echo (echo resize -r $2 $3 $mx $my '&gt;' $1/wctl) } # print the commands to get the windows back to # the original positions. This does not seem to # work always. (can use wloc too.) fn savewin { windows=/dev/wsys/* for (i in $windows) { loc=`{cat $i/window | winpos} echo (echo resize -r $loc '&gt;' $i/wctl) } } # Tall configuration, with a main window, on one # half of the screen, and child windows on the other # the main window is the window from which command is # invoked fn tall { maxx=$1 maxy=$2 mywin=$3 windows=/dev/wsys/* childht=`{echo $maxy $#windows 1 - / p| dc} ylast=0 xhalf=`{getwidth} halfx=`{echo $maxx $xhalf - p| dc} for (i in $windows) { switch ($i) { case /dev/wsys/$mywin movcmd $i 0 0 $xhalf $maxy case * movcmd $i $xhalf $ylast $halfx $childht ylast=`{echo $ylast $childht + p| dc} } } } # Rows configuration fn rows { maxx=$1 maxy=$2 windows=/dev/wsys/* childht=`{echo $maxy $#windows / p| dc} ylast=0 for (i in $windows) { movcmd $i 0 $ylast $maxx $childht ylast=`{echo $ylast $childht + p| dc} } } fn main { myscreen=`{screen} mywin=`{cat /mnt/wsys/winid} switch ($1) { case rows rows $myscreen $mywin case tall tall $myscreen $mywin case save savewin case * echo (supported: tall rows save) } # For some reason, this line does not # really get the original window focus. echo (echo current '&gt;' /dev/wsys/$mywin/wctl) } main $* </code></pre>
[]
[]
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-05-10T03:45:14.907", "Id": "11643", "Score": "3", "Tags": [ "rc" ], "Title": "Plan 9 rio script to tile windows" }
11643
<p>Plan9 is a distributed operating system with many advanced ideas. These include per process namespaces, all resources in the system exposed as files, a single protocol 9p to communicate with other distributed resources instead of multiple protocols like HTTP, FTP, etc.</p> <p>Quite a few of these ideas found its way back to linux (incldes /proc filesystem, 9p)</p>
[]
[]
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-05-10T03:47:54.060", "Id": "11644", "Score": "0", "Tags": null, "Title": null }
11644
<p>Rio is the window manager for Plan9 Operating system. It is a simple window manager that makes its controls and the windows it controls available as file system resources mounted under /dev. The unix window manager wmii takes its inspiration from Rio.</p>
[]
[]
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-05-10T03:49:33.917", "Id": "11646", "Score": "0", "Tags": null, "Title": null }
11646
Rio is the window manager for Plan9 Operating System.
[]
[]
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-05-10T03:49:33.917", "Id": "11647", "Score": "0", "Tags": null, "Title": null }
11647
Rc is the shell for Plan9 Operating System.
[]
[]
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-05-10T03:50:07.363", "Id": "11649", "Score": "0", "Tags": null, "Title": null }
11649
<p>I have to write a comparison logic.</p> <p>Following is the code to refactor (as it is looking bad).</p> <pre><code> // 1. item has filter criteria // 2. return true if current matches filter criteria // 3. Criteria -&gt; 3 fields should be matched ( Security, OrderType, CounterType) // 4. Criteria -&gt; User can specify All (*), If any matching field is All, (NONE for enum), only that field should not be matched, other should be matched private static bool CompareOrderItem(Item item, Item current) { String all="All"; bool flag = true; if (!( String.Equals(item.Security, all) ||String.Equals(current.Security, item.Security))) flag = false; if (!( item.OrderType == OrderTypeEnum.None ||Enum.Equals(current.OrderType, item.OrderType))) flag = false; if (!( String.Equals(item.Counterparty, all) || String.Equals(current.Counterparty, item.Counterparty))) flag = false; return flag ; } </code></pre>
[]
[ { "body": "<p>This is a subjective opinion, but I find it useful to extract methods for the three types of matches you are checking in your code. </p>\n\n<p>I refactored your code and extracted the methods: </p>\n\n<ul>\n<li><code>bool OrderPartyMatches(Item item, Item current)</code></li>\n<li><code>bool OrderTypeMatches(Item item, Item current)</code></li>\n<li><code>bool SecurityMatches(Item item, Item current)</code></li>\n</ul>\n\n<p>While all I did was move stuff around, I think this version gains in readability, because I find</p>\n\n<pre><code>OrderPartyMatches(item, current)\n</code></pre>\n\n<p>to reveal its intent more clearly than</p>\n\n<pre><code>( String.Equals(item.Security, all) ||String.Equals(current.Security, item.Security)\n</code></pre>\n\n<p>which is now encapsulated in this named method.</p>\n\n<p>The final code I ended up with is:</p>\n\n<pre><code>const string all = \"All\";\n\nprivate static bool CompareOrderItem(Item item, Item current)\n{\n return\n SecurityMatches(item, current) &amp;&amp;\n OrderTypeMatches(item, current) &amp;&amp;\n OrderPartyMatches(item, current);\n}\n\nprivate static bool SecurityMatches(Item item, Item current)\n{\n return \n String.Equals(item.Security, all) || \n String.Equals(current.Security, item.Security);\n}\n\nprivate static bool OrderTypeMatches(Item item, Item current)\n{\n return \n item.OrderType == OrderTypeEnum.None || \n Equals(current.OrderType, item.OrderType);\n}\n\nprivate static bool OrderPartyMatches(Item item, Item current)\n{\n return \n String.Equals(item.Counterparty, all) || \n String.Equals(current.Counterparty, item.Counterparty);\n}\n</code></pre>\n\n<p>Please note how the need for comments disappears, as the code now explains itself progressively.</p>\n\n<p>Some people may only be interested to see that three fields are matched (and thus only look at the first method). Others may also be interested to see how the matching is done, and the explanation is just a few lines away.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-05-10T08:54:08.763", "Id": "18694", "Score": "0", "body": "Yep I agree in moving complex boolean logic to either a method to to seperate variables with good names" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-05-10T09:02:42.590", "Id": "18696", "Score": "1", "body": ">>While all I did was move stuff around -> This is good enough. It is indeed clean code, much much cleaner than original one." } ], "meta_data": { "CommentCount": "2", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-05-10T08:46:12.657", "Id": "11654", "ParentId": "11651", "Score": "5" } } ]
{ "AcceptedAnswerId": "11654", "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-05-10T04:51:43.870", "Id": "11651", "Score": "0", "Tags": [ "c#" ], "Title": "Refactor c# comparision/filter logic" }
11651
<p>After reading <a href="https://stackoverflow.com/questions/2129214/backup-a-local-git-repository/10458663">this Stack Overflow question</a> I decided to write a backup utility for local git repositories.</p> <p>The result is on <a href="https://github.com/najamelan/git-backup" rel="nofollow noreferrer">GitHub</a>.</p> <p>I would like this application to be well-behaved with an installer, manpages and no bugs.</p> <p>It is my first time writing Ruby, so there might well be better, safer, more correct or simply more elegant ways of doing things. I also still wonder if git bundle is the best way of creating an identical repository (I still consider tar as an option too).</p> <p>3/4 of the code is just error handling, but I suppose that is just normal.</p> <p>The restore script is currently a functional dummy, it resides on GitHub, but is probably not worth reviewing. My tabwidth is 3, though mid-line alignment is done with spaces.</p> <pre><code>#!/usr/bin/env ruby # # For documentation please sea man git-backup(1) # # TODO: # - make it a class rather than a function # - check the standard format of git warnings to be conform # - do better checking for git repo than calling git status # - if multiple entries found in config file, specify which file # - make it work with submodules # - propose to make backup directory if it does not exists # - depth feature in git config (eg. only keep 3 backups for a repo - like rotate...) # - TESTING # allow calling from other scripts def git_backup # constants: git_dir_name = '.git' # just to avoid magic "strings" filename_suffix = ".git.bundle" # will be added to the filename of the created backup # Test if we are inside a git repo `git status 2&gt;&amp;1` if $?.exitstatus != 0 puts 'fatal: Not a git repository: .git or at least cannot get zero exit status from "git status"' exit 2 else # git status success until File::directory?( Dir.pwd + '/' + git_dir_name ) \ or File::directory?( Dir.pwd ) == '/' Dir.chdir( '..' ) end unless File::directory?( Dir.pwd + '/.git' ) raise( 'fatal: Directory still not a git repo: ' + Dir.pwd ) end end # git-config --get of version 1.7.10 does: # # if the key does not exist git config exits with 1 # if the key exists twice in the same file with 2 # if the key exists exactly once with 0 # # if the key does not exist , an empty string is send to stdin # if the key exists multiple times, the last value is send to stdin # if exaclty one key is found once, it's value is send to stdin # # get the setting for the backup directory # ---------------------------------------- directory = `git config --get backup.directory` # git config adds a newline, so remove it directory.chomp! # check exit status of git config case $?.exitstatus when 1 : directory = Dir.pwd[ /(.+)\/[^\/]+/, 1] puts 'Warning: Could not find backup.directory in your git config file. Please set it. See "man git config" for more details on git configuration files. Defaulting to the same directroy your git repo is in: ' + directory when 2 : puts 'Warning: Multiple entries of backup.directory found in your git config file. Will use the last one: ' + directory else unless $?.exitstatus == 0 then raise( 'fatal: unknown exit status from git-config: ' + $?.exitstatus ) end end # verify directory exists unless File::directory?( directory ) raise( 'fatal: backup directory does not exists: ' + directory ) end # The date and time prefix # ------------------------ prefix = '' prefix_date = Time.now.strftime( '%F' ) + ' - ' # %F = YYYY-MM-DD prefix_time = Time.now.strftime( '%H:%M:%S' ) + ' - ' add_date_default = true add_time_default = false prefix += prefix_date if git_config_bool( 'backup.prefix-date', add_date_default ) prefix += prefix_time if git_config_bool( 'backup.prefix-time', add_time_default ) # default bundle name is the name of the repo bundle_name = Dir.pwd.split('/').last # set the name of the file to the first command line argument if given bundle_name = ARGV[0] if( ARGV[0] ) bundle_name = File::join( directory, prefix + bundle_name + filename_suffix ) puts "Backing up to bundle #{bundle_name.inspect}" # git bundle will print it's own error messages if it fails `git bundle create #{bundle_name.inspect} --all --remotes` end # def git_backup # helper function to call git config to retrieve a boolean setting def git_config_bool( option, default_value ) # get the setting for the prefix-time from git config config_value = `git config --get #{option.inspect}` # check exit status of git config case $?.exitstatus # when not set take default when 1 : return default_value when 0 : return true unless config_value =~ /(false|no|0)/i when 2 : puts 'Warning: Multiple entries of #{option.inspect} found in your git config file. Will use the last one: ' + config_value return true unless config_value =~ /(false|no|0)/i else raise( 'fatal: unknown exit status from git-config: ' + $?.exitstatus ) end end # function needs to be called if we are not included in another script git_backup if __FILE__ == $0 </code></pre>
[]
[ { "body": "<p>There is a great deal of vertical white space; probably more than is good for readability. Unless it is an artifact of cut and paste, you might consider removing some of it.</p>\n\n<p>The usual indent level for Ruby is 2 spaces. You don't have to do what's usual, of course, but it will make life easier for your code's readers if you can do it.</p>\n\n<p>Good job with the constants <code>git_dir_name</code> and <code>prefix</code>. You can improve them by making them all caps: <code>GIT_DIR_NAME = '.git'</code>enter code here`. This tells both Ruby and your reader that they are indeed constants.</p>\n\n<p>Checking that the file is run directly by comparing <code>__FILE__</code> to <code>$0</code> is a common practice, not always necessary, but often done even when not strictly needed. Its appearance here is unusual, in that it exits with an error if required. More commonly, it simply does nothing, e.g.:</p>\n\n<pre><code>def do_what_the_script_does\n ...\nend`\n\ndo_what_the_script_does unless __FILE__ == $0\n</code></pre>\n\n<p>That allows a script that can be run directly to also be required by another script, so that the other script can have access to this script's functions, classes, &amp;c.</p>\n\n<p>rather than <code>$?.exitstatus != 0</code>, you can just check <code>$? != 0</code>.</p>\n\n<p>When running an external program that can have an error, and the error messages reported by the program are acceptable to you, you can simplify your code by replacing sequences such as:</p>\n\n<pre><code>`run_some_program`\nif $? != 0\n puts \"An error happened\"\n exit(1)\nend\n</code></pre>\n\n<p>With:</p>\n\n<pre><code>system('run_some_program')\nexit if $? != 0\n</code></pre>\n\n<p>The duplicate logic in the two big case statements ought to be put in one function. That makes maintenance easier and makes the code easier to follow.</p>\n\n<p>Creating a one-line if statement using <code>:</code> works in Ruby 1.8, but not in Ruby 1.9 (and even though it works in Ruby 1.8, it's a little bit funky). To be compatible with future versions of ruby, use <code>then</code> instead. Or, if the line is at all long, just hit enter. </p>\n\n<p>Consider using methods to group little bits of code together. The name of the method will serve as an executable comment.</p>\n\n<p>No, you do not really need to call <code>chomp</code> when creating the bundle_name.</p>\n\n<p>An easy way to quote interpolated strings is:</p>\n\n<pre><code>puts \"Backing up to bundle #{bundle_name.inspect}\"\n</code></pre>\n\n<p>Although Widows uses spaces in filenames as a matter of practice, Unix programmers look less kindly upon the practice. I would omit the spaces in the filename, but that's my personal preference.</p>\n\n<p>Consider using optparse, a library that comes with Ruby, to parse arguments.</p>\n\n<p>If you use File.join to create your path, it won't matter whether or not <code>directory</code> ends with a /. So do this:</p>\n\n<pre><code>bundle_path = File.join(directory, prefix + bundle_name + suffix)\n</code></pre>\n\n<p>and you can eliminate this:</p>\n\n<pre><code>directory = directory.chomp('/')\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-05-15T17:03:19.513", "Id": "18889", "Score": "0", "body": "Thanks alot. Very helpful. I corrected the script. I kept $?.exitstatus because it is less cryptic and because $? doesn't really refer to the exit status. I used Fill::join. Regarding spaces in file names, well spaces are a natural part of our language, as well as valid filename characters. I don't see why not to use them. If it breaks something, then it probably reveals inadequate escaping." } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-05-15T03:59:42.403", "Id": "11764", "ParentId": "11660", "Score": "1" } } ]
{ "AcceptedAnswerId": "11764", "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-05-10T14:11:06.030", "Id": "11660", "Score": "2", "Tags": [ "beginner", "ruby", "git" ], "Title": "Backup utility for local git repositories" }
11660
<p>I am building a library and I need suggestions on how to improve it (security, performance, etc).</p> <pre><code>&lt;?php /** * Authentication Library * * @author John Svensson */ class Auth { public $captchaCount; protected $db; protected $PasswordLib; private $message; public function __construct(PDO $db, PasswordLib\PasswordLib $PasswordLib) { $this-&gt;db = $db; $this-&gt;PasswordLib = $PasswordLib; } public function login($username, $password) { try { $sth = $this-&gt;db-&gt;prepare("SELECT id, username, password, active FROM user WHERE username = ?"); $sth-&gt;setFetchMode(PDO::FETCH_OBJ); $sth-&gt;execute(array($username)); $result = $sth-&gt;fetch(); } catch (PDOException $e) { throw new Exception($e-&gt;getMessage()); } if ($result) { if ($this-&gt;PasswordLib-&gt;verifyPasswordHash($password, $result-&gt;password)) { if ($result-&gt;active == 0) { $this-&gt;setMessage("&lt;p&gt;You must activate your account!&lt;/p&gt;"); return FALSE; } session_regenerate_id(); $_SESSION['userid'] = $result-&gt;userid; return TRUE; } else { $this-&gt;addLoginAttempt($username); $this-&gt;captchaCount++; $this-&gt;setMessage("&lt;p&gt;The password you entered is incorrect. Please try again.&lt;/p&gt;&lt;p&gt;Forgot your password? &lt;a href=\"forgotpassword.php\"&gt;Request a new one.&lt;/a&gt;"); return FALSE; } } else { $this-&gt;addLoginAttempt($username); $this-&gt;captchaCount++; $this-&gt;setMessage("&lt;p&gt;Incorrect username&lt;/p&gt;"); return FALSE; } } public function IsLoggedIn() { if (isset($_SESSION['userid'])) { return TRUE; } } public function getLoginAttempts() { $ip_address = ip2long($_SERVER['REMOTE_ADDR']); $sth = $this-&gt;db-&gt;prepare("SELECT COUNT(*) FROM login_attempts WHERE ip_address = ? AND attempted &gt; DATE_SUB(NOW(), INTERVAL 15 minute)"); $sth-&gt;bindParam(1, $ip_address); $sth-&gt;execute(); return $sth-&gt;fetchColumn(); } private function addLoginAttempt($username) { $ip_address = ip2long($_SERVER['REMOTE_ADDR']); $sth = $this-&gt;db-&gt;prepare("INSERT INTO login_attempts(username, ip_address, attempted) VALUES(?, ?, NOW())"); $sth-&gt;execute(array($username, $ip_address)); } public function getMessage() { return $this-&gt;message; } private function setMessage($value) { $this-&gt;message = $value; } } ?&gt; &lt;?php $data = array(); $Auth-&gt;captchaCount = $Auth-&gt;getLoginAttempts(); var_dump($Auth-&gt;captchaCount); if ($Auth-&gt;captchaCount &gt; 0) { //sleep (2 ^(intval($count) -1)); } $data['captcha'] = false; if ($Auth-&gt;captchaCount &gt; 9) { $data['captcha'] = true; } if (isset($_POST['submit'])) { if (isset($_POST['token']) &amp;&amp; $_POST['token'] === $_SESSION['token']) { if ($data['captcha']) { $resp = recaptcha_check_answer ($private_key, $_SERVER["REMOTE_ADDR"], $_POST["recaptcha_challenge_field"], $_POST["recaptcha_response_field"]); if (!$resp-&gt;is_valid) { $data['error'] = 'The reCaptcha was entered incorrectly.'; } } if (!isset($data['error'])) { if ($Auth-&gt;login($_POST['username'], $_POST['password'])) { } else { $data['error'] = $Auth-&gt;getMessage(); if ($Auth-&gt;captchaCount &gt; 9) { $data['captcha'] = true; } } } } else { } } $data['token'] = $_SESSION['token']; $data['public_key'] = $public_key; echo $twig-&gt;render('login.html', $data); ?&gt; </code></pre>
[ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-05-15T01:34:01.603", "Id": "18868", "Score": "0", "body": "Not sure if this got mentioned below but I'd separate any DB/SQL stuff into a separate class and pass and instance of that DB class instead of PDO." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-02-18T05:30:20.460", "Id": "35100", "Score": "0", "body": "I wouldn't generate the HTML in the with class... Makes it less reusable" } ]
[ { "body": "<p>Want to know about security? Don't claim that I'm paranoid sociopath.</p>\n\n<p><code>$this-&gt;db = $db;</code> So, you agree to accept (and use later) any DB connection? Don't even mention that it may be simply <code>NULL</code> (in the best case?)</p>\n\n<p><code>$_SESSION</code> do you really trust global variables? Especially if you insetr their values into your (well, already compromized) data base? Look at <code>create_account</code> from this point of view.</p>\n\n<p><code>mt_srand</code> is obsolete since PHP 4.2.0.</p>\n\n<p><code>md5</code> is not safe anymore</p>\n\n<p><code>check_email</code> will accept anything, but should (usually) accept valid e-mail only.</p>\n\n<p>IP address check does not care if IP is at least routable.</p>\n\n<p>Etc, etc, etc</p>\n\n<p>The answer if way less than full analysis.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-05-10T18:48:39.480", "Id": "18707", "Score": "0", "body": "The validation of the data is seperated from the library, the e-mail has a validated format (by FILTER_VALIDATE) + I use prepared statement?" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-05-14T16:43:28.617", "Id": "18847", "Score": "1", "body": "For the `$db` to be a security problems - you'd need access to the code on the server to be able to inject your own db instance - which is.. not particularly useful. If someone can inject their own $db - they can also just edit the code to do whatever they want. The session is always global and accessed as $_SESSION in php - that's fine (in the context of php) unless you're doing `extract($userSubmitted)` somewhere - which I don't think is in scope." } ], "meta_data": { "CommentCount": "2", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-05-10T18:11:41.587", "Id": "11663", "ParentId": "11661", "Score": "1" } }, { "body": "<p><strong>Disclaimer:</strong> I am no security guru. So a lot of what I say in regards to security are assumptions. The code review is good, but you should get a second, third, maybe even fourth opinion on my suggestions regarding security. I will denote each \"opinion\" that way you know to take it with a grain of salt. That being said, on to the review!</p>\n\n<p><strong>Session Variables</strong></p>\n\n<p>Are these session variables, <code>userid</code> and <code>username</code>, not the same? Most people only use one or the other, but I'm assuming that since you use both that means userid is a numerical representation of that person. I would try finding some way of limiting the amount of dependencies you need, especially if those two are more or less the same. Code is like a machine. The more moving parts you have, the more things there are to break. If you need both <code>username</code> and <code>userid</code> in your code I would find some way of producing one fromt the other. Also, I do not see where you set these variables. If they are crucial for checking if a user is logged in I would set them inside the class that way there is no confusion about where they come from.</p>\n\n<p><strong>Logging In</strong></p>\n\n<p>When you are checking if a user is logged in you only return TRUE. What if they aren't logged in? You should return either TRUE or FALSE that way you don't have to write anything extra when checking for it.</p>\n\n<p>This is one of those grain of salt moments, though I feel confident in what I'm saying, I may be missing a step or may have misunderstood my source. From what I've read the more secure way is to compare the current session id to that of the one last used to log in. If the user has not logged in in a while then it would force the user to the login page to refresh credentials. After verifying session id, it would THEN verify that <code>userid</code> and <code>username</code> are set.</p>\n\n<p><strong>Logging Out</strong></p>\n\n<p>When logging out, it is unnecessary to use <code>session_unset()</code>. At least from what I gather. <code>session_destroy()</code> destroys everything in the session so that it is completely empty, wheras <code>session_unset()</code> merely unsets everything but leaves information such as session id available meaning the session still technically exists. So, even if it was necessary to use both, you got them backwards as there would be nothing left to unset once everything was destroyed, but plenty to destroy after everything has been unset.</p>\n\n<p>I also do not think that exit is necessary. After setting a header your script will stop running before even getting to it.</p>\n\n<p><strong>Expanding Variables</strong></p>\n\n<p>This is a preference, but one MANY agree with. Variables should be expanded so it is completely obvious at first glance what they are used for. I won't argue for expanding <code>$db</code> or any other commonly used abbreviation that everyone seems to know, but I would argue that you shouldn't go making your own abbreviations. Its just a matter of legibility. So, in this instance <code>$dest</code> should probably be expanded to <code>$destination</code>. Normally I would point out <code>$sth</code> but having seen it so many times recently, I think that is also one of those standardly accepted abbreviations.</p>\n\n<p><strong>Separating Code</strong></p>\n\n<p>I do not think that the <code>create_account()</code> and <code>generate_salt()</code> methods should be included in this class as it does not have anything to do with authentication. It does share a common resource, <code>$db</code>, but it does two completely different things with it. One class should only read it, while the other manipulates it. However, this might be considered one of those design preferences. So I leave this up to you. Just figured I'd point it out.</p>\n\n<p>Also, I would group my public/private/protected methods separately. I personally separate my code with long comment breaks that visually as well as physically separate each section so that it is easier to find the beginning of each section when scrolling. I'm not saying you need to do that, but I would at least separate them from each other. Makes it much easier to find methods if they are sorted in some fashion.</p>\n\n<p><strong>Code Dependency</strong></p>\n\n<p>This is a common mistake. Classes, generally, should not be dependent on any other file. No outside magical constants, variables, or classes should find their way into your models or controllers. Even if you aren't using an MVC pattern, it is good practice to make your classes completely self dependent, that way if something breaks you wont have to go hunting for it, it will all be self contained. So <code>SITE_KEY</code> and, in my opinion, those session variables should be defined inside this class.</p>\n\n<p><strong>Braces</strong></p>\n\n<p>Please, please, please use braces <code>{}</code>. I say this a lot, so please excuse me if I rant a little. A matching brace pair only adds 2 bits to your file size so there is no reason to exclude them for speed or file size limitations, though you should never have a file size \"limit\" to begin with. Braces, when combined with brace-matching in IDE's make it easy to determine where one statement ends, and another begins. Not only in IDE's, but also just in plain reading. The fact that PHP allows this sadens me to no end. It just supports poor coding habits and I wish they would deprecate and do away with its support.</p>\n\n<p><strong>Verifying Variables or Attributes Exist</strong></p>\n\n<p>What do you do if, for some unknown reason, <code>get_salt()</code> doesn't have a salt set? For one, your code will produce a nice pretty error for your clients. Even if you are sure of the source, if you did not set it in the imediate scope, you should verify that it is there and, if necessary, provide error support. There is always room for errors or unforseen circumstances.</p>\n\n<p><strong>Reusing Code</strong></p>\n\n<p>If possible, I would try to find some way of reusing the code with <code>get_attempts()</code> and <code>add_attempt()</code>. They are so similar it would be a shame to not reuse that code. And why are these public? I can only imagine that they would be necessary when performing a login, so I would make them private and then filter all calls to them through the login function.</p>\n\n<p>I've been seeing a lot of these prepared statements recently and something I end up doing for all of them is cleaning them up. To prevent yourself from having to rewrite code, or in case you ever wish to expand upon this, as you did mention you wanted to reuse this, I would rewrite your prepared statements like so...</p>\n\n<pre><code>$fields = array(\n 'username' =&gt; $username,\n 'password' =&gt; $password,\n 'salt' =&gt; $salt,\n 'email' =&gt; $email,\n 'created' =&gt; $created,\n);\n\n$attributes = implode(', ', array_keys($fields));\n$values = implode(', :', array_keys($fields));\n\n$sth = $this-&gt;db-&gt;prepare(\"INSERT INTO `user` ($attributes) VALUES (:$values)\");\n</code></pre>\n\n<p>If you are wondering why I added those values in the <code>$fields</code> array then never used them, it is so you can set all of that information once then reuse it later. I noticed that you reuse this information in multiple methods and you just keep passing them as arguments. Do it once, save it as a class property and then reuse it.</p>\n\n<p>Also, you have this perfectly good <code>check_record()</code> method, but don't use it to its fullest. You could convert it to execute more of your prepared statements by simply passing another argument.</p>\n\n<pre><code>protected function check_record($field, $select, $value) {\n $sth = $this-&gt;db-&gt;prepare(\"SELECT $select FROM user WHERE $field = ?\");\n $sth-&gt;execute(array($value));\n return $sth;\n}\n\nprotected function get_salt($username) {\n $sth = $this-&gt;check_record('username', 'salt', $username);\n\n if ($sth-&gt;rowCount() &gt; 0) {\n $row = $sth-&gt;fetch();\n return $row['salt'];\n }\n}\n</code></pre>\n\n<p>There's more to it than this of course. You'll notice I removed a bit from the end of the <code>check_record()</code> method, so you'd have to do some tweaking, but it would clean up some of your code elsewhere.</p>\n\n<p>By the way. Those braces you hade in your prepared statement were unnecessary. The only time you need to use braces between double quotes is if you are using a class property or array element. There may be a couple of more instances, but I can't remember them off the top of my head right now. Just know that they aren't necessary for a basic variable.</p>\n\n<pre><code>\"{$array['element']} or {$this-&gt;property}\"\n</code></pre>\n\n<p><strong>Clearing Up Confusion</strong></p>\n\n<p>You should work on that return statement for <code>check_record()</code>, it is rather confusing. You have it set up to return a boolean, then typecast it to return an integer... So you really want a 1 for true or 0 for false... Then its to return null if <code>$count</code> was initially false... Kind of confusing.</p>\n\n<p><strong>!!!UPDATE!!!</strong></p>\n\n<p><strong>New Code</strong></p>\n\n<p>In your \"login.php\" example, I'm not sure if its just some stackoverflow quirk, but if you do indeed have two if statements on the same line I would separate them. Just helps with legibility.</p>\n\n<p>Also, where did <code>$user-&gt;active</code> come from? I've scanned the authentication class again and I didn't see an <code>active</code> property instantiated at the beginning, nor one in the code. After hunting it down I determined that its coming from the returned SQL object you got from the login method, but otherwise I would be lost as to where this came from. I would suggest that you create a new method for queries such as this. Let the class handle gathering information and the controller, or view, or whatever you are using, request it. Hope this makes sense.</p>\n\n<p><strong>Logged In Method</strong></p>\n\n<p>What you have for the <code>logged_in()</code> method is fine I just want to point out that the else statement is unnecessary. If the if statement is true, it will never get to the rest of the code, so there is no need for an else.</p>\n\n<p>I will look for a resource, but it was a while ago that I was reading that, so it might not even be the same one that I find for you. I will look through any resource I find to make sure its similar enough though. When I find such a resource I will leave you a comment so that you are aware of the update, much like I did for this update.</p>\n\n<p><strong>Separating Code</strong></p>\n\n<p>It was just a suggestion. A lot of people do combine functionality in their authentication classes I just find it counter intuitive.</p>\n\n<p><strong>Reusing Your Class</strong></p>\n\n<p>If you wish to leave the class unchanged between each use then I would suggest using a config file to set those variables and adding an include for it in the construct method so that they are registered on instantiation gauranteed. I suggest a config file that way you can keep a copy with your class and then only have to update the config file for the new information. I don't know if this is the cleanest way of doing it, just the first that came to mind.</p>\n\n<p>Also, just because you don't want to change it after you have it the way you want it, I would still come back to it periodically and read over it. This does two things. First, it keeps you familiar with it. And second, as you grow as a programmer your style and knowledge will grow with you and you may find that you could do something better.</p>\n\n<p><strong>Verifying Variables</strong></p>\n\n<p>If there is no \"salt\" key PHP would throw an unknown offset, or some other similar error. If you are not seeing it then you either have error reporting set too low or it just hasn't happened to you yet. As for if that is the proper way to go about it, not a clue. I'd have to see it in action and still wouldn't be sure. If you think that it is proper, more than likely it will be, as you know more about your system than I do :) Everything here is, more or less, suggestions. In the end you know more about your program and what is best for it and you have the final call.</p>\n\n<p><strong>Check Record Method</strong></p>\n\n<p>When I said you'd still have to tweak your <code>check_record()</code> method, I meant that my version no longer did everything the original did. The original <code>check_record()</code> function got the column count and returned it. The one I suggested only returns the statement and expects anything further to be done outside of the method. If you wished to continue to get a count, you'd have to tweak your code in the appropriate places to do so. Because I changed it to be more reusable and handle different kinds of records, you'd have to find some other way for getting the desired results. I'd personally lean more towards creating a new method, maybe with a switch statement for different kinds of results, that way it could be reused.</p>\n\n<p><strong>!!!Final Update!!!</strong></p>\n\n<p>Your last update should have been a new question as it completely changed the code, making my previous comments seem out of place. I will leave them as I believe they are still pertinent to you and I don't feel like reading through them to trim whats now unnecessary. This answer has gotten a bit large and difficult to read, and possibly redundant, so this will be the last update I do for it. If you wish further help, I would suggest starting a new question. Also, my apologies for that couple days of silence. Mother's day and all...</p>\n\n<p><strong>Namespaces</strong></p>\n\n<p>I don't have much experience with namespaces myself, but this advice should still be valid. If you are using namespaces, I would make them more unique. <code>PasswordLib\\PasswordLib</code> is not very informative and kind of confusing, especially followed by <code>$PasswordLib</code>. Also, it seems like we're taking a step backwards here. This is using a dependency that will only cause you to have to update your class later, which you wanted to avoid. Using an object of <code>PasswordLib</code>, like you did for <code>PDO</code> would be fine, but using the namespace could cause issues. Should you ever decide to use some other source to supply the instance of <code>PasswordLib</code> other than the file where it is defined for instance.</p>\n\n<p><strong>Reusing Code</strong></p>\n\n<p>I would reuse the following code from your <code>login()</code> method. Just make it part of the <code>addLoginAttempt()</code> method.</p>\n\n<pre><code> $this-&gt;captchaCount++;\n $this-&gt;setMessage($message);\n return FALSE;\n</code></pre>\n\n<p>Then you can just do <code>return addLoginAttempt($username, $message);</code>.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-05-11T12:39:08.127", "Id": "18732", "Score": "0", "body": "I updated my post with an answer to your POST, thanks!" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-05-11T14:22:16.217", "Id": "18742", "Score": "0", "body": "@John: I updated my answer to cover your update." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-05-11T15:47:58.993", "Id": "18747", "Score": "0", "body": "I think you missunderstand the login method, its function is to return a object of the user if its available, and then on a login.php file check like $user->active == 1 (is the user activated or not?) and if all validation goes through it sets sessions. (basically, the controller grab a object does some additional checks then decides whetever the user should be logged in or not)" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-05-11T16:33:30.910", "Id": "18765", "Score": "0", "body": "@John: I did not misunderstand the login method. I just don't think it should return that object. I may be wrong and what you are doing is perfectly fine, but I doubt it. You are returning the full user object from the database, password and all, to a potentially insecure script. Someone could potentially create a new file and then do something like `var_dump($userObject);` and have all that information." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-05-11T16:33:49.833", "Id": "18767", "Score": "0", "body": "@John: Also, I just find it unintuitive to return a \"magic\" property from something. It's just another one of those things that is not verified before being used. If you were to move that to a separate method in your auth class and have it return the value of \"active\" you could run any verification you needed to without your login.php script being any the wiser." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-05-11T16:41:14.503", "Id": "18770", "Score": "0", "body": "@John: Looked at it again, and while you would already need to know the login information if you were to abuse that object in that way. It is still better, in my opinion, to separate it in case there is some sort of leak. Not saying I know how someone would be able to do it. Just think of it as one less potential loop hole." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-05-11T16:59:58.357", "Id": "18771", "Score": "0", "body": "What? I can't see the potential hole? :O The only way a User would be able to see the username, id, and active column would be if in the code var_dump() was made, or am I missing somethiing?" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-05-11T17:55:59.137", "Id": "18773", "Score": "0", "body": "@John: I don't pretend to understand how malicious users would do something. I just know that making it easier for them to do so doesn't seem wise. Maybe there isn't anything wrong with it, I'm not a security expert. I'm just poking at things that, if I were to write it, I would change because they seem hazardous to me. If you truly wish to know if it is dangerous or not, I'd suggest submitting that example to the regular stackoverflow community to see what they say." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-05-12T00:34:34.283", "Id": "18795", "Score": "0", "body": "Once again, I have been updating my STRUCTURe, What do you think now? I moved the SESSION variables (set, update, delete) to the library." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-05-12T15:55:34.637", "Id": "18801", "Score": "0", "body": "Updated! Two files now (Auth.php) and the controller \"login.php\"" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-05-14T14:47:48.273", "Id": "18845", "Score": "0", "body": "@John: Here's my latest update." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-05-17T10:32:07.780", "Id": "18994", "Score": "0", "body": "Well the namespace is already instantited I am just telling the class what the construct should expect, yet again thanks for your post" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-05-17T18:40:54.617", "Id": "19015", "Score": "0", "body": "@John: TIL that exit after a header is good practice, so you can disregard that comment. Should have looked that up before I spoke :)" } ], "meta_data": { "CommentCount": "13", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-05-10T19:59:35.990", "Id": "11667", "ParentId": "11661", "Score": "11" } }, { "body": "<p>To add to showerhead's answer, I would suggest to keep your functions as simple and specialized as possible. The <code>logout</code> function in particular should do just that - logout the user. It shouldn't redirect to anything, and it should definitely not kill the current PHP session by calling <code>exit</code>. That will make your library unusable by many developers.</p>\n\n<p>What if the developer wants to use their own redirect function and not a <code>header()</code> call?</p>\n\n<p>What if the developer wants to do something else, clean up, etc. after calling <code>logout</code>?</p>\n\n<p>Those are questions you won't actually need to answer if you keep your functions simple and specialized.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-05-12T12:34:52.413", "Id": "11717", "ParentId": "11661", "Score": "5" } }, { "body": "<p>The first thing I would change is the way the <code>else</code> blocks inside of <code>login()</code> are handled. They are almost doing the exact same thing.</p>\n\n<pre><code>if ($result) {\n\n if ($this-&gt;PasswordLib-&gt;verifyPasswordHash($password, $result-&gt;password)) {\n } else {\n $this-&gt;addLoginAttempt($username);\n $this-&gt;captchaCount++;\n $this-&gt;setMessage(\"&lt;p&gt;The password you entered is incorrect. Please try again.&lt;/p&gt;&lt;p&gt;Forgot your password? &lt;a href=\\\"forgotpassword.php\\\"&gt;Request a new one.&lt;/a&gt;\");\n return FALSE;\n } \n} else {\n $this-&gt;addLoginAttempt($username);\n $this-&gt;captchaCount++;\n $this-&gt;setMessage(\"&lt;p&gt;Incorrect username&lt;/p&gt;\");\n return FALSE;\n}\n</code></pre>\n\n<p>To help make your code more <a href=\"http://en.wikipedia.org/wiki/Don%27t_repeat_yourself\" rel=\"nofollow\">DRY</a> I would combine the <code>addLoginAttempt</code> and <code>setMessage</code> to one method. Which would make your code look like this.</p>\n\n<pre><code>if ($result) {\n\n if ($this-&gt;PasswordLib-&gt;verifyPasswordHash($password, $result-&gt;password)) {\n } else {\n $this-&gt;addLoginAttemptWithMessage($username, \"&lt;p&gt;The password you entered is incorrect. Please try again.&lt;/p&gt;&lt;p&gt;Forgot your password? &lt;a href=\\\"forgotpassword.php\\\"&gt;Request a new one.&lt;/a&gt;\");\n $this-&gt;captchaCount++;\n return FALSE;\n } \n} else {\n $this-&gt;addLoginAttemptWithMessage($username, \"&lt;p&gt;Incorrect username&lt;/p&gt;\");\n $this-&gt;captchaCount++;\n return FALSE;\n}\n\n/* added after `addLoginAttempt` */\nprivate function addLoginAttemptWithMessage($username, $message) {\n $this-&gt;addLoginAttempt($username);\n $this-&gt;setMessage($message);\n}\n</code></pre>\n\n<p>You could possibly put the <code>$this-&gt;captchaCount++</code> call inside of the new method as well.</p>\n\n<hr>\n\n<p><code>IsLoggedIn</code> can be written more simply as</p>\n\n<pre><code>public function IsLoggedIn() {\n return isset($_SESSION['userid']);\n}\n</code></pre>\n\n<hr>\n\n<p>Regarding security your code looks fine, just make sure you use something like bcrypt when hashing your passwords.</p>\n\n<p>The most important thing you could do is write tests using PHPUnit or something similar. You have a lot of routes that can be taken when someone enters a wrong username or incorrect login information.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-05-14T15:12:47.130", "Id": "11749", "ParentId": "11661", "Score": "1" } }, { "body": "<p>I think for sql injection you're ok. Some tips that are general points though:</p>\n\n<p><strong>Don't catch exceptions just to throw a new exception</strong></p>\n\n<pre><code>try {\n $sth = $this-&gt;db-&gt;prepare(\"SELECT id, username, password, active FROM user WHERE username = ?\");\n $sth-&gt;setFetchMode(PDO::FETCH_OBJ);\n $sth-&gt;execute(array($username));\n $result = $sth-&gt;fetch();\n/* Remove this\n} catch (PDOException $e) {\n throw new Exception($e-&gt;getMessage());\n*/\n}\n</code></pre>\n\n<p>Don't catch exceptions that you don't know how to handle. Unless there's a reason you're catching PDO exceptions - in which case document it.</p>\n\n<p><strong>Use less nesting.</strong></p>\n\n<p>Don't needlessly use <code>} else { only one possibility }</code>. </p>\n\n<p>This is easier to read than the original:</p>\n\n<pre><code>if ($result) { \n if ($this-&gt;PasswordLib-&gt;verifyPasswordHash($password, $result-&gt;password)) {\n if ($result-&gt;active == 0) {\n $this-&gt;setMessage(\"&lt;p&gt;You must activate your account!&lt;/p&gt;\");\n return FALSE;\n }\n session_regenerate_id();\n $_SESSION['userid'] = $result-&gt;userid;\n return TRUE;\n }\n $this-&gt;addLoginAttempt($username);\n $this-&gt;captchaCount++;\n $this-&gt;setMessage(\"&lt;p&gt;The password you entered is incorrect. Please try again.&lt;/p&gt;&lt;p&gt;Forgot your password? &lt;a href=\\\"forgotpassword.php\\\"&gt;Request a new one.&lt;/a&gt;\");\n return FALSE;\n}\n$this-&gt;addLoginAttempt($username);\n$this-&gt;captchaCount++;\n$this-&gt;setMessage(\"&lt;p&gt;Incorrect username&lt;/p&gt;\");\nreturn FALSE;\n</code></pre>\n\n<p><strong>Be aware of the difference between isset and empty</strong></p>\n\n<p>This will return true if the userid in the session is e.g. \"\"</p>\n\n<pre><code>public function IsLoggedIn() {\n if (isset($_SESSION['userid'])) {\n return TRUE;\n }\n}\n</code></pre>\n\n<p>This will return true only if the userid is truethy:</p>\n\n<pre><code>public function IsLoggedIn() {\n if (!empty($_SESSION['userid'])) {\n return TRUE;\n }\n}\n</code></pre>\n\n<p>As one of the other answers mentions you can also just write it as:</p>\n\n<pre><code>public function IsLoggedIn() {\n return isset($_SESSION['userid']);\n}\n</code></pre>\n\n<p><strong>Don't assume html</strong></p>\n\n<pre><code>$this-&gt;setMessage(\"&lt;p&gt;...\n</code></pre>\n\n<p>A message inside a class like this shouldn't assume it is to serve html - what if it's responding to an ajax request, in xml, json or even just a log file?</p>\n\n<p><strong>Don't sleep</strong></p>\n\n<p>I'm not sure if this is just code for demonstration but this is actually the one \"problem\" with the code in the question. </p>\n\n<p>Using sleep will tie up <em>your</em> resources - that's not in your interest. Consider instead bailing early and just returning a 403. Right now before prompting a user with a captcha - you are holding the request open for more than a minute. If you get enough users (and enough could be a relatively small number) trying to login at once and getting it wrong - you're going to take your own server offline by occupying all connections with 1 minute long sleep calls.</p>\n\n<p><strong>Don't use empty if blocks</strong></p>\n\n<p>Again, not sure if this is just for demo purposes:</p>\n\n<pre><code>if ($Auth-&gt;login($_POST['username'], $_POST['password'])) {\n // why is this empty\n</code></pre>\n\n<p>Either invert the test (!) or put some logic in there - e.g. redirecting the user to their profile page.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-05-17T10:32:44.223", "Id": "18995", "Score": "0", "body": "The sleep() is to prevent bruteforce attacks, sleep a while before you can try login in again, (Delays)" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-05-17T11:50:05.203", "Id": "18998", "Score": "0", "body": "How would I rather handle the process of delaying a login attempt?" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-05-17T11:50:30.497", "Id": "18999", "Score": "1", "body": "I know what it's for, it's simply a bad idea. Consider this analogy: you go to check in at the airport and you are too early - instead of immediately telling you to come back in 30mins - you get silence for 30 minutes and then \"certainly, tickets please\". How do these 2 responses affect the queue of people behind, who want to go somewhere else? Don't tie up your own resources with such logic - finish the process as soon as posible for malicious users, and leave available for 'real' users." } ], "meta_data": { "CommentCount": "3", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-05-14T16:34:39.220", "Id": "11752", "ParentId": "11661", "Score": "4" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "2", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-05-10T16:00:44.370", "Id": "11661", "Score": "3", "Tags": [ "php", "performance", "security", "library", "authentication" ], "Title": "Authentication library" }
11661
<p>I Needed a method to randomly sample an IEnumerable collection without replacement. I'm using this for writing behavioral acceptance tests.</p> <p>For example, in the test code, I write: <code>GetElements("#SearchResults &gt; li").Sample(3);</code></p> <p>Here's the how I implemented it:</p> <p>I welcome any feedback or optimizations!</p> <pre><code> /// &lt;summary&gt; /// returns a random sample of the elements in an IEnumerable /// &lt;/summary&gt; public static IEnumerable&lt;T&gt; Sample&lt;T&gt;(this IEnumerable&lt;T&gt; population, int sampleSize) { List&lt;T&gt; localPopulation = population.ToList(); if (localPopulation.Count() &lt; sample.size) return localPopulation; List&lt;T&gt; sample = new List&lt;T&gt;(sampleSize); Random random = new Random(); while(sample.Count &lt; sampleSize) { int i = random.Next(0, localPopulation.Count); sample.Add(localPopulation[i]); localPopulation.RemoveAt(i); } return sample; } </code></pre>
[]
[ { "body": "<p>Make the <code>Random</code> generator a class-level member so you're not generating a new one with the default seed each time. Also, check your <code>population</code> for null:</p>\n\n<pre><code>/// &lt;summary&gt;\n/// random number generator for the enumerable sampler.\n/// &lt;/summary&gt;\nprivate static readonly Random random = new Random();\n\n/// &lt;summary&gt;\n/// returns a random sample of the elements in an IEnumerable\n/// &lt;/summary&gt;\npublic static IEnumerable&lt;T&gt; Sample&lt;T&gt;(this IEnumerable&lt;T&gt; population, int sampleSize)\n{\n if (population == null)\n {\n return null;\n }\n\n List&lt;T&gt; localPopulation = population.ToList();\n if (localPopulation.Count &lt; sample.size) return localPopulation;\n\n List&lt;T&gt; sample = new List&lt;T&gt;(sampleSize);\n\n while(sample.Count &lt; sampleSize)\n {\n int i = random.Next(0, localPopulation.Count);\n sample.Add(localPopulation[i]);\n localPopulation.RemoveAt(i);\n }\n\n return sample;\n}\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-05-10T19:17:06.950", "Id": "18708", "Score": "0", "body": "just a question but does .Count enumerate over all it's internals on each call or does it contain a local record count. Just interested in the performance of including it in the while loop rather than storing to a local etc" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-05-10T19:23:48.070", "Id": "18709", "Score": "0", "body": "`.Count()` does, but `.Count` does not. Subtle distinction there. `.Count` on a `List<T>` does not enumerate while `.Count()` is a LINQ extension on `IEnumerable<T>` which will enumerate." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-05-10T19:29:00.773", "Id": "18710", "Score": "0", "body": "@JesseC.Slicer even `Count()` doesn't do that, if the source is `ICollection<T>`." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-05-10T19:31:01.743", "Id": "18711", "Score": "0", "body": "@svick so it does type checking every time it's called and picks the best counting method available?" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-05-10T19:32:54.417", "Id": "18712", "Score": "2", "body": "@JesseC.Slicer, exactly, see [Jon Skeet's article about `Count()`](http://msmvps.com/blogs/jon_skeet/archive/2010/12/26/reimplementing-linq-to-objects-part-7-count-and-longcount.aspx)." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-05-10T19:37:31.440", "Id": "18713", "Score": "0", "body": "@svick cool, thanks for the info and link." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-05-10T20:41:50.417", "Id": "18716", "Score": "0", "body": "cheers thanks for that. Subtle but good distinction to know!" } ], "meta_data": { "CommentCount": "7", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-05-10T19:11:23.847", "Id": "11665", "ParentId": "11664", "Score": "3" } } ]
{ "AcceptedAnswerId": "11665", "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-05-10T18:58:44.937", "Id": "11664", "Score": "1", "Tags": [ "c#", "linq" ], "Title": "LINQ style Sample method" }
11664
<p>I'm not too used to working with arrays in javascript, so was wondering if there is a good way to condense this down.</p> <p>Any pointers much appreciated!</p> <p>you can see it in action @ <a href="http://www.productionlocations.com/locations" rel="nofollow">http://www.productionlocations.com/locations</a></p> <pre><code>if($('.filters').length) { if(url === 'http://www.productionlocations.com/locations' || url === 'http://www.productionlocations.com/locations/') { searchval[0] = 'Find a location…'; searchval[1] = 'Try searching by zip code, like 90012…'; searchval[2] = 'Know your location ID? Find it like so: #xxxx'; searchval[3] = 'Search locations by type, like apartment, office, or retail...'; searchval[4] = 'Search locations by area, like downtown, Pasadena, or Hollywood...'; searchval[5] = 'Search locations by style, like art deco, tudor, or industrial...'; searchval[6] = 'Search locations by feature, like fireplace, pond, or tiled floors...'; } else { searchval[0] = 'Modify your search by type, like apartment, office, or retais...'; searchval[1] = 'Modify your search by area, like downtown, Pasadena, or Hollywood...'; searchval[2] = 'Modify your search by style, like art deco, tudor, or industrial...'; searchval[3] = 'Modify your search by feature, like fireplace, pond, or tiled floors...'; searchval[4] = 'Modify your search…'; searchval[5] = 'Modify your search by zip code, like 90012…'; } searchkey = Math.floor(Math.random() * searchval.length); $('#s').val(searchval[searchkey]); } else { searchval[0] = 'Find a location…'; $('#s').val(searchval[0]); inputReplace(); } </code></pre>
[ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-05-11T06:52:32.090", "Id": "18723", "Score": "0", "body": "What are the intended effects of this code? Do you just want to call the appropriate `$('#s').val()` and `inputReplace()` if necessary, or do you also want to keep `searchval` and `searchkey` around?" } ]
[ { "body": "<pre><code>//use array literal\nvar searchval = [];\n\n//cache length, if ever it's needed more than once\nvar filterLength = $('.filters').length;\n\n//cache the condition, for readability\nvar url = url === 'http://www.productionlocations.com/locations' || url === 'http://www.productionlocations.com/locations/';\n\n//cache s because it's used more than once\nvar s = $('#s');\n\nif(filterLength) {\n if(url) {\n searchval = [\n 'Find a location…',\n 'Try searching by zip code, like 90012…',\n 'Know your location ID? Find it like so: #xxxx',\n 'Search locations by type, like apartment, office, or retail...',\n 'Search locations by area, like downtown, Pasadena, or Hollywood...',\n 'Search locations by style, like art deco, tudor, or industrial...',\n 'Search locations by feature, like fireplace, pond, or tiled floors...'\n ]\n } else {\n searchval = [\n 'Modify your search by type, like apartment, office, or retais...',\n 'Modify your search by area, like downtown, Pasadena, or Hollywood...',\n 'Modify your search by style, like art deco, tudor, or industrial...',\n 'Modify your search by feature, like fireplace, pond, or tiled floors...',\n 'Modify your search…',\n 'Modify your search by zip code, like 90012…'\n ]\n }\n\n //if needed elsewhere, it's ok to store in variable\n searchkey = Math.floor(Math.random() * searchval.length);\n s.val(searchval[searchkey]);\n\n //otherwise, just use directly\n //s.val(searchval[Math.floor(Math.random() * searchval.length)]);\n\n} else {\n\n //if needed elsewhere, it's ok to store in array\n searchval[0] = 'Find a location…';\n s.val(searchval[0]);\n\n //otherwise, just use the string directly\n //s.val('Find a location…');\n\n inputReplace();\n}​\n</code></pre>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-05-11T02:53:26.753", "Id": "11672", "ParentId": "11669", "Score": "1" } }, { "body": "<p>Assuming the variables you're using aren't needed later, you can condense it down to this:</p>\n\n<pre><code>var messages = [\n 'Find a location…',\n 'Try searching by zip code, like 90012…',\n 'Know your location ID? Find it like so: #xxxx',\n 'Search locations by type, like apartment, office, or retail...',\n 'Search locations by area, like downtown, Pasadena, or Hollywood...',\n 'Search locations by style, like art deco, tudor, or industrial...',\n 'Search locations by feature, like fireplace, pond, or tiled floors...',\n 'Modify your search…',\n 'Modify your search by zip code, like 90012…'\n], messageSets = [\n [3, 4, 5, 6, 7, 8],\n [0, 1, 2, 3, 4, 5, 6],\n [0]\n];\n\nvar s = messageSets[$('.filters').length ? +/^\\/locations\\/?$/.test(location.pathname) : 3];\n$('#s').val(messages[s[Math.random() * s.length | 0]]);\ninputReplace();\n</code></pre>\n\n<p>Ideally the first var statement would be at a higher level, so it would only be run once, not every time the function is executed.</p>\n\n<p>You could shorten it even further by using ranges instead of sets, but that could get complicated if you want to add more messages later. On the flip side, if you are planning to add a lot more messages, it would probably be clearer to make <code>messages</code> and <code>messageSets</code> objects (= dictionaries), so that you can name each message and set.</p>\n\n<p><strong>edit</strong>: here's how you would do the same thing using objects instead of arrays. The only difference is that each message, and set, has a name instead of a number, which makes references to it clearer to read.</p>\n\n<pre><code>var messages = {\n default: 'Find a location…',\n zip: 'Try searching by zip code, like 90012…',\n id: 'Know your location ID? Find it like so: #xxxx',\n type: 'Search locations by type, like apartment, office, or retail...',\n area: 'Search locations by area, like downtown, Pasadena, or Hollywood...',\n style: 'Search locations by style, like art deco, tudor, or industrial...',\n feature: 'Search locations by feature, like fireplace, pond, or tiled floors...',\n modify: 'Modify your search…',\n modify_zip: 'Modify your search by zip code, like 90012…'\n}, messageSets = {\n locations: 'default zip id type area style feature'.split(' '),\n filters: 'type area style feature modify modify_zip'.split(' '),\n default: ['default']\n};\n\nvar s = messageSets[$('.filters').length ?\n /^\\/locations\\/?$/.test(location.pathname) ? 'locations' : 'filters' :\n 'default'\n];\n$('#s').val(messages[s[Math.random() * s.length | 0]]);\ninputReplace();\n</code></pre>\n\n<p>Note that this has the additional advantage of making the order of the objects not matter: you could add <code>alert: 'Enter something!',</code> directly under the first line and it wouldn't break anything.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-05-11T16:39:21.163", "Id": "18769", "Score": "0", "body": "Hey Boost, could you elaborate on using `messages` and `messageSets` as objects? I think I will be adding more messages and making it more complex in the future. thanks!" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-05-11T19:33:57.420", "Id": "18780", "Score": "0", "body": "Sure, answer edited. The only difference is that you get to give everything variable names instead of just referring to it by number." } ], "meta_data": { "CommentCount": "2", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-05-11T07:37:31.300", "Id": "11676", "ParentId": "11669", "Score": "2" } } ]
{ "AcceptedAnswerId": "11676", "CommentCount": "1", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-05-10T22:02:16.847", "Id": "11669", "Score": "0", "Tags": [ "javascript", "array" ], "Title": "Help me condense a series of lengthy javascript conditional arrays" }
11669
<p>I'm writing a <a href="https://github.com/kentcdodds/Java-Helper" rel="nofollow noreferrer">Java-Helper library</a>. I want to include a method to zip files together, and this is what I've come up with. I'm using the <code>java.util.zip.*</code> library (<a href="http://docs.oracle.com/javase/1.4.2/docs/api/java/util/zip/ZipOutputStream.html" rel="nofollow noreferrer"><code>ZipOutputStream</code></a> and <a href="http://docs.oracle.com/javase/1.4.2/docs/api/java/util/zip/ZipEntry.html" rel="nofollow noreferrer"><code>ZipEntry</code></a> specifically).</p> <pre><code>/** * This uses the java.util.zip library to zip the given files to the given destination. * * @param destination * @param files * @throws FileNotFoundException * @throws IOException */ public static void zipFiles(File destination, File... files) throws FileNotFoundException, IOException { try (ZipOutputStream out = new ZipOutputStream(new FileOutputStream(destination))) { byte[] buffer = new byte[1024]; for (int i = 0; i &lt; files.length; i++) { try (FileInputStream in = new FileInputStream(files[i])) { out.putNextEntry(new ZipEntry(files[i].getName())); // Transfer bytes from the file to the ZIP file int length; while ((length = in.read(buffer)) &gt; 0) { out.write(buffer, 0, length); } // Complete the entry out.closeEntry(); } } } } </code></pre> <p>Any pointers?</p> <p>Also, from the code, is this a good buffer size?</p> <blockquote> <pre><code>byte[] buffer = new byte[1024]; </code></pre> </blockquote> <p>I've seen a lot of disks with a blocksize of 512 KB. Would that be a more "optimal" size?</p>
[ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-05-11T11:25:56.100", "Id": "18729", "Score": "1", "body": "Why don't you benchmark that?" } ]
[ { "body": "<p>Well, I benchmarked it and found that a buffer size of 10485760 (10 MB) was fastest... Kind of surprised about that and I'm thinking that's not the most efficient. I think I'll leave it at 1 MB unless someone else has any thoughts.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-05-11T14:03:51.583", "Id": "18738", "Score": "1", "body": "Interesting result. Thinking of it, it isn't too easy to come up with a good benchmark for a case like this. You are both reading a file and writing one, and I'd imagine the optimum buffer size is different for reading and writing. The block size of your file system and the hardware you are using are likely to have an influence. You would probably get different results for regular old HDs and SSDs. Also, disks have buffers of fast memory into which they store writes that come in too fast and into which they may prefetch data from adjacent locations when you request data from one location." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-05-11T14:06:34.050", "Id": "18739", "Score": "0", "body": "Because this is supposed to be for developers who may work on all different types of systems do you think it would be helpful to include the buffer size as a parameter? That way they can benchmark it themselves." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-05-11T14:25:31.760", "Id": "18743", "Score": "3", "body": "Unfortunately, I highly doubt anyone would do the benchmarking, unless it would be absolutely critical for the system that the compression algorithm worked as fast as possible. The general principle is that you shouldn't optimize a part of code unless you are sure that that part is the current bottleneck of the system. How big were the differences in your benchmark anyway? Within 5, 10, 50 or 100% of speed up? This seems to be a classical example of a [leaky abstraction](http://www.joelonsoftware.com/articles/LeakyAbstractions.html) that the programmer shouldn't need to worry about." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2017-07-10T06:01:07.490", "Id": "320665", "Score": "0", "body": "Well, I'm not that surprised by that result. HDs tend to have quite large writer buffers nowadays, so that the actual blocksize does not matter. On the other hand, we have so much memory today, that 10 MB is *nothing*, esp. not causing memory and garbage allocation problems. Thus, getting as close as possible to your disks write buffer size should be the best. Nevertheless, this is micro-management and as ZeroOne already mentioned, is probably not worth much." } ], "meta_data": { "CommentCount": "4", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-05-11T12:21:21.827", "Id": "11680", "ParentId": "11671", "Score": "0" } }, { "body": "<p>The code looks perfect.</p>\n\n<p>The only thing I would do differently is to leave out the <code>FileNotFoundException</code>.</p>\n\n<p>If you are going to write some Javadoc it should mention that the files are stored with only their name, omitting all information about the directories they come from. If you need that feature, passing the files as a <code>LinkedHashMap&lt;String, File&gt;</code> would be my first choice.</p>\n\n<p>Regarding the buffer size, I would probably settle on 8 kB, without measuring. It's small enough not to cause a garbage collection because of a fragmented heap.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2017-07-10T05:50:20.500", "Id": "168830", "ParentId": "11671", "Score": "0" } } ]
{ "AcceptedAnswerId": "11680", "CommentCount": "1", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-05-11T00:55:00.390", "Id": "11671", "Score": "1", "Tags": [ "java", "performance", "compression" ], "Title": "Java-Helper library for compressing (zipping) files" }
11671
<p>I am programing in C language and have created the below functions to read files. There are two functions that I can use to read files. I wanted to know how I can further improve these two in terms of efficiency and out of these two which one would be better to use for reading files. </p> <p>First is:</p> <pre><code> char *read_data_from_file(char *data, char *path, int *fsz1) { int imgFD=0; struct stat fst; int fsz = *fsz1; fsz = 0; imgFD = open(path, O_RDONLY); if (imgFD &lt;= 0){ *fsz1 = fsz; return NULL; } fstat(imgFD, &amp;fst); fsz = fst.st_size; printf("the size %s = %d inmfd = %d \n ", path, fsz, imgFD); if (fsz &lt;= 0){ *fsz1 = fsz; return NULL; } data = (char *)malloc(sizeof(char)*(fsz+1)); read(imgFD, data, fsz); close(imgFD); *fsz1 = fsz; return (data); } </code></pre> <p>Another is:</p> <pre><code> int read_data_from_file(int fd, void *buffer, int count) { void *pts = buffer; int status = 0, n; if(count &lt; 0) return -1; while(status != count) { n = read(fd, pts+status, count-status); if(n &lt; 1) return n; status += n; } return (status); } </code></pre> <p>The calling portion of the above mentioned function is:</p> <pre><code> int main(int argc, char *argv[]) { struct stat sb; off_t len; char *p, *buffer = NULL; int fd; fd = open("test.txt" , O_RDONLY); if (fd == -1) { perror ("open"); return 1; } if (fstat (fd, &amp;sb) == -1) { perror ("fstat"); return 1; } if (!S_ISREG (sb.st_mode)) { fprintf (stderr, "%s is not a file\n", argv[1]); return 1; } debug_print("printing start time and size : %d\n", sb.st_size); buffer = (char *)malloc(sizeof(char) * (sb.st_size + 1)); read_data_from_file(fd, buffer, sb.st_size); </code></pre>
[]
[ { "body": "<p>In your first <code>read_data_from_file()</code>, you're filling in the out parameter <code>fsz1</code> with zero, or with <code>-1</code>, depending, when things go wrong. However, your caller isn't going to be able to DO anything with that number. Don't fill it in, just return <code>NULL</code>.</p>\n\n<p>In your second <code>read_data_from_file()</code>, you carefully loop on <code>read()</code> to handle the possibility that <code>read()</code> will only return part of the data you ask it for. In the first, you don't. Are you worried about this or not? If <code>read()</code> will actually return partial data put the loop in your first function; if it won't, take the loop out of the second.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-05-11T18:24:11.910", "Id": "11695", "ParentId": "11675", "Score": "4" } }, { "body": "<p>The two functions do not do the same thing so comparing their efficiency is not sensible. A few comments on the code though (adding to those of @mjfgates)</p>\n\n<p>first read_data_from_file:</p>\n\n<ul>\n<li><code>path</code> should be const</li>\n<li><code>imgFD</code> should be comapred &lt;0 not &lt;=0</li>\n<li>check the return value of <code>fstat</code> instead of checking whether <code>fsz</code> is less than 0.</li>\n<li>use <code>perror</code> to print failure reason after detecting open failure</li>\n<li><code>fsz == 0</code> is valid and should return an empty buffer (ie return <code>data</code> and set <code>*fsz1</code> to zero)</li>\n<li>don't cast the return value of malloc</li>\n<li><code>sizeof(char)</code> is 1 by definition</li>\n<li>check whether malloc succeeded.</li>\n<li>you allocated <code>fsz+1</code> bytes, presumably allowing for a terminator but didn't add one (\\0)</li>\n<li>check whether read succeeded.</li>\n<li>check whether close succeeded (if pedantic).</li>\n<li>why does <code>data</code> get brackets in <code>return (data)</code> and NULL not in <code>return NULL</code>? Prefer the latter (no brackets).</li>\n</ul>\n\n<p>second read_data_from_file:</p>\n\n<ul>\n<li><code>pts</code> should be <code>char *</code> or else you will get a compiler warning. Are warnings enabled for you?</li>\n<li>keywords (if, while, etc) preferred with a space - ie. <code>if (...)</code> instead of <code>if(...)</code></li>\n<li>if you are reading a normal file, the loop is not required. Just one read, as in the first version.</li>\n<li>if you are reading something other than a file, then a loop is needed, but your loop is incorrect. If the read call gave some data, you will get n = number read, if it got to end of file, you will get 0, if there was an error or if reading was interrupted before any daat was received you will get an error (-1) and errno will be set. In the latter case you must work out whether there was an error or whether the call was interrupted in which case you can loop.</li>\n<li>if count is bigger than the actual file size, your loop never exits.</li>\n<li>status is misnamed - it holds the number of bytes read so far.</li>\n</ul>\n\n<p>main:</p>\n\n<ul>\n<li>return EXIT_FAILURE or EXIT_SUCCESS</li>\n<li>ok, it is a file you are reading so the loop in the second read_data_from_file is not necessary.</li>\n<li>as before, don't cast malloc return and <code>sizeof(char)</code> is 1 by definition</li>\n</ul>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-05-11T23:02:41.207", "Id": "11711", "ParentId": "11675", "Score": "5" } }, { "body": "<pre><code> if (imgFD &lt;= 0){\n *fsz1 = fsz;\n return NULL;\n }\n</code></pre>\n\n<p>In this particular case the assignment to <code>*fsz1</code> is a no-op, since <code>fsz</code>'s value came from <code>*fsz1</code>.</p>\n\n<p>However, I would argue that doing something inside every <code>return</code> block (like your assignments to <code>*fsz1</code>) get tedious to maintain. One style would be to not have early <code>return</code> statements, and do the assignments you want at the end. You can still check for errors, just don't heave repeated <code>return</code>s, example:</p>\n\n<pre><code>char *data = NULL;\n\nif (imgFd &gt;= 0)\n{\n // Do the rest of the work of the function\n\n data = malloc(/* ... */);\n}\n\nif (data)\n{\n // more work ...\n}\n\n// Single block which assigns to fsz1 in all cases.\n// This would also be a good place to free any buffers, etc.\n//\n*fsz1 = fsz;\nreturn data;\n</code></pre>\n\n<p>Moving on to:</p>\n\n<pre><code> fstat(imgFD, &amp;fst);\n</code></pre>\n\n<p>You're not checking for a failure from <code>fstat</code>.</p>\n\n<pre><code> fsz = fst.st_size;\n</code></pre>\n\n<p>What if <code>int</code> is not big enough to hold file size? For example if <code>int</code> were 32-bits, and the file were greater than 2GB. The type of <code>st_size</code> is <code>off_t</code> which is likely to be at least 64 bits in sane platform.</p>\n\n<pre><code> data = (char *)malloc(sizeof(char)*(fsz+1));\n</code></pre>\n\n<p><code>malloc</code> can return <code>NULL</code> on failure. In C you don't need to cast from <code>(void*)</code> to another pointer type. <code>sizeof(char)</code> is also always 1. Further it seems that you've clobbered the <code>data</code> parameter entirely, so there is no sense in having that as a parameter. Lastly, it seems like a really big file would make this allocation unlikely to succeed.</p>\n\n<pre><code> read(imgFD, data, fsz);\n</code></pre>\n\n<p>You need to observe the return value here too. It returns the number of bytes read, or <code>0</code> on end of file, or <code>-1</code> on error.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-01-07T19:56:08.850", "Id": "20244", "ParentId": "11675", "Score": "2" } }, { "body": "<p>Another pretty popular way of reading files into memory is <a href=\"http://en.wikipedia.org/wiki/Mmap\" rel=\"nofollow\">memory mapping (mmap)</a>. That's usually the way programs and shared libraries loaded in linux.</p>\n\n<p>Aside of that what that <code>char *data</code> parameter is for? You just override value of local variable which receives that parameter with pointer to newly allocated memory<br>\n<code>data = (char *)malloc(sizeof(char)*(fsz+1));</code> </p>\n\n<p>Why do you use that <code>fsz+1</code> since you already pass back to caller the size of your file? Just for simplifying converting it to <a href=\"http://en.wikipedia.org/wiki/Null-terminated_string\" rel=\"nofollow\">ASCIIz string</a>?<br>\nNote that C language standart clearly states that <code>sizeof(char)</code> always equals to <strong>1</strong> and nothing else. So multiplying to it will just disappear during compilation.</p>\n\n<p>Note that the most awful issues you can introduce into the code is scrambling it in that way that no one can understand you. Consider to choose some guide lines in naming your variables <code>fsz</code> and <code>fsz1</code> is might be understand as \"file size\" and \"file size\" (with tick or alternative). But types of those variables are totally different (<code>int</code> and <code>int*</code>).</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-01-07T20:27:55.377", "Id": "20248", "ParentId": "11675", "Score": "2" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-05-11T04:09:08.497", "Id": "11675", "Score": "3", "Tags": [ "optimization", "c", "performance", "linux", "file-system" ], "Title": "Improving C file reading function" }
11675
<p>One day I realised that my Android project utilizes AlertDialogs here and there in very ineffective way. The heavily duplicated portion of code looked like this (actually, copied and pasted from some documentation):</p> <pre><code>AlertDialog.Builder builder = new AlertDialog.Builder(context); builder.setMessage("Are you sure you want to close application?") .setPositiveButton("Yes", new DialogInterface.OnClickListener() { public void onClick(DialogInterface dialog, int id) { dialog.dismiss(); System.runFinalizersOnExit(true); System.exit(0); } }) .setNegativeButton("No", new DialogInterface.OnClickListener() { public void onClick(DialogInterface dialog, int id) { dialog.dismiss(); } }); builder.create().show(); </code></pre> <p>Apparently, this code fragment should be transformed into a function accepting 2 parameters: a question to ask, and an action to perform.</p> <p>After several iterations of code optimizations (each one of which seemed as the last and most minimal one), I came to the following class:</p> <pre><code>public abstract class DialogCallback implements DialogInterface.OnClickListener,Runnable { DialogCallback(Context c, String q) { AlertDialog.Builder builder = new AlertDialog.Builder(c); builder.setMessage(q) .setPositiveButton("Yes", this) .setNegativeButton("No", this); builder.create().show(); } public void onClick(DialogInterface dialog, int which) { dialog.dismiss(); if(which == DialogInterface.BUTTON_POSITIVE) run(); } } </code></pre> <p>with the following usage:</p> <pre><code>new DialogCallback(context, "are you sure?") { public void run() { // some action } }; </code></pre> <p>Is there a way of further optimization? What other methods for effective dialog callbacks can be used?</p>
[]
[ { "body": "<p>for a confirmation dialog use setCancelable(true) to make the user able to cancel the dialog using the back button. This is the native way and you don't have to implement anything.</p>\n\n<p>Note: in Android you are not supposed to close the application. The operating system will close it when it feels like to do so.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-05-13T20:20:52.763", "Id": "18817", "Score": "0", "body": "Thanks for your response, yet I don't think we should discuss application design (as opposed to programming techniques) in the context of this question. This area is very controversial itself." } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-05-13T20:14:10.860", "Id": "11735", "ParentId": "11677", "Score": "3" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-05-11T09:02:40.943", "Id": "11677", "Score": "3", "Tags": [ "java", "android", "callback" ], "Title": "Efficient implemetation of AlertDialog callback in Android" }
11677
<p>The Qt documentation recommend an iterator-based solution to iterate over an associative container like QMap and QHash, and I always wondered if there really isn't a (nice) solution using a <code>foreach</code> loop like in PHP:</p> <pre class="lang-php prettyprint-override"><code>foreach($container as $key =&gt; $value) </code></pre> <p>I looked into the source code of the <code>foreach</code> macro and extended it by a key variable. The following code is only the GCC version of the loop (it doesn't work with all compilers, see <code>Q_FOREACH</code> macro definition in <code>qglobal.h</code> for other versions).</p> <pre class="lang-c++ prettyprint-override"><code>#define foreachkv(keyvar, variable, container) \ for (QForeachContainer&lt;__typeof__(container)&gt; _container_(container); \ !_container_.brk &amp;&amp; _container_.i != _container_.e; \ __extension__ ({ ++_container_.brk; ++_container_.i; })) \ for (keyvar = _container_.i.key();; __extension__ ({break;})) \ for (variable = *_container_.i;; __extension__ ({--_container_.brk; break;})) </code></pre> <p>Now you can do the following:</p> <pre class="lang-c++ prettyprint-override"><code>QVariantHash m; m.insert("test", 42); m.insert("foo", true); foreachkv(QString k, QVariant v, m) qDebug() &lt;&lt; k &lt;&lt; "=&gt;" &lt;&lt; v; </code></pre> <p>The output will be:</p> <blockquote> <pre class="lang-c++ prettyprint-override"><code>"foo" =&gt; QVariant(bool, true) "test" =&gt; QVariant(int, 42) </code></pre> </blockquote> <p>Tests I've done so far:</p> <ul> <li>examples from above</li> <li><code>foreachkv</code> works as expected with <code>break</code> and <code>continue</code> statements within the loop.</li> </ul> <p>What did I do? I just added another for loop to introduce the key variable (called <code>keyvar</code> in the macro). Maybe I don't need this loop?</p>
[ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-05-09T21:31:12.733", "Id": "18733", "Score": "0", "body": "Actually I think the best place would be [qt-project.org/contribute](http://qt-project.org/contribute). It would definitely be useful for code clarity." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-05-09T22:21:39.307", "Id": "18734", "Score": "0", "body": "AFAIK, Qt is no longer interested in improving the C++ API. They fully concentrate on QML / QtQuick now." } ]
[ { "body": "<p>You can probably do something simpler to avoid making this a special case macro, e.g. using <code>std::tie</code> or <code>boost::tie</code> if that's not available:</p>\n\n<pre><code>#include &lt;map&gt;\n#include &lt;functional&gt;\n#include &lt;boost/foreach.hpp&gt;\n#include &lt;iostream&gt;\n\nint main() {\n std::map&lt;int, std::string&gt; map = {std::make_pair(1,\"one\"), std::make_pair(2,\"two\")};\n int k;\n std::string v;\n BOOST_FOREACH(std::tie(k, v), map) {\n std::cout &lt;&lt; \"k=\" &lt;&lt; k &lt;&lt; \" - \" &lt;&lt; v &lt;&lt; std::endl;\n }\n}\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-06-23T12:12:41.733", "Id": "20940", "Score": "2", "body": "If you’ve got `std::tie` then you also have range-based `for`." } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-05-09T20:12:40.633", "Id": "11682", "ParentId": "11681", "Score": "2" } } ]
{ "AcceptedAnswerId": "11682", "CommentCount": "2", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-05-09T19:53:04.933", "Id": "11681", "Score": "4", "Tags": [ "c++", "macros", "qt" ], "Title": "Qt foreach-like alternative to iterate over value AND key of an associative container" }
11681
<p>I am trying to have a <code>ReentrantLock</code> with another way to determinate which thread will have the lock in the waiting queue. <code>ReentrantLock</code> implementation manages a Fair/Unfair policy, that's not what I want.</p> <p>I would like to give a priority when I call the <code>.lock()</code> method, and this priority will determinate the order of current thread in the waiting threads queue.</p> <p>I wrote a class, based on a <code>PriorityBlockingQueue</code>, and I'd like your opinion.</p> <pre><code>import java.util.Date; import java.util.concurrent.PriorityBlockingQueue; /** * Class to lock a resource. * When multiple threads are waiting for the resource to be unlocked, the one with the greatest priority will have the resource. * When two threads have the same priority, the first added thread will lock the resource. * */ public class PrioritizedLock { private PriorityBlockingQueue&lt;PrioritizedThread&gt; waitingQueue = new PriorityBlockingQueue&lt;PrioritizedThread&gt;(); private volatile PrioritizedThread activeThread; private volatile Object syncStartNext = new Object(); private volatile boolean shutdown = false; public PrioritizedLock() { startQueueWatcher(); } /** * Starts a queue watcher, which takes PrioritizedThread from the PriorityBlockingQueue and notify them to wake them up. */ private void startQueueWatcher() { new Thread(new Runnable() { @Override public void run() { while (!shutdown) { /* * Wait until a PrioritizedThread is added to the PriorityBlockingQueue */ while (activeThread == null) { try { activeThread = waitingQueue.take(); } catch (InterruptedException e1) { // } } /* * Notify the thread to wake up (now it has locked the resource) */ synchronized (activeThread) { activeThread.notify(); } /* * Wait until the resource has been released from the active thread */ while (activeThread != null) { synchronized (syncStartNext) { try { syncStartNext.wait(); } catch (InterruptedException e) { // } } } } } }).start(); } /** * Waits until the thread is woken up by the Queue Watcher thread * @param thread */ private void wait(PrioritizedThread thread) { synchronized (thread) { while (activeThread != thread) { try { thread.wait(); } catch (InterruptedException e) { // } } } } static class PrioritizedThread implements Comparable&lt;PrioritizedThread&gt; { Thread thread; int priority; Date date = new Date(); public PrioritizedThread(Thread aThread, int aPriority) { thread = aThread; priority = aPriority; } @Override public int compareTo(PrioritizedThread other) { int diffPriorities = this.priority - other.priority; if (diffPriorities == 0) { return date.compareTo(other.date); } return diffPriorities; } } /** * Waits until the resource is locked by the current thread * @param priority Priority of the lock, the less has the greatest priority */ public void lock(int priority) { PrioritizedThread prioritizedThread = new PrioritizedThread(Thread.currentThread(), priority); waitingQueue.add(prioritizedThread); wait(prioritizedThread); } /** * Unlock the resource */ public void unlock() { activeThread = null; synchronized (syncStartNext) { syncStartNext.notify(); } } /** * Trigger a shutdown of the lock, */ public void shutdown() { shutdown = true; } } </code></pre>
[]
[ { "body": "<p>After calling shutdown(), the shutdown boolean may never get checked. The Thread may be stuck in waitingQueue.take().</p>\n\n<p>It's probably not a good idea to catch and swallow InterruptedException.</p>\n\n<p>Considering those two points together, it makes sense to remove the Thread and use <a href=\"http://docs.oracle.com/javase/7/docs/api/java/util/concurrent/Executors.html#newSingleThreadExecutor%28%29\" rel=\"nofollow\">Executors.newSingleThreadExecutor()</a> instead, and delegate to its <a href=\"http://docs.oracle.com/javase/7/docs/api/java/util/concurrent/ExecutorService.html#shutdown%28%29\" rel=\"nofollow\">shutdown()</a> method.</p>\n\n<p>Finally, it's fairly low-level and error prone to use wait() and notifyAll(). Using notify() is even riskier than notifyAll(). I'd recommend using a <a href=\"http://docs.oracle.com/javase/7/docs/api/java/util/concurrent/locks/Condition.html\" rel=\"nofollow\">Condition</a> instead.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-05-15T15:50:04.223", "Id": "11771", "ParentId": "11683", "Score": "2" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-05-07T15:26:27.653", "Id": "11683", "Score": "1", "Tags": [ "java", "multithreading", "locking" ], "Title": "ReentrantLock with priorities for waiting threads" }
11683
<p>I have this function which is pretty easy to read and works just fine. I'm looking to advance my coding abilities by writing more concise code, though.</p> <p>Does anyone know of an elegant way to condense this down? Any pointers very much appreciated! Thank you! </p> <pre><code>var $_GET = {}; document.location.search.replace(/\??(?:([^=]+)=([^&amp;]*)&amp;?)/g, function () { function decode(s) { return decodeURIComponent(s.split("+").join(" ")); } $_GET[decode(arguments[1])] = decode(arguments[2]); }); function create_filter_input($name, $termname) { var $input = '&lt;input class="query-input" type="hidden" value="' + $termname + '" name="' + $name + '" /&gt;'; return $input; } area = $_GET["area"], type = $_GET["property_type"], style = $_GET["style"], feature = $_GET["feature"], if(area || type || style || feature) { if(area) { areainput = create_filter_input('area',area); $filterTerms.append(areainput); } if(type) { typeinput = create_filter_input('property_type',type); $filterTerms.append(typeinput); } if(style) { styleinput = create_filter_input('style',style); $filterTerms.append(styleinput); } if(feature) { featureinput = create_filter_input('feature',feature); $filterTerms.append(featureinput); } } </code></pre> <hr> <p>This is my current solution based on your answers! I think it's pretty concise. Let me know what you think! thanks again.</p> <pre><code>function create_filter_input($name, $termname, $filterterms) { if($termname) { var $input = '&lt;input class="query-input" type="hidden" value="' + $termname + '" name="' + $name + '" /&gt;'; $filterterms.append($input); } } create_filter_input('area',area,$filterTerms); create_filter_input('property_type',type,$filterTerms); create_filter_input('style',style,$filterTerms); create_filter_input('feature',feature,$filterTerms); </code></pre>
[ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-05-11T16:01:36.090", "Id": "18751", "Score": "0", "body": "what language is this? you have `$_GET[]`, PHP? but you also have variables with no `$`, JS?" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-05-11T16:10:20.947", "Id": "18760", "Score": "0", "body": "I've added some more code which should explain! it's all JS" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-05-11T19:47:35.810", "Id": "18783", "Score": "1", "body": "It's considered bad practice to use the `$` in variable names in javascript - the symbol was originally intended for machine use. Yes, I know libraries love it, but that's just one more reason not to use it - confusion with library code." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-05-11T19:51:04.260", "Id": "18784", "Score": "0", "body": "also, you don't have to pass `$filterTerms` - it is present in the scope in which the function was declared, so the function has access to it, even when it is not passed." } ]
[ { "body": "<p>What's the idea of having those OR checking, when you check them again individually? </p>\n\n<pre><code>if(area || type || style || feature){...\n</code></pre>\n\n<p>If none hold true, they never run anyway. If one exists, all of your 4 <code>if</code>s run also, <em>and checking again</em></p>\n\n<p>Assuming that they are not DOM elements, and the variables are not used anywhere else, you can do this:</p>\n\n<pre><code>if (area) {\n $filterTerms.append(create_filter_input('area', area));\n}\n\nif (type) {\n $filterTerms.append(create_filter_input('property_type', type));\n}\n\nif (style) {\n $filterTerms.append(create_filter_input('style', style));\n}\n\nif (feature) {\n $filterTerms.append(create_filter_input('feature', feature));\n}\n</code></pre>\n\n<p>but if they are DOM elements (and it looks like jQuery):</p>\n\n<pre><code>var container = $('&lt;div&gt;'); //create container that is not yet in DOM\n\nif (area) {\n container.append(create_filter_input('area', area));\n}\n\nif (type) {\n container.append(create_filter_input('property_type', type));\n}\n\nif (style) {\n container.append(create_filter_input('style', style));\n}\n\nif (feature) {\n container.append(create_filter_input('feature', feature));\n}\n\ncontainer.contents().appendTo($filterTerms); //append to DOM in one go\n</code></pre>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-05-11T15:30:53.630", "Id": "11687", "ParentId": "11686", "Score": "1" } }, { "body": "<p>The main thing I would question is why you have so many boolean or rather \"truthy\" values in the first place. If you're using <code>area</code>, <code>type</code>, <code>style</code>, <code>feature</code> more than here, you <em>might</em> be essentially duplicating decision logic all over the place. if the conditions are all exclusive, it'd be better to have </p>\n\n<ol>\n<li>a set of objects (or rather Javascript \"classes\" or \"constructors\" which we can use to create said objects\") with a commonly named method, each doing their respective thing, and </li>\n<li>a factory method that determines which of those objects to create.</li>\n</ol>\n\n<p>After all that, the whole block of code (bessides the constructor and object factory definitions might become something like</p>\n\n<pre><code>var filterThing = objectFactory.makMeAFilter(x,y,z);\nfilterThing.addInput($filterterms);\n</code></pre>\n\n<p><strong>HOWEVER</strong>, if the conditions aren't exclusionary.. well, you still have options, and you could do the object factory thing, but it might just be better to leave it alone. It really depends on how the <code>area</code>, <code>type</code>, <code>style</code>, <code>feature</code> things are used elsewhere.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-05-11T15:57:49.543", "Id": "18748", "Score": "0", "body": "Jay-- I've updated my answer with more info. What you're describing here is essentially the direction I'd like to go in! If you elaborate a little more that would be great. Thanks!" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-05-11T15:59:09.667", "Id": "18749", "Score": "0", "body": "Also this snippet is the only place in the code where I use those variables (area, style, type, feature)" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-05-11T15:59:48.683", "Id": "18750", "Score": "0", "body": "productionlocations.com is the live site... this function deals with searching / filtering properties FYI" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-05-11T16:08:53.267", "Id": "18759", "Score": "0", "body": "wait... $_GET? That's likely PHP *not* javascript." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-05-11T16:11:02.023", "Id": "18761", "Score": "0", "body": "I've updated my answer... it's all javascript. I know what language I'm coding :)" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-05-11T16:11:43.200", "Id": "18762", "Score": "0", "body": "LOL, confusing." } ], "meta_data": { "CommentCount": "6", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-05-11T15:49:20.450", "Id": "11688", "ParentId": "11686", "Score": "1" } }, { "body": "<p>Expanding on @Joseph's answer - and I haven't spent much time with javascript, so treat with caution - I would think you could write a method to simplify it further.</p>\n\n<pre><code>var container = $('&lt;div&gt;'); //create container that is not yet in DOM\n\nprocess(container, area, 'area')\nprocess(container, type, 'property_type')\nprocess(container, style, 'style')\nprocess(container, feature, 'feature')\n\ncontainer.contents().appendTo($filterTerms); //append to DOM\n\n...\n\nfunction process($container, $category, $tag) {\n if ($category) {\n $container.append(create_filter_input($tag, $category));\n }\n}\n</code></pre>\n\n<p>This kind of Extract Method refactoring is good low-hanging fruit with duplication of this sort.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-05-11T16:07:16.553", "Id": "11691", "ParentId": "11686", "Score": "1" } }, { "body": "<p>Try to avoid repetition. </p>\n\n<pre><code>var args, i, check, len, filtered;\n\nfunction parseUrl() {\n var getArgs = {};\n\n function decode(s) { // declare this function only once, don't declare functions inside any kind of loop\n return decodeURIComponent(s.replace(/\\+/g, ' '));\n\n document.location.search.replace(/\\??(?:([^=]+)=([^&amp;]*)&amp;?)/g, function () {\n getArgs[decode(arguments[1])] = decode(arguments[2]);\n });\n\n return getArgs;\n}\n\nfunction create_filter_input($name, $termname) {\n var $input = '&lt;input class=\"query-input\" type=\"hidden\" value=\"' + $termname + '\" name=\"' + $name + '\" /&gt;';\n return $input;\n}\n\nargs = parseUrl();\ncheck = ['area', 'property_type', 'style', 'feature'];\nlen=check.length;\n\nfor(var i=0; i&lt;len; i++) {\n if (!args[check[i]]) {\n continue;\n }\n filtered = create_filter_input(check[i], args[check[i]]); \n $filterTerms.append(filtered);\n}\n</code></pre>\n\n<p>Try to write code anticipating change and write it to make your life easy. For example this:</p>\n\n<pre><code>type = $_GET[\"property_type\"],\n</code></pre>\n\n<p>creates a variable named type but you then effectively need a map to get back to \"property_type\":</p>\n\n<pre><code>create_filter_input('property_type',type);\n</code></pre>\n\n<p>Is the same as:</p>\n\n<pre><code>create_filter_input('property_type', $_GET[\"property_type\"]);\n</code></pre>\n\n<p>(Which, incidentally is the same as: <code>create_filter_input('property_type', $_GET.property_type);</code> - use dot notation where possible.)</p>\n\n<p>If you write it like that - seeing that you are passing (almost) the same argument in all use cases to your create_filter_input function - you can start to see/think that you don't need 2 local variables - just having \"property_type\" is enough.</p>\n\n<p>As one of the other answers says - don't serially append to the dom. each write is relatively expensive. it's better to build a dom fragment and append it to the dom in one go.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-05-11T16:15:27.930", "Id": "18763", "Score": "0", "body": "Very cool solution. Do you think the one in my updated answer at the bottom is more efficient? I think it's more readable at least..." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-05-11T16:33:38.850", "Id": "18766", "Score": "0", "body": "updated after your update to the question and comment - I doubt there is any different in efficiency, it's simply more flexible to use a loop and process it." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-05-11T16:38:57.377", "Id": "18768", "Score": "0", "body": "+1 as anything I'd do would probably be an attempt to explain the same. not I'd sure that the appending to the DOM issue really needs to be brought up, though, for such a small set of things." } ], "meta_data": { "CommentCount": "3", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-05-11T16:12:37.083", "Id": "11692", "ParentId": "11686", "Score": "2" } } ]
{ "AcceptedAnswerId": "11692", "CommentCount": "4", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-05-11T15:10:06.250", "Id": "11686", "Score": "1", "Tags": [ "javascript" ], "Title": "Refactoring and condensing a Javascript function with many repeat conditions, strings, and variables" }
11686
<p>The c# newbie is back :) I have another problem with my threads. Here is what i am trying to achieve:</p> <p>I am starting 5 threads which are performing the same task but on different URLs. So i am keeping a "masterLogFile.txt" to keep track of what URLs have already been visited. Each thread compares its own "thread1LogFile.txt" to the "masterLogFile.txt" before deciding whether to execute the task.</p> <p>My question is, is there any more efficient way to handle this? Currently each thread runs this piece of code before deciding if the URL is ok or not:</p> <pre><code>using (FileStream fs = File.Open("masterLogFile.txt", FileMode.Open, FileAccess.Read, FileShare.Read)) { byte[] bff = new byte[1024]; UTF8Encoding temp = new UTF8Encoding(true); while (fs.Read(bff,0,bff.Length) &gt; 0) { if (temp.GetString(bff).Contains(variableWithUrlFrom_thread1LogFile.txt)) { found = true; } } fs.Close(); } </code></pre>
[ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-05-10T13:25:00.403", "Id": "18754", "Score": "0", "body": "Ah no, sorry. I just wanted to ask if my logic for comparing data in files from different threads can be improved" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-05-10T13:27:03.807", "Id": "18755", "Score": "0", "body": "Why do to want to use files to track the work? Aren't all the threads in the same process?" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-05-10T13:28:52.563", "Id": "18756", "Score": "0", "body": "Are you reading in the master log file each time the thread is called - and does this change?" } ]
[ { "body": "<p>I'd use a dictionary (or a HashSet if you don't need the ID information) for coordination.</p>\n\n<pre><code>class UrlLog {\n private Dictionary&lt;string, int&gt; visited = new Dictionary&lt;string, int&gt;();\n public bool HasUrlBeenVisited(string Url) {\n lock(visited) return visited.ContainsKey(Url);\n }\n public void SetUrlVisited(string Url, int threadId) { /* id not strictly necessary */\n lock(visited) visited[Url] = threadId;\n }\n}\n</code></pre>\n\n<p>Then pass one instance of this UrlLog to your threads, and they can use that.</p>\n\n<p>Also, I'm not sure you even need the locks for the checks, but it's better to be safe than sorry. :)</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-05-10T13:26:27.440", "Id": "18757", "Score": "0", "body": "This. Here is another post to get you started: http://stackoverflow.com/questions/823860/c-listt-contains-too-slow" } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-05-10T13:25:50.087", "Id": "11690", "ParentId": "11689", "Score": "5" } } ]
{ "AcceptedAnswerId": "11690", "CommentCount": "3", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-05-10T13:20:45.040", "Id": "11689", "Score": "1", "Tags": [ "c#", "multithreading" ], "Title": "Threads and logfiles" }
11689
<p>How can I improve the performance of this method or is it already good?</p> <pre><code>private static void LoadAssembliesWithInjectorModule(IEnumerable&lt;FileInfo&gt; files) { var moduleType = typeof (InjectorModule); foreach (var file in files) { try { var assembly = Assembly.LoadFrom(file.FullName); var moduleTypes = from assemblyType in assembly.GetTypes() where moduleType.IsAssignableFrom(assemblyType) &amp;&amp; !assemblyType.IsAbstract select assemblyType; if (!moduleTypes.Any()) continue; foreach (var instance in moduleTypes.Select(type =&gt; Activator.CreateInstance(type) as InjectorModule)) { instance.Load(); } } catch (BadImageFormatException) { //Files that aren't class libraries will throw this exception, just eat it and move on. } catch (ReflectionTypeLoadException e) { throw new AppDomainUnloadedException(string.Format("Error loading {0} exception {1} loading errors {2}", file.FullName, e.Message, e.LoaderExceptions), e); } } } </code></pre>
[ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-05-11T19:30:21.673", "Id": "18778", "Score": "2", "body": "How can we know? Is it good enough for your intended usage? Is this method a bottleneck in your program?" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-05-11T19:32:41.710", "Id": "18779", "Score": "0", "body": "@svick There is a theoretical chance that this could be very intensive depending on the amount of assemblies are available for it to pick up, so it all depends. If there's a small amount, it should never be an issue, but if there's a large amount then it possibly could be. I'm looking to see if there is possibly any way to improve upon what there is now." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-05-18T13:55:06.407", "Id": "19060", "Score": "0", "body": "Looks pretty much like every dynamic loader I've seen. My guess is that this method is only called once per program activation? If so, unless you're talking close to a thousand assemblies being loaded, it's not going to be a significant percentage of your program's execution time." } ]
[ { "body": "<p>I would suggest swapping the checks on this line from</p>\n\n<p><code>where moduleType.IsAssignableFrom(assemblyType) &amp;&amp; !assemblyType.IsAbstract</code></p>\n\n<p>to</p>\n\n<p><code>where !assemblyType.IsAbstract &amp;&amp; moduleType.IsAssignableFrom(assemblyType)</code></p>\n\n<p>Checking a boolean property will be faster than a method call to check the type. If it's not abstract why check the type?</p>\n\n<p>You might also want to filter further by requiring that it is a class:</p>\n\n<pre><code>where assemblyType.IsClass \n &amp;&amp; !assemblyType.IsAbstract \n &amp;&amp; moduleType.IsAssignableFrom(assemblyType)\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-05-18T16:28:24.937", "Id": "19076", "Score": "0", "body": "I agree with your changes as it would make sense to check something that's already set rather than making a method call first." } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-05-18T15:27:57.570", "Id": "11878", "ParentId": "11696", "Score": "2" } } ]
{ "AcceptedAnswerId": "11878", "CommentCount": "3", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-05-11T18:26:19.953", "Id": "11696", "Score": "1", "Tags": [ "c#", "performance", ".net", "linq" ], "Title": "Load assemblies with injector module" }
11696
<p>I feel like I can vastly improve this. Any ideas?</p> <pre><code>// get orientation of device getOrientation(); // animate var num = 400; if( $('body').hasClass("landscape") ) { $('.example').animate({'bottom', 0}); } else { $('.example').animate({'bottom', num}); } function getOrientation(){ switch(window.orientation) { case -90: case 90: $('body').addClass("landscape"); // alert('landscape'); break; default: //alert('portrait'); $('body').addClass("portrait"); break; } } window.onorientationchange = function() { getOrientation(); }; </code></pre>
[ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-05-11T20:16:43.067", "Id": "18785", "Score": "0", "body": "I think that your `window.onorientationchange` will never trigger any change." } ]
[ { "body": "<p>Use ternary operators, something like:</p>\n\n<pre><code> // get orientation of device\ngetOrientation();\n\n// animate\nvar num = 400;\n\n$('.example').animate({'bottom', $('body').hasClass(\"landscape\") ? 0 : num});\n\nfunction getOrientation(){\n $('body').removeAttr('class'); //Removing all classes\n $('body').addClass(90===Math.abs(window.orientation) ? \"landscape\" : \"portrait\");\n}\n\nwindow.onorientationchange = function() {\n getOrientation();\n};\n</code></pre>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-05-11T19:10:27.517", "Id": "11700", "ParentId": "11697", "Score": "1" } }, { "body": "<p>Well for starters bind the event using the jQuery standard</p>\n\n<pre><code>var $win = $(window).bind('orientationchange', function(){\n // math.abs to reduce logical operators \n $('body').removeClass('landscape portrait') // reset\n .addClass(Math.abs(this.orientation) === 90 ? \"landscape\" : \"portrait\"); \n});\n\n// now you can trigger the orientation manually on doc ready to set the class\n$win.trigger('orientationchange');\n\nvar num = 400,\n $body = $('body'),\n $example = $('.example');\n\nif($body.hasClass(\"landscape\"))\n $example.animate({'bottom', 0});\nelse\n $example.animate({'bottom', num});\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-05-11T19:41:57.987", "Id": "18781", "Score": "0", "body": "Thanks for this! What is different between binding the event and how I originally had it?" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-05-11T22:16:29.493", "Id": "18789", "Score": "0", "body": "There are several benefits adding events using addEventListener vs just assigning a property. For example you can add many listeners instead of just one, etc. But additionally jQuery normalizes the event arg0 passed into the handler so that events behave the same across browsers." } ], "meta_data": { "CommentCount": "2", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-05-11T19:11:51.763", "Id": "11701", "ParentId": "11697", "Score": "2" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "1", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-05-11T18:39:11.417", "Id": "11697", "Score": "1", "Tags": [ "javascript", "jquery" ], "Title": "Get device orientation" }
11697
<p>I have various strings that contain codes, e.g. like this:</p> <pre><code>"file = new JarFile(new File()" + "\nSystem.out.println(file" </code></pre> <p>but also</p> <pre><code>"args" </code></pre> <p>Now I want to find the substring that is in the beginning and in the end of the string. E.g. in the first case the result would be <code>file</code>. In the second example the result has to be <code>args</code></p> <p>I now wrote the following method:</p> <pre><code>public static String findWord(String text) { String result = null; boolean found = false; for (int i = 0; i &lt; text.length(); i++) { for (int j = 0; j &lt; text.length(); j++) { String first = text.substring(0, i*j); String last = text.substring(text.length() - i*j, text.length()); if (first.equals(last) &amp;&amp; first.length() &gt; 0) { result = first; found = true; break; } } if (found) { break; } } return result; } </code></pre> <p>This seems to work for the test cases I tested, but I'm not sure if it works for all cases. Additionally, I'm not sure if there isn't a simpler solution. I need two loops and ugly break statements. So how could I improve that?</p>
[]
[ { "body": "<p>I'm not completely sure about the requirements, but what about the following?</p>\n\n<pre><code>public static String findWord2(final String text) {\n for (int i = text.length() - 1; i &gt; 0 ; i--) {\n final String first = text.substring(0, i);\n final String last = text.substring(text.length() - i);\n if (first.equals(last)) {\n return first;\n }\n }\n return text;\n}\n</code></pre>\n\n<p>Here are my tests:</p>\n\n<pre><code>import static org.junit.Assert.assertEquals;\n\nimport java.util.Arrays;\nimport java.util.Collection;\n\nimport org.junit.Test;\nimport org.junit.runner.RunWith;\nimport org.junit.runners.Parameterized;\nimport org.junit.runners.Parameterized.Parameters;\n\n@RunWith(Parameterized.class)\npublic class FindWords2Test {\n\n private final String expected;\n private final String input;\n\n public FindWords2Test(final String expected, final String input) {\n this.expected = expected;\n this.input = input;\n }\n\n @Parameters\n public static Collection&lt;String[]&gt; data() {\n //@formatter:off\n final String[][] data = new String[][] { \n {\"file\", \"file = new JarFile(new File()\\nSystem.out.println(file\"},\n {\"file \", \"file = new JarFile(new File()\\nSystem.out.println(file \"},\n {\"file = new JarFile(new File()\\nSystem.out.println(\", \n \"file = new JarFile(new File()\\nSystem.out.println(\"}, \n {\"args\", \"args\"},\n {\"\", \"\"}, \n {\"a\", \"a\"}, \n {\"a\", \"aa\"}};\n //@formatter:on\n return Arrays.asList(data);\n }\n\n @Test\n public void testFindWords() throws Exception {\n assertEquals(expected, FindWords2.findWord2(input));\n }\n}\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-05-12T22:52:57.367", "Id": "18806", "Score": "0", "body": "Wow, I never knew about that Parameterized runner. Looks quite useful. :)" } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-05-11T22:27:48.777", "Id": "11707", "ParentId": "11705", "Score": "1" } }, { "body": "<p>Firstly, if you are actually working with code, there is a good chance whatever you are doing would be better done with a real parser then whatever string hackery you are proposing.</p>\n\n<p>Secondly, I believe your code will throw exceptions for \"argst\". </p>\n\n<p>Thirdly, your problem need a bit better defining. There may be multiple substrings that exist at the beginning and end of the string. In any case, you always have the trivial empty string and the whole string. You need to define exactly which solution you are trying to find</p>\n\n<pre><code>public static String findWord(String text) {\n String result = null;\n boolean found = false;\n</code></pre>\n\n<p>You don't need two variables, just check if result == null</p>\n\n<pre><code> for (int i = 0; i &lt; text.length(); i++) {\n</code></pre>\n\n<p>I don't know why you included this outer loop. At any rate for <code>i == 0</code>, the inner loop never succeeds. </p>\n\n<pre><code> for (int j = 0; j &lt; text.length(); j++) {\n</code></pre>\n\n<p>This loop misses the case of the whole string. It should be <code>j &lt;= text.length()</code></p>\n\n<pre><code> String first = text.substring(0, i*j);\n String last = text.substring(text.length() - i*j, text.length());\n</code></pre>\n\n<p>If you elide the second parameter, it takes to the end of the list</p>\n\n<pre><code> if (first.equals(last) &amp;&amp; first.length() &gt; 0) {\n</code></pre>\n\n<p>You can skip the second text by starting <code>i</code> and <code>j</code> at 1.</p>\n\n<pre><code> result = first;\n found = true;\n break;\n</code></pre>\n\n<p>Just return. It'll make the code much cleaner</p>\n\n<pre><code> }\n }\n if (found) {\n break;\n }\n }\n return result;\n }\n</code></pre>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-05-12T05:34:04.480", "Id": "11714", "ParentId": "11705", "Score": "1" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-05-11T21:49:55.227", "Id": "11705", "Score": "1", "Tags": [ "java", "algorithm", "strings" ], "Title": "Find two equal substrings in a string" }
11705
<p>A Java desktop application exposes the class/containment hierarchy of its Swing GUI through RPC. I'm building a Haskell client that connects to the application. The objective is to be able to perform queries like "find all the buttons of width less than <strong>w</strong>, located within screen rectangle <strong>r</strong>" over a data structure on the Haskell side.</p> <p>I'm not sure about how to best represent the structure, especially regarding inheritance/subtyping. I have tried two approaches. The first one:</p> <pre><code>data Component = Component { componentId::Int, pos::(Int,Int), dim::(Int,Int), componentType::ComponentType, children::[Component] } data ComponentType = ButtonComponent Button -- other component types here |OtherComponent data Button = Button { buttonText::Text -- other button attributes here } </code></pre> <p>I'm also considering a <a href="https://github.com/danidiaz/haskell-sandbox/blob/master/existential2.hs">second solution</a> using existential types, together with Typeable to implement "downcasting":</p> <pre><code>data Component = Component { componentId::Int, pos::(Int,Int), dim::(Int,Int), children::[AnyComponent] } deriving Typeable data AnyComponent = forall a . ( Typeable a, HasComponent a ) =&gt; AnyComponent a class HasComponent a where base :: a -&gt; Component downcast :: Typeable b =&gt; a -&gt; Maybe b instance HasComponent Component where base = id downcast = cast -- cast function is from Data.Typeable instance HasComponent AnyComponent where base (AnyComponent a) = base a downcast (AnyComponent a) = cast a data Button = Button { buttonComponent:: Component, -- pointer to "superclass" info buttonText::Text -- other button attributes here } deriving Typeable instance HasComponent Button where base = buttonComponent downcast = cast </code></pre> <p>What solution is more idiomatic Haskell? Are there better solutions?</p>
[ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-04-09T13:19:43.707", "Id": "38481", "Score": "0", "body": "BTW, if you like mucking around with dynamic types, you might try `Data.Dynamic`, which builds atop `Data.Typeable`." } ]
[ { "body": "<p>EDIT: Faithfully representing OO semantics in Haskell is currently impossible. In particular, method resolution can be simulated (but not easily, and not quite faithfully) via type classes and instances. This <a href=\"https://research.microsoft.com/en-us/um/people/simonpj/papers/oo-haskell/\" rel=\"nofollow\">paper</a> is very informative about current best practice, and possible future evolution.</p>\n\n<p>Here is one possibility, which is similar to your first solution:</p>\n\n<pre><code>data ComponentClass a\n = ComponentClass {\n ...\n , comSubclass :: a\n ...\n }\ntype Component = ComponentClass ()\n\ndata ButtonClass a\n = ButtonClass {\n , buttonText :: Text\n , btSubclass :: a\n ...\n }\ntype Button = ComponentClass (ButtonClass ())\n</code></pre>\n\n<p>This is what I would do if I thought a simple hierachy fit my problem\ndomain well (but not necessarily to mirror the OO in another language).\nHowever, this strategy does not work well if you need to track deep\nhierarchies, or multiple superclasses (such as in Python).</p>\n\n<p>Another disadvantage is that you cannot deconstruct an arbitrary\n<code>ComponentClass a</code> into its subtype <code>a</code>. You can only do this if you\nknow the type of <code>a</code> in advance. However, you could use dynamic typing\nto fix this issue, such as via <code>Typable</code>.</p>\n\n<p>Note that you could also represent the hierachy in the up direction as well:</p>\n\n<pre><code>data ButtonClass a\n = ButtonClass {\n btText :: Text\n , btSuperClass :: a\n }\ntype Button = ButtonClass ComponentClass\n</code></pre>\n\n<p>You could then build each object \"down the class hierarchy\" until you\ndiscovered the most concrete type to wrap it up in.</p>\n\n<p>Also note that <a href=\"http://hackage.haskell.org/package/gtk\" rel=\"nofollow\">Gtk2Hs</a> uses a\ntypeclassing strategy similar to your second one to represent the class\nhierachy of Gtk. Perhaps a look at its source code would be edicational,\nor even just browsing its documentation on Hackage.</p>\n\n<p>Finally, the <code>Exception</code> hierachy implemented in <code>GHC</code> is quite interesting, though I don't think it would help you as much as either of the above---it's quite flat by comparison.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-04-09T13:09:26.710", "Id": "24902", "ParentId": "11715", "Score": "2" } } ]
{ "AcceptedAnswerId": "24902", "CommentCount": "1", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-05-12T09:55:44.820", "Id": "11715", "Score": "6", "Tags": [ "haskell" ], "Title": "Representing a Java Swing containment hierarchy in Haskell" }
11715
<p>I need to pass an array of values in <code>Url.Action</code>.</p> <p>Currently I'm doing:</p> <pre><code>var redirectUrl = Url.Action("search", new { q = criteria.Q, advanced = criteria.Advanced, salaryfrom = criteria.SalaryFrom, salaryto = criteria.SalaryTo, }); if (criteria.JobTypes != null) redirectUrl += criteria.JobTypes.Aggregate(string.Empty, (a, x) =&gt; a += "&amp;jobTypes=" + x); </code></pre> <p>To give me something like:</p> <pre><code>/search?q=developer&amp;advanced=false&amp;salaryfrom=20000&amp;salaryto=80000&amp;jobTypes=Full%20Time&amp;jobTypes=Contract </code></pre> <p>Is there a nicer/cleaner approach?</p>
[]
[ { "body": "<p>I assume you \"own\" the controller?\nIf so, I'd serialize and deserialize the list as a comma separated string on each side.\nIt'd also be nice if criteria.JobTypes is an empty list instead of a possible null, then you don't need the ?? below.</p>\n\n<pre><code>var redirectUrl = Url.Action(\"search\", new {\n // ...\n jobTypes = String.Join(criteria.JobTypes ?? new string[0], \",\")\n}\n</code></pre>\n\n<p>And do <code>jobTypes.split(\",\")</code> in the action.</p>\n\n<p>URL would look a bit nicer too:</p>\n\n<pre><code>/search?q=developer&amp;advanced=false&amp;salaryfrom=20000&amp;salaryto=80000&amp;jobTypes=Full%20Time,Contract\n</code></pre>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-05-14T08:22:06.460", "Id": "11743", "ParentId": "11716", "Score": "5" } }, { "body": "<p>To expand on Lars-Erik's answer, you can also use the other overload, <a href=\"http://msdn.microsoft.com/en-us/library/dd492912.aspx\" rel=\"nofollow\">the one that takes a dictionary</a>.<br>\nThis is also useful to construct e.g. an input that might or might not be disabled.</p>\n\n<pre><code>RouteValueDictionary args = new RouteValueDictionary {\n {\"q\", criteria.Q},\n {\"advanced\", criteria.Advanced},\n {\"salaryfrom\", criteria.SalaryFrom},\n {\"salaryto\", criteria.SalaryTo},\n};\nif(criteria.JobTypes != null) {\n // Either foreach the jobTypes or go Lars-Erik's way (nicer).\n args.Add(\"jobTypes\", \"foo\");\n}\n</code></pre>\n\n<p>Take care about special characters!<br>\nIf you don't fully control the input, you might get a jobType \"R&amp;D\" that will break your url: <code>/search?q=...&amp;jobTypes=R&amp;D</code> gets you <code>jobTypes=R</code>.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-06-13T08:55:24.353", "Id": "12524", "ParentId": "11716", "Score": "4" } }, { "body": "<p>You can add the array elements individually to the RouteValueDictionary -- you just have to change the name to match the model binding name for round trip purposes.</p>\n\n<p>The second argument to your action can be a RouteValueDictionary as ANeves said. </p>\n\n<pre><code>RouteValueDictionary rvd = new RouteValueDictionary { { \"name\", \"value\"}, ...};\nint i = 0;\ncriteria.JobTypes.ForEach(v =&gt; rvd.Add(String.Format(\"jobTypes[{0}]\", i++), (object) v));\n</code></pre>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2015-12-08T21:48:03.323", "Id": "113307", "ParentId": "11716", "Score": "3" } }, { "body": "<p>Instead of Type Casting to 'object<code>or</code>object[]<code>or using</code>RouteValueDictionary`. A simple way to achieve the same is using “Newtonsoft.Json”</p>\n\n<p><strong>If using .Net Core 3.0 or later;</strong></p>\n\n<p>Default to using the built in <code>System.Text.Json</code> parser implementation.</p>\n\n<pre><code>@using System.Text.Json;\n\n…….\n\n@Url.Action(“ActionName”, “ControllerName”, new {object = JsonConvert.SerializeObject(‘@ModalObject’) }))\n\n</code></pre>\n\n<p><strong>If stuck using .Net Core 2.2 or earlier;</strong></p>\n\n<p>Default to using Newtonsoft JSON.Net as your first choice JSON Parser.</p>\n\n<pre><code>@using Newtonsoft.Json;\n\n…..\n\n@Url.Action(“ActionName”, “ControllerName”, new {object = JsonConvert.SerializeObject(‘@ModalObject’) }))\n</code></pre>\n\n<p>you may need to install the package first.</p>\n\n<pre><code>PM&gt; Install-Package Newtonsoft.Json\n</code></pre>\n\n<p>Then, </p>\n\n<pre><code>public ActionResult ActionName(string modalObjectJSON)\n{\n Modal modalObj = new Modal();\n modalObj = JsonConvert.DeserializeObject&lt;Modal&gt;(modalObjectJSON);\n\n}\n</code></pre>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-04-04T17:29:29.493", "Id": "239934", "ParentId": "11716", "Score": "2" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-05-12T10:00:47.660", "Id": "11716", "Score": "9", "Tags": [ "c#", "asp.net-mvc-3" ], "Title": "Passing an array of values in Url.Action" }
11716
<p>I have a program where it takes the students name and last name and score and saves it. When checking to see if a <code>textbox</code> has information in it, I use <em>a lot</em> of <code>if</code> statements. Is there a cleaner way to do this?</p> <pre><code>public void CheckData() { if (first1.Text != empty &amp; score1.Text != empty &amp; last1.Text != empty &amp; first2.Text != empty &amp; score2.Text != empty &amp; last2.Text != empty &amp; first3.Text != empty &amp; score3.Text != empty &amp; last3.Text != empty &amp; first4.Text != empty &amp; score4.Text != empty &amp; last4.Text != empty &amp; first5.Text != empty &amp; score5.Text != empty &amp; last5.Text != empty) { student1 = new Student(first1.Text, last1.Text, Convert.ToInt32(score1.Text)); student2 = new Student(first2.Text, last2.Text, Convert.ToInt32(score2.Text)); student3 = new Student(first3.Text, last3.Text, Convert.ToInt32(score3.Text)); student4 = new Student(first4.Text, last4.Text, Convert.ToInt32(score4.Text)); student5 = new Student(first5.Text, last5.Text, Convert.ToInt32(score5.Text)); if (first6.Text != empty &amp; score6.Text != empty &amp; last6.Text != empty) { student6 = new Student(first6.Text, last6.Text, Convert.ToInt32(score6.Text)); if (first7.Text != empty &amp; score7.Text != empty &amp; last7.Text != empty) { student7 = new Student(first7.Text, last7.Text, Convert.ToInt32(score7.Text)); if (first8.Text != empty &amp; score8.Text != empty &amp; last8.Text != empty) { student8 = new Student(first8.Text, last8.Text, Convert.ToInt32(score8.Text)); if (first9.Text != empty &amp; score9.Text != empty &amp; last9.Text != empty) { student9 = new Student(first9.Text, last9.Text, Convert.ToInt32(score9.Text)); if (first10.Text != empty &amp; score10.Text != empty &amp; last10.Text != empty) { student10 = new Student(first10.Text, last10.Text, Convert.ToInt32(score10.Text)); if (first11.Text != empty &amp; score11.Text != empty &amp; last11.Text != empty) { student11 = new Student(first11.Text, last11.Text, Convert.ToInt32(score11.Text)); if (first12.Text != empty &amp; score12.Text != empty &amp; last12.Text != empty) { student12 = new Student(first12.Text, last12.Text, Convert.ToInt32(score12.Text)); if (first13.Text != empty &amp; score13.Text != empty &amp; last13.Text != empty) { student13 = new Student(first13.Text, last13.Text, Convert.ToInt32(score13.Text)); if (first14.Text != empty &amp; score14.Text != empty &amp; last14.Text != empty) { student14 = new Student(first14.Text, last14.Text, Convert.ToInt32(score14.Text)); if (first15.Text != empty &amp; score15.Text != empty &amp; last15.Text != empty) { student15 = new Student(first15.Text, last15.Text, Convert.ToInt32(score15.Text)); } } } } } } } } } } } else { MessageBox.Show("You need a Minimum of 5 Students"); } } </code></pre> <p><strong>Variables</strong></p> <pre><code>Student student1; Student student2; Student student3; Student student4; Student student5; Student student6; Student student7; Student student8; Student student9; Student student10; Student student11; Student student12; Student student13; Student student14; Student student15; string empty = ""; public class Student { string First { get; set; } string Last { get; set; } int Score { get; set; } public Student(string first, string last, int score) { first = First; last = Last; score = Score; } } </code></pre>
[ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-05-12T14:26:07.360", "Id": "18797", "Score": "4", "body": "You should have the textboxes and the students in a collection, not have fifteen variables." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-05-12T14:39:54.300", "Id": "18798", "Score": "0", "body": "Yikes! You certainly need to use right data structure(s) here to make your life simple. Also consider using a DataGridView instead of 32 TextBoxes, since you are working with a table essentially." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-05-12T15:15:22.853", "Id": "18799", "Score": "0", "body": "@Leonid Lol **45** Textboxes" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-05-12T15:16:33.990", "Id": "18800", "Score": "0", "body": "@svick Like a `Dictionary`?" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-05-12T15:58:41.580", "Id": "18802", "Score": "0", "body": "45 is an odd number ... so, not everything logically belongs in one table obviously. I have found it very useful to use separate panes - one for buttons at the bottom, one for the grid in the middle, and one for other inputs and controls at the top. Make sure to experiment with the Dock property for these panes. Since Winforms, unlike WPF are tied to a specific resolution, and can look like crap on a different screen (and maybe there is a better approach), I find it is much easier to implement the resizing logic when I use separate panes and docking. As far as collections, List<...> should do." } ]
[ { "body": "<p>First things first, that nesting is horrible! You could revert the conditions on the <code>if</code>s, and use a return to avoid using an <code>else</code>.</p>\n\n<pre><code>public void BadNesting() {\n if(cond1) {\n //...\n if(cond2) {\n // ...\n if(cond3) {\n //...\n }\n }\n }\n}\n\npublic void Better() {\n if(!cond1) {\n return;\n }\n // ...\n if(!cond2) {\n return;\n }\n // ...\n if(!cond3) {\n return;\n }\n // ...\n}\n</code></pre>\n\n<p>You also repeat your code a lot. We can use the suggestions to use a DataGridView and make the code magically expand to however many students you might get:</p>\n\n<pre><code>List&lt;Student&gt; Students;\npublic void CheckData(int minStudents = 5) {\n Students = new List&lt;Student&gt;();\n for (int i = 0; i &lt; gridView.Rows.Count; i++) {\n var row = gridView.Rows[i];\n TextBox firstName = (TextBox)row.Controls[0];\n TextBox lastName = (TextBox)row.Controls[1];\n TextBox scoreTB = (TextBox)row.Controls[2];\n\n string name = firstName.Text;\n string familyName = lastName.Text;\n int score;\n if (string.IsNullOrEmpty(name)\n || string.IsNullOrEmpty(familyName)\n || !int.TryParse(scoreTB.Text, out score)\n ) {\n // Will not parse any more students.\n if (i &lt; minStudents) {\n MessageBox.Show(string.Format(\"You need a minimum of {0} students\", minStudents));\n }\n break;\n }\n var student = new Student(name, familyName, score);\n Students.Add(student);\n }\n}\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-05-12T22:19:08.413", "Id": "18805", "Score": "0", "body": "Um, this is `wpf`, not `winforms`. No such thing as `DataGridView`" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-05-13T00:26:13.760", "Id": "18808", "Score": "0", "body": "Hehe, and now you get why my answer is community wiki. ;) But surely there is an equivalent control? Anyway, I would prefer @w0lf's answer." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-05-13T00:31:11.133", "Id": "18809", "Score": "0", "body": "Yes, but I my UserControl does not show up on wpf:P" } ], "meta_data": { "CommentCount": "3", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-05-12T18:04:22.080", "Id": "11720", "ParentId": "11718", "Score": "3" } }, { "body": "<p>The duplication problem can be solved using a custom UserControl, to encapsulate the controls used to edit a <code>Student</code>, as well as the validation.</p>\n\n<p>To define the control:</p>\n\n<ul>\n<li>right click you project in the Solution Explorer</li>\n<li>select Add -> UserControl...</li>\n<li>enter a name for the control (ex: StudentControl)</li>\n<li>press the Add button</li>\n</ul>\n\n<p>After adding the user control, you can design it just like you would any other form. Add all the controls needed for a single Student: the three textboxes (for example, <code>txtFirstName</code>, <code>txtLastName</code> and <code>txtScore</code>), as well as labels, if you consider necessary.</p>\n\n<p>Build your solution.</p>\n\n<p>After that, on your form, instead of the 45 textboxes, place 15 <code>StudentControl</code>s (you should find them in the Toolbox).</p>\n\n<p>Now, for the code part.</p>\n\n<p>Your control needs to be able to read a student from its controls, so inside the <code>StudentControl</code> class, add the following code:</p>\n\n<pre><code>public Student GetStudent()\n{\n if (txtFirstName.Text == String.Empty || \n txtLastName.Text == String.Empty || \n txtScore.Text == String.Empty)\n return null;\n\n return new Student(txtFirstName.Text, txtLastName.Text, int.Parse(txtScore.Text));\n}\n</code></pre>\n\n<p>Now your <code>CheckData()</code> method can be simplified like this:</p>\n\n<pre><code>public void CheckData()\n{\n var students = Controls.OfType&lt;StudentControl&gt;()\n .Select(studentControl =&gt; studentControl.GetStudent())\n .Where(student =&gt; student != null)\n .ToList();\n\n if(students.Count&lt;5)\n MessageBox.Show(\"You need a Minimum of 5 Students\");\n}\n</code></pre>\n\n<p>Doing this we've gained some advantages:</p>\n\n<ul>\n<li>we've reduced the duplication. If some day you have to add a new field for a Student, you only have to add it once, not 15 times. Also, if tomorrow you need you form to hold 10 or 20 students, that's a simple operation to perform in the form designer, with no code implications.</li>\n<li>we've separated concerns: now the user control handles the logic of editing a single student, while the form only knows that it has some <code>StudentControl</code> instances that are used to somewhow construct <code>Student</code> objects.</li>\n<li>the code got significantly smaller. This means that anyone can read and understand it faster, thus leading to better maintainability.</li>\n</ul>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-05-12T23:07:16.387", "Id": "18807", "Score": "0", "body": "Yeah validation is very good way to separate the concerns. For wpf look at IDataErrorInfo that will prevent you from doing those sorts of checks and keep the user informed. \"Prevention is better than cure\"" } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-05-12T18:43:22.050", "Id": "11721", "ParentId": "11718", "Score": "8" } } ]
{ "AcceptedAnswerId": "11721", "CommentCount": "5", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-05-12T14:10:22.013", "Id": "11718", "Score": "4", "Tags": [ "c#", "wpf" ], "Title": "Saving student scores" }
11718
<p>The problem can be <a href="http://mitpress.mit.edu/sicp/full-text/book/book-Z-H-15.html#%_sec_2.2.3" rel="nofollow">found online here</a>.</p> <p>In short, we're given the following function definition, that will recursively generate all the possible solutions for the "eight-queen-problem". </p> <pre><code>(define (queens board-size) (define (queen-cols k) (if (= k 0) (list empty-board) (filter (lambda (positions) (safe? k positions)) (flatmap (lambda (rest-of-queens) (map (lambda (new-row) (adjoin-position new-row k rest-of-queens)) (enumerate-interval 1 board-size))) (queen-cols (- k 1)))))) (queen-cols board-size)) </code></pre> <p>The problem consists of:</p> <ol> <li>implementing the representation of board positions and define <code>empty-board</code>.</li> <li>writing the function definitions for <code>adjoin-position</code> and <code>safe?</code></li> </ol> <p>The two following functions have already been defined in previous exercises:</p> <pre><code>(define (enumerate-interval low high) (if (&gt; low high) '() (cons low (enumerate-interval (+ low 1) high)))) (define (flatmap proc seq) (fold-rigth append '() (map proc seq))) </code></pre> <p>Here's my commented working solution. You'll find I express my ideas in Python a lot, because it's practically like writing pseudo-code and, sadly, it still governs pretty much the way I think of code. I'm looking for any kind of feedback, from how to improve execution time, to how to make it more readable or any Scheme good practice you may mention. I don't know anybody in real-life who codes in Scheme, so I seek feedback from the next best place :)</p> <pre><code>;; A set of position is a list of pairs. ;; The pairs are cons where the car is the value of the row and the cdr is the column. ;; Since we're recursively iterating through the board horizontally, the cdr can be seen as the index. (define empty-board '()) (define (adjoin-position row col board) (append board (list (cons row col)))) ;; in python there's the bracket syntax to return an element from a list: ;; f[3] returns the 4th element of f. I could not find such a thing in Scheme, so I wrote this function. (define (getposval pos idx) (caar (filter (lambda (pair) (= (cdr pair) idx)) pos))) ;; any/all (say it quickly it sounds like Annie Hall) are inspired by their Python equivalent. ;; Is there something similar in Scheme? (define (any? seq) (fold-right (lambda (x y) (or x y)) #f seq)) (define (all? seq) (fold-right (lambda (x y) (and x y)) #t seq)) ;; A position set is not safe if there exist i such as: ;; - pos[col] == pos[i] # they're on the same row ;; or ;; - abs(pos[col] - pos[i]) == col - i # they're on a diagonal (define (safe? col positions) (all? (map (lambda (x) (or (= col (cdr x)) ;; I should not write (getposval positions) so often ;; maybe replace it with a let? (not (or (= (getposval positions col) (getposval positions (cdr x))) (= (abs (- (getposval positions col) (getposval positions (cdr x)))) (- col (cdr x))))))) positions))) </code></pre>
[ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-05-16T20:28:26.543", "Id": "18960", "Score": "1", "body": "srfi-1 provides some of the utility functions you define. Look at `list-ref`, `every`, and `any`. Your particular dialect of scheme may also provide them without having to require them specifically." } ]
[]
{ "AcceptedAnswerId": null, "CommentCount": "1", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-05-12T17:56:50.803", "Id": "11719", "Score": "1", "Tags": [ "scheme", "sicp" ], "Title": "SICP ex. 2.42 \"eight queens puzzle\"" }
11719
<p>I have the following script that I'm part way through and I'm not happy with it at all, it feels messy:</p> <pre><code>&lt;?php class Process { public $search = 'http://api.themoviedb.org/2.1/Person.search/en/json/xxx/'; public $info = 'http://api.themoviedb.org/2.1/Person.getInfo/en/json/xxx/'; public function returnId($name){ return $this-&gt;returnJson($this-&gt;search . $name); } public function returnMovies($id){ return $this-&gt;returnJson($this-&gt;info . $id); } public function returnJson($url){ $raw = file_get_contents($url); $json = json_decode($raw, true); return $json; } } $p = new Process(); $first = urlencode($_POST['first']); $second = urlencode($_POST['second']); $id = $p-&gt;returnId($first); $movies = $p-&gt;returnMovies($id[0]['id']); </code></pre> <p>Now the idea is that two parameters get sent to this script and each of them run through the first API call (<code>$search</code>) and then the ID field is extracted from that results and passed into the <code>$info</code> URL call. The two arrays that come back from <code>returnMovies</code> will be compared with each other and any matches will be popped into another array.</p> <p>Now, has anyone got any way for this to be better in structure and cleanliness?</p> <p>It's not finished yet but its a simple script that I'd like to tidy up before I go on.</p>
[]
[ { "body": "<p>I'd start firstly by moving your <code>urlencode()</code> into the class... You should assume that everything passed to a method is unclean and therefore act appropriately.</p>\n\n<p>Secondly, I'd give the class a meaningful name - <code>Process</code> isn't entirely descriptive.</p>\n\n<p>Throw some comments in - follow a set standard such as the PHPDoc format, using @param, @return etc. Always handy to have, even if the code doesn't become public or used by others.</p>\n\n<p>Look at your public/private declarations - or lack of. Personally, I'd look to make your <code>$search</code> and <code>$info</code> URLs private, as well as your <code>returnJson()</code> method.</p>\n\n<p>I'd possibly look to use cURL instead of <code>file_get_contents()</code> - due to some server configs disabling that etc. </p>\n\n<p>Anyway, just a few suggestions!</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-05-13T19:54:03.817", "Id": "11733", "ParentId": "11722", "Score": "4" } }, { "body": "<p>I agree with Michael Wright completely +1, I only have a few additions.</p>\n\n<p>If both of those URLs are that similar you should use a URL header and append the differences to each in their respective variables. Saves having to change it multiple times should the URL ever change.</p>\n\n<pre><code>private $urlHeader = 'http://api.themoviedb.org/2.1/';\npublic $search = $url_header . 'Person.search/en/json/xxx/';\npublic $info = $url_header . 'Person.getInfo/en/json/xxx/';\n</code></pre>\n\n<p>I would try and find some way of combining <code>returnId()</code> and <code>returnMovies()</code>. As they are so similar it would be a shame not to reuse it. I first thought to use a switch statement, but that would create as much work and mess as using two separate methods, so thats no good. Second, I thought of variable-variables. I don't much like variable-variables, but it was the first \"clean\" idea to pop into my head. I say that last with a shudder. However, a third solution came to me as I was writting the variable-variable solution out. If you don't use those URL variables (<code>$search</code> and <code>$info</code>) anywhere else, you could just set it on the fly.</p>\n\n<pre><code>public function returnInfo($search, $method = 'search'){\n $url = \"http://api.themoviedb.org/2.1/Person.$method/en/json/xxx/\";\n return $this-&gt;returnJson($url . $search);\n}\n</code></pre>\n\n<p>Because each method basically only changed a part of the URL before passing it to <code>returnJson()</code>, I passed that part as an argument to save time. I also gave it a default setting so it wouldn't always have to be passed. However, for legibility, this is only advisable if you find yourself using more than the two methods you already have.</p>\n\n<p>Here's the variable-variable solution, also with a default URL.</p>\n\n<pre><code>public function returnInfo($search, $url = 'search'){\n return $this-&gt;returnJson($this-&gt;$url . $search);\n}\n</code></pre>\n\n<p><strong>Disclaimer:</strong> I am not condoning the use of variable-variables, merely showing it. I wouldn't have even shown it if I hadn't already typed it, but I did, so here it is. I really would not suggest its use. They are very confusing, even if well documented.</p>\n\n<p>And finally, since you are only using <code>returnJson()</code> inside the class, you should make it a private method. No need to give everyone access to it if you don't plan on letting them use it.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-05-14T13:57:16.900", "Id": "11748", "ParentId": "11722", "Score": "0" } } ]
{ "AcceptedAnswerId": "11733", "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-05-12T19:09:59.123", "Id": "11722", "Score": "2", "Tags": [ "php", "object-oriented", "api" ], "Title": "Two similar API calls PHP optimisation and structure" }
11722
<p>This falls straight into the same category with the recent "<em><a href="https://codereview.stackexchange.com/questions/11544/is-it-better-practice-to-return-if-false-or-execute-an-if-statement-if-true">Is it better practice to return if false or execute an if statement if true?</a></em>" question.</p> <p>Often, while writing code, I find myself presented with two options. Either I can do this:</p> <pre><code>public void myMethod() throws Exception { // Some code validate(some_object_or_condition); // Some code } private void validate(Object arg) throws Exception { // Code that validates the argument and throws an exception if it's invalid } </code></pre> <p>Or this:</p> <pre><code>public void myMethod() throws Exception { // Some code if( !isValid(some_object_or_condition) ) throw new Exception(); // Some code } private boolean isValid(Object arg) { // Code that returns a boolean based on whether or not the argument is valid } </code></pre> <p>Is either one preferable over the other? When I was still just learning Java the latter felt more "object oriented" and somehow more natural. However, with experience the former has started to feel better because then the code looks cleaner to me, but I'm afraid people might find it less readable.</p> <p><strong>Edit/Add:</strong> This time I ran into this problem when implementing a game (just for the fun of it) where the user would place words into a grid. The <code>playWord</code> method may fail because of the word not actually being a real word (yielding an InvalidWordException) or because the user is trying to place a valid word into an illegal position (yielding a WordPlacementException). If the method does not fail, it should return the score of the word as an integer. So in my case the playWord method first calls the method that validates the word and later the method that validates the location of the word, and these provoked this question here.</p>
[]
[ { "body": "<p>There's quite a few questions about this on stackoverflow but I think my general rule tends to be leave exceptions for exceptional circumstances and booleans for where failure occurances is an accepted/known possible behaviour. </p>\n\n<p>So I personally probably prefer your option 2 (interested to see what others think), where if anything the exception is thrown a bit higher up the chain. That way I could re-use the isValid logic elsewhere and deal with the failure without needing to wrap it in an exception handler.</p>\n\n<p>Of course, I think this is probably a case by case basis and depends on the kind of logic being checked.</p>\n\n<p>I'm sure I remember a really good Q&amp;A on this somewhere but can't quite find it. However found a couple of discussions:</p>\n\n<p><a href=\"https://stackoverflow.com/questions/5230978/is-it-a-good-practice-to-throw-an-exception-on-validate-methods-or-better-to-r\">Throw exception or return boolean - SO</a> </p>\n\n<p><a href=\"https://stackoverflow.com/questions/2972307/when-to-return-bool-throw-an-exception-and-which-exception-to-throw\">Throwing exceptions - SO</a></p>\n\n<p>EDIT: To further comment after the edits, perhaps you could also consider the option of returning status codes (enums) instead of the exceptions if there are a number of options. This has the benefit of being more efficient however as some have mentioned on SO could expose unecessary workings if this is a API or assembly. Some links I found on SO about this with some good discussions were:</p>\n\n<p><a href=\"https://stackoverflow.com/questions/1799217/exception-or-error-code-enum\">Exception or error code enum</a>\n<a href=\"https://stackoverflow.com/questions/4415573/to-use-error-codes-or-not-to-use-error-codes\">to use error codes or not</a></p>\n\n<p>And there were more. I see this coming down to a few options.</p>\n\n<ol>\n<li>Throw exception</li>\n<li>Return true/false</li>\n<li>Return a status/error code enum</li>\n</ol>\n\n<p>All probably have their place. Exceptions do occur the most overhead so if performance is an issue or the routine is called in many places perhaps this is not the best solution. I also saw mention that it was not necessarily a good idea to use exceptions to control the flow of application logic which it would seem to be doing in your case?</p>\n\n<p>Basically my thoughts are to use return true/false, use a status error code, and then exceptions in that order.</p>\n\n<p>An alternative suggestion might be something along the lines of (whether it's a decent alternative or not hopefully someone might comment on ???):</p>\n\n<pre><code>public int playWord(string w) {\n Word word = new Word(word);\n if (word.isValid()) {\n return word.getScore();\n } else {\n throw new InvalidDataException(word.GetErrorMessage());\n }\n}\n\nclass Word {\n private String word;\n private String errorMessage = null;\n\n public Word(string w) {\n word = w;\n }\n\n public boolean IsValid() {\n // TODO: perform various checks calling private methods as required and if fail store against errorMessage\n return errorMessage == null;\n }\n\n public String GetErrorMessage() {\n return errorMessage;\n }\n\n public int getScore(string word) {\n // return the score of the word no matter what it is\n }\n}\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-05-13T22:03:05.283", "Id": "18820", "Score": "0", "body": "Hey, thanks for the links. I indeed didn't take a look at SO before posting this because SO is not generally very welcoming for these kinds of questions where a definite answer may not exist and where there's no broken code. \n\nThe problem with leaving exceptions for exceptional circumstances is how to define when a circumstance is exceptional enough. I've edited my post to contain a practical example (or two, if you want to read it that way), could you please take a look at it again?" } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-05-12T23:52:43.797", "Id": "11725", "ParentId": "11724", "Score": "11" } }, { "body": "<p>Returning a Boolean seems more natural to me. It gives you the option to handle this condition in different ways, depending on the situation. The <code>IsValid</code> method has only one very specific task, which is to determine if the object is valid. This follows <a href=\"http://en.wikipedia.org/wiki/Single_responsibility_principle\">SRP</a>, the single responsibility principle, which states that a code entity (class, method, component) should have only one responsibility.</p>\n\n<pre><code>if(IsValid(obj))\n Save(obj);\nelse\n Messagebox.Show(\"Please enter a valid code\");\n</code></pre>\n\n<p>In another context the same <code>IsValid</code> method can be reused without any changes</p>\n\n<pre><code>if(!IsValid(obj))\n throw new WhateverException();\n</code></pre>\n\n<p>Note: Wikipedia defines SRP on classes; however this principle can be applied to different levels of granularity.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-05-13T21:41:16.833", "Id": "18818", "Score": "0", "body": "The `validate` method also has the same single specific task, it just expresses the result in a different way. Actually, I think you could argue that `myMethod` follows the single response principle better when it calls the `validate` method!" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-05-13T21:56:11.863", "Id": "18819", "Score": "1", "body": "I am not a SRP purist; however, I would say that your method (which is OK) validates AND throws an exception if the test fails and therefore does two things. Of cause you can argue that this is just another way of returning a result, but it influences the flow of execution as well. I am just telling my personal preference; both solutions are OK." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-05-15T22:22:47.997", "Id": "18897", "Score": "0", "body": "Thanks for your opinion. :) For the sake of discussion I'd like to add that actually the playWord method originally implemented the validation code in itself and it used to throw an exception. In order to keep the code clean I then refactored the validation part into its own private method. So basically the exception-throwing `validate()` would just be a copy-paste creation, whereas with `isValid()` I'd actually need to add a little something." } ], "meta_data": { "CommentCount": "3", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-05-13T00:25:46.110", "Id": "11726", "ParentId": "11724", "Score": "6" } }, { "body": "<p>The answer is it depends, or both.</p>\n\n<ol>\n<li>If you are the user of that method, and know this is an infrequent occurrence, throw exceptions.</li>\n<li>If you are user of the method, and know it is a frequent error, use booleans.</li>\n<li>If you don't know the frequence because you are not the only user, have a Try pattern. I.e.</li>\n</ol>\n\n<p><code>public void MyMethod throws ArgumentException { }</code></p>\n\n<p>And</p>\n\n<pre><code>public bool TryMyMethod\n{\n}\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-05-13T22:05:01.070", "Id": "18821", "Score": "0", "body": "These are nice rules of thumb, but the problem with this approach is how to define \"frequent\" and \"infrequent\". I've edited my post to contain an example, could you please take a look at it again?" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-05-14T08:31:44.310", "Id": "18833", "Score": "0", "body": "@ZeroOne that's an IsValid imo. User input will frequently be invalid, doesn't make sense to inccur the overhead of an exception to validate it." } ], "meta_data": { "CommentCount": "2", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-05-13T06:37:08.030", "Id": "11729", "ParentId": "11724", "Score": "3" } }, { "body": "<p>There's another option that is used more frequently in some other languages, which is to return the exception. This makes some sense when failure is not really exceptional and can be ignored in some cases. </p>\n\n<pre><code>public void myMethod() throws Exception {\n // Some code\n Exception e = validate(some_object_or_condition);\n if(e!=null) throw e;\n // Some code\n}\n\nprivate Exception validate(Object arg) {\n if(...) { \n return new Exception(...);\n }\n ...\n return null; \n}\n</code></pre>\n\n<p>Now admittedly in many cases this looks pretty cumbersome, but where it really shines is when you start to need inversion of control or callbacks (where you pass the return values and exceptions to the callbacks rather than return them directly.)</p>\n\n<p>When inversion of control is used this often looks like</p>\n\n<pre><code>public void myMethod() {\n Validator validator = getValidator();\n ErrorHandler eh = getErrorHandler();\n validator.validate(some_object_or_condition, eh);\n}\n\npublic abstract class ErrorHandler {\n public void process(Exception e);\n}\n\npublic void myMethod() throws Exception {\n // Some code\n Exception e = validate(some_object_or_condition);\n if(e!=null) throw e;\n // Some code\n}\n\nclass Validator \n private void validate(Object arg, XYZ xyz) {\n if(...) {\n xyz.process( new Exception(...) );\n return;\n }\n ...\n xyz.process(null); \n}\n</code></pre>\n\n<p>Again this can be uglier than the pure throw, or boolean return style, but in some cases it can result in more testable and code that can work better in a multi-threaded environment.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-02-05T03:31:52.423", "Id": "70082", "Score": "0", "body": "Wouldn't that be a misuse of a class? Repurposing a class just because it's convenient. I suggest that you could return something else (a Validation object, perhaps), and provide a facility to turn that into an Exception (`throw new ValidationException(validation)`). An example of what you suggest is Spring's BindException: I think Spring's Errors interface is reasonable, but the decision to have BindException implement Errors is one of Spring's odder ones." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-02-05T07:39:31.030", "Id": "70119", "Score": "0", "body": "One reason for returning an exception, rather than your own class, is that the type heirachy is already there and users are likely to be familiar with it. Also it them makes it easy if you decide later that it is \"fatal\" and you can throw it. Javascript captures the call stack at the point an exception is constructed, rather than (or in addition to) when it is thrown - solving another issue that often occurs with using your own custom error reporting class. However I'm not sure what java does on that front." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-02-05T08:33:52.397", "Id": "70129", "Score": "0", "body": "Yes, it does make things easier to do it that way. But the class isn't a kind-of Exception. Encapsulation is appropriate, but not inheritance, IMO." } ], "meta_data": { "CommentCount": "3", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-02-05T00:49:24.983", "Id": "40906", "ParentId": "11724", "Score": "0" } }, { "body": "<p>Return the boolean (or better, return a meaningful object as suggested by Michael Anderson). If the validation failure is invalid, the calling method can choose to throw an exception.</p>\n\n<p>That way, <code>isValid()</code> can throw an exception <em>if there is an error while validating</em> (perhaps loading a dictionary fails). This separates normal flow from exception processing.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-02-05T03:35:22.067", "Id": "40914", "ParentId": "11724", "Score": "1" } }, { "body": "<p>It is interesting that everyone is saying boolean. While booleans can be useful exceptions are extremely powerful and offer you a lot of flexibility. Booleans leaves a hole for people who aren't paying attention to not validate that the function worked. With exceptions a single function can have multiple reasons for failure and each exception will explain that failure. Sometimes one failure is acceptable while another is not. This way you can catch one failure and just throw the others up the chain.</p>\n\n<pre><code>public void validate(String top, String bottom) {\n if(top == \"\") {\n throw EmptyTopException(\"You forgot to put something on the top\");\n }\n if(bottom == \"\") {\n throw EmptyBottomException(\"You forgot to put something on the bottom\");\n }\n}\n\npublic void main(String args[]) {\n try {\n validate(\"spire\", \"foundation\");\n }\n catch(EmptyTopException ex) {\n System.out.println(\"The top was empty we will have a shorter tower\");\n }\n catch(EmptyBottomException ex) {\n throw new Exception(\"There was no foundation this tower is not physically possible\", ex);\n }\n}\n</code></pre>\n\n<p>It can get a little big with a lot of try catches but as you can see you can fail for two different reasons here. one which doesn't really make a difference and another that will tell the user that the input can not be accepted.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-03-27T14:33:09.447", "Id": "45505", "ParentId": "11724", "Score": "1" } } ]
{ "AcceptedAnswerId": "11725", "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-05-12T22:28:02.763", "Id": "11724", "Score": "16", "Tags": [ "java", "validation", "exception" ], "Title": "Is it better practice to have void method throw an exception or to have the method return a boolean?" }
11724
<p>I created a small Android project with an AsyncTask. It simulates a time consuming task.</p> <p>Please review my code and tell me what you would do on a different way and why. Comments not specific to Android but general software development are welcome.</p> <p>CounterTask.java:</p> <pre><code>package my.tasks; import java.util.Random; import android.app.AlertDialog; import android.app.AlertDialog.Builder; import android.app.Dialog; import android.app.ProgressDialog; import android.os.AsyncTask; import android.util.Log; /** * @author 2 * * Simulates a time consuming task, counts in the background from 0 to * the given value in first parameter. Its progress is published via an * integer which is a percentual value 0..100. The task may not * complete, it may fail or it may be cancelled by the user. In case of * success it returns true. */ public class CounterTask extends AsyncTask&lt;Integer, Integer, Boolean&gt; { private static final long DELAY = 100; private static final int PROBABILITY_TO_FAIL_EVERY_STEP = 1; private static final String TAG = "CounterTask"; private ProgressDialog progressDialog; private Random random; /** * @param progressDialog * a ProgressDialog the task can use to display its progress. */ public CounterTask(ProgressDialog progressDialog) { this.progressDialog = progressDialog; this.progressDialog.setMax(100); this.random = new Random(); } /* * (non-Javadoc) * * @see android.os.AsyncTask#doInBackground(Params[]) * * Set params[0] to the maximum value you want the task to count to. */ @Override protected Boolean doInBackground(Integer... params) { validateParams(params); int count_max = params[0]; for (int i = 0; i &lt; count_max; i++) { int progressPercent = calculateProgressPercent(i, count_max); publishProgress(progressPercent); Log.i(TAG, "Counter: " + Integer.toString(i)); Log.i(TAG, "Progress published: " + Integer.toString(progressPercent) + "%"); if (sleep() == false) { return false; } if (doesFail(PROBABILITY_TO_FAIL_EVERY_STEP)) { Log.i(TAG, "Background fails."); return false; } } Log.i(TAG, "Background succeeds."); return true; } @Override protected void onCancelled() { super.onCancelled(); Log.i(TAG, "Background cancelled."); } @Override protected void onPostExecute(Boolean result) { super.onPostExecute(result); progressDialog.dismiss(); String message = null; if (result) message = "Background succeeded."; else message = "Background failed."; Log.i(TAG, message); createAlertDialog(message).show(); } private Dialog createAlertDialog(String message) { AlertDialog.Builder builder = new Builder(progressDialog.getContext()); AlertDialog dialog = builder.setMessage(message).setTitle("Result").setCancelable(true).create(); return dialog; } @Override protected void onProgressUpdate(Integer... values) { super.onProgressUpdate(values); progressDialog.setProgress(values[0]); } /** * Helper method to decide if the task fails in this step. * * @param probabilityToFail * Value 0..100 the probability to fail. * @return true if it fails, false if not */ private boolean doesFail(int probabilityToFail) { int prob = random.nextInt(100); if (prob &lt; probabilityToFail) return true; else return false; } /** * The thread sleeps from step to step to simulate a time consuming task. * * @return */ private boolean sleep() { try { Thread.sleep(DELAY); } catch (InterruptedException e) { return false; } return true; } private int calculateProgressPercent(int done, int max) { done = done * 100; return done / max; } private void validateParams(Integer... integers) { if (integers == null || integers.length != 1 || integers[0] &lt; 0) throw new IllegalArgumentException(); } } </code></pre> <p>MainActivity.java:</p> <pre><code>package my.application; import my.tasks.CounterTask; import android.app.Activity; import android.app.ProgressDialog; import android.content.DialogInterface; import android.content.DialogInterface.OnCancelListener; import android.os.Bundle; import android.view.View; import android.view.View.OnClickListener; import android.widget.Button; public class MainActivity extends Activity implements OnClickListener, OnCancelListener { private CounterTask counterTask; @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.main); Button startButton = (Button) findViewById(R.id.startButton); startButton.setOnClickListener(this); } @Override public void onClick(View view) { int id = view.getId(); switch (id) { case R.id.startButton: ProgressDialog progressDialog = createProgressDialog(); progressDialog.show(); CounterTask ct = new CounterTask(progressDialog); counterTask = (CounterTask) ct.execute(100); break; default: break; } } private ProgressDialog createProgressDialog() { ProgressDialog progressDialog = new ProgressDialog(this); progressDialog.setProgress(0); progressDialog.setMax(100); progressDialog.setTitle("Progress"); progressDialog.setCancelable(true); progressDialog.setOnCancelListener(this); progressDialog.setProgressStyle(ProgressDialog.STYLE_HORIZONTAL); return progressDialog; } @Override public void onCancel(DialogInterface arg0) { counterTask.cancel(true); } } </code></pre>
[]
[ { "body": "<p>Looks good. You could put the progressDialog creation and show in onPreExecute: <a href=\"http://developer.android.com/reference/android/os/AsyncTask.html#onPreExecute\" rel=\"nofollow\">http://developer.android.com/reference/android/os/AsyncTask.html#onPreExecute</a>() . It will run in the UI thread and will encapsulate more of the dialog logic.</p>\n\n<p>You can cut out a few lines here</p>\n\n<pre><code>String message = null;\nif (result)\n message = \"Background succeeded.\";\nelse\n message = \"Background failed.\";\n</code></pre>\n\n<p>becomes</p>\n\n<pre><code>String message = result ? \"Background succeeded.\" : \"Background failed\";\n</code></pre>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-05-15T00:12:16.677", "Id": "11760", "ParentId": "11730", "Score": "3" } }, { "body": "<p>Conditional operator can be used to improve the following method:</p>\n\n<pre><code>private boolean doesFail(int probabilityToFail) {\n\n int prob = random.nextInt(100);\n if (prob &lt; probabilityToFail)\n return true;\n else\n return false;\n}\n</code></pre>\n\n<p>Can be improved as </p>\n\n<pre><code>private boolean doesFail(int probabilityToFail) {\n return (random.nextInt(100) &lt; probabilityToFail);\n}\n</code></pre>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-04-01T07:38:25.533", "Id": "45919", "ParentId": "11730", "Score": "1" } }, { "body": "<ul>\n<li>do not pass ProgressDialog as parameter in constructor \n(what will happend when activity will be recreated and task is still running or finished?) read more about <strong>SERIALIZATION</strong> </li>\n<li>don't use keyword this in constructor if u not calling other constructor involving creation of its object or using it as a qualifier when referencing fields</li>\n<li><p>use onPreExecute() to show ProgressDialog like this:</p>\n\n<pre><code>@Override\nprotected void onPreExecute() {\n /** show progress dialog */\n showProgressDialog(_context,_message);\n}\n\n/** show pd method */\nprivate void showProgressDialog(Context context, String message) {\n /** check if progress dialog is not already created or if context didn't changed - eg. during screen rotation */\n if(_progressDialog == null || _progressDialog.getContext().equals(context)) {\n /** create progress dialog */\n _progressDialog = new ProgressDialog(context);\n _progressDialog.setCancelable(false);\n }\n /** set message */\n _progressDialog.setMessage(message);\n /** show pd */\n _progressDialog.show();\n}\n</code></pre></li>\n<li><p>always find places when your task could be terminatet by you or other factors and try dismiss progress dialog </p>\n\n<pre><code>private void dismissProgressDialog() {\n try {\n /** check if progress dialog is showing */\n if (_progressDialog != null &amp;&amp; _progressDialog.isShowing()) {\n /** dismiss login dialog */\n _progressDialog.dismiss();\n }\n } catch (Exception e) {\n // Handle or log or ignore\n } finally {\n _progressDialog = null;\n }\n}\n</code></pre>\n\n<ul>\n<li><p>onPostExecute you should dismiss progress dialog not showing it </p></li>\n<li><p>to show your result create a callback to Activity</p></li>\n</ul></li>\n</ul>\n\n<p>define interface:</p>\n\n<pre><code>public interface AsyncTaskResultListener&lt;T&gt; {\n\n /** notifies Activity when task is done.\n * @return true if result parsed OK\n * other way false to repeat with RepeatTask()*/\n boolean onTaskComplete(T result);\n void repeatTask();\n}\n</code></pre>\n\n<p>in async task:</p>\n\n<pre><code> AsyncTaskResultListener&lt;T&gt; _callback;\n Context _context;\n\n MyAsyncTask(Context context) {\n /** check for valid context */\n if(Activity.class.isAssignableFrom(context.getClass()) {\n _contex = context;\n /** check for valid callback */\n if(AsyncTaskResultListener.class.isAssignableFrom(context.getClass()) {\n /** cast it to interface */\n _callback = (AsyncTaskResultListener&lt;T&gt;) context;\n }\n }\n }\n\n @Override\n protected void onPostExecute(T result) {\n if(_callback!=null) {\n if(!callback.onTaskComplete(result) {\n /** repeat task */\n callback.repeatTask()\n }\n }\n /** dismiss pd */\n }\n</code></pre>\n\n<p>in activity:</p>\n\n<pre><code>public MyActivity exrtends Activity implements AsyncTaskResultListener&lt;T&gt; {\n\n @Override \n boolean onTaskComplete(T result) {\n /** do work with your result \n if satisfied return true, to repeat task return false */\n return true;\n }\n\n @Override\n public void repeatTask() {\n /** free to make decision what to do */\n }\n}\n</code></pre>\n\n<p>i got little more to point out but my hands have enough</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2015-07-02T09:30:36.523", "Id": "95560", "ParentId": "11730", "Score": "0" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-05-13T07:05:26.933", "Id": "11730", "Score": "2", "Tags": [ "java", "android" ], "Title": "Small Android AsyncTask project" }
11730
<p>I have a list of resources which can be voted on. There are 3 voting states: upvoted, downvoted and no vote.</p> <p>In a fashion identical to Stack Exchange voting, it follows these rules:</p> <ol> <li>If you upvote a post you've already upvoted, it will set it to 'no vote'</li> <li>If you upvote a post set to 'no vote' it will set it to upvote</li> <li><strong>if you downvote a post you've upvoted, it will set it to 'downvote'</strong> (I bolded this because in another post everyone gave me grief that this way is 'stupid', yet every voting site I have seen uses this style... Reddit, Digg. Stack Overflow, etc)</li> </ol> <p>The exact same rules (except inverse) hold true for downvote.</p> <p>Here's how I call my <code>sendVote()</code> function, when you click on upvote or downvote:</p> <pre><code> // Voting $('.res-list').delegate('.vote .up', 'click', function() { flashColor($(this),'#fffc00'); sendVote($(this).parent(),'upvoted'); return false; }); $('.res-list').delegate('.vote .down', 'click', function() { flashColor($(this),'#fffc00'); sendVote($(this).parent(),'downvoted'); return false; }); </code></pre> <p>I believe that above code is fine, but his code below is what I feel is awful and could really be refactored, but I don't know how. I'm kind of new to JavaScript and jQuery.</p> <pre><code>function sendVote(object, direction) { var votesContainer = $(object).find('.m p'); var votes = parseInt($(votesContainer).html()); // UPVOTED if (direction == 'upvoted') { if ($(object).hasClass('downvoted')) { // Overwrite Downvote $(votesContainer).html(votes + 2); $(object).removeClass('downvoted'); $(object).addClass(direction); } else if ($(object).hasClass(direction)) { // Undo Upvote $(votesContainer).html(votes - 1); $(object).removeClass(direction); } else { // Do Upvote $(votesContainer).html(votes + 1); $(object).addClass(direction); }; // Ajax function here to /votes/upvote?id=x // DOWNVOTED } else { if ($(object).hasClass('upvoted')) { // Overwrite Upvote $(votesContainer).html(votes - 2); $(object).removeClass('upvoted'); $(object).addClass(direction); } else if ($(object).hasClass(direction)) { // Undo Downvote $(votesContainer).html(votes + 1); $(object).removeClass(direction); } else { // Do Downvote $(votesContainer).html(votes - 1); $(object).addClass(direction); }; // Ajax function here to /votes/downvote?id=x } } </code></pre>
[]
[ { "body": "<p>Both portions of code could be simplified if you use numbers, instead of words, to represent upvotes and downvotes. So I would change your calls to <code>sendVote</code> to look like this:</p>\n\n<pre><code>sendVote(this.parentNode, 1);\nsendVote(this.parentNode, -1);\n</code></pre>\n\n<p>When modifying elements with javascript, I suggest using <code>element.style.x</code> (or <code>element.style.cssText</code> for multiple attributes) instead of classes, where possible. This is more efficient (browser doesn't have to re-test css selectors for the rest of the page), simpler (don't have to polyfill classList), and it means putting javascript-only css in js files, which means they aren't loaded in browsers that don't support javascript and therefore don't want them anyway. But the main reason is that is allows you to shorten your code to this:</p>\n\n<pre><code>var voteCSS = {\n '1': 'background:blue;',\n '0': 'background:grey;',\n '-1': 'background:red;'\n};\n\nfunction sendVote(element, newVote) {\n var countEl = element.querySelector('.m p'),\n prevVote = +element.dataset.prevVote || 0;\n\n if (newVote == prevVote)\n newVote = 0;\n countEl.innerHTML = +countEl.innerHTML - prevVote + newVote;\n element.dataset.prevVote = newVote;\n element.style.cssText = voteCSS[newVote];\n // ajax here to /votes/submit?id=x&amp;direction=`newVote`\n}\n</code></pre>\n\n<p>Alternatively, if you want to keep all your CSS in one place, you can make sure that \"upvoted\" or \"downvoted\" is the only class the element has, then just use <code>.className</code>. You could still apply default styling by selecting it from above, something like this: <code>.votecontainer div {}</code>.</p>\n\n<p>ps: notice that I didn't use jQuery even once. Try to solve your problems without jQuery before you let yourself use it - a lot of the time you'll find that your solutions are simpler and more efficient without it.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-05-14T01:37:13.473", "Id": "11739", "ParentId": "11732", "Score": "4" } } ]
{ "AcceptedAnswerId": "11739", "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-05-13T18:21:44.133", "Id": "11732", "Score": "3", "Tags": [ "javascript", "jquery", "state-machine" ], "Title": "State machine for upvoting/downvoting" }
11732
<p>The goal is to</p> <ul> <li>make an object that persists upon page reloads,</li> <li>have an interface as close as possible to the <code>Object</code> class.</li> </ul> <pre><code>function PersistentObject(key,initial_value) //use for(..in data.keys()) instead of for(..in data) { var ret; if(localStorage[key]) ret=JSON.parse(localStorage[key]); if(!ret) ret = initial_value; if(!ret) ret = {}; //JSON.stringify ignores put and keys functions ret.put=function() { localStorage[key]=JSON.stringify(this) }; ret.keys=function() { var res = {}; for(var prop in this) if(this[prop] !== this.put &amp;&amp; this[prop] !== this.keys) res[prop]=true; return res; }; return ret; } </code></pre> <p>The code is used as follows:</p> <pre><code>var myPersistentObject = new PersistentObject('myPersistentObject'); var myPersistentArray = new PersistentObject('myPersistentArray',[]); </code></pre> <p>Unfortunately there is AFAIK no way to get the name of the variable and therefore the name of the variable needs to be passed as first argument.</p> <p>Also unfortunate is that the function <code>keys</code> needs to be called in order to iterate over the object. I'm aware of the <code>defineProperty</code> function that allow to add a propoerty that is not enumerable but AFAIK cross browser compability is an issue with <code>defineProperty</code>.</p>
[]
[ { "body": "<p>It is impossible to know the variable name without passing it separately because the name is not part of the object itself, but only one (of potentially many) signs pointing to that object. Expecting the object to know that variable name is like expecting a building to know which road you drove in on. Besides, specifying the localStorage key separately is a good thing - it allows you to refer to the same key using different names in different parts of the program.</p>\n\n<p>You can get around having your methods show up in for-in loops by using getters instead of properties or prototypes. If you're concerned about compatibility, you can fallback to <code>__defineGetter__</code>.</p>\n\n<p>Here's what I came up with.</p>\n\n<pre><code>function localObject(key) {\n var _this = JSON.parse(localStorage[key] || '{}');\n Object.defineProperty(_this, 'save', {\n get: function () {\n return function () {\n localStorage[key] = JSON.stringify(this);\n };\n }\n });\n return _this;\n}\n</code></pre>\n\n<p>The <code>new</code> is optional - you can write both</p>\n\n<pre><code>var scores = new localObject('highscores'); // and\nvar scores = localObject('highscores');`.\n</code></pre>\n\n<p>While the above solution works, it is somewhat inefficient and messy. This stems from the fact that you're trying to get javascript to work the way you want, when what you should be doing is trying to understand how javascript wants to work. Each language has a style, even a personality, and if you're flexible enough to go with it then your code will be shorter, faster, and cleaner. Here's how I would abstract away my JSONification.</p>\n\n<pre><code>function local(key, value) {\n if (value === undefined) {\n return key in localStorage ? JSON.parse(localStorage[key]) : undefined;\n } else {\n localStorage[key] = JSON.stringify(value);\n return value;\n }\n}\n</code></pre>\n\n<p>Now we can write code like this:</p>\n\n<pre><code>var score = local('highscore');\n// use score like a normal variable, because it is one. then, eventually:\nlocal('highscore', score);\n</code></pre>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-05-15T05:16:32.810", "Id": "11767", "ParentId": "11747", "Score": "2" } }, { "body": "<p>I think you are making things more complicated than they need to be. Wouldn't it be simpler to use a library such as <a href=\"https://github.com/marcuswestin/store.js\" rel=\"nofollow\">store.js</a> and just do:</p>\n\n<pre><code>var o = store.get('someObject');\nif (!o) o = new SomeClass();\n</code></pre>\n\n<p>Then store it back:</p>\n\n<pre><code>store.set('someObject', o);\n</code></pre>\n\n<p>It takes three lines and a rather clean code.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-05-15T08:12:34.930", "Id": "18884", "Score": "0", "body": "It sounds like brillout is satisfied with the compatibility of localStorage, so there's no need for such a large and complex function." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-05-15T09:33:23.127", "Id": "18886", "Score": "0", "body": "store.js is actually only 5KB with indeed the added benefit of being cross-browser." } ], "meta_data": { "CommentCount": "2", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-05-15T05:59:35.780", "Id": "11768", "ParentId": "11747", "Score": "1" } }, { "body": "<p>Another approach to take with this is to use a get accessor to trigger a save to <code>localStorage</code>. For instance, if you have an object <code>mem</code>, you can set up an accessor for a <code>data</code> property which will return a backing object and save the updated backing object to <code>localStorage</code> via a <code>setTimeout(..., 0)</code> call. </p>\n\n<p>You could then set a value like the following and it would be accessible on page-reload:</p>\n\n<pre><code>mem.data.highscore = 9999;\n</code></pre>\n\n<p>One way to set this up:</p>\n\n<pre><code>window.mem = (function() {\n\n return createChan('mem_default');\n\n function createChan(chanKey) {\n\n var key = chanKey,\n data = JSON.parse(localStorage[chanKey] || '{}'),\n sched = schedSave,\n api = {\n save: doSave,\n suppressSave: noSave,\n clear: clear,\n createChan: createChan\n },\n saveTimeout;\n\n Object.defineProperty(api, \"data\", {\n get: function() {\n sched();\n return data; \n },\n set: function(value) {\n if (value != data) {\n data = validateData(value); \n sched();\n }\n },\n enumerable : true\n });\n\n return api;\n\n function schedSave() {\n\n sched = noop;\n if (saveTimeout) {\n return;\n }\n saveTimeout = setTimeout(doSave, 0);\n }\n\n function doSave() {\n\n if (saveTimeout) {\n clearTimeout(saveTimeout)\n }\n saveTimeout = undefined;\n localStorage[key] = JSON.stringify(data);\n sched = schedSave;\n }\n\n function noSave() {\n if (saveTimeout) {\n clearTimeout(saveTimeout)\n }\n sched = noop;\n saveTimeout = setTimeout(function() {\n sched = schedSave;\n saveTimeout = undefined;\n }, 0);\n }\n\n function clear() {\n // TODO\n }\n }\n\n function validateData(value) {\n\n var newData;\n\n switch (typeof value) {\n\n case 'string':\n case 'boolean':\n case 'number':\n return {value: value};\n\n case 'function':\n newData = {};\n for (var p in value) {\n if (value.hasOwnProperty(p)) {\n newData[p] = value[p];\n }\n }\n return newData;\n\n case 'object':\n return value ? value : {};\n }\n return {};\n }\n\n function noop() {}\n\n})();\n</code></pre>\n\n<p>Here is a <a href=\"http://jsfiddle.net/HneEn/\" rel=\"nofollow\">jsFiddle demo</a>.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-12-27T08:15:50.153", "Id": "19961", "ParentId": "11747", "Score": "0" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-05-14T13:50:28.813", "Id": "11747", "Score": "6", "Tags": [ "javascript", "browser-storage" ], "Title": "Persistent Object using localStorage" }
11747
<p>This is a fairly trivial example of a question I come up to often. In the example below I tend to think that allowing duplication sometimes results in clearer code.</p> <p>Does anyone agree/disagree on this point?</p> <p>First way: an additional local variable is used so <code>method.Invoke</code> is called just once on the last line. <em>I think this has slightly more logic to decode than the second way.</em></p> <pre><code>private static void Invoke&lt;T&gt;(string[] args, MethodInfo method) where T : new() { T target = new T(); target.InvokeMethod("Initialize", errorIfMethodDoesNotExist: false, accessNonPublic: true); string[] methodArgs = null; if (args.Length &gt; 1) { methodArgs = args.Skip(1).ToArray(); } method.Invoke(target, methodArgs); } </code></pre> <p>Second way: No additional local variable but the call to <code>method.Invoke</code> is duplcated in both branches of the if statement. <em>I think this is clearer even though logic was duplicated.</em></p> <pre><code>private static void Invoke&lt;T&gt;(string[] args, MethodInfo method) where T : new() { T target = new T(); target.InvokeMethod("Initialize", errorIfMethodDoesNotExist: false, accessNonPublic: true); if (args.Length &gt; 1) { method.Invoke(target, args.Skip(1).ToArray()); } else { method.Invoke(target, null); } } </code></pre>
[ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-05-14T23:04:01.043", "Id": "18866", "Score": "0", "body": "I personally like your first option in this case as for me it reads easier and is actually less logic in my view to decode as such" } ]
[ { "body": "<p>I think this would be even better, in this case.</p>\n\n<pre><code>private static void Invoke&lt;T&gt;(string[] args, MethodInfo method) where T : new()\n{\n T target = new T();\n target.InvokeMethod(\n \"Initialize\", errorIfMethodDoesNotExist: false, accessNonPublic: true);\n string[] methodArgs = args.Skip(1).ToArray();\n method.Invoke(target, methodArgs);\n}\n</code></pre>\n\n<p><a href=\"http://msdn.microsoft.com/en-us/library/bb358985.aspx\"><code>Skip()</code></a> on an empty collection returns an empty collection.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-05-14T17:51:34.583", "Id": "11756", "ParentId": "11753", "Score": "8" } }, { "body": "<p>or if you want to keep the <code>null</code> value, you can inline the things in the method call with a ternary <code>if</code> like this :</p>\n\n<pre><code>method.Invoke(target, args.Length &gt; 1 ? args.Skip(1).ToArray() : null);\n</code></pre>\n\n<p>Not super effective here considering svick answer, but in a more general case I think it is preferable to your two options (as long as it doesn't makes you write a 200 characters line).</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-05-16T06:39:06.627", "Id": "11795", "ParentId": "11753", "Score": "0" } } ]
{ "AcceptedAnswerId": "11756", "CommentCount": "1", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-05-14T16:47:46.337", "Id": "11753", "Score": "4", "Tags": [ "c#" ], "Title": "Duplicate method call or add logic to set local variables as parameters?" }
11753
<p>I have 12 games that I need to sort through that each have a date and img string. I'm fairly new to jQuery and was wondering what is the best way to accomplish this. Is there a way that I can run this through a loop of some sort rather than having 12 <code>else</code>-<code>if</code> statements like I currently have (code condensed to 3 for readability)? This code works, I was just looking for the cleaner more concise way of writing it.</p> <pre><code>var now = new Date(); boise = { date: new Date ('May 15, 2012'), img: 'Boise' }; central = { date: new Date ('May 21, 2012'), img: 'Central' }; notreDame = { date: new Date ('May 27, 2012'), img: 'NotreDame' }; ... banner = $('#nextGameBanner'); imgDir = 'images/nextGame'; if (now &lt; boise.date ) { banner.attr('src', imgDir+boise.img+'.jpg'); } else if (now &lt; central.date) { banner.attr('src', imgDir+central.img+'.jpg'); } else if (now &lt; notreDame.date) { banner.attr('src', imgDir+notreDame.img+'.jpg'); } ... </code></pre> <p>HTML</p> <pre><code>&lt;img src="/website/images/nextGame.jpg" id="nextGameBanner" /&gt; </code></pre>
[ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-05-14T19:36:28.510", "Id": "18860", "Score": "0", "body": "@j08691: The moderators prefer that you flag such things for their attention, that way they can move the question and avoid duplicate posts on different sites." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-05-14T19:38:14.087", "Id": "18861", "Score": "0", "body": "@muistooshort - it was just a suggestion for the OP. Wasn't sure if that was the best spot and whether it needed to be moved." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-05-14T19:07:49.830", "Id": "18862", "Score": "0", "body": "Since you are applying the same function across different variables, look into implementing a [partial function](http://ejohn.org/blog/partial-functions-in-javascript/) and simply change the variable to be the game name you are referencing." } ]
[ { "body": "<p>Try something like this:</p>\n\n<pre><code>if (now.getTime() &lt; boise.date.getTime() ) {\n banner.attr('src', imgDir+boise.img+'.jpg');\n}\n.....\n</code></pre>\n\n<p>In total,</p>\n\n<pre><code>var now = new Date();\n objs = { \n // here I change your 12 variables to a single object, so I can loop over them\n boise : { date: new Date ('May 15, 2012'), img: 'Boise' },\n central : { date: new Date ('May 21, 2012'), img: 'Central' },\n notreDame : { date: new Date ('May 27, 2012'), img: 'NotreDame' }\n },\n banner = $('#nextGameBanner'),\n imgDir = 'images/nextGame';\n\n// making loop with objs\n\n$.each(objs, function(key, singleObj) { \n // compare time with now and stored time in object\n if (now.getTime() &lt; singleObj.date.getTime() ) {\n // assigning src to image when the condition satisfied\n banner.attr('src', imgDir+ singleObj.img +'.jpg');\n break; // stop the loop when match found\n }\n});\n</code></pre>\n\n<p>​\n<a href=\"https://developer.mozilla.org/en/JavaScript/Reference/Global_Objects/Date/getTime\" rel=\"nofollow\">read about getTime()</a></p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-05-14T19:36:41.920", "Id": "18863", "Score": "0", "body": "Looks like it should work however I did this and I'm always getting the '.img' from the last object (even though previous dates should have settled the if statement condition) , any ideas?" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-05-14T19:44:45.167", "Id": "18864", "Score": "0", "body": "@user1394450 check my update answer. Loop should break when match found. I edited that." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-05-14T19:49:17.857", "Id": "18865", "Score": "0", "body": "This worked with 1 exception, I cant \"break;\" I need to \"return false;\" Thank you very much!" } ], "meta_data": { "CommentCount": "3", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-05-14T19:04:21.020", "Id": "11758", "ParentId": "11757", "Score": "1" } } ]
{ "AcceptedAnswerId": "11758", "CommentCount": "3", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-05-14T19:03:04.197", "Id": "11757", "Score": "0", "Tags": [ "javascript", "jquery", "datetime" ], "Title": "Finding image by date" }
11757
<p>In my Backbone.Collection I need to parse the response before to render it in Backbone.View. The following code works, but it will be great to have some suggestions:</p> <pre><code>// response is array of object // [{id:1, prop: null },{id:2, prop: "bar" }] // the output parsed_response can be //[{id:1, prop: null, isProp: true }, // {id:2, prop: "bar", isProp: false }] parse: function(response) { var parsed_response; parsed_response = _(response).clone(); var parsed_response = _.map(parsed_response, function (obj) { return function (_obj) { if (_obj.prop === "" || typeof _obj.prop === "null" ) { _obj.isProp = false; } else { _obj.isProp = true; } return _obj; }(obj) }); return parsed_response; } </code></pre> <p>My questions are:</p> <ol> <li>Is there a way to improve the code? Also renaming the name of variables to make it more clear. </li> <li>Since this code should be reused from other collections, what is the best way to generalise it?</li> </ol>
[]
[ { "body": "<p>Based on the way your <code>parse</code> function works you're worried about mutability. Your code can be much shorter. Also, your use of <code>_.clone</code> is wasted since it's only a shallow copy. I've rewritten <code>parse</code> code and now it looks like this:</p>\n\n<pre><code>// response is array of object \n// [{id:1, prop: null },{id:2, prop: \"bar\" }]\n\n// the output parsed_response can be \n//[{id:1, prop: null, isProp: true },\n// {id:2, prop: \"bar\", isProp: false }]\n\nparse: function(response)\n{\n return _.map(response, function(obj) {\n obj = _.clone(obj);\n obj.isProp = obj.prop !== \"\" &amp;&amp; obj.prop !== null;\n return obj;\n });\n}\n</code></pre>\n\n<p>If you want further explanation let me know :)</p>\n\n<p>The only thing I'm concerned with is how your <code>prop</code> works? Can you just check for a falsey value here (i.e. <code>!obj.prop</code>) or do you <em>really</em> need to explicitly check for an empty string or <code>null</code>?</p>\n\n<p>In term of re-usability, you're covered here. <code>parse()</code> doesn't reference <code>this</code> so it can more or less be called statically from anywhere in your code. But be careful where you use it from, if you start calling this all over the place, it would make more sense to refactor this <code>parse()</code> function to a more generic object.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-05-15T04:54:40.727", "Id": "18878", "Score": "0", "body": "Just one question: What is the goalp of writing `obj = _.clone(obj);` since the result is the same?" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-05-15T05:38:33.747", "Id": "18879", "Score": "0", "body": "Calling clone will modify cloned objects, leaving the original `response` objects alone. You have to do it on the each object since `_.clone` will only shallow copy. If you don't care about modifying the original `response`, take the clone line out and switch to `_.each`." } ], "meta_data": { "CommentCount": "2", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-05-15T00:32:24.453", "Id": "11761", "ParentId": "11759", "Score": "3" } } ]
{ "AcceptedAnswerId": "11761", "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-05-14T20:56:59.567", "Id": "11759", "Score": "2", "Tags": [ "javascript", "backbone.js" ], "Title": "How to parse a collection of objects in Backbone?" }
11759
<p>I have written this code which precisely calculates the nth power of x by a recursive method.</p> <p>I compared my program with Java's <code>pow(double, double)</code> function, and most of the time I get comparable results, although sometimes <code>pow</code> is slow and the other times this program is slow.</p> <p>Can anyone suggest any improvements or the way Java implements this function?</p> <pre><code>public double power(long x, int n) { double pow = 1L; if(n==0) return 1; if (n == 1) return x; if(n%2==0){ pow = power(x, n / 2); return pow * pow; } else{ pow = power(x,n/2); return pow * pow * x; } } </code></pre>
[ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-05-15T03:23:58.140", "Id": "18870", "Score": "0", "body": "http://gizmoworks.wordpress.com/sicp-exercises/ is the simplest to comprehend, but probably is not the fastest." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-05-15T03:28:34.407", "Id": "18871", "Score": "0", "body": "Thank you, I was wondering that this can be done. Could you suggest me any link where I can read or find out, how to calculate product of two numbers(numbers are not necessarily powers of 2) with the help of binary shifting. PS: I know that any number can be represented as a sum of a(subscript)k * 2 ^ k when k running from 0 - n." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-05-15T03:29:37.713", "Id": "18872", "Score": "0", "body": "I took my words back. There must be some cool tricks though." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-05-15T03:30:57.290", "Id": "18873", "Score": "0", "body": "http://martin.ankerl.com/2007/02/11/optimized-exponential-functions-for-java/" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-05-15T03:35:47.893", "Id": "18874", "Score": "0", "body": "http://stackoverflow.com/questions/3870305/pure-java-implementation-of-the-java-lang-math-class" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-05-15T03:36:47.627", "Id": "18875", "Score": "0", "body": "http://stuq.nl/weblog/2009-01-28/why-many-java-performance-tests-are-wrong" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-05-15T07:18:01.270", "Id": "18881", "Score": "0", "body": "Note that binary exponentiation isn't always the fastest. e.g. x^15 = x*(x*(x*x²)²)² needs 6 multiplications, while (x*(x²)²)³ needs only 5 multiplications. See http://en.wikipedia.org/wiki/Exponentiation_by_squaring for the different algorithms." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-05-15T16:32:10.800", "Id": "18888", "Score": "1", "body": "Fractional exponents, e.g. 2 ** 0.5?" } ]
[ { "body": "<p>The Java implementation of <code>pow</code> is implemented for double, rather than long, and probably uses logarithms. This makes direct comparison difficult - <code>pow</code> should have a more or less constant factor time, but double precision arithmetic can be expensive.</p>\n\n<p>Otherwise, it seems reasonably straightforward.</p>\n\n<p>If you're looking for speed, did you try using bit shifts rather than divides? It's possible that the compiler optimizes a divide by 2 to a bit shift, put possibly not. Though, the bit shift is probably somewhat less readable than the divide - and it is possible to be too clever.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-05-15T03:40:35.953", "Id": "18876", "Score": "0", "body": "Sorry! for the trouble num was for my own purpose to count the number of recursions. I have removed it now." } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-05-15T03:35:52.247", "Id": "11763", "ParentId": "11762", "Score": "6" } }, { "body": "<p>@Donals's suggestion was a good one. I do not check for overflow - I suppose an exception will be thrown then.</p>\n\n<p>I did not try to compile and run this using Java. Please do try it yourself.</p>\n\n<p>Note that fast code quickly starts to look ugly ...</p>\n\n<p>Remember to properly measure the performance of your code.\n<a href=\"http://stuq.nl/weblog/2009-01-28/why-many-java-performance-tests-are-wrong\" rel=\"nofollow\">http://stuq.nl/weblog/2009-01-28/why-many-java-performance-tests-are-wrong</a></p>\n\n<p>Also these two could be used to figure out if the number is a power of 2, and what that power is.</p>\n\n<p><a href=\"http://docs.oracle.com/javase/1.5.0/docs/api/java/lang/Integer.html#highestOneBit(int\" rel=\"nofollow\">http://docs.oracle.com/javase/1.5.0/docs/api/java/lang/Integer.html#highestOneBit(int</a>)\n<a href=\"http://docs.oracle.com/javase/1.5.0/docs/api/java/lang/Integer.html#lowestOneBit(int\" rel=\"nofollow\">http://docs.oracle.com/javase/1.5.0/docs/api/java/lang/Integer.html#lowestOneBit(int</a>)</p>\n\n<p>Basically, the lowest and the highest should be the same.</p>\n\n<p>Here is an interesting and useful page: <a href=\"http://graphics.stanford.edu/~seander/bithacks.html#IntegerLogObvious\" rel=\"nofollow\">http://graphics.stanford.edu/~seander/bithacks.html#IntegerLogObvious</a></p>\n\n<pre><code>// Do you want to optimize for the worst case (2 ^ 1024) or the average case / the ammortized cost?? \npublic static double power(long x, int n) {\n\n if (n == 0)\n {\n return 1;\n }\n\n if (n == 1) {\n return x;\n }\n\n // Something to think about - do you allow negative x ?\n if (x &gt; -3 &amp;&amp; x &lt; 3) {\n return shortcutPower(x, n);\n }\n\n // TODO: Should finally check whether +/-n is some power of two,\n // and if so, then try to piggy-back on the binary shifting of 2.\n // I am not sure how long it takes to figure out which bit is set.\n\n return powerHelper(x, n);\n}\n\nprivate static boolean isPosOrNegPowerOfTwofast(int n) {\n{\n return isPowerOfTwoFast(n) || isPowerOfTwoFast(-n);\n}\n\n// http://sabbour.wordpress.com/2008/07/24/interview-question-check-that-an-integer-is-a-power-of-two/\nprivate static boolean isPowerOfTwoFast(int n) {\n return ((n!=0) &amp;&amp; (n&amp;(n-1))==0);\n}\n\n// No longer performs the checks every time ...\nprivate static powerHelper(long x, int n) {\n double pow = power(x, n &gt;&gt; 1); // I bet Java compiler will generate the same bytecode as for / 2\n if (n % 2 == 0) {\n return pow * pow;\n }\n\n return pow * pow * x;\n}\n\n// You can keep on adding optimizations like these ... but remember to profile.\nprivate static double shortcutPower(long x, int n) {\n if (x == 0) {\n return 0;\n }\n\n double sign = (n % 2 == 0) ? 1 : -1;\n if (x == 1 || x == -1) {\n return sign;\n }\n\n return sign * pow2(n);\n}\n\n// Please check this code\npublic static double pow2(int n) {\n double result = (1L &lt;&lt; n % 60);\n while (n = n - 60 &gt; 60) {\n result *= 1L &lt;&lt; 60; // I am sure that Java compiler can optimize this.\n }\n}\n</code></pre>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-05-15T04:17:52.630", "Id": "11765", "ParentId": "11762", "Score": "4" } }, { "body": "<p>You're missing a case for <code>n &lt; 0</code>. Either <code>return 1.0 / power(x, -n);</code> or delegate to <code>Math.pow()</code> in that case.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-03-07T01:19:28.823", "Id": "43664", "ParentId": "11762", "Score": "1" } }, { "body": "<p>Few notes:</p>\n\n<ul>\n<li><p>Formatting</p>\n\n<ol>\n<li>Spacing. <code>if(n==0)</code> and <code>if (n == 1)</code>.</li>\n<li>Braces: Though optional for single statements but most prefer it to be there. Your choice.</li>\n</ol></li>\n<li><p>Naming: Though its a simple method but we could use variables like base, exponent.</p></li>\n<li>Can <code>pow</code> store LONG_MAX ^ INT_MAX ? If not should we use Long and throw exception for out-of-range cases?</li>\n<li>Since the power is an <code>int</code> , would you like to handle negative powers as well or a check for <code>n&lt;0</code> is required?</li>\n</ul>\n\n<p>Another algorithm you can resort to:</p>\n\n<pre><code>// 10^5(101 base 2) = 10^ (4 + 1) = 10^1 * 10^4 = 10000.\npublic static long power(long base, int exponent){\n long result = 1;\n long pow = base;\n while(exponent&gt;0){\n if((exponent &amp; 1) == 1){\n result *=pow;\n }\n pow*= pow;\n exponent = exponent&gt;&gt;1;\n }\n return result ;\n}\n</code></pre>\n\n<p>Its significantly faster than <code>Math.pow()</code>. Ideone <a href=\"http://ideone.com/k6RJ1a\" rel=\"nofollow\">link</a>.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-12-29T05:27:04.897", "Id": "75106", "ParentId": "11762", "Score": "1" } }, { "body": "<p>These answers are correct if your result stays within the precision limit of the processor. The fallacy is assuming that a multiplication is O(1). It is not when your precision needs to exceed the built in precision.</p>\n\n<p>When you multiply two 10 bit numbers, the algorithm used is a shift and add which must cycle across all 10 bits. If I were to raise a 10 bit number to the 8th power, it would take 70 shifts and adds using a short loop which multiplies the result by the number 7 times.</p>\n\n<p>Using the power algorithm that reduces the steps by half each time, actually doubles the amount of work that it must do. Raising the same 10 bit number to the 8th power will yield: 10 shifts and adds to get X*X. But now X is a 20 bit number needing to be raised to the 4th power. Next time through takes 20 shifts and adds, with X resulting in a 40 bit number that needs to be squared. The last pass takes 40 shifts and adds and X is the result. Adding the passes up, 10 + 20 + 40, is 70 shifts and adds. </p>\n\n<p>This is no more efficient than using a simply multiplication loop.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2015-11-11T20:40:19.160", "Id": "110486", "ParentId": "11762", "Score": "2" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "8", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-05-15T03:15:59.727", "Id": "11762", "Score": "7", "Tags": [ "java", "algorithm", "performance", "mathematics" ], "Title": "Calculating nth power of x" }
11762
<p>I'm attempting to implement various data structures and algorithms to better learn C. I would appreciate comments on style, correctness of the implementation, memory management, etc.</p> <p>One specific question is how to address an error case where either the table or key is null in the hash function. In get or rm I can use an unsigned return of 0 or 1 representing a boolean value.</p> <pre><code>#include &lt;stdio.h&gt; #include &lt;string.h&gt; #include &lt;stdlib.h&gt; typedef struct HashTable { size_t size; char ** buckets; } HashTable; HashTable * create_table(size_t size); int hash_code(char * key, HashTable * ht); char * get_val(char * key, HashTable * ht); unsigned int set_val(char * key, char * val, HashTable * ht); unsigned int rm_val(char * key, HashTable * ht); //Bernstein's function uses INITIAL_VALUE of 5381 and M of 33; unsigned int INITIAL_VALUE = 5381; unsigned int M = 33; /* * Function which allocates a Hash table and * bucket array of specified size * @param size the size of the bucket array * */ HashTable * create_table(size_t size) { HashTable * ht = (HashTable*)malloc(sizeof(*ht)); ht-&gt;size = size; ht-&gt;buckets = (char **)malloc(sizeof(char*) * size); return ht; } /* * Function which returns multiplicative hash of key, which is used as bucket * @param key pointer to key * @param ht HashTable structure * */ int hash_code(char * key, HashTable * ht) { if (ht == NULL || key == NULL) return -1; unsigned int hash = INITIAL_VALUE; //seed unsigned int i; for (i=0;i&lt;strlen(key);i++) hash = M * hash + key[i]; return hash % ht-&gt;size; } /* * Function which gets a value from the hashtable, computes hash of key * and queries the buckets at idx of hash * @param key pointer to key * @param ht HashTable structure * */ char * get_val(char * key, HashTable * ht) { if (ht == NULL || key == NULL) return NULL; unsigned int hash = hash_code(key,ht); char * val = ht-&gt;buckets[hash]; if (val != NULL) return val; return NULL; } /* * Function which sets a value in the hashtable, computes hash of key * and queries the buckets at idx of hash, if key is already set * it fails * @param key pointer to key * @param val pointer to val * @param ht HashTable structure * */ unsigned int set_val(char * key, char * val, HashTable * ht) { if (ht == NULL || val == NULL || key == NULL) return 0; int hash = hash_code(key, ht); if (hash &lt; 0) return 0; if (ht-&gt;buckets[hash] == NULL) { ht-&gt;buckets[hash] = val; return 1; } else { return 0; } } /* * Function which removes a value from the hash table * based upon key * @param key pointer to key * @param ht HashTable structure * */ unsigned int rm_val(char * key, HashTable * ht) { if (ht == NULL || key == NULL) return 0; unsigned int hash = hash_code(key, ht); if (ht-&gt;buckets[hash] != NULL) { ht-&gt;buckets[hash] = NULL; return 1; } else { return 0; } } int main(void) { char * key = "foo"; char * val = "bar"; HashTable * ht = create_table(1000); unsigned int set = set_val(key, val, ht); if (set) { unsigned int rm = rm_val(key, ht); if (rm) { return 0; } } return 1; } </code></pre>
[]
[ { "body": "<p>Regarding the problem of the error case where either the table or key is null in hash_code, you might pass in ht->size instead of ht, thus halving the problem. If you redefine the 'contract' so that a NULL key is treated the same as an empty string \"\", then you no longer have an error case.</p>\n\n<p>Some comments on the code:</p>\n\n<ul>\n<li>I'd expect a short description of the nature of the hashtable and how it is used at the start.</li>\n<li>INITIAL_VALUE and M should be <code>const</code></li>\n<li>function parameters should be <code>const</code> where possible</li>\n<li>return values not stated in headers</li>\n<li><p>I would omit things like 'Function which'... from comments. If it is a function then this can be assumed.</p></li>\n<li><p>hash_code uses -1 as an error code while set/rm_val use 0. Inconsistent.</p></li>\n<li>Generally, unsigned should be used for values that are not numeric, such as bitmaps, not for numbers that you don't intend to go negative (although size_t contradicts that).</li>\n</ul>\n\n<p>create_table()</p>\n\n<ul>\n<li>don't cast malloc return value</li>\n<li>check malloc return</li>\n<li><p>ht->buckets not initialised to 0; use calloc instead?</p></li>\n<li><p>you could avoid the first malloc by passing in a pointer to a statically allocated HashTable or by defining the buckets array as a flexible member and then allocate the necessary total size</p>\n\n<p>typedef struct HashTable {</p>\n\n<pre><code> size_t size;\n char *buckets[];\n</code></pre>\n\n<p>} HashTable;</p></li>\n</ul>\n\n<p>hash_code():</p>\n\n<ul>\n<li><p>parameter <code>ht</code>: I'd pass in the size (ht->size) instead of ht. In general, it is easier to test a function that takes simple scalar inputs than one that receives structures. </p></li>\n<li><p>use of strlen in loop control is inefficient; key size does not change but will be evaluated each loop. Perhaps for (; *key; ++key) {...}</p></li>\n<li><p>prefer spaces after ';' in for-loop conditions</p></li>\n<li><p><code>return hash % ht-&gt;size;</code> loses precision (compiler warning due to type conversion). Just use int throughout unless your hash is ever going to be big enough for the extra bit to matter. If you thought it might get big enough (eg if using a processor where int is small) then you would have to check for overflow of an unsigned int too (I'm not suggesting you do that here).</p></li>\n</ul>\n\n<p>get_val()</p>\n\n<ul>\n<li>ignores -ve return from hash_code on error</li>\n<li>last 4 lines reduce to <code>return ht-&gt;buckets[hash];</code></li>\n</ul>\n\n<p>set_val()</p>\n\n<ul>\n<li>Better to return int, not unsigned int</li>\n<li><code>hash</code> is signed. Other uses are unsigned.</li>\n<li>should <code>val</code> be duplicated (allocated)? If not you have to tell the caller that the string must be persistent (ie. the caller must not free it or pass a stack value).</li>\n<li><code>else { return 0; }</code> at the end of function can be reduced to <code>return 0;</code></li>\n<li>comment could be said to be excessive - describing what is obvious from the code; its first ',' should be '.' I would say just: \"Set hashtable value unless already set. Returns 1 on success, 0 on failure (value already set).\"</li>\n</ul>\n\n<p>rm_val()</p>\n\n<ul>\n<li>Better to return int, not unsigned int</li>\n<li>ignores -ve return from hash_code on error</li>\n<li><code>else { return 0; }</code> at the end of function can be reduced to <code>return 0;</code></li>\n</ul>\n\n<p>main()</p>\n\n<ul>\n<li>use EXIT_SUCCESS and EXIT_FAILURE</li>\n</ul>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-05-16T03:30:19.517", "Id": "11788", "ParentId": "11766", "Score": "3" } } ]
{ "AcceptedAnswerId": "11788", "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-05-15T05:14:06.613", "Id": "11766", "Score": "3", "Tags": [ "c", "hash-map" ], "Title": "Open addressed hash table" }
11766
<p>I'm attempting to implement driver-layer (shared library) from top-level app to hardware.</p> <p>In the first, I extracted interface functions, which further will be called from "extern "C" SHARED" wrappers to separate class <code>IDriverInterface</code>.</p> <p>In the second, I want to hot-test some functions before the correct implementation and don't want to use <code>#define</code>, so I created a <code>QDriverInterfaceSim</code> class which inherits <code>QDriverInterface</code>.</p> <p>Can anyone suggest any improvements on this?</p> <p><strong><code>IDriverInterface</code> class:</strong></p> <pre><code>#ifndef IDRIVERINTERFACE_H #define IDRIVERINTERFACE_H #include "types.h" class IDriverInterface { public: virtual int connectToHardware() = 0; virtual int sendData(dev_addr_t dev, com_t com, pdata_t pdata, data_sz_t data_sz) = 0; virtual int sendDataWithAck(dev_addr_t dev, com_t com, pdata_t pdata, data_sz_t data_sz, ack_id_t *p_ack_id) = 0; virtual int sendDataWithAckBlocked(dev_addr_t dev, com_t com, pdata_t pdata, data_sz_t data_sz, timeout_t timeout_ms) = 0; virtual void reg_OnData_callback(onData_callback cb) = 0; virtual void reg_OnAck_callback(onAck_callback cb) = 0; virtual int addRouteRecord(dev_addr_t dev, dev_addr_t dest, dev_addr_t next) = 0; virtual int removeRouteRecord(dev_addr_t dev, dev_addr_t dest) = 0; virtual int getRouteTable(dev_addr_t dev, route_t route_table[1], rows_cnt_t *prow_count) = 0; virtual int setAutoRoute(dev_addr_t dev, bool en) = 0; virtual int ping(dev_addr_t dev, timeout_t timeout_ms) = 0; }; #endif // IDRIVERINTERFACE_H </code></pre> <p><strong><code>QDriverInterface</code> class:</strong></p> <pre><code>#ifndef QDRIVERINTERFACE_H #define QDRIVERINTERFACE_H #include &lt;QObject&gt; #include &lt;QMutex&gt; #include &lt;QDebug&gt; #include "qmyserialport.h" #include "qserialportconfigdialog.h" #include "qserialportinterface.h" #include "idriverinterface.h" #include "types.h" class QDriverInterface : public QObject, public IDriverInterface { Q_OBJECT public: explicit QDriverInterface(QObject *parent = 0); // from IDriverInterface virtual int connectToHardware(); virtual int sendData(dev_addr_t dev, com_t com, pdata_t pdata, data_sz_t data_sz); virtual int sendDataWithAck(dev_addr_t dev, com_t com, pdata_t pdata, data_sz_t data_sz, ack_id_t *p_ack_id); virtual int sendDataWithAckBlocked(dev_addr_t dev, com_t com, pdata_t pdata, data_sz_t data_sz, timeout_t timeout_ms); virtual void reg_OnData_callback(onData_callback cb); virtual void reg_OnAck_callback(onAck_callback cb); virtual int addRouteRecord(dev_addr_t dev, dev_addr_t dest, dev_addr_t next); virtual int removeRouteRecord(dev_addr_t dev, dev_addr_t dest); virtual int getRouteTable(dev_addr_t dev, route_t route_table[1], rows_cnt_t *prow_count); virtual int setAutoRoute(dev_addr_t dev, bool en); virtual int ping(dev_addr_t dev, timeout_t timeout_ms); private slots: void setSerialParams(); protected: onData_callback m_onData; onAck_callback m_onAck; void debug_print(QString fun_name, QString msg = ""); private: void init(); void showConfigDialog(); void sendTestPacket(); QMySerialPort *m_serialPort; QSerialPortConfigDialog *m_serialConfigDialog; QSerialPortInterface *m_SerialPortInterface; }; #endif // QDRIVERINTERFACE_H </code></pre> <p><strong><code>QDriverInterfaceSim</code> class:</strong></p> <pre><code>#ifndef QDRIVERINTERFACESIM_H #define QDRIVERINTERFACESIM_H #include &lt;QObject&gt; #include &lt;QDebug&gt; #include "qdriverinterface.h" class QDriverInterfaceSim : public QDriverInterface { Q_OBJECT public: explicit QDriverInterfaceSim(QObject *parent = 0); // from IDriverInterface //virtual int connectToHardware() { return 0;} virtual int sendData(dev_addr_t dev, com_t com, pdata_t pdata, data_sz_t data_sz); //virtual int sendDataWithAck(dev_addr_t dev, com_t com, pdata_t pdata, data_sz_t data_sz, ack_id_t *p_ack_id) { return 0;} //virtual int sendDataWithAckBlocked(dev_addr_t dev, com_t com, pdata_t pdata, data_sz_t data_sz, timeout_t timeout_ms) { return 0;} //virtual void reg_OnData_callback(onData_callback cb); //virtual void reg_OnAck_callback(onAck_callback cb); //virtual int addRouteRecord(dev_addr_t dev, dev_addr_t dest, dev_addr_t next) { return 0;} //virtual int removeRouteRecord(dev_addr_t dev, dev_addr_t dest) { return 0;} //virtual int getRouteTable(dev_addr_t dev, route_t route_table[1], rows_cnt_t *prow_count) { return 0;} //virtual int setAutoRoute(dev_addr_t dev, bool en) { return 0;} //virtual int ping(dev_addr_t dev, timeout_t timeout_ms) { return 0;} private slots: void callOnData(); void callOnAck(); private: void setOnData(onData_callback cb, dev_addr_t *pdev, com_t *pcom, pdata_t pdata, data_sz_t *pdata_sz); private: dev_addr_t *m_pdev; com_t *m_pcom; pdata_t m_pdata; data_sz_t *m_pdata_sz; }; #endif // QDRIVERINTERFACESIM_H </code></pre>
[]
[ { "body": "<p>I do not really understand what you mean by <em>first</em> and <em>second</em>. Does this source code go all into one single module/dll/exe? Or is there an intended hierarchy? </p>\n\n<p>There are a few (more general) suggestions I can give:</p>\n\n<ul>\n<li><p><strong>avoid include-file name clashes</strong></p>\n\n<p>I would change the name of your header <code>\"types.h\"</code> into something like <code>\"legotron_driver_types.h\"</code> because there are thousands of software environments and libraries that also have a header called <code>\"types.h\"</code>. You want to avoid these name clashes.</p></li>\n<li><p><strong>make your interface symmetric</strong></p>\n\n<p>There are <code>sendData()</code> functions for sending data. Are there only call-back functions for recieving available? I see a <code>getRouteTable()</code> function while there is no <code>setRouteTable()</code> function. You should have the following functions as well:</p>\n\n<pre>\ndisconnectFromHardware();\nreceiveData();\nreceiveDataWithAck();\nreceiveDataWithAckBlocked();\nsetRouteTable();\nremoveAutoRoute();\n</pre>\n\n<p>Having the interface completely symmetric can divide your problem up into more manageable chunks. </p></li>\n<li><p><strong>divide the interface into \"levels\"</strong></p>\n\n<p>You may also want to divide the interface into high-level, middle-level and low-level functions. For example the <code>sendData(); receiveData();</code> function pair may be considered low-level. While the <code>sendDataWithAck(); receiveDataWithAck();</code> may be considered a higher level. This allows you to test the levels independently and to first build the lower level where you can build on higher levels later.</p></li>\n<li><p><strong>use <code>const</code> keyword to specify input arguments</strong> </p>\n\n<p>I'm not a big fan of <a href=\"https://stackoverflow.com/questions/1228161/why-use-prefixes-on-member-variables-in-c-classes\">name pre-fixes</a> however, you have an interesting way of using them in the type definitions. But you could qualify the functions arguments that are not changed by the function with <code>const</code>. This can effectively specify which arguments are input-only and which have output:</p>\n\n<pre>\n sendDataWithAck(dev_addr_t const dev, // \"in\" device\n com_t const com, // \"in\" com port ?\n pdata_t const pdata, // \"in\" pointer to data\n data_sz_t const data_sz, // \"in\" data size\n ack_id_t *p_ack_id); // \"out\" ack ID\n</pre></li>\n<li><p><strong>indicate error</strong></p>\n\n<p>Most of your functions have int as a return value. I assume that this will be an error code. Declare a type for this:</p>\n\n<pre>\nenum class retCode {\n NO_ERROR = 0,\n SYNTAX_ERROR,\n OTHER_ERROR,\n INTERFACE_ERROR = 400,\n CANNOT_CREATE_INTERFACE_ERROR\n};\n</pre></li>\n<li><p><strong>be clear about C/C++ borders</strong></p>\n\n<p>You mention in the intro text something about <em>\"extern \"C\" SHARED\" wrappers</em>. Where exactly is your border from C to C++? Do you really <strong>need to fall back</strong> to C? I see that your member functions mostly use C-Style types. Where is the exact border where you jump from C to C++? In some cases, this may be the only way to do it, but try to use \"C++ thinking\" whenever you can. It will simplify your code and increase readability. </p>\n\n<p>Have a look at the defintition of <code>getRouteTable()</code>:</p>\n\n<pre>\nvirtual int getRouteTable(dev_addr_t dev, \n route_t route_table[1], \n rows_cnt_t *prow_count) = 0;\n</pre>\n\n<p>What is the second argument supposed to pass?</p></li>\n<li><p><strong>in C++ use references when you can</strong></p>\n\n<p>The <code>sendData()</code> function could look like this in more C++ style:</p>\n\n<pre>\nclass Device; // declaration of device class\nclass Port; // declaration of com port class\nclass DataBlock;\n\nvirtual retCode sendData( Device const & dev,\n Port const & com,\n DataBlock const & pdata,\n size_t const & data_sz );\n</pre></li>\n</ul>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2015-10-07T12:09:11.160", "Id": "106822", "ParentId": "11770", "Score": "2" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-05-15T14:33:26.340", "Id": "11770", "Score": "1", "Tags": [ "c++", "object-oriented", "inheritance", "qt" ], "Title": "Driver-layer from top-level app to hardware" }
11770
<p>I am currently writing an embedded application for audio streaming purposes. The embedded app will receive audio packets being sent over WiFi, buffer the packets, then send the audio data over to a decoder chip. I have a ring buffer implementation written, but am getting some weird behavior sometimes. In terms of audio, I am hearing some parts of the song repeat during playback. I found out that this is due to the tail pointer being set to the beginning of the buffer twice.</p> <p>(In my implementation, the head pointer marks the end of valid data whereas the tail pointer marks the beginning of valid data)</p> <p>For example, I see:</p> <ul> <li>Head pointer reset to start of buffer</li> <li>Tail pointer reset to start of buffer</li> <li>Tail pointer reset to start of buffer &lt;-- this is where I hear audio repeating</li> <li>Head pointer reset to start of buffer</li> </ul> <p>Here is the ring buffer implementation:</p> <pre><code>typedef struct ring_buffer { UINT8 *buffer; /* data buffer */ UINT8 *buffer_end; /* end of data buffer */ size_t capacity; /* maximum number of mp3Bytes in the buffer */ size_t count; /* number of mp3Bytes in the buffer */ size_t typesize; /* size of each mp3Byte in the buffer */ UINT8 *head; /* ring buffer head pointer */ UINT8 *tail; /* ring buffer tail pointer */ } ring_buffer; PUBLIC UINT8 AppAudioStream_RingBufInit(ring_buffer *rb, size_t capacity, size_t typesize) { /* alloc buffer of size capacity * typesize */ rb-&gt;buffer = malloc(capacity * typesize); if(rb-&gt;buffer == NULL) { printf("ring buffer init fail\r\n"); return RING_BUF_INIT_FAIL; } /* init rb buffer to 0 */ memset(rb-&gt;buffer, 0, capacity * typesize); /* rb struct element init */ rb-&gt;capacity = capacity; rb-&gt;buffer_end = rb-&gt;buffer + capacity * typesize; rb-&gt;count = 0; rb-&gt;typesize = typesize; rb-&gt;head = rb-&gt;buffer; rb-&gt;tail = rb-&gt;buffer; return RING_BUF_INIT_DONE; } PUBLIC VOID AppAudioStream_RingBufWrite(ring_buffer *rb, UINT8 *mp3Byte) { /* default: allow overwriting if ring buffer is full */ memcpy(rb-&gt;head, mp3Byte, rb-&gt;typesize); rb-&gt;head = rb-&gt;head + rb-&gt;typesize; if(rb-&gt;head == rb-&gt;buffer_end) { printf("head back to start\r\n"); rb-&gt;head = rb-&gt;buffer; } if(rb-&gt;count == rb-&gt;capacity) { printf("buffer full\r\n"); if (rb-&gt;head &gt; rb-&gt;tail) rb-&gt;tail = rb-&gt;tail + rb-&gt;typesize; } else { rb-&gt;count++; } } PUBLIC VOID AppAudioStream_RingBufRead(ring_buffer *rb, UINT8 *mp3Byte) { /* insert 'comfort noise' if the ring buffer is empty */ if(rb-&gt;count == 0){ printf("buffer empty\r\n"); *mp3Byte = NOISE_BYTE; } else { /* copy data to mp3Byte and increase tail pointer */ memcpy(mp3Byte, rb-&gt;tail, rb-&gt;typesize); rb-&gt;tail = rb-&gt;tail + rb-&gt;typesize; if(rb-&gt;tail == rb-&gt;buffer_end) { printf("TAIL back to start\r\n"); printf("Tbuffer count: %i\r\n", rb-&gt;count); rb-&gt;tail = rb-&gt;buffer; } rb-&gt;count--; } } </code></pre> <p>Here is how the ring buffer write function is called:</p> <pre><code>while (1) { AppAudioStream_BufRecv(sd, dataLen, &amp;addr); } PUBLIC VOID AppAudioStream_BufRecv(int sd, INT32 dataLen, struct sockaddr_in *addr) { INT32 addrlen = sizeof(struct sockaddr_in); UINT8 j, i = 0; UINT8 *audioByte; /* listen to incoming audio data packets */ dataLen = recvfrom(sd, (char *) appRxBuf, sizeof(appRxBuf), 0, (struct sockaddr *)&amp;addr, &amp;addrlen); /* set pointer to first element in recieve buffer */ audioByte = appRxBuf; /* buffer received packets into FIFO */ while (dataLen &gt; 0) { /* write 1 byte into audio FIFO */ AppAudioStream_RingBufWrite(&amp;audioFIFO, audioByte); /* increase pointer index and update # of bytes left to write */ audioByte++; dataLen--; } /* wait until buffer is 2/3 full to start decoding */ if (audioFIFO.count &gt;= FIFO_TWO_THIRD_FULL &amp;&amp; audioStreamStatus == GSN_STREAM_BUFFERING) { audioStreamStatus = GSN_STREAM_START; //printf("stream start\r\n"); } } </code></pre> <p>The ring buffer read function is called in a callback which happens every 2 ms (this is basically an ISR):</p> <pre><code>PRIVATE VOID AppAudioStream_DecoderCb(UINT32* pDummy, UINT32 TimerHandle) { UINT8 spiWriteCount = 0; UINT8 mp3Byte; int i = 0; GSN_SPI_NUM_T spiPortNumber = GSN_SPI_NUM_0; /* read 32 bytes of data from FIFO and write to SPI */ while (spiWriteCount &lt; DATA_WRITE_AMT) { /* set stream status to decoding */ audioStreamStatus = GSN_STREAM_DECODING; /* read 1 byte of audio data from FIFO */ AppAudioStream_RingBufRead(&amp;audioFIFO, &amp;mp3Byte); /* write 1 byte of audio data out to VS1053 */ AppSpi_SdiByteWrite(spiPortNumber, &amp;mp3Byte); /* increase byte written count */ spiWriteCount++; } } </code></pre> <p>I am sure I am just overlooking something really obvious right now.</p>
[ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-06-14T04:15:07.810", "Id": "20237", "Score": "0", "body": "For small embedded systems, it's a good old trick to align the buffer on a `2 << (n+1)` boundary, and then after each increment operation on head/tail pointers to and them with `~(2<<n)`. This works on only if you increment the pointers. It keeps the n-th bit always zeroed, as it's effectively the carry bit." } ]
[ { "body": "<p>If I'm right you need some synchronization/locking to make visible every data change properly for every thread since two threads use the ring buffer at the same time: <code>AppAudioStream_BufRecv</code> and <code>AppAudioStream_DecoderCb</code>.</p>\n\n<p>Two posts from SO which look useful: </p>\n\n<ul>\n<li><a href=\"https://stackoverflow.com/questions/4989451/mutex-example-tutorial\">Mutex example / tutorial?</a></li>\n<li><a href=\"https://stackoverflow.com/questions/879077/is-changing-a-pointer-considered-an-atomic-action-in-c\">Is changing a pointer considered an atomic action in C?</a></li>\n</ul>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-05-15T22:20:17.653", "Id": "18896", "Score": "1", "body": "I think you are right. The AppAudioStream_BufRecv is running in one thread, but the decoderCb is being executed every time a periodic timer expires. According to the documentation, the periodic timer will issue an interrupt and call the callbacks of all expired timers. \n\nBut either way, the fact remains that the same buffer is being read from/written to (maybe at the same time), which as you pointed out is not a good idea. Thank you for the pointers, and my apologies that I can't up vote your reply since I don't have enough reputation." } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-05-15T19:22:02.680", "Id": "11775", "ParentId": "11774", "Score": "3" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "1", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-05-15T18:44:45.787", "Id": "11774", "Score": "3", "Tags": [ "c", "audio", "circular-list" ], "Title": "Ring buffer in C tail pointer issue (for audio streaming)" }
11774
<p>I have an app that does a fair bit of text-parsing based on free-form user inputs. In this, I run searches on the whole string, and then on the last value of the string separate from the rest of the string. Here is a pair of functions I wrote to <code>getLast</code> and <code>getSubString</code>.</p> <pre><code>&lt;cffunction name="getLast" output="no" returnType="string" access="public" hint="Takes a string and returns the last value by either comma or space, or returns nothing if the string is only one value long"&gt; &lt;cfargument name="str" required="yes" type="string"&gt; &lt;cfset var returnVar = ""&gt; &lt;cfif listLen(arguments.str) GT 1&gt; &lt;cfoutput&gt;listLen(#arguments.str#)&lt;/cfoutput&gt; &lt;cfset returnVar = trim(listLast(arguments.str))&gt; &lt;cfelseif listLen(arguments.str, " ") GT 1&gt; &lt;cfoutput&gt;listLen(#arguments.str#, " ")&lt;/cfoutput&gt; &lt;cfset returnVar = trim(listLast(arguments.str, " "))&gt; &lt;/cfif&gt; &lt;cfreturn returnVar&gt; &lt;/cffunction&gt; &lt;cffunction name="getSubString" output="no" returnType="string" access="public" hint="Takes a string and returns the beginning of the string minus the last value"&gt; &lt;cfargument name="str" required="yes" type="string"&gt; &lt;cfset var last = getLast(arguments.str)&gt; &lt;cfset var lastLen = len(last) + 1&gt; &lt;cfset var thisLen = len(str) - lastLen&gt; &lt;cfset var returnVar = str&gt; &lt;cfif thisLen GTE 1&gt; &lt;cfset returnVar = trim(mid(str, 1, thisLen))&gt; &lt;/cfif&gt; &lt;!--- remove trailing commas ---&gt; &lt;cfif right(trim(returnVar), 1) IS ","&gt; &lt;cfset returnVar = mid(returnVar, 1, len(trim(returnVar)) - 1)&gt; &lt;/cfif&gt; &lt;cfreturn returnVar&gt; &lt;/cffunction&gt; </code></pre> <p>And just for fun, some code that was commented out of the second function:</p> <pre><code>&lt;!--- &lt;cfset var listDelim = ","&gt; &lt;cfset var i = 0&gt; &lt;cfset var returnVar = ""&gt; &lt;!--- if the string is longer than one value ---&gt; &lt;cfif len(last)&gt; &lt;cfif NOT findNoCase(arguments.str, ",")&gt; &lt;cfset listDelim = " "&gt; &lt;/cfif&gt; &lt;cfloop from="1" to="#evaluate(listLen(arguments.str, listDelim) - 1)#" index="i"&gt; &lt;cfset returnVar = "#returnVar# #listGetAt(arguments.str, i, listDelim)#"&gt; &lt;/cfloop&gt; &lt;cfset returnVar = trim(returnVar)&gt; &lt;cfelse&gt; &lt;cfset returnVar = arguments.str&gt; &lt;/cfif&gt; ---&gt; </code></pre> <p>Next time I think I'm going to avoid parsing all my own text and just dumping it all into SOLR.</p>
[ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-05-08T21:29:33.967", "Id": "62809", "Score": "0", "body": "I didn't look here to see if there are UDFs exactly for this, but before I write UDFs, I always check here: http://cflib.org/" } ]
[ { "body": "<p>I believe ColdFusion already has similar function to your first:\nListLast() - Gets the last item in a list\n<a href=\"http://livedocs.adobe.com/coldfusion/8/htmldocs/help.html?content=functions_l_14.html\" rel=\"nofollow\">http://livedocs.adobe.com/coldfusion/8/htmldocs/help.html?content=functions_l_14.html</a></p>\n\n<p>I would suggest in getSubString that you trim the input when you assign it to 'last', then you can remove the trim()s used later on.</p>\n\n<pre><code>&lt;cfset var last = trim(getLast(arguments.str))&gt;\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-05-15T20:58:50.550", "Id": "18893", "Score": "0", "body": "If you look at her getLast(); function you can see that she's making use of ListLast(); her function basically just performs ListLast( x ); and ListLast( x , \" \" );" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-06-19T14:46:51.683", "Id": "20637", "Score": "0", "body": "Yeah, my problem with \"listLast\" is that I'm not sure which delimiter might be required, depending on what the user types in. This is all part of a text parsing routine where a user could type in an address, including spaces and/or commas." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-06-19T14:47:51.057", "Id": "20638", "Score": "0", "body": "In fact, now that I think about it, I believe my original solution to this did a loop on characters starting at the right and stopping when it hit a space or a comma." } ], "meta_data": { "CommentCount": "3", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-05-15T20:55:36.543", "Id": "11778", "ParentId": "11776", "Score": "0" } }, { "body": "<p>If you are using ColdFusion 9+, you should abandon your vars within functions and move toward using the LOCAL scope. LOCAL vars do not escape the function.</p>\n\n<p>This:</p>\n\n<pre><code>&lt;cfset var last = getLast(arguments.str)&gt;\n&lt;cfset var lastLen = len(last) + 1&gt;\n&lt;cfset var thisLen = len(str) - lastLen&gt;\n&lt;cfset var returnVar = str&gt;\n</code></pre>\n\n<p>Should be:</p>\n\n<pre><code>&lt;cfset LOCAL.last = getLast(arguments.str)&gt;\n&lt;cfset LOCAL.lastLen = len(LOCAL.last) + 1&gt;\n&lt;cfset LOCAL.thisLen = len(LOCAL.str) - LOCAL.lastLen&gt;\n&lt;cfset LOCAL.returnVar = str&gt;\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-05-04T07:22:15.780", "Id": "39938", "Score": "1", "body": "Disagree (and it's subjective either way). Actively scoping local variables makes the code more verbose and clunky to read. But mileage varies. I'd not - however - advocate changing existing code from one to the other approach." } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-06-13T14:14:45.443", "Id": "12539", "ParentId": "11776", "Score": "3" } }, { "body": "<p>I know this is very old, but just wanted to give some thoughts on your <code>getSubString()</code> function:</p>\n\n<ol>\n<li><p><code>getLast()</code> and <code>lastLen</code> use:</p>\n\n<pre><code>&lt;cfset var last = getLast(arguments.str)&gt;\n&lt;cfset var lastLen = len(last) + 1&gt;\n&lt;cfset var thisLen = len(str) - lastLen&gt;\n&lt;cfset var returnVar = str&gt;\n</code></pre>\n\n<ul>\n<li><p>If <code>str</code> is just a single word and not a comma- or space-delimited list, your <code>lastLen</code> will be 1, and your <code>thisLen</code> will now be 1 less than the length of <code>str</code>'s value.</p>\n\n<p>Subsequently, your <code>returnVar</code> will just return your <code>str</code> without its last character. This may be what you intended, or it may be not...</p></li>\n<li>Be consistent in scoping your vars - use <code>arguments.str</code> everywhere.</li>\n<li>I would <code>trim(arguments.str)</code> in the 3 lines above where it is used, and drop all the <code>trim()</code>s in subsequent lines.</li>\n</ul></li>\n<li><p>Instead of <code>&lt;cfif thisLen GTE 1&gt;</code>, which is same as GT 0 in this case, just test for boolean: <code>&lt;cfif thisLen&gt;</code>.</p></li>\n<li><p><code>&lt;cfset returnVar = trim(mid(str, 1, thisLen))&gt;</code> - why not just use <code>left()</code> function instead: <code>&lt;cfset returnVar = left(returnVar, thisLen)&gt;</code>? + use <code>returnVar</code> instead of <code>str</code> and drop <code>trim()</code> if you used it in var setting code. </p></li>\n<li><p>This code block:</p>\n\n<pre><code>&lt;cfif right(trim(returnVar), 1) IS \",\"&gt;\n &lt;cfset returnVar = mid(returnVar, 1, len(trim(returnVar)) - 1)&gt;\n&lt;/cfif&gt;\n</code></pre>\n\n<p>should be inside the <code>&lt;cfif&gt;</code> block above it - it is only relevant when <code>thisLen &gt; 0</code>. And again, just use <code>left()</code> function instead of <code>mid()</code> (and drop all <code>trim()</code> calls if you changed the var setting lines to use it).</p></li>\n<li><p>To simplify things even more, your two <code>&lt;cfif&gt;</code> blocks can be compressed into these 3 lines:</p>\n\n<pre><code>&lt;cfif thisLen&gt;\n &lt;cfset returnVar = rereplace(left(returnVar, thisLen), \"[\\s,]+$\", \"\")&gt;\n&lt;/cfif&gt;\n</code></pre></li>\n</ol>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-06-18T16:55:23.553", "Id": "12707", "ParentId": "11776", "Score": "2" } }, { "body": "<p>Observations:</p>\n\n<ul>\n<li><code>getLast()</code> is very vaguely named. It looks like you're trying to get the last \"word\" in a string, so unless <code>getLast()</code> is in a CFC called Sentence.cfc or WordList.cfc, I think its name could be improved, eg: <code>getLastWord()</code>.</li>\n<li>if you are after getting the last \"word\" when there's regex support for that, which makes for a much smaller function, and is also more robust in that it uses an accepted definition for what constitutes a \"word\":</li>\n</ul>\n\n<p>(the editor is ignoring my formatting if I position the code here, for some reason. I've put it at the bottom...)</p>\n\n<p>Or just use <code>listLast()</code> with multiple delimiters:</p>\n\n<pre><code>listLast(str, \", .\");\n</code></pre>\n\n<p>But the regex solution is probably more robust.</p>\n\n<p>I would use a variation of the regex approach above, or just <code>listDeleteAt()</code> for the second function. And, again, improve its name.</p>\n\n<p>Code from above:</p>\n\n<pre><code>public string function getLastWord(required string str){\n var result = reReplace(str, \".*\\W(.+)$\", \"\\1\", \"ONE\");\n result = reReplace(result, \"\\W\", \"\", \"ALL\"); // any non-word characters \n return result;\n}\nwriteOutput(getLastWord(\"the quick brown fox jumps over the lazy dog.\"));\n</code></pre>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-05-04T07:40:51.763", "Id": "25803", "ParentId": "11776", "Score": "2" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "1", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-05-15T20:37:31.667", "Id": "11776", "Score": "2", "Tags": [ "strings", "coldfusion", "cfml" ], "Title": "A couple of basic string parsing functions" }
11776
<p>I have a Visual Studio 2008 C++03 project where I need a timer. I have an implementation that works well, but I'd like any general suggestions from the community on how to improve it. (More generic, lower cost of creating timers, etc...)</p> <pre><code>class Timer { public: typedef boost::function&lt; void( ) &gt; OnTimer; Timer( const OnTimer&amp; f, DWORD timeout ) : cancel_event_( ::CreateEvent( NULL, FALSE, FALSE, NULL ), ::CloseHandle ), timer_thread_( boost::bind( &amp;Timer::TimerThread, cancel_event_.get(), f, timeout ) ), timeout_( timeout ) { }; ~Timer() { ::SetEvent( cancel_event_.get() ); }; DWORD Timeout() const { return timeout_; }; private: static void TimerThread( HANDLE cancel_event, const OnTimer&amp; f, DWORD timeout ) { if( WAIT_OBJECT_0 != ::WaitForSingleObject( cancel_event, timeout ) ) f(); }; /// time to wait for the timer to fire UINT timeout_; /// event signaled when the timer should be canceled boost::shared_ptr&lt; void &gt; cancel_event_; /// thread that runs the timer (similar to boost::thread, but doesn't require `localtime`, `gmtime`, or `abort`) util::CThread timer_thread_; }; // class Timer </code></pre> <p>Preemptive:</p> <ul> <li>My project does not have a window message pump so <code>SetTimer</code> is unsuitable.</li> <li>I do not want to incur the cost of importing the mmtimer library.</li> <li>I can only use boost header libraries, therefore <code>boost::timer</code> is unsuitable.</li> <li>I would prefer to keep the discussion limited to this block of code.</li> </ul>
[]
[ { "body": "<p>I think that you can create one thread to handle all timers. When a new timer is created, you should add it in a (synchronized) queue of \"timers to trigger\". The background thread must wait for the closest timer to be triggered. Also you should wake it up each time you modify the queue of timers and recalculate \"which is the closest timer now?\".</p>\n\n<p>When the queue is empty, the background thread can be destroyed (joined) or you can wait an \"exit\" event (or the creation of another timer). Those are just details. The background thread can be created by the first timer and joined when the last timer is destroyed, or it can just live in the whole program execution.</p>\n\n<p>Another thing, to improve portability you could use boost::thread library and boost's condition variables instead of raw Windows events.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-05-15T23:42:57.503", "Id": "11782", "ParentId": "11777", "Score": "2" } } ]
{ "AcceptedAnswerId": "11782", "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-05-15T20:42:06.990", "Id": "11777", "Score": "1", "Tags": [ "c++", "timer" ], "Title": "Timer implementation" }
11777
<p>Is this the best way to prevent that <code>foreach</code> loop from happening if <code>$terms</code> doesn't exist?</p> <pre><code>$terms = get_the_terms( $postid, 'fecha' ); if(!empty($terms)) { foreach($terms as $term) { $myterm = $term-&gt;slug; if(in_array($myterm, $queried_terms)) {continue;} $queried_terms[] = $myterm; } } </code></pre>
[]
[ { "body": "<p>The loop won't be executed if <code>$terms</code> is <code>false</code>/<code>null</code>/an empty array.</p>\n\n<p>As such: you don't need the empty check. It doesn't hurt, but it's simply not required.</p>\n\n<p><strong>If <code>$terms</code> is sometimes not an array</strong></p>\n\n<p>You can just cast it to an array before use:</p>\n\n<pre><code>$terms = get_the_terms( $postid, 'fecha' );\nforeach((array) $terms as $term) {\n $myterm = $term-&gt;slug;\n if(in_array($myterm, $queried_terms)) {\n continue;\n }\n $queried_terms[] = $myterm;\n}\n</code></pre>\n\n<p>The code would work with or without casting to an array - the only difference is that if <code>$terms</code> is not an array, a notice would be thrown without it. </p>\n\n<p><strong>if this is part of another function</strong></p>\n\n<p>you can simply return-early to keep your code concise:</p>\n\n<pre><code>function foo() {\n $terms = get_the_terms( $postid, 'fecha' );\n if (!$terms) {\n return array();\n }\n\n $queried_terms = array();\n foreach($terms as $term) {\n $myterm = $term-&gt;slug;\n if(in_array($myterm, $queried_terms)) {\n continue;\n }\n $queried_terms[] = $myterm;\n }\n return $queried_terms;\n}\n</code></pre>\n\n<p>But, any way you slice it - the empty check isn't strictly required, and deeper code nesting is something to be aware of and avoid.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-05-16T13:12:12.720", "Id": "18922", "Score": "0", "body": "+1 However I question the wisdom in typecasting a variable like that. A variable, in my opinion, should not change types so frequently that you would not know its type. If you find yourself doing this then you should probably implement new variables into your program for those other types. At most my variables are either a boolean or of the desired type so that I can check if it did indeed pass some check or has the value I am looking for. Just my two cents :)" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-05-16T13:20:07.967", "Id": "18923", "Score": "0", "body": "if terms is either an array or falsey - it's fine and appropriate." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-05-16T13:25:36.357", "Id": "18924", "Score": "0", "body": "It still should be used with caution. That's all I was trying to point out. I personally wouldn't use it, but I know many programmers do. That's why I was trying to explain that it shouldn't be used to force your code to work." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-05-16T13:32:19.760", "Id": "18925", "Score": "0", "body": "I agree with your sentiment, but `get_the_terms` sounds like wordpress. That probably gives some indication of expectations and the environment (notices ignored, because otherwise you'd drown in them). Casting to an array only avoids a notice and only \"If $terms is sometimes not an array\" - IME you can't trust anything coming out of wordpress to consistently be what you expect. Casting variables in and of itself is not a bad thing - especially if you work in a type-sensitive system (e.g. mongo as db, json as output)." } ], "meta_data": { "CommentCount": "4", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-05-15T22:36:07.880", "Id": "11781", "ParentId": "11779", "Score": "9" } }, { "body": "<pre><code>$terms = get_the_terms( $postid, 'fecha' );\n\nif(is_array($terms)) {\n foreach($terms as $term) {\n $myterm = $term-&gt;slug;\n if(in_array($myterm, $queried_terms)) {continue;}\n $queried_terms[] = $myterm;\n }\n}\n</code></pre>\n\n<p>I always use this method and never get problem</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-08-15T04:37:59.567", "Id": "14678", "ParentId": "11779", "Score": "1" } } ]
{ "AcceptedAnswerId": "11781", "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-05-15T22:03:16.523", "Id": "11779", "Score": "5", "Tags": [ "php" ], "Title": "!empty() check before a foreach statement" }
11779
<p>The program is supposed perform discrete mathematics operations on a number of conjunctive statements (see lines 34 - 50). Currently I just have it so they print out the tables in 0's and 1's, but I'll be adding a compare functionality shortly. </p> <p>Even though I'm sure this work leaves much to be desired I'm currently worried that about the repetition on lines 78 - 79 as the only unique part is the expression itself while the <code>if else</code> part isn't or never will be unique. </p> <p>What can I do to condense?</p> <pre><code># Module is created to allow the user to easily select their expression,$ # prints the output and test it to be confident it works.$ import itertools, sys$ $ def setup_table(variables=2):$ ''' setup_table prints out all possibilities of a truth_table based on-$ the amount of variables passed to it'''$ return (list(itertools.product(range(2), repeat = variables)))$ $ def printer(truth_table):$ '''printer simply outputs the truth_table in a easier to read way'''$ selection = input('print to the command line? (yes/no): ')$ if selection == 'yes':-$ for table in truth_table:$ print(table)$ else: return truth_table$ --------$ def expression_menu():$ ''' expression menu offers the user a selection of expressions to evulate'''$ expression = int(input('''$ choose your expression(s)$ A single expression will print out the truth table$ selecting two expressions will print both and compare:$ $ **************************************************$ Whew look at that list! do you really want to type all that in?$ Type EVALALL in order to compare them all$ $ 1. ((p and q) or (p or q)) and not(r or not q)$ 2. (p or r) or (q and s)$ 3. (p or r) and ( q or (p and s))$ 4. not (p and q)$ 5. not (p or q)$ 6. p -&gt; q$ 7. (not p) -&gt; (not q)$ 8. p or ( q and r)-$ 9. (not p) and (not q)$ 10. (not p) or (not q)$ 11. (not p) or q$ 12. p and (not q)$ 13. (p or q) and (p or r)$ ----$ BETA (type in your own!)$ ----$ **************************************************$ expression: '''))$ #TODO: this is not a good way to do this.., watch your inputs!.$ if expression == 1: variables = 3$ elif expression == 2: variables = 4$ elif expression == 3: variables = 4$ elif expression == 4:$ elif express$ print '''Type in your own is still under contruction'''$ sys.exit()$ --------$ $ return truth(expression,variables)$ $ def truth(expression, variables):$ ''' truth evulates the expression selected in expression_menu using$ the table built in setup_table and the boolean logic contained below'''$ truth_table = []$ $ ----$ for line in setup_table(variables):$ # all this mess is to get them so their the same type! TODO: type conv$ str_line = ''$ for number in line:$ str_num = str(number)$ str_line += str_num + ' '$ # add your expressions here!$ # TODO: there has to be a way to streamline these expressions, if,else$ if expression == 1:$ if (((line[0] and line[1]) or (line[0] or line[1])) and not (line[2] or not line[1]))&gt; str_line += '1'$ else:$ str_line += '0'$ $ truth_table.append(str_line)$ elif expression == 2:$ if (line[0] or line[2]) or ( line[1] and line[3]):$ str_line += '1'$ else:$ str_line += '0'$ $ truth_table.append(str_line)$ elif expression == 3:$ if (line[0] or line[2]) and (line[1] or (line[0] and line[3])):$ str_line += '1'$ else:$ str_line += '0'$ elif expressoin == 4:$ $ truth_table.append(str_line)$ # un comment printer to have print to comman line.$ #printer(truth_table)-$ return truth_table$ $ def selection():$ selection = raw_input('choose another expression? (yes/no)')$ if selection == 'yes':$ return expression_menu()$ else: sys.exit()$ ---$ if __name__ == '__main__':$ expression_menu()$ </code></pre>
[ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-05-16T00:31:01.937", "Id": "18899", "Score": "2", "body": "If there's repetition, you need to show more of it so we can get an idea of how it repeats. And while you're at it, explain to us what this code is used for. It looks like you're doing some boolean logic here and some K-maps could help." } ]
[ { "body": "<p>I don't know if you are generating the conditions or if they will just be in your code. If you have to write them all out, you can at least factor the logic out in a function. If you can generate the conditions, use a loop within my_function, then you only have to call it once.</p>\n\n<p>I haven't tested this, but something like this should work.</p>\n\n<pre><code>elif expression == 3 :\n\n ( line, str_line ) += my_function( (line[0] or line[2]) and ( line[1] or (line[0] and line[3]) ) )\n ( line, str_line ) += my_function( (line[1] or line[2]) and ( line[1] or (line[0] and line[3]) ) )\n ( line, str_line ) += my_function( (line[2] or line[2]) and ( line[1] or (line[0] and line[3]) ) )\n\nend\n\n....\n\ndef my_function( condition ) :\n line = str_line = ''\n\n if( condition )\n\n line += '1' \n\n else: \n\n str_line += '0'\n\n return ( line, str_line )\nend\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-05-16T03:04:31.183", "Id": "18904", "Score": "0", "body": "isn't line[0] line[2], etc... going to be undefined?" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-05-16T03:12:45.993", "Id": "18905", "Score": "0", "body": "line is not being sent into the function, only the result of the boolean expression which gets evaluated in the outer scope. What I didn't look up is how python evaluates such expressions outside an if statement, but I assume that the 'and' and 'or' operators cause it to be a boolean." } ], "meta_data": { "CommentCount": "2", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-05-16T00:39:36.933", "Id": "11784", "ParentId": "11783", "Score": "1" } }, { "body": "<pre><code># Module is created to allow the user to easily select their expression, \n# prints the output and test it to be confident it works. \nimport itertools, sys \n\ndef setup_table(variables=2): \n</code></pre>\n\n<p>setup isn't really helpful in understanding this function. Normally, we'd use create. It might be a good idea to give a longer description as well. </p>\n\n<pre><code> ''' setup_table prints out all possibilities of a truth_table based on- \n the amount of variables passed to it''' \n return (list(itertools.product(range(2), repeat = variables))) \n</code></pre>\n\n<p>You don't need the parens around this expression</p>\n\n<pre><code>def printer(truth_table): \n '''printer simply outputs the truth_table in a easier to read way''' \n selection = input('print to the command line? (yes/no): ') \n</code></pre>\n\n<p>The command line is where you enter commands, here you are printing to standard output or the terminal</p>\n\n<pre><code> if selection == 'yes': \n for table in truth_table: \n</code></pre>\n\n<p>A truth table doesn't contain multiple tables, so this variable shouldn't be called table</p>\n\n<pre><code> print(table) \n else: return truth_table\n</code></pre>\n\n<p>Why in the world you want to return the truth_table here? A calling function can't really make use of it because it doesn't get returned consistently, and the calling function already has the table anyways</p>\n\n<pre><code>def expression_menu(): \n ''' expression menu offers the user a selection of expressions to evulate'''\n expression = int(input(''' \n choose your expression(s) \n A single expression will print out the truth table \n selecting two expressions will print both and compare: \n\n ************************************************** \n Whew look at that list! do you really want to type all that in? \n Type EVALALL in order to compare them all \n\n 1. ((p and q) or (p or q)) and not(r or not q) \n 2. (p or r) or (q and s) \n 3. (p or r) and ( q or (p and s)) \n 4. not (p and q) \n 5. not (p or q) \n 6. p -&gt; q \n 7. (not p) -&gt; (not q) \n 8. p or ( q and r)- \n 9. (not p) and (not q) \n 10. (not p) or (not q) \n 11. (not p) or q \n 12. p and (not q) \n 13. (p or q) and (p or r) \n BETA (type in your own!) \n ************************************************** \n expression: ''')) \n</code></pre>\n\n<p>For crazy long strings, I recommend putting them global constants so as not the interrupt your flow</p>\n\n<pre><code> #TODO: this is not a good way to do this.., watch your inputs!. \n if expression == 1: variables = 3 \n elif expression == 2: variables = 4 \n elif expression == 3: variables = 4 \n elif expression == 4: \n elif express \n</code></pre>\n\n<p>This syntax is invalid, I assume it got messed up in the same way your got $ thrown all over it</p>\n\n<pre><code> print '''Type in your own is still under contruction''' \n sys.exit() \n\n return truth(expression,variables) \n\ndef truth(expression, variables): \n ''' truth evulates the expression selected in expression_menu using \n the table built in setup_table and the boolean logic contained below''' \n truth_table = [] \n\n for line in setup_table(variables): \n # all this mess is to get them so their the same type! TODO: type conv\n str_line = '' \n for number in line: \n str_num = str(number) \n str_line += str_num + ' ' \n</code></pre>\n\n<p>This loop can be written as <code>str_line = ' '.join(map(str, line)) + ' '</code></p>\n\n<pre><code> # add your expressions here! \n # TODO: there has to be a way to streamline these expressions, if,else\n if expression == 1: \n if (((line[0] and line[1]) or (line[0] or line[1])) and not (line[2] or not line[1])):\n</code></pre>\n\n<p>You don't need the outer parens</p>\n\n<pre><code> str_line += '1' \n else: \n str_line += '0' \n</code></pre>\n\n<p>Adding strings is expensive. Instead, putting everything in a list and then convert that into a string using <code>' '.join</code></p>\n\n<pre><code> truth_table.append(str_line) \n elif expression == 2: \n if (line[0] or line[2]) or ( line[1] and line[3]): \n str_line += '1' \n else: \n str_line += '0' \n\n truth_table.append(str_line) \n elif expression == 3: \n if (line[0] or line[2]) and (line[1] or (line[0] and line[3])): \n str_line += '1' \n else: \n str_line += '0' \n elif expressoin == 4: \n\n truth_table.append(str_line) \n</code></pre>\n\n<p>Yes, that's some annoying duplication. I'll talk about what to do about it at the end</p>\n\n<pre><code> # un comment printer to have print to comman line. \n #printer(truth_table)- \n return truth_table \n\ndef selection(): \n selection = raw_input('choose another expression? (yes/no)')\n if selection == 'yes': \n return expression_menu()\n</code></pre>\n\n<p>Don't return things unless your caller need them</p>\n\n<pre><code> else: sys.exit() \n</code></pre>\n\n<p>You should only really use <code>sys.exit()</code> if the program has an error or something. Otherwise, just let your code return.</p>\n\n<pre><code>if __name__ == '__main__': \n expression_menu() \n</code></pre>\n\n<p>In order to solve your repetition, you need to store the expression as data not code. Basically you need some classes like:</p>\n\n<pre><code>class Variable(object):\n def __init__(self, number):\n self.number = number\n\nclass And(object):\n def __init__(self, left, right):\n self.left = left\n self.right = right\n\nclass Or(object):\n def __init__(self, left, right):\n self.left = left\n self.right = right\n\nclass Not(object):\n def __init__(self, expression):\n self.expression = expression\n</code></pre>\n\n<p>Then you should have a list of your expressions</p>\n\n<pre><code>P = Variable(0)\nQ = Variable(1)\nR = Variable(2)\nEXPRESSIONS = [\n And(Or(And(P,Q),Or(P,Q)),Not(Or(R,Not(q)))),\n ...\n]\n</code></pre>\n\n<p>Then you should be able to write methods to do things like:</p>\n\n<ul>\n<li>Convert the expression to a string</li>\n<li>Evaluate the truth values of the expression</li>\n<li>Count the number of variables in the expression</li>\n</ul>\n\n<p>If you do that, you should only have to define your expression in exactly one place. So your printing out function should end up looking something like</p>\n\n<pre><code>def truth(expression):\n variable_table = setup_table( expression.count_variables() )\n truth_table = []\n for line in variable_table:\n value = expression.evaluate(line)\n truth_table.append( ' '.join(line + [value]) )\n return truth_table\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-05-18T18:47:27.367", "Id": "19089", "Score": "0", "body": "If you need an idea of how to dynamically parse expressions and create executable trees, you might want to check out the following: http://code.activestate.com/recipes/577469/" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-05-19T07:30:16.610", "Id": "19099", "Score": "2", "body": "What a wonderfully detailed review! i wish i could somehow reward you beyond a simple checkmark" } ], "meta_data": { "CommentCount": "2", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-05-18T15:32:34.903", "Id": "11879", "ParentId": "11783", "Score": "5" } } ]
{ "AcceptedAnswerId": "11879", "CommentCount": "1", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-05-16T00:09:31.700", "Id": "11783", "Score": "3", "Tags": [ "python" ], "Title": "Performing discrete mathematics operations on conjunctive statements" }
11783
<p>I am about to >explode&lt; :) due to amount of reading on this subject... My head hurts, and I need some honest opinions... There is a <a href="https://codereview.stackexchange.com/q/9091">similar question/review</a> that I noticed, but I believe my approach is bit different so I wanted to ask.</p> <p>We are embarking on a really big project that will use ASP.NET MVC 4 with Web API and would like to use Entity Framework Code First. Before I post code for review, <strong>please consider following</strong></p> <ul> <li>My project will be big (possibly 100+ domain entities)</li> <li>There needs to SOLID approach to architecture</li> <li>By now, I understand that Entity Framework <code>DbContext</code> is (entirely or to some extent) implementing Unit of Work and Repository patterns, so I could skip all this ;)</li> <li>I am really concerned using EF injected directly into Controller constructors (testability, separation of concerns, etc, etc)</li> <li>I am also aware that there is more than one way to implement UoW and Repository patterns.</li> <li>I am not worried or wanting to build abstractions that will allow me to "swap" ORM (e.g. swap Entity Framework for NHiberante or such).</li> </ul> <h2>My Approach</h2> <ul> <li>Repositories are generic and have a base class that implement much of the standard logic. </li> <li>Repositories need <code>DbContext</code> via constructor (which is provided by <code>UnitOfWork</code>)</li> <li><code>UnitOfWork</code> is responsible for managing access to all repositories and insuring context is shared among them.</li> <li><code>UnitOfWork</code> is disposable, Repositories are not...</li> <li>In order to "hide" <code>DbContext</code>, <code>UnitOfWork</code> is constructed using <code>IDbContextFactory</code>. </li> </ul> <h2>Questions</h2> <ul> <li>This seems to work for me, and the advantage I see is that every Controller just needs UoW injected which is nice. Some Controllers need 2-3 repositories in addition to domain services so this makes things nice...I think...</li> <li>Over time, UoW will grow with repositories (there could be 65+ aggregate roots each having a repo). Any ides on how to better manage this? Should I somehow inject Repositories instead od new()-ing them up in the <code>UnitOfWork</code>? I'd love to be able to create a IoC module (Autofac is my poison) to wire up all repos (somehow)</li> <li>Is use of <code>IDbContextFactory</code> an overkill or should I just inject <code>DbContext</code> to constructor of <code>UnitOfWork</code> instead? Right now, my web app has no direct dependency on Entity Framework it only depends n DAL (which in turn depends on EF). On the other hand DbContextFactory new()es up <code>MyAppDbContext</code> and is not handled by IoC</li> <li>Does anyone notices any other "code smell" ?</li> <li>Some of the questions are in code NOTEs to make them more relevant...</li> </ul> <p>Ok here is the code with 2 repositories and sample use (all namespaces are omitted for brevity sake)</p> <h2>IDbContextFactory and DbContextFactory</h2> <pre><code>/// &lt;summary&gt; /// Creates instance of specific DbContext /// &lt;/summary&gt; public interface IDbContextFactory //: IDisposable //NOTE: Since UnitOfWork is disposable I am not sure if context factory has to be also... { DbContext GetDbContext(); } public class DbContextFactory : IDbContextFactory { private readonly DbContext _context; public DbContextFactory() { // the context is new()ed up instead of being injected to avoid direct dependency on EF // not sure if this is good approach...but it removes direct dependency on EF from web tier _context = new MyAppDbContext(); } public DbContext GetDbContext() { return _context; } // see comment in IDbContextFactory inteface... //public void Dispose() //{ // if (_context != null) // { // _context.Dispose(); // GC.SuppressFinalize(this); // } //} } </code></pre> <h2>IRepository, Repository, and 2 specific Repositories wiht extra interfaces (Vehicle and Inventory)</h2> <pre><code>public interface IRepository&lt;T&gt; where T : class { /// &lt;summary&gt; /// Get the total objects count. /// &lt;/summary&gt; int Count { get; } /// &lt;summary&gt; /// Gets all objects from database /// &lt;/summary&gt; IQueryable&lt;T&gt; All(); /// &lt;summary&gt; /// Gets object by primary key. /// &lt;/summary&gt; /// &lt;param name="id"&gt; primary key &lt;/param&gt; /// &lt;returns&gt; &lt;/returns&gt; T GetById(object id); /// &lt;summary&gt; /// Gets objects via optional filter, sort order, and includes /// &lt;/summary&gt; /// &lt;param name="filter"&gt; &lt;/param&gt; /// &lt;param name="orderBy"&gt; &lt;/param&gt; /// &lt;param name="includeProperties"&gt; &lt;/param&gt; /// &lt;returns&gt; &lt;/returns&gt; IQueryable&lt;T&gt; Get(Expression&lt;Func&lt;T, bool&gt;&gt; filter = null, Func&lt;IQueryable&lt;T&gt;, IOrderedQueryable&lt;T&gt;&gt; orderBy = null, string includeProperties = ""); /// &lt;summary&gt; /// Gets objects from database by filter. /// &lt;/summary&gt; /// &lt;param name="predicate"&gt; Specified a filter &lt;/param&gt; IQueryable&lt;T&gt; Filter(Expression&lt;Func&lt;T, bool&gt;&gt; predicate); /// &lt;summary&gt; /// Gets objects from database with filting and paging. /// &lt;/summary&gt; /// &lt;param name="filter"&gt; Specified a filter &lt;/param&gt; /// &lt;param name="total"&gt; Returns the total records count of the filter. &lt;/param&gt; /// &lt;param name="index"&gt; Specified the page index. &lt;/param&gt; /// &lt;param name="size"&gt; Specified the page size &lt;/param&gt; IQueryable&lt;T&gt; Filter(Expression&lt;Func&lt;T, bool&gt;&gt; filter, out int total, int index = 0, int size = 50); /// &lt;summary&gt; /// Gets the object(s) is exists in database by specified filter. /// &lt;/summary&gt; /// &lt;param name="predicate"&gt; Specified the filter expression &lt;/param&gt; bool Contains(Expression&lt;Func&lt;T, bool&gt;&gt; predicate); /// &lt;summary&gt; /// Find object by keys. /// &lt;/summary&gt; /// &lt;param name="keys"&gt; Specified the search keys. &lt;/param&gt; T Find(params object[] keys); /// &lt;summary&gt; /// Find object by specified expression. /// &lt;/summary&gt; /// &lt;param name="predicate"&gt; &lt;/param&gt; T Find(Expression&lt;Func&lt;T, bool&gt;&gt; predicate); /// &lt;summary&gt; /// Create a new object to database. /// &lt;/summary&gt; /// &lt;param name="entity"&gt; Specified a new object to create. &lt;/param&gt; T Create(T entity); /// &lt;summary&gt; /// Deletes the object by primary key /// &lt;/summary&gt; /// &lt;param name="id"&gt; &lt;/param&gt; void Delete(object id); /// &lt;summary&gt; /// Delete the object from database. /// &lt;/summary&gt; /// &lt;param name="entity"&gt; Specified a existing object to delete. &lt;/param&gt; void Delete(T entity); /// &lt;summary&gt; /// Delete objects from database by specified filter expression. /// &lt;/summary&gt; /// &lt;param name="predicate"&gt; &lt;/param&gt; void Delete(Expression&lt;Func&lt;T, bool&gt;&gt; predicate); /// &lt;summary&gt; /// Update object changes and save to database. /// &lt;/summary&gt; /// &lt;param name="entity"&gt; Specified the object to save. &lt;/param&gt; void Update(T entity); } public class Repository&lt;T&gt; : IRepository&lt;T&gt; where T : class { protected readonly DbContext _dbContext; protected readonly DbSet&lt;T&gt; _dbSet; public Repository(DbContext dbContext) { _dbContext = dbContext; _dbSet = _dbContext.Set&lt;T&gt;(); } public virtual int Count { get { return _dbSet.Count(); } } public virtual IQueryable&lt;T&gt; All() { return _dbSet.AsQueryable(); } public virtual T GetById(object id) { return _dbSet.Find(id); } public virtual IQueryable&lt;T&gt; Get(Expression&lt;Func&lt;T, bool&gt;&gt; filter = null, Func&lt;IQueryable&lt;T&gt;, IOrderedQueryable&lt;T&gt;&gt; orderBy = null, string includeProperties = "") { IQueryable&lt;T&gt; query = _dbSet; if (filter != null) { query = query.Where(filter); } if (!String.IsNullOrWhiteSpace(includeProperties)) { foreach (var includeProperty in includeProperties.Split(new[] {','}, StringSplitOptions.RemoveEmptyEntries)) { query = query.Include(includeProperty); } } if (orderBy != null) { return orderBy(query).AsQueryable(); } else { return query.AsQueryable(); } } public virtual IQueryable&lt;T&gt; Filter(Expression&lt;Func&lt;T, bool&gt;&gt; predicate) { return _dbSet.Where(predicate).AsQueryable(); } public virtual IQueryable&lt;T&gt; Filter(Expression&lt;Func&lt;T, bool&gt;&gt; filter, out int total, int index = 0, int size = 50) { int skipCount = index*size; var resetSet = filter != null ? _dbSet.Where(filter).AsQueryable() : _dbSet.AsQueryable(); resetSet = skipCount == 0 ? resetSet.Take(size) : resetSet.Skip(skipCount).Take(size); total = resetSet.Count(); return resetSet.AsQueryable(); } public bool Contains(Expression&lt;Func&lt;T, bool&gt;&gt; predicate) { return _dbSet.Count(predicate) &gt; 0; } public virtual T Find(params object[] keys) { return _dbSet.Find(keys); } public virtual T Find(Expression&lt;Func&lt;T, bool&gt;&gt; predicate) { return _dbSet.FirstOrDefault(predicate); } public virtual T Create(T entity) { var newEntry = _dbSet.Add(entity); return newEntry; } public virtual void Delete(object id) { var entityToDelete = _dbSet.Find(id); Delete(entityToDelete); } public virtual void Delete(T entity) { if (_dbContext.Entry(entity).State == EntityState.Detached) { _dbSet.Attach(entity); } _dbSet.Remove(entity); } public virtual void Delete(Expression&lt;Func&lt;T, bool&gt;&gt; predicate) { var entitiesToDelete = Filter(predicate); foreach (var entity in entitiesToDelete) { if (_dbContext.Entry(entity).State == EntityState.Detached) { _dbSet.Attach(entity); } _dbSet.Remove(entity); } } public virtual void Update(T entity) { var entry = _dbContext.Entry(entity); _dbSet.Attach(entity); entry.State = EntityState.Modified; } } public class VehicleRepository : Repository&lt;Vehicle&gt;, IVehicleRepository { public VehicleRepository(DbContext dbContext) : base(dbContext) { } } public interface IVehicleRepository : IRepository&lt;Vehicle&gt; { //RFU } public interface IInventoryRepository : IRepository&lt;InventoryItem&gt; { IList&lt;InventoryItem&gt; GetByVehicleId(string vehicleId); // NOTE: InventoryItem.VehicleId != InventoryItem.Id } public class InventoryItemRepository : Repository&lt;InventoryItem&gt;, IInventoryItemRepository { public InventoryItemRepository(DbContext dbContext) : base(dbContext) { } public IList&lt;InventoryItem&gt; GetByVehicleId(string vehicleId) { return Filter(vii =&gt; vii.Vehicle.Id == vehicleId).ToList(); } } </code></pre> <h2>IUnitOfWork, UnitOfWork</h2> <pre><code>public interface IUnitOfWork : IDisposable { InventoryItemRepository InventoryItemRepository { get; } VehicleRepository VehicleRepository { get; } void Save(); } public class UnitOfWork : IUnitOfWork { private readonly DbContext _dbContext; private bool _disposed; private InventoryItemRepository _inventoryItemRepository; private VehicleRepository _vehicleRepository; /// &lt;summary&gt; /// NOTE: repository getters instantiate repositories as needed (lazily)... /// i wish I knew of IoC "way" of wiring up repository getters... /// &lt;/summary&gt; /// &lt;param name="dbContextFactory"&gt;&lt;/param&gt; public UnitOfWork(IDbContextFactory dbContextFactory) { _dbContext = dbContextFactory.GetDbContext(); } public void Save() { if (_dbContext.GetValidationErrors().Any()) { // TODO: move validation errors into domain level exception and then throw it instead of EF related one } _dbContext.SaveChanges(); } public InventoryItemRepository InventoryItemRepository { get { return _inventoryItemRepository ?? (_inventoryItemRepository = new InventoryItemRepository(_dbContext)); } } public VehicleRepository VehicleRepository { get { return _vehicleRepository ?? (_vehicleRepository = new VehicleRepository(_dbContext)); } } public void Dispose() { Dispose(true); GC.SuppressFinalize(this); } protected virtual void Dispose(bool disposing) { if (!_disposed) { if (disposing) { _dbContext.Dispose(); } } _disposed = true; } } </code></pre> <h2>Sample Usage in ASP.NET MVC4 + Web API</h2> <p><strong>Global.asax.cs (Application_Start)</strong></p> <pre><code>// relevant registration builder.RegisterType&lt;UnitOfWork&gt;().As&lt;IUnitOfWork&gt;() .WithParameter("dbContextFactory", new DbContextFactory()) .InstancePerHttpRequest() .InstancePerApiRequest(); </code></pre> <p><strong>InventoryController</strong></p> <pre><code>public class InventoryController : ApiController { private readonly InventoryItemMapper _mapper; // NOTE: maps viewModel to domain entities and vice versa using ValueInjector private readonly IUnitOfWork _unitOfWork; public InventoryController(IUnitOfWork unitOfWork) { _unitOfWork = unitOfWork; // UoW (with all repos) is injected and ready for use... _mapper = new VehicleInventoryItemMapper(); //TODO: this will be injected also... } public IEnumerable&lt;InventoryViewModel&gt; Get() { var inventoryItems = _unitOfWork.InventoryItemRepository.All().ToList(); var inventory = _mapper.MapToModel(inventoryItems); return inventory; } } </code></pre>
[ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-10-22T23:24:00.960", "Id": "28369", "Score": "4", "body": "I don´t like the relationship you have between the Unit of Work and the repositories.\nEvery time you need to add a repository you need to touch the UnitOfWork class, that for me is a code smell." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-10-23T14:40:46.273", "Id": "28409", "Score": "0", "body": "@Markust I agree with you - I have been modifying my \"design\" since I posted this 5 months ago, and one of the things I have changed was to decouple UoW from Repositories." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-01-10T14:40:15.410", "Id": "32634", "Score": "0", "body": "@zam6ak How did you decouple the repos from the UOW? I have been working on a similar pattern to this and found that although I need to edit the UOW to add new repos it was still pretty clean." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-01-11T20:24:12.567", "Id": "32725", "Score": "0", "body": "@SecretDeveloper Create a common interface, and then have ORM specific implementations. Of course the more abstract you get, the more ORM specific functionality you lose." } ]
[ { "body": "<p>It looks good except filter for paging will through error . </p>\n\n<p>The method 'Skip' is only supported for sorted input in LINQ to Entities. The method 'OrderBy' must be called before the method 'Skip'.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-08-16T22:38:50.603", "Id": "47351", "Score": "0", "body": "Same here.. any ideas how to fix?" } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-06-02T11:17:02.710", "Id": "12231", "ParentId": "11785", "Score": "2" } }, { "body": "<p>It may have just been a typo, but I would probably suggest having the <code>IUnitOfWork</code> expose interfaces instead of the concrete implementations, e.g. <code>IVehicleRepository</code> instead of <code>VehicleRepository</code>.</p>\n\n<p>I quite like the use of <code>IDBContextFactory</code> in this regard, it's not entirely overkill but nicely abstracts <code>DBContext</code> away. However upon implementing this would you not then pass the factory into the <code>Repository&lt;T&gt;</code> constructors rather than <code>DBContext</code> itself?</p>\n\n<p>I've always wondered myself about how to ensure controllers have access to a number or repositories etc. I am interested to see other people's comments on exposing all the repositories on the <code>UnitOfWork</code>.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-10-05T22:02:16.927", "Id": "26448", "Score": "0", "body": "You would not want to pass the IDBContextFactory to each repository. Entity Framework deals with tracking changes and does this through attaching entities to its DBContext. If you do not share the DBContext created by the IDBContextFactory with each repository then you will lose this capability and will have issues when updating linked entities such as a Contact and the Contact's -> EmailAddress. It's a natural tenancy to want to create a new instance of the DBContext for each repository but I've made that mistake and trust me you don't want to do the same." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-10-06T04:58:29.627", "Id": "26450", "Score": "0", "body": "@Curry. Yeah, dbcontexts should be shared I agree. I've seen the same problems you mention. But the use of the contextfactory seems overkill if it's not going to be used anywhere else. Otherwise dbcontext may as well just be injected when setting up the injection rules especially if using frameworks such as Unity or Ninject...." } ], "meta_data": { "CommentCount": "2", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-06-02T21:51:42.423", "Id": "12234", "ParentId": "11785", "Score": "0" } }, { "body": "<p>If you are likely to grow to 100+ domain objects, I'm making the assumption you will have a lot of logic.</p>\n\n<p>I wouldn't access the repositories directly via the controllers, I would add a service layer that is retrieved by the controllers via the UnitOfWork.</p>\n\n<p>reason being:</p>\n\n<ul>\n<li><p>Your controller actions are likely to bloat and become unmanageable. As you will have alot of boiler code (e.g. Get, Update, Save).</p></li>\n<li><p>The service layer would make you avoid from breaking the DRY principle because you won't be repeating the typical repository code.</p></li>\n<li><p>You could use the Facade pattern to group common tasks that require multiple repositories \n<a href=\"http://en.wikipedia.org/wiki/Facade_pattern\" rel=\"noreferrer\">http://en.wikipedia.org/wiki/Facade_pattern</a></p></li>\n<li><p>Your business logic will be in the Service Layer, allowing them to be reused elsewhere, plus your controllers will be loosely coupled to your business logic</p></li>\n</ul>\n\n<p>example I've built: <a href=\"https://gist.github.com/3025099\" rel=\"noreferrer\">https://gist.github.com/3025099</a></p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-06-30T18:58:48.617", "Id": "13231", "ParentId": "11785", "Score": "22" } }, { "body": "<p>I would agree with @Mike reasoning of avoiding controller bloat via services.</p>\n<p>Wrapping up DbContext is a leaky abstraction. No matter what, you'll end up in some kind of dependency on EF in your services/controller layer.</p>\n<p>Besides that, I would avoid an extra layer of <code>UnitOfWork</code> and <code>Repository</code> simply because <code>DbContext</code> wraps that up for you already.</p>\n<p>Per <a href=\"http://msdn.microsoft.com/en-us/library/system.data.entity.dbcontext%28v=vs.103%29.aspx\" rel=\"noreferrer\">MSDN</a>:</p>\n<blockquote>\n<p>DbContext Class</p>\n<p>Represents a combination of the Unit-Of-Work and Repository patterns\nand enables you to query a database and group together changes that\nwill then be written back to the store as a unit.</p>\n</blockquote>\n<p>If you use any DI framework, you can manage lifetime of the DbContext and the services pretty easily.</p>\n<p>Further reading:\n<a href=\"http://ayende.com/blog/4784/architecting-in-the-pit-of-doom-the-evils-of-the-repository-abstraction-layer\" rel=\"noreferrer\">Architecting in the pit of doom: The evils of the repository abstraction layer</a></p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-10-15T13:57:16.130", "Id": "27930", "Score": "1", "body": "Nice link. I also follow Ayende's blog, and am well aware of his \"position\" on UoW and Repository :) You are right, EF's DbContext is already an abstraction, but I still think you should not use it in controllers directly (but via services, as you mentioned)." } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-10-14T00:30:20.783", "Id": "17513", "ParentId": "11785", "Score": "12" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "4", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-05-16T01:22:47.173", "Id": "11785", "Score": "65", "Tags": [ "c#", "design-patterns", "asp.net-mvc-3" ], "Title": "EF Code First with Repository, UnitOfWork and DbContextFactory" }
11785
<p>I'm developing a <a href="https://github.com/kentcdodds/Java-Helper">Java Helper Library</a> which has useful methods developers don't want to type out over and over. I'm trying to think of the best way of checking whether a string is a valid number.</p> <p>I've always just tried something like <code>Integer.parseInt(iPromiseImANumber);</code> and if it throws an exception then it's not a valid number (integer in this case). I'm thinking that trying to catch an exception isn't good practice. Is there a better way to do this? (I'm thinking a regular expression could do it, but it doesn't seem to be as reliable as the <code>parse</code> option).</p> <p>Here's my method as it stands. What could be improved?</p> <pre><code>/** * Does a try catch (Exception) on parsing the given string to the given type * * @param c the number type. Valid types are (wrappers included): double, int, float, long. * @param numString number to check * @return false if there is an exception, true otherwise */ public static boolean isValidNumber(Class c, String numString) { try { if (c == double.class || c == Double.class) { Double.parseDouble(numString); } else if (c == int.class || c == Integer.class) { Integer.parseInt(numString); } else if (c == float.class || c == Float.class) { Float.parseFloat(numString); } else if (c == long.class || c == Long.class) { Long.parseLong(numString); } } catch (Exception ex) { return false; } return true; } </code></pre>
[ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-05-16T02:15:23.067", "Id": "18900", "Score": "1", "body": "http://stackoverflow.com/questions/8391979/does-java-have-a-int-tryparse-that-doesnt-throw-an-exception-for-bad-data" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-05-16T02:24:34.863", "Id": "18902", "Score": "0", "body": "More relevant - http://stackoverflow.com/questions/9042922/does-googles-guava-have-a-java-tryparse-integer-method-or-something-simliar" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-05-16T10:57:57.683", "Id": "18913", "Score": "0", "body": "What exactly do you consider a \"valid number\"? IMHO in most use cases a \"valid number\" doesn't necessarily mean it has to be a valid Java Integer/Long/Float/Double." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-05-16T11:21:04.923", "Id": "18917", "Score": "0", "body": "What else could it be?" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-05-16T12:55:43.397", "Id": "18919", "Score": "0", "body": "I'm guessing that @RoToRa is referring to range checking. It won't matter if the value can be legally parsed to a given type if it is outside the range of reasonable/permitted values." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-05-16T13:10:27.643", "Id": "18920", "Score": "0", "body": "@Donald.McLean Basically, yes. It's unlikely that a real-life application has the same requirements to a \"number\" (range, decimal places, format) that the Java `parse*` methods allow." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-05-16T14:07:58.843", "Id": "18926", "Score": "0", "body": "Maybe I'm still not quite getting you, but the purpose of this method is to check whether a string can be parsed as an actual number, not whether it fulfills application-level requirements. Those can be handled by the application once the number's been parsed. But maybe I'm misunderstanding you..." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-05-20T10:16:36.723", "Id": "19127", "Score": "0", "body": "@kentcdodds But what is the point of having a program know if a string can be parsed as a number, especially if you want to parse it as a number anyway? You call `parse*` twice, first check for an exception, but throw away the result, and then again to get the number? Can you give a real life use case where you \"just\" need to know if a string is any kind of number." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-05-20T22:16:49.267", "Id": "19146", "Score": "0", "body": "@RoToRa, that's a good point. But how do you recommend as a return value in the case the given string is invalid? I suppose I could have the return be a wrapper and if it's invalid have the wrapper be null. But I don't know if that'd be as helpful. Do you have any other recommendations?" } ]
[ { "body": "<p>Well, my first instinct would be to apply a refactoring - specifically <a href=\"http://c2.com/cgi/wiki?ReplaceConditionalWithPolymorphism\">Replace Conditional With Polymorphism</a>.</p>\n\n<p>To do this, create an interface with one method (<code>isValidNumber</code> works). Create four implementations, one each for ints, doubles, floats and longs. Create a <code>HashMap&lt;Class, MyInterface&gt;</code>. Create one instance of each of the four classes and add them to the collection <em>twice</em>, once using the wrapped and unwrapped form of each type (int and Integer).</p>\n\n<p>Now your main <code>isValidNumber</code> implementation has about two lines. You get the implementation object out of the <code>HashMap</code> and then call it, returning the result.</p>\n\n<p>Now whether to use the parse methods from the numeric types or to use regular expressions or to code something of your own, such as a simple state machine, that's almost a matter of circumstances and personal taste. Each approach has strengths and weaknesses, though all three will work. If it's inside a tight loop, performance might even matter (though it's highly doubtful it will make that much difference).</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-05-16T05:41:26.783", "Id": "18909", "Score": "0", "body": "I'm not sure how to refactor this as the article you linked to discusses. You recommend making classes with the method?" } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-05-16T03:43:26.893", "Id": "11792", "ParentId": "11786", "Score": "5" } }, { "body": "<p>You could always just brute force it (NOTE: Not internationalized):</p>\n\n<pre><code>int decimalpoints = 0;\nforeach (Char i: numString) {\n if (i.isDigit()) continue;\n if (i != '.') return false;\n if (decimalpoints &gt; 0) return false;\n decimalpoints += 1;\n}\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-05-16T21:23:59.290", "Id": "18963", "Score": "1", "body": "Nope, this one won't work for all cases. For example, `Double.parseDouble(\"10E-3\")` is valid and evaluates to 0.01." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-05-16T23:58:38.707", "Id": "18975", "Score": "1", "body": "True, but it still may be acceptable to just not handle scientific notation input formats." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-05-17T09:06:00.657", "Id": "18992", "Score": "0", "body": "That's true too." } ], "meta_data": { "CommentCount": "3", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-05-16T07:17:08.240", "Id": "11797", "ParentId": "11786", "Score": "2" } }, { "body": "<p><a href=\"http://grepcode.com/file/repo1.maven.org/maven2/commons-lang/commons-lang/2.3/org/apache/commons/lang/math/NumberUtils.java#1366\" rel=\"noreferrer\"><code>NumberUtils.isNumber</code></a> from <a href=\"http://commons.apache.org/lang/\" rel=\"noreferrer\">Apache Commons Lang</a> does that.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-05-16T15:35:40.713", "Id": "18930", "Score": "0", "body": "See my benchmarking answer. This was definitely the fastest. Thanks for the tip!" } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-05-16T08:05:33.943", "Id": "11799", "ParentId": "11786", "Score": "10" } }, { "body": "<p>Ok, don't hate me, but this is all the answers above compiled into one. I benchmarked all the answers with the following code:</p>\n\n<pre><code>public static void parseNumber() throws Exception {\n long numberHelperTotal = 0;\n long numberUtilsTotal = 0;\n long regExTotal = 0;\n long bruteForceTotal = 0;\n long scannerTotal = 0;\n int iterations = 5;\n for (int i = 0; i &lt; iterations; i++) {\n long numberHelper = 0;\n long numberUtils = 0;\n long regEx = 0;\n long bruteForce = 0;\n long scanner = 0;\n for (int j = 0; j &lt; 99999; j++) {\n long start;\n long end;\n Random rand = new Random();\n String string = ((rand.nextBoolean()) ? \"\" : \"-\") + String.valueOf(rand.nextDouble() * j);\n //NumberHelper this is the try/catch solution seen above\n start = System.nanoTime();\n NumberHelper.isValidNumber(double.class, string);\n end = System.nanoTime();\n numberHelper += end - start;\n\n //NumberUtils\n start = System.nanoTime();\n NumberUtils.isNumber(string);\n end = System.nanoTime();\n numberUtils += end - start;\n\n //RegEx\n start = System.nanoTime();\n Pattern p = Pattern.compile(\"^[-+]?[0-9]*\\\\.?[0-9]+$\");\n Matcher m = p.matcher(string);\n if (m.matches()) {\n Double.parseDouble(string);\n }\n end = System.nanoTime();\n regEx += end - start;\n\n //Brute Force (not international support) and messy support for E and negatives\n //This is not the way to do it...\n start = System.nanoTime();\n int decimalpoints = 0;\n for (char c : string.toCharArray()) {\n if (Character.isDigit(c)) {\n continue;\n }\n if (c != '.') {\n if (c == '-' || c == 'E') {\n decimalpoints--;\n } else {\n //return false\n //because it should never return false in this test, I will throw an exception here if it does.\n throw new Exception(\"Brute Force returned false! It doesn't work! The character is \" + c + \" Here's the number: \" + string);\n }\n }\n if (decimalpoints &gt; 0) {\n //return false\n //because it should never return false in this test, I will throw an exception here if it does.\n throw new Exception(\"Brute Force returned false! It doesn't work! The character is \" + c + \" Here's the number: \" + string);\n }\n decimalpoints++;\n }\n end = System.nanoTime();\n bruteForce += end - start;\n\n //Scanner\n start = System.nanoTime();\n Scanner scanNumber = new Scanner(string);\n if (scanNumber.hasNextDouble()) {//check if the next chars are integer\n //return true;\n } else {\n //return false;\n //because it should never return false in this test, I will throw an exception here if it does.\n throw new Exception(\"Scanner returned false! It doesn't work! Here's the number: \" + string);\n }\n end = System.nanoTime();\n scanner += end - start;\n\n //Increase averages\n //For debug:\n //System.out.println(\"String: \" + string);\n //System.out.println(\"NumberHelper: \" + numberHelper);\n //System.out.println(\"NumberUtils: \" + numberUtils);\n //System.out.println(\"RegEx: \" + regEx);\n //System.out.println(\"Brute Force: \" + bruteForce);\n //System.out.println(\"Scanner: \" + scanner);\n }\n numberHelperTotal += numberHelper;\n numberUtilsTotal += numberUtils;\n regExTotal += regEx;\n bruteForceTotal += bruteForce;\n scannerTotal += scanner;\n }\n\n long numberHelperAvg = numberHelperTotal / iterations;\n long numberUtilsAvg = numberUtilsTotal / iterations;\n long regExAvg = regExTotal / iterations;\n long bruteForceAvg = bruteForceTotal / iterations;\n long scannerAvg = scannerTotal / iterations;\n System.out.println(\"NumberHelper: \" + (numberHelperAvg / 1000000) + \" milliseconds -&gt; \" + (numberHelperAvg / 1000000000) + \" seconds\");\n System.out.println(\"NumberUtils: \" + (numberUtilsAvg / 1000000) + \" milliseconds -&gt; \" + (numberUtilsAvg / 1000000000) + \" seconds\");\n System.out.println(\"RegEx: \" + (regExAvg / 1000000) + \" milliseconds -&gt; \" + (regExAvg / 1000000000) + \" seconds\");\n System.out.println(\"Brute Force: \" + (bruteForceAvg / 1000000) + \" milliseconds -&gt; \" + (bruteForceAvg / 1000000000) + \" seconds\");\n System.out.println(\"Scanner: \" + (scannerAvg / 1000000) + \" milliseconds -&gt; \" + (scannerAvg / 1000000000) + \" seconds\");\n}\n</code></pre>\n\n<p>The standings in the end were:</p>\n\n<pre><code>NumberHelper: 158 milliseconds -&gt; 0 seconds //Third place (this is the try/catch solution)\nNumberUtils: 26 milliseconds -&gt; 0 seconds //First place\nRegEx: 444 milliseconds -&gt; 0 seconds //Fourth place\nBrute Force: 39 milliseconds -&gt; 0 seconds //Second place, but a messy solution...\nScanner: 22204 milliseconds -&gt; 22 seconds //LAST place. Slow solution\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-05-16T22:07:36.583", "Id": "18970", "Score": "1", "body": "I am sorry but this is a horrible benchmark. How do you actually run it? Do you have any warm up at all?" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-05-17T01:27:27.317", "Id": "18978", "Score": "0", "body": "Haha, well I guess I still have a lot to learn about benchmarking. I've never done it before. I run it as is..." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-05-17T02:08:45.020", "Id": "18979", "Score": "0", "body": "A nice little read for you. http://stackoverflow.com/questions/504103/how-do-i-write-a-correct-micro-benchmark-in-java My last comment was bad, should have added in a few things sorry.. (Regex is slow and I wouldn't use it for this but not as slow as your benchmark because the pattern should be static and well... just read the other post.)" } ], "meta_data": { "CommentCount": "3", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-05-16T15:34:28.657", "Id": "11808", "ParentId": "11786", "Score": "4" } }, { "body": "<p>Saying \"is this string a valid number\" is quite pointless when you don't have a spec what a valid number is. For example, a valid JSON number can have a leading minus but not a leading plus, it can't start with a zero unless the integer part is a single zero, if there's a decimal point (not comma) then there must be digits after it, and the exponent can have a plus or minus and as many leading zeroes as it wants, just to be inconsistent. </p>\n\n<p>So there may be a spec, and you better test for that spec. If Double.parseDouble can't handle it then tough; check it by hand. Or you are handling user input. In that case I'd ask for common sense. 10e-3 should probably not be considered valid input, nor should 0x1234, nor should 0777 be different from 777. I'd probably ask to be nice about spaces, use localised decimal and thousand separators, handle $ or € gracefully. </p>\n\n<p>About the pattern matching speed test: I think patterns need to be compiled, and the compiling takes a long time, compared to the actual matching. I would assume that to parse a number using some specific method, a pattern would be compiled once and then reused again and again, so that's how it should be measured. </p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-03-14T16:47:49.590", "Id": "44367", "ParentId": "11786", "Score": "1" } } ]
{ "AcceptedAnswerId": "11799", "CommentCount": "9", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-05-16T01:59:49.457", "Id": "11786", "Score": "11", "Tags": [ "java", "strings", "validation" ], "Title": "Checking whether a string is a valid number" }
11786
<p>I have two icon animations that pretty much do the same thing, the only difference between them is positioning... one is left and the other right.</p> <p>I would like to use one block of code for both left and right icon animations.</p> <pre><code>//////////// Left Icon Animation //////////// $('.recent .left-icon').css({opacity:0, left:33}); $('.recent .controls-wrap').hover(function() { $(this).find('.left-icon').stop() .animate({left:63}, {duration:300}) .animate({opacity:'0.99'}, {duration:400}); },function() { $(this).find('.left-icon').stop() .animate({left:33}, {duration:550}) .animate({opacity:'0'}, {duration:300}); }); //////////// Right Icon Animation //////////// $('.recent .right-icon').css({opacity:0, right:33}); $('.recent .controls-wrap').hover(function() { $(this).find('.right-icon').stop() .animate({right:63}, {duration:300}) .animate({opacity:'0.99'}, {duration:400}); },function() { $(this).find('.right-icon').stop() .animate({right:33}, {duration:550}) .animate({opacity:'0'}, {duration:300}); }); </code></pre>
[]
[ { "body": "<p>Make a function with one parameter, depending on the direction (right or left), copy a block of code and replace the key word there. </p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-05-16T03:42:49.440", "Id": "11791", "ParentId": "11789", "Score": "1" } }, { "body": "<p>Why don't you add a common class name, say, <code>anim-icon</code> to both the icons, and add a <code>left</code> and <code>right</code> class to each one of them.</p>\n\n<p>Then: </p>\n\n<pre><code>$('.recent .anim-icon').each(function(){\n // thisClass will have either left or right\n var thisClass = $(this).attr('class').replace('anim-icon ',''),\n $this = $(this);\n $this.css({opacity:0, thisClass:33});\n $('.recent .controls-wrap').hover(function() {\n $this.stop()\n .animate({thisClass:63}, {duration:300})\n .animate({opacity:'0.99'}, {duration:400});\n },function() {\n $this.stop()\n .animate({thisClass:33}, {duration:550})\n .animate({opacity:'0'}, {duration:300});\n });\n});\n</code></pre>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-05-16T03:44:41.603", "Id": "11793", "ParentId": "11789", "Score": "1" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-05-16T03:31:31.090", "Id": "11789", "Score": "0", "Tags": [ "javascript", "jquery", "animation" ], "Title": "Two icon animations — one on the left, one on the right" }
11789
<p>I've written a program that creates the (minimal unique) directed acyclic graph from the tree structure of an XML-document. The program prints a Bplex-Grammar to cout. I'm interested in all kinds of remarks, and especially performance optimization. </p> <pre><code>#include &lt;iostream&gt; #include &lt;sstream&gt; #include &lt;boost/foreach.hpp&gt; #include &lt;boost/functional/hash.hpp&gt; #include &lt;libxml++/libxml++.h&gt; #include &lt;string&gt; #include &lt;stack&gt; #include &lt;vector&gt; #include &lt;tr1/unordered_map&gt; #include &lt;tr1/unordered_set&gt; #include &lt;list&gt; // compile with: g++ -Wall -g -Wno-deprecated `pkg-config --cflags libxml++-2.6` -o Dag dag.cpp `pkg-config --libs libxml++-2.6` using namespace std; using namespace tr1; class TreeNode; class TreeNodeHasher; class TreeNodeEqualityTester; typedef list&lt;unsigned int&gt; childrenList; typedef unordered_map&lt;unsigned int, unsigned int&gt; GRAMMAR_MAP; typedef unordered_map&lt;TreeNode*, unsigned int, TreeNodeHasher, TreeNodeEqualityTester&gt; TREE_HASH_MAP; typedef unordered_map&lt;unsigned int, TreeNode*&gt; RULES_MAP; class TreeNodeHasher : unary_function&lt;TreeNode*, size_t&gt;{ public: size_t operator()(TreeNode * pNode) const; }; class TreeNodeEqualityTester : std::binary_function&lt;TreeNode*, TreeNode*, bool&gt;{ public: bool operator()(TreeNode *pNode1, TreeNode *pNode2) const; }; class TreeNode{ friend class TreeNodeHasher; friend class TreeNodeEqualityTester; public: TreeNode(){;} TreeNode(string namePar, childrenList childrenListPar); ~TreeNode(){;} string getName(){return this-&gt;name;} unsigned int getNumberOfChildren(){return this-&gt;numberOfChildren;} childrenList getKidsList(){return this-&gt;kidsList;} void incrementRefCount(){refCount++;} unsigned int getRefCount(){return refCount;} private: string name; childrenList kidsList; unsigned int numberOfChildren; unsigned int refCount; }; class MySaxParser : public xmlpp::SaxParser { public: MySaxParser(char * pFilePath, bool printProductionsPar); ~MySaxParser(void); void printProduction(TreeNode *pNode, unsigned int lhs, bool start); protected: //overrides: virtual void on_end_document(); virtual void on_start_element(const Glib::ustring&amp; name,const AttributeList&amp; properties); virtual void on_end_element(const Glib::ustring&amp; name); private: unsigned int leftHandSides; /** * For print use only. */ unsigned int printedLeftHandSides; /** * The childrenStack is needed for parsing only. */ stack&lt; childrenList*&gt; childrenStack; /** * The hash map of all trees encountered till now. TreeNode-&gt;unsigned int */ TREE_HASH_MAP treeHashMap; /** * Only if a rule is the start production or encountered at least twice is it added to grammarMap. * It maps to the id of the TreeNode that has been found at least twice. */ GRAMMAR_MAP grammarMap; /** * All unsigned int -&gt; TreeNode are placed here. We need this for printing. */ RULES_MAP rulesMap; /** * If true, we print the productions. */ bool printProductions; }; bool isNumber(string s){ if(atoi(s.c_str()) &gt; 0) return true; else return false; } string toString(unsigned int number){ stringstream ss;//create a stringstream ss &lt;&lt; number;//add number to the stream return ss.str();//return a string with the contents of the stream } TreeNode::TreeNode(string namePar, childrenList childrenListPar): name(namePar), kidsList(childrenListPar), refCount(1){ numberOfChildren = kidsList.size(); } size_t TreeNodeHasher::operator()(TreeNode *pNode) const { size_t hash_value = 0; hash_value = tr1::hash&lt;string&gt;()(pNode-&gt;name); boost::hash_combine(hash_value, pNode-&gt;kidsList); return hash_value; } bool TreeNodeEqualityTester::operator()(TreeNode *pNode1, TreeNode *pNode2) const{ if(pNode1-&gt;name != pNode2-&gt;name){ return false; } if(pNode1-&gt;numberOfChildren != pNode2-&gt;numberOfChildren){ return false; } if(pNode1-&gt;kidsList != pNode2-&gt;kidsList){ return false; } return true; } MySaxParser::MySaxParser(char * pFilePath, bool printProductionsPar) : xmlpp::SaxParser::SaxParser(), leftHandSides(2), printedLeftHandSides(2), printProductions(printProductionsPar){ this-&gt;set_substitute_entities(true); // this-&gt;parse_file(pFilePath); } MySaxParser::~MySaxParser(void){ BOOST_FOREACH(TREE_HASH_MAP::value_type i, treeHashMap){ delete i.first; } } void MySaxParser::on_start_element(const Glib::ustring&amp; name,const AttributeList&amp; attributes){ childrenList * chList = new childrenList(); childrenStack.push(chList); } void MySaxParser::on_end_element(const Glib::ustring&amp; name){ unsigned int lhs = 0; string tmpname = name.raw(); TreeNode * pTopNode = new TreeNode(tmpname, *childrenStack.top()); delete childrenStack.top(); childrenStack.pop(); TREE_HASH_MAP::iterator it = treeHashMap.find(pTopNode); if(it == treeHashMap.end()){ // we've found the node for the first time if(childrenStack.size() == 0){ //root node treeHashMap[pTopNode] = 1; rulesMap[1] = pTopNode; grammarMap[1] = 1; if(printProductions){ printProduction(pTopNode, 1, true); cout &lt;&lt; endl; } return; }else{ //non-root node. treeHashMap[pTopNode] = leftHandSides; rulesMap[leftHandSides] = pTopNode; } lhs = leftHandSides; leftHandSides++; } else{ delete pTopNode; lhs = it-&gt;second; it-&gt;first-&gt;incrementRefCount(); if(it-&gt;first-&gt;getRefCount() == 2 &amp;&amp; it-&gt;first-&gt;getNumberOfChildren() &gt; 0 ){ //we've found the rule twice, hence we add it to the grammarMap. grammarMap[lhs] = printedLeftHandSides; if(printProductions){ printProduction(it-&gt;first, printedLeftHandSides, true); cout &lt;&lt; endl; } printedLeftHandSides++; } } childrenList * chList = childrenStack.top(); chList-&gt;push_back(lhs); } void MySaxParser::on_end_document(){ cout &lt;&lt; "size: " &lt;&lt; treeHashMap.size() &lt;&lt; endl; } void MySaxParser::printProduction(TreeNode *pNode, unsigned int lhs, bool start){ if(start) cout &lt;&lt; "A" &lt;&lt; lhs &lt;&lt; " -&gt; "; cout &lt;&lt; pNode-&gt;getName() ; if(pNode-&gt;getNumberOfChildren() &gt; 0){ unsigned int commaCounter = 1; TreeNode * pKidNode = 0; childrenList printList = pNode-&gt;getKidsList(); childrenList::iterator chIt; GRAMMAR_MAP::iterator grIt; RULES_MAP::iterator ruIt; cout &lt;&lt; "(" ; for(chIt = printList.begin(); chIt != printList.end(); chIt++){ grIt = grammarMap.find(*chIt); if(grIt == grammarMap.end()){ ruIt = rulesMap.find(*chIt); pKidNode = ruIt-&gt;second; printProduction(pKidNode, lhs, false); } else{ cout &lt;&lt; grIt-&gt;second; } if(commaCounter &lt; pNode-&gt;getNumberOfChildren()){ cout &lt;&lt; ", "; } commaCounter++; } cout &lt;&lt; ")" ; } } int main(int argc, char* args[]){ if(argc &lt; 2){ cout &lt;&lt; "Please add file. " &lt;&lt; endl; return 0; } char * pFilePath = args[1]; MySaxParser mySaxParser(pFilePath, true); return 0; } </code></pre>
[]
[ { "body": "<p>You don't need the semi-colon(';') here (it looks weird).</p>\n\n<pre><code> TreeNode(){;}\n</code></pre>\n\n<p>The default destructor also does nothing.<br>\nIf you are not doing anything use the one provided.</p>\n\n<pre><code> ~TreeNode(){;}\n</code></pre>\n\n<p>You TreeNode methods are not <code>const correct</code>:<br>\nMark methods that are non mutating as <code>const</code>. Return objects by reference to avoid a copy operation. If you don not want to give access to the underlying object then return a const reference to the object.</p>\n\n<pre><code> string const&amp; getName() const {return this-&gt;name;}\n unsigned int getNumberOfChildren() const {return this-&gt;numberOfChildren;}\n childrenList const&amp; getKidsList() const {return this-&gt;kidsList;}\n unsigned int getRefCount() const {return refCount;}\n</code></pre>\n\n<p>Prefer pre-increment to post-increment.<br>\nFor fundamental types there is no advantage for either. But for object types there is a difference as the default implementation requires an extra copy construction for post-increment. Even though you are using a fundamental type here that may not always be the case (future extensions may change things) in which case you have to go and change your post-increment to pre-increment to stay effecient. So it is a good habbit to get into.</p>\n\n<pre><code> void incrementRefCount() {refCount++;}\n</code></pre>\n\n<p>I am not convinced you is_Number() function works: </p>\n\n<pre><code>bool isNumber(string s){\n if(atoi(s.c_str()) &gt; 0)\n return true;\n else\n return false;\n}\n</code></pre>\n\n<p>What happens for <code>isNumber(\"0\")</code></p>\n\n<p>Also pass the string parameter by <code>const reference</code> This allows remporaries to be passed to the function (otherwise the above call will not work as the compiler can not construct a temporary std::string object and pass it to isNumber()).</p>\n\n<p>Other issues:</p>\n\n<ul>\n<li>atoi() is relatively expensive.</li>\n<li>\"12.34\" is a number and would return true (I think) is that what you intended?</li>\n</ul>\n\n<p>Your convert to string method:</p>\n\n<pre><code>string toString(unsigned int number){\n stringstream ss;//create a stringstream\n ss &lt;&lt; number;//add number to the stream\n return ss.str();//return a string with the contents of the stream\n}\n</code></pre>\n\n<p>Find a standard one they have been done a million times before.</p>\n\n<pre><code>boost::lexical_cast&lt;std::string&gt;() // should work for you.\n</code></pre>\n\n<p>If you must do it yourself at least templatise it so that it works for anything:</p>\n\n<pre><code>template&lt;typename T&gt;\nstring toString(T const&amp; number)\n{\n stringstream ss; //create a stringstream\n ss &lt;&lt; number; //add object to the stream\n return ss.str(); //return a string with the contents of the stream\n}\n</code></pre>\n\n<p>One operation per line please. That includes the initalizer list:</p>\n\n<pre><code>TreeNode::TreeNode(string namePar, childrenList childrenListPar):\n // \n // This is hard to read.\n name(namePar), kidsList(childrenListPar), refCount(1){\n numberOfChildren = kidsList.size();\n}\n\n// I like:\n\nTreeNode::TreeNode(string namePar, childrenList childrenListPar)\n : name(namePar)\n , kidsList(childrenListPar)\n , numberOfChildren(kidsList.size())\n , refCount(1)\n{}\n</code></pre>\n\n<p>Dislkie the use of this argument to call methods with:</p>\n\n<pre><code>this-&gt;set_substitute_entities(true); //\nthis-&gt;parse_file(pFilePath);\n</code></pre>\n\n<p>Why not just use:</p>\n\n<pre><code>set_substitute_entities(true);\nparse_file(pFilePath);\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-05-16T20:21:36.783", "Id": "18959", "Score": "0", "body": "Thank you very much for your answer. You're right with the isNumber()-method, it actually isn't correct that way. I think I will find something better to replace it, but for that code it works because I don't use 0 anywhere. I worked in all the other suggestions (I also removed the toString()-method)." } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-05-16T16:25:37.937", "Id": "11810", "ParentId": "11801", "Score": "1" } } ]
{ "AcceptedAnswerId": "11810", "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-05-16T09:57:18.670", "Id": "11801", "Score": "2", "Tags": [ "c++", "optimization", "xml" ], "Title": "Create Directed Acyclic Graph (DAG) from XML-Tree" }
11801
<p>I have translated the following F# code to C# and would appreciate constructive criticism. This code computes the symbolic derivative of the expression f(x)=x³-x-1:</p> <pre><code>type Expr = | Int of int | Var of string | Add of Expr * Expr | Mul of Expr * Expr let rec d f x = match f with | Var y when x=y -&gt; Int 1 | Int _ | Var _ -&gt; Int 0 | Add(f, g) -&gt; Add(d f x, d g x) | Mul(f, g) -&gt; Add(Mul(f, d g x), Mul(g, d f x)) let f = let x = Var "x" Add(Add(Mul(x, Mul(x, x)), Mul(Int -1, x)), Int -1) d f "x" </code></pre> <p>My translation from F# to C# fragments the <code>d</code> function into member functions in classes that implement an <code>Expr</code> interface and adds a hand-written structural pretty printers:</p> <pre><code>using System; public interface Expr { Expr d(string x); } public class Int : Expr { int n; public Int(int m) { n = m; } public int Value { get { return n; } } public Expr d(string x) { return new Int(0); } public override string ToString() { return "Int " + n.ToString(); } } public class Var : Expr { string x; public Var(string y) { x = y; } public string Value { get { return x; } } public Expr d(string y) { return (x == y ? new Int(1) : new Int(0)); } public override string ToString() { return "Var \"" + x + "\""; } } public class Add : Expr { Expr f, g; public Add(Expr a, Expr b) { f = a; g = b; } public Tuple&lt;Expr, Expr&gt; Value { get { return Tuple.Create(f, g); } } public Expr d(string y) { return new Add(f.d(y), g.d(y)); } public override string ToString() { return "Add(" + f.ToString() + ", " + g.ToString() + ")"; } } class Mul : Expr { Expr f, g; public Mul(Expr a, Expr b) { f = a; g = b; } public Tuple&lt;Expr, Expr&gt; Value { get { return Tuple.Create(f, g); } } public Expr d(string y) { return new Add(new Mul(f, g.d(y)), new Mul(g, f.d(y))); } public override string ToString() { return "Mul(" + f.ToString() + ", " + g.ToString() + ")"; } } class SymbolicDerivative { static void Main(string[] args) { var x = new Var("x"); var f = new Add(new Add(new Mul(x, new Mul(x, x)), new Mul(new Int(-1), x)), new Int(-1)); Console.WriteLine("{0}", f.d("x").ToString()); } } </code></pre> <p>I have also written the derivative function externally to the class hierarchy using the <code>is</code> operator to inspect the type of a given value but I chose this code because I believe it is more idiomatic OOP style.</p>
[ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-06-18T18:46:45.453", "Id": "20559", "Score": "1", "body": "I think that's as good as it gets in C# (sigh)." } ]
[ { "body": "<p>First, there are some code naming and formatting standards in C# that you should follow:</p>\n\n<ul>\n<li>Interfaces begin with I</li>\n<li>Method names are Pascal-cased</li>\n</ul>\n\n<p>And here are a small smattering of my personal standards:</p>\n\n<ul>\n<li>Specify access modifiers at all times (source code are for humans to read)</li>\n<li>Declare non-changing fields with <code>readonly</code> (primarily for intent,\nbut there is supposed performance advantages)</li>\n<li>Declare non-inheritable classes with <code>sealed</code> (again, for intent, but there could be\nperformance advantages)</li>\n<li>Use <code>this.</code> as a prefix for class members</li>\n</ul>\n\n<p>Simple matters:</p>\n\n<ul>\n<li>Test for <code>null</code> where you would not want to have <code>null</code> objects (i.e. in the constructor)</li>\n<li>Instead of returning a <code>new Int(0)</code> each time in <code>D()</code>, have it be a pre-initialized <code>static</code> member.</li>\n<li>I'm thinking the same for <code>new Int(1)</code>? Your mileage may vary.</li>\n</ul>\n\n<p>All in all, I really like your approach as loosely-coupled OOP using injection.</p>\n\n<p>Given those, I would lightly refactor as such:</p>\n\n<pre><code>namespace SymbolicDerivative\n{\n using System;\n\n public interface IExpr\n {\n IExpr D(string x);\n }\n\n public sealed class Int : IExpr\n {\n private static readonly IExpr intZero = new Int(0);\n\n private static readonly IExpr intOne = new Int(1);\n\n private readonly int n;\n\n public Int(int m)\n {\n this.n = m;\n }\n\n public static IExpr IntZero\n {\n get { return intZero; }\n }\n\n public static IExpr IntOne\n {\n get { return intOne; }\n }\n\n public int Value\n {\n get { return this.n; }\n }\n\n public IExpr D(string x)\n {\n return intZero;\n }\n\n public override string ToString()\n {\n return \"Int \" + this.n;\n }\n }\n\n public sealed class Var : IExpr\n {\n private readonly string x;\n\n public Var(string y)\n {\n if (y == null)\n {\n throw new ArgumentNullException(\"y\");\n }\n\n this.x = y;\n }\n\n public string Value\n {\n get { return this.x; }\n }\n\n public IExpr D(string y)\n {\n return this.x == y ? Int.IntOne : Int.IntZero;\n }\n\n public override string ToString()\n {\n return \"Var \\\"\" + this.x + \"\\\"\";\n }\n }\n\n public sealed class Add : IExpr\n {\n private readonly IExpr f;\n\n private readonly IExpr g;\n\n public Add(IExpr a, IExpr b)\n {\n if (a == null)\n {\n throw new ArgumentNullException(\"a\");\n }\n\n if (b == null)\n {\n throw new ArgumentNullException(\"b\");\n }\n\n this.f = a;\n this.g = b;\n }\n\n public Tuple&lt;IExpr, IExpr&gt; Value\n {\n get { return Tuple.Create(this.f, this.g); }\n }\n\n public IExpr D(string y)\n {\n return new Add(this.f.D(y), this.g.D(y));\n }\n\n public override string ToString()\n {\n return \"Add(\" + this.f + \", \" + this.g + \")\";\n }\n }\n\n public sealed class Mul : IExpr\n {\n private readonly IExpr f;\n\n private readonly IExpr g;\n\n public Mul(IExpr a, IExpr b)\n {\n if (a == null)\n {\n throw new ArgumentNullException(\"a\");\n }\n\n if (b == null)\n {\n throw new ArgumentNullException(\"b\");\n }\n\n this.f = a;\n this.g = b;\n }\n\n public Tuple&lt;IExpr, IExpr&gt; Value\n {\n get { return Tuple.Create(this.f, this.g); }\n }\n\n public IExpr D(string y)\n {\n return new Add(new Mul(this.f, this.g.D(y)), new Mul(this.g, this.f.D(y)));\n }\n\n public override string ToString()\n {\n return \"Mul(\" + this.f + \", \" + this.g + \")\";\n }\n }\n\n internal static class SymbolicDerivative\n {\n private static void Main()\n {\n var x = new Var(\"x\");\n var f = new Add(new Add(new Mul(x, new Mul(x, x)), new Mul(new Int(-1), x)), new Int(-1));\n\n Console.WriteLine(\"{0}\", f.D(\"x\"));\n Console.ReadLine();\n }\n }\n}\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-05-16T14:29:09.423", "Id": "18927", "Score": "0", "body": "I don't think always specifying access modifiers is an accepted standard. (Though personally I agree it's usually a good idea to specify them even when it's not necessary.)" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-05-16T14:41:37.060", "Id": "18928", "Score": "0", "body": "I thought I had a document from MS where they said this, but I can't find my reference for the life of me. Editing to de-emphasize." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-05-16T17:01:08.363", "Id": "18936", "Score": "1", "body": "@svick, I see nothing wrong with such mandate (unless it does not compile, such as when declaring an interface). What is a good reason to omit those? Personally, I do not remember all of the defaults off the top of my head. That is a damn good reason to force those. That plus there is a StyleCop rule for that, and I personally would gladly exchange freedom for convenience in that case." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-05-16T17:14:36.457", "Id": "18937", "Score": "0", "body": "@Leonid, I wasn't arguing against it (although, personally, I think `intenal` modifiers for types are useless), just that I don't think it's an accepted standard." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2016-09-20T15:58:56.260", "Id": "266046", "Score": "0", "body": "I find `private readonly` to be redundant with just `readonly`." } ], "meta_data": { "CommentCount": "5", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-05-16T14:19:52.423", "Id": "11806", "ParentId": "11804", "Score": "2" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "1", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-05-16T13:42:25.877", "Id": "11804", "Score": "6", "Tags": [ "c#", "f#" ], "Title": "Symbolic derivative in C#" }
11804
<p>This is <a href="http://htdp.org/2003-09-26/Book/curriculum-Z-H-16.html#node_sec_12.4" rel="nofollow">HtDP Excercise 12.4.2</a>:</p> <blockquote> <p>Develop a function insert-everywhere. It consumes a symbol and a list of words. The result is a list of words like its second argument, but with the first argument inserted between all letters and at the beginning and the end of all words of the second argument.</p> </blockquote> <p>This is what I wrote:</p> <pre><code>#lang racket ;Data Definition: ;a symbol, list of symbols ;Contract: ;insert-everywhere: symbol, list of symbols -&gt; list of list of symbols ;The function returns a list of list of symbols wherein the symbol is inserted at every position ;Example: ; (insert-everywhere 'a '(b c d)) -&gt; '((a b c d) (b a c d) (b c a d) (b c d a)) ;Definition: (define (insert-everywhere sym los) (define lst-len (find-len los)) (define (iter n) (cond ((= n (+ lst-len 1)) '()) (else (cons (insert n sym los) (iter (+ n 1)))))) (iter 0)) ;The above function first finds the list length. ;Then it itereratively inserts the symbol at every position one by one, including in the end. ;Data Definition: ;list of symbols ;Contract: ;find-len : list of symbols-&gt; number ;find the length of the list ;Example: ;(find-len (list 'b 'c 'd)) -&gt; 3 ;Definition: (define (find-len los) (cond ((null? los) 0) (else (+ 1 (find-len (cdr los)))))) ;Data Definition: ;number , symbol, list of symbols ;Contract: ;insert : position, element, list of symbols-&gt; list of symbols ;insert the element in the given position in the list ;Example: ;(insert 2 'a '(b c d)) -&gt; '(b c a d) ;Definition: (define (insert pos elm los) (cond ((= pos 0) (cons elm los)) (else (cons (car los) (insert (- pos 1) elm (cdr los)))))) </code></pre> <p>Here is the tests I conducted:</p> <pre><code>(insert-everywhere 'a '()) ; returns '((a)) (insert-everywhere 'a '(b)) ; returns '((a b) (b a)) (insert-everywhere 'a '(b c d)) ; returns '((a b c d) (b a c d) (b c a d) (b c d a)) </code></pre> <p>It works, but I think this is not the way it was supposed to be solved. In their hint, they ask to use only recursion and append, but I didn't really get it. Could someone suggest a better answer?</p>
[ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-03-07T07:10:55.157", "Id": "36338", "Score": "0", "body": "You may have misunderstood the question. Also use standard procedures as much as possible. e.g. `length` instead of `find-len`." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2015-07-29T09:20:09.017", "Id": "180393", "Score": "0", "body": "I also think you may have misunderstood the challenge. I believe `(insert-everywhere 'a '(b c d))` should produce `'(a b a c a d a)`." } ]
[ { "body": "<p>Check <a href=\"https://stackoverflow.com/questions/20125784/insert-everywhere-procedure/\">this Stack Overflow question</a> out, which has a solution to the same problem. A simplified version would look like this</p>\n\n<pre><code>(define (insert-at pos elmt lst)\n (if (empty? lst) (list elmt)\n (if (= 1 pos)\n (cons elmt lst)\n (cons (first lst) \n (insert-at (- pos 1) elmt (rest lst))))))\n\n(define (insert-everywhere sym los)\n (map (lambda (i)\n (insert-at i sym los)\n )\n (range 1 (+ 2 (length los)))))\n</code></pre>\n\n<ol>\n<li><p>There is a function written for inserting at a particular position.</p></li>\n<li><p>Then we have our iterative function that maps over the elements in the list. </p></li>\n</ol>\n\n<p>Alternatively, there is the recursive solution found in the link above. It does this by using conditions and cons (which appends to lists together). It seams a bit clunky, but <code>map</code> really cleans it up.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2015-07-29T06:08:56.597", "Id": "98424", "ParentId": "11805", "Score": "2" } }, { "body": "<p>Inserting an element into a list at some index is not really idiomatic in Lisp-like languages. With proper use of recursion, indexing is not necessary at all, and the solution is much simpler.</p>\n\n<pre><code>(define (insert-everywhere sym los)\n (define (prepend a) (lambda (as) (cons a as)))\n (if (empty? los)\n (list (list sym))\n (cons (cons sym los)\n (map (prepend (car los)) \n (insert-everywhere sym (cdr los))))))\n</code></pre>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2015-07-29T07:21:15.790", "Id": "98432", "ParentId": "11805", "Score": "1" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "2", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-05-16T14:06:46.247", "Id": "11805", "Score": "5", "Tags": [ "scheme", "racket" ], "Title": "Insert-everywhere function" }
11805
<p>I've used this PHP/AJAX method of validation for a bit, but I think it could use a little peer review. The basic idea was to create a way of verifying forms in a nice manor using AJAX, but also fall-back to PHP when the user disables JavaScript.</p> <p>One extra note: jQuery is used throughout the JavaScript files.</p> <p><strong>field_validation.php</strong></p> <pre><code>if (isset($_POST['field']) &amp;&amp; isset($_POST['value'])) { require_once('includes/functions.php'); // Allows connection to the database $field = $_POST['field']; $value = $_POST['value']; echo validate_input($field, $value); } function validate_input($field, $input) { switch ($field) { case 'email': if ($input != '') { // We need the validate_email() function, so we now require the file with it in. (Not included as I'm happy with it's validation and this is only used as an example) require_once ('validate_email.php'); if (validate_email($input) == false) { return 'Please enter a valid email'; } } else { return 'Please enter an email'; } // Check email address is not already taken $db = mysqlConnect(); $stmt = $db-&gt;stmt_init(); $stmt-&gt;prepare("SELECT EXISTS(SELECT 1 FROM users WHERE email = ?)"); $stmt-&gt;bind_param('s', $input); $stmt-&gt;execute(); $stmt-&gt;bind_result($alreadyTaken); $stmt-&gt;fetch(); $stmt-&gt;close(); $db-&gt;close(); if ($alreadyTaken) { return 'Email address already in use, you cannot sign up again'; } return true; break; case 'password': if (strlen($input) &lt;= 6) { return 'Please enter a password more than 6 characters in length'; } return true; break; case 'twitter': if (strlen($input) &lt; 1 ) { return true; } if (strlen($input) &gt;= 16) { return 'Twitter Usernames cannot be more than 15 cahraters in length (excluding the @ symbol)'; } $apiurl = 'http://api.twitter.com/1/users/show.xml?screen_name=' . $input; if (!@fopen($apiurl, 'r')) { return 'Username does not exist, please enter a valid username'; } // Check twitter name is not already taken $db = mysqlConnect(); $stmt = $db-&gt;stmt_init(); $stmt-&gt;prepare("SELECT EXISTS(SELECT 1 FROM users WHERE twitter = ?)"); $stmt-&gt;bind_param('s', $input); $stmt-&gt;execute(); $stmt-&gt;bind_result($alreadyTaken); $stmt-&gt;fetch(); $stmt-&gt;close(); $db-&gt;close(); if ($alreadyTaken) { return 'Twitter name already in use, please chose another name'; } return true; break; case 'displayname': if (strlen($input) &lt; 1) { return 'Please enter a Display Name'; } if (strlen($input) &gt; 64) { return 'Please enter a Display Name shorter than 65 charaters'; } $db = mysqlConnect(); $stmt = $db-&gt;stmt_init(); $stmt-&gt;prepare("SELECT EXISTS(SELECT 1 FROM users WHERE display_name = ?)"); $stmt-&gt;bind_param('s', $input); $stmt-&gt;execute(); $stmt-&gt;bind_result($alreadyTaken); $stmt-&gt;fetch(); $stmt-&gt;close(); $db-&gt;close(); if ($alreadyTaken) { return 'Display Name already in use, please chose another name'; } return true; break; case 'termsandconditons': if ($input != 'on') { return 'You must accept the Terms and Conditions'; } return true; break; default: return true; break; } } function showErrors($errors) { ?&gt; &lt;div id="errors"&gt; Errors&lt;br&gt; &lt;ul&gt; &lt;? for ($i = 0; $i &lt; count($errors); $i++) { if (isset($errors[$i]['name'])) { // Highlight the field ?&gt; &lt;script&gt; var cross = '&lt;img src="/images/cross.png"&gt;'; $(document).ready(function(){ $('#&lt;? echo $errors[$i]['name']; ?&gt;hint').html(cross); }); &lt;/script&gt; &lt;? } ?&gt; &lt;li&gt; &lt;? echo $errors[$i]['message']; ?&gt;&lt;br &gt; &lt;/li&gt; &lt;? } ?&gt; &lt;/ul&gt; &lt;/div&gt; &lt;? } </code></pre> <p>This is included in each of the pages that require validation. I have removed some of the extra cases since they are pretty much the same as the ones shown.</p> <p><strong>validatefields.js</strong></p> <pre><code>var cross = '&lt;img src="/images/cross.png"&gt;'; var tick = '&lt;img src="/images/tick.png"&gt;'; var loading = '&lt;img src="images/loading.gif"&gt;'; // Send the data from the form to the PHP file 'jqueryvalidate.php', where they will call the function to validate the data $('input:text,input:password,input[type=email]').blur(function() { // Get the input from the form var fieldid = $(this).attr('id'); var fieldvalue = $(this).attr('value'); $('#' + fieldid + 'hint').html(loading); $.ajax ({ url: 'field_validation.php', data: {field: fieldid, value: fieldvalue}, type: 'post', cache: false, success: function(message) { if (message != true) { // Error was returned, show a cross $('#' + fieldid + 'hint').html(cross + message); } else { // No error, show a tick $('#' + fieldid + 'hint').html(tick); } } }); }); $('input:checkbox').click(function() { // Get the input from the form var fieldid = $(this).attr('id'); if ($(this).attr('checked') == 'checked') { var fieldvalue = 'on'; } else { var fieldvalue = 'off'; } $('#' + fieldid + 'hint').html(loading); $.ajax ({ url: 'jqueryvalidate.php', data: {field: fieldid, value: fieldvalue}, type: 'post', cache: false, success: function(message) { if (message != true) { // Error was returned, show a cross $('#' + fieldid + 'hint').html(cross + message); } else { // No error, show a tick $('#' + fieldid + 'hint').html(tick); } } }); }); </code></pre> <p>As you can see, this has two different functions for the validation: one for text, password and email fields and another for checkboxes. Could this be tidied up a little?</p> <p><strong>Finally, an example form (mypage.php)</strong></p> <pre><code>if($_SERVER['REQUEST_METHOD'] == "POST") { $errors = array(); // Form has been submitted foreach($_POST as $key =&gt; $value) { $$key = $value; // Set the title of the field to its name if (validate_input($key, $value) != 'true') { // Value is invalid $error['message'] = validate_input($key, $value); $error['name'] = $key; array_push($errors, $error); } } if (!isset($_POST['termsandconditions'])) { // This could be improved if (validate_input('termsandconditions', 'off') != 'true') { // Value is invalid $error['message'] = validate_input('termsandconditions', 'off'); $error['name'] = 'termsandconditions'; array_push($errors, $error); } } if (count($errors) &gt; 0) { // Input data failed validation showErrors($errors); } else { // The form has successfully validated } &lt;form action="mypage.php" method="POST"&gt; &lt;label for="displayname"&gt;*Display Name: &lt;/label&gt; &lt;input type="text" name="displayname" id="displayname" &lt;? if (isset($_POST['displayname'])) echo 'value="' . $_POST['displayname'] . '"' ?&gt; &gt;&lt;br&gt; &lt;div id="displaynamehint"&gt;&lt;/div&gt;&lt;br&gt; &lt;label for="email"&gt;*Email: &lt;/label&gt; &lt;input type="email" name="email" id="email" &lt;? if (isset($_POST['email'])) echo 'value="' . $_POST['email'] . '"' ?&gt; &gt;&lt;br&gt; &lt;div id="emailhint"&gt;&lt;/div&gt;&lt;br&gt; &lt;label for="password"&gt;*Password: &lt;/label&gt; &lt;input type="password" name="password" id="password"&gt;&lt;br&gt; &lt;div id="passwordhint"&gt;&lt;/div&gt;&lt;br&gt; &lt;label for="twitter"&gt;Twitter Username: &lt;/label&gt; &lt;span class="twitterinput"&gt;@&lt;input type="text" name="twitter" id="twitter" &lt;? if (isset($_POST['twitter'])) echo 'value="' . $_POST['twitter'] . '"' ?&gt; &gt;&lt;/span&gt;&lt;br&gt; &lt;div id="twitterhint"&gt;&lt;/div&gt;&lt;br&gt; &lt;input type="checkbox" name="termsandconditions" id="termsandconditions" &lt;? if (isset($_POST['termsandconditions'])) echo 'checked="checked"'?&gt; &gt;&lt;label for="termsandconditions"&gt;*I have fully read, understand and agree to &lt;a href="termsandconditions.php" target="_blank"&gt;the terms and conditions&lt;/a&gt;&lt;/label&gt;&lt;div id="termsandconditionshint"&gt;&lt;/div&gt;&lt;br&gt; &lt;input type="submit" name="submit" value="Submit"&gt; &lt;/form&gt; </code></pre>
[ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-05-16T18:26:38.917", "Id": "18942", "Score": "1", "body": "I'm feeling too lazy at the moment to write a proper answer, so a few pointers: Don't compare a boolean to it's string equivalent. Either do `if ($a)` or `if ($a === true)` or `if (!$a)` or `if ($a === false)` (if you know it's a boolean, I'd tend towards the `===` options). Pass your DB instance to the validate_input function. You're unnecessarily tying your validate_input function to mysqlConnect(). A random function should not be responsible for setting up a DB connection. And lastly, validate_input is doing way too much. Try to break it into smaller logical functions." } ]
[ { "body": "<p><strong>Code Separation</strong></p>\n\n<p>Break up your functions! That has got to be the largest function I've ever seen!</p>\n\n<p>There's no reason to type that MySQL block over and over again. Make it a function and it will go a long way towards cleaning this up.</p>\n\n<pre><code>function alreadyTaken($input, $where) {\n $db = mysqlConnect();\n $stmt = $db-&gt;stmt_init();\n $stmt-&gt;prepare(\"SELECT EXISTS(SELECT 1 FROM users WHERE $where = ?)\");\n $stmt-&gt;bind_param('s', $input);\n $stmt-&gt;execute();\n $stmt-&gt;bind_result($alreadyTaken);\n $stmt-&gt;fetch();\n $stmt-&gt;close();\n $db-&gt;close();\n return $alreadyTaken;\n}\n</code></pre>\n\n<p>I'm still not thrilled with the extra large switch statement and would suggest making the code in each of those cases their own function. Sure, you aren't going to reuse them, but at least it will be cleaner. Also, if all of your cases return true if nothing is wrong, you can just end the <code>validate_input()</code> function with <code>return true;</code> and remove all those other <code>return true;</code> statements. Then you can remove the default case because that eventuallity would already be covered.</p>\n\n<p><strong>Sanitizing As Well As Validating</strong></p>\n\n<p>If your PHP version is >= 5.2 you can use PHP's <code>filter_var()</code> or <code>filter_input()</code> function to sanitize your user input. You should always sanitize your user input before using it. Never trust it. If you do not have PHP >= 5.2 you'll have to look around for the best way of sanitizing your input.</p>\n\n<p><strong>PHP Short Tags</strong></p>\n\n<p>Some servers do not accept PHP short tags. You should always expand <code>&lt;?</code> to <code>&lt;?php</code> for compatibility.</p>\n\n<p><strong>Foreach > For</strong></p>\n\n<p>No need to use a for loop for what you can more easily do with a foreach loop. I would rewrite your <code>showErrors()</code> function to something more like this...</p>\n\n<pre><code>function showErrors($errors) {\n?&gt;\n &lt;script&gt;\n var cross = '&lt;img src=\"/images/cross.png\"&gt;';\n $(document).ready(function(){\n&lt;?php foreach(array_keys($errors) as $name) { echo \"$('#{$name}hint').html(cross);\"; } ?&gt;\n });\n &lt;/script&gt;\n &lt;div id=\"errors\"&gt;\n Errors&lt;br /&gt;\n &lt;ul&gt;\n&lt;?php foreach($errors as $message) { echo \"&lt;li&gt;$message&lt;/li&gt;\"; } ?&gt;\n &lt;/ul&gt;\n &lt;/div&gt;\n&lt;?php\n}\n</code></pre>\n\n<p>Not to say this works 100%. I haven't tested it myself, but it should. I'm unclear about the JQuery because I haven't done much with it, but from what I remember it should still work. If not you should only have to recreate that function, not the cross variable and script blocks. You probably wont even need the cross variable as you do indeed define it again on the next script \"validatefields.js\".</p>\n\n<p>Also, after coming to the end of your scripts I noticed that you always set <code>$error['name']</code>. Why do you check if it is set? Remove the <code>isset()</code> if it is not necessary I wrote the above revision to <code>showErrors()</code> with this in mind...</p>\n\n<p><strong>Variable Templates</strong></p>\n\n<p>You can do this in <a href=\"http://us3.php.net/manual/en/function.sprintf.php\" rel=\"nofollow\">PHP</a> too, not just <a href=\"http://www.diveintojavascript.com/projects/javascript-sprintf\" rel=\"nofollow\">JavaScript</a>. Those links are to their respective documentation pages.</p>\n\n<pre><code>var template = '&lt;img src=\"/images/%s\"&gt;';\n\nvar cross = sprintf(template, 'cross.png');\nvar tick = sprintf(template, 'tick.png');\nvar loading = sprintf(template, 'loading.gif');\n</code></pre>\n\n<p>I'm not going to look at the rest of your JavaScript as it appears to be mostly JQuery and I'm too unfamiliar with that to lend a hand. You'll have to get someone else to help you with that.</p>\n\n<p><strong>getError Function and Variable Comparisons</strong></p>\n\n<pre><code>if (validate_input($key, $value) != 'true')\n</code></pre>\n\n<p>Does indeed return as you would expect, but only because none of your statements returns a string with the value of \"true\". What you have now is not a boolean comparison but a string comparison. <code>!=</code> and <code>==</code> are for loose comparison where the string \"true\" (or any other none empty string or non \"false\" string) is equivalent to boolean TRUE. <code>!==</code> and <code>===</code> are for absolute comparison, where only two variables of the same type with the same value ever return TRUE (\"true\" is not true). It should be written with an absolute comparison because what you are looking for is not the string \"true\" but the boolean TRUE.</p>\n\n<pre><code>if (validate_input($key, $value) !== true)\n</code></pre>\n\n<p>Now, because you seem to set your errors the same every time I would make it a function to reduce the need to type it.</p>\n\n<pre><code>function getError($name, $message) {\n $error = array();\n\n $error['message'] = validate_input('termsandconditions', 'off');\n $error['name'] = $name;\n\n return $error;\n}\n</code></pre>\n\n<p>Finally, since you reuse the same <code>validate_input()</code> line for your error message, if it has one, I would set it as a variable before the if statement and then check the variable before setting the error with the new <code>getError()</code> function.</p>\n\n<pre><code>$isValid = validate_input($key, $value);\nif($isValid !== true) { array_push($errors, getError($key, $isValid)); }\n</code></pre>\n\n<p><strong>Variable Variables</strong></p>\n\n<pre><code>$$key = $value; // Set the title of the field to its name\n</code></pre>\n\n<p><code>$$key</code> is a variable variable. And most people agree that these are bad. Not only are they almost impossible to spot (I almost missed it) but they are impossible to document. No IDE that I know of will even recognize them. Not only that, but you don't even use it as far as I can tell. My advice, stay away from variable variables. They only cause headaches.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-05-19T09:08:48.347", "Id": "19103", "Score": "0", "body": "Thank you for all your comments, they are very useful. As for the variable variables, they are used once the form has been submitted, so if I want to put a field into the database, I just use `$fieldname` e.g. the input field `displayname`'s value would be `$displayname`. Other than manually assigning each field, is there a way to improve this? (I don't want this to seem lazy, it's more that I was after a \"catch all\" type of system!)" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-06-16T22:30:52.873", "Id": "20379", "Score": "0", "body": "One more thing before answer, you've set those variables before even determining if they were valid. That was also bad. But I WOULD use that function I mentioned, `filter_input()`, to get a clean version of it before passing it to the validate function. Once in the if statement, then I'd set them. I wouldn't really call it \"lazy\", because the \"one\" time they are considered \"ok\" is when used in controllers in MVC to do what you are trying to do. You could take a look at that, or you could set those to a new array and just `extract()` them out in the new file." } ], "meta_data": { "CommentCount": "2", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-05-17T16:35:20.260", "Id": "11844", "ParentId": "11807", "Score": "3" } } ]
{ "AcceptedAnswerId": "11844", "CommentCount": "1", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-05-16T15:28:28.837", "Id": "11807", "Score": "1", "Tags": [ "javascript", "php", "validation", "ajax" ], "Title": "Form validation using AJAX with PHP fallback" }
11807
<p>I have a user class comprised of the code below. It has functions to insert a user, update a user, delete a user, look up a user, and search for users. What I'm wondering is if I this class would pass the Single Responsibility Principle as stated here (http://en.wikipedia.org/wiki/Single_responsibility_principle).</p> <pre><code>class user{ $first_name = ""; $last_name = ""; $physical_address1 = ""; $physical_address2 = ""; $physical_city = ""; $physical_state = ""; $physical_zip = ""; $mailing_address1 = ""; $mailing_address2 = ""; $mailing_city = ""; $mailing_state = ""; $mailing_zip = ""; function __construct($array){ if(!isset($array['first_name']) &amp;&amp; !empty($array['first_name'])){ $this-&gt;first_name = ""; } if(!isset($array['last_name']) &amp;&amp; !empty($array['last_name'])){ $this-&gt;last_name = ""; } if(!isset($array['physical_address1']) &amp;&amp; !empty($array['physical_address1'])){ $this-&gt;set_physicalAddress(array( "address_1"=&gt;$array['physical_address1'], "address_2=&gt;$array['physical_address2']", "city"=&gt;$array['physical_city'], "state"=&gt;$array['physical_state'], "zip"=&gt;$array['physical_zip'] )); } if(!isset($array['mailing_address1']) &amp;&amp; !empty($array['mailing_address1'])){ $this-&gt;set_mailingAddress(array( "address_1"=&gt;$array['mailing_address1'], "address_2=&gt;$array['mailing_address2']", "city"=&gt;$array['mailing_city'], "state"=&gt;$array['mailing_state'], "zip"=&gt;$array['mailing_zip'] )); } } function set_physicalAddress($array){} function get_physicalAddress(){} function set_mailingAddress($array){} function get_mailingAddress(){} static function insert($array){} static function update($array){} static function delete($int){} static function lookup($array){} static function search($array){} } $obj = new user(array( "first_name"=&gt;"John", "last_name"=&gt;"Smith" )); </code></pre> <p>The purpose of having the constructor parameter value be an array is that I feed it only the values I want without having to deal with errors caused by not setting a parameter. Instead of setting the parameters to null it's easier to just not put them in the array.</p>
[ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-05-16T18:07:01.920", "Id": "18941", "Score": "0", "body": "Can you post an example usage of this class? I'm not quite sure I understand how you're using it. Why does the constructor accept an array? What is in the array the constructor accept? And are you modeling your users with arrays?" } ]
[ { "body": "<p>I don't think the user class you provided satisfies the Single Responsibility Principle.</p>\n\n<p>I can see a few situations that may require changes to the user class. </p>\n\n<ol>\n<li><p>You want to change what information about the user is stored. This could happen if you need to allow a title (Mr., Mrs., etc.) and/or a middle name. Doing so would require a change to the user class.</p></li>\n<li><p>You want to create a new class that also contains address information. The new class would likely duplicate code that is already present in the user class.</p></li>\n<li><p>You want include the user's country with the physical and mailing addresses. Doing so would require a change to the user class. It would also require changes to the class in #2.</p></li>\n<li><p>You want to change where the information is stored. You may decide you want to be able to test your class without needing to connect to the database (assuming you're connecting to a database). Doing so would require a change to the CRUD methods (insert, update, delete, lookup, and search) of your class.</p></li>\n</ol>\n\n<p>(1) is related to the user class and changing the class is expected. No problem here.</p>\n\n<p>(2), (3), and (4) are really not the responsibility of the user class, yet they would probably require changes to the user class.</p>\n\n<p>You should consider creating an additional \"address\" class that can be reused for the physical and mailing addresses for the user. The user class could contain instances of the address class, and would not require changes if the address functionality changed. Any new classes that need address information could reuse this class.</p>\n\n<p>You should also consider creating a new class (let's call it userProvider) that is responsible for the CRUD functions. This class could have the CRUD methods with a user object as a parameter. Your user class could still define the CRUD methods if you want, but would simply pass the user instance to the userProvider class, which would be responsible for storing/retrieving the user information.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-05-17T02:47:30.033", "Id": "18984", "Score": "0", "body": "Ah, my class allows for all parts of a name prefix through suffix. I just didn't want to include all of the code. I hadn't noticed the duplicity of locations. Thank you for pointing that out. I do in fact have a class for locations. I like the idea of a userProvider class it would solve a lot of my issues and allow for more usability. Though wouldn't these changes and others to mirror these changes to all other lead to over classation for lack of a better term." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-05-17T04:25:35.113", "Id": "18986", "Score": "0", "body": "@Brook Yes, implementing these changes will likely lead to more classes. The changes may or may not be appropriate for your project. If this is a small one-off project, you may not need to worry about it. If this is a project that could grow beyond your current expectations, the additional separation may be helpful.\n\nI don't know the details of your project. I was simply answering your question of whether or not the example class you provided met the Single Responsibility Principle. It is up to you to decide whether or not the changes are really neccessary, based on your project." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-05-17T11:38:26.603", "Id": "18996", "Score": "0", "body": "Thank you for your detailed explanation. You have been a great help to me." } ], "meta_data": { "CommentCount": "3", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-05-17T00:48:10.047", "Id": "11827", "ParentId": "11809", "Score": "3" } } ]
{ "AcceptedAnswerId": "11827", "CommentCount": "1", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-05-16T16:18:19.823", "Id": "11809", "Score": "3", "Tags": [ "php", "classes" ], "Title": "PHP, would this class pass the single responsibility principle?" }
11809
<p>I am trying to create a simple factory pattern demo in PHP. I am not sure if my codes are the best practice. It seems that I have some duplicated codes but I am not sure how to improve it. Basically, I want to create 3 types of accounts (basic, premium and vip). Please advise. Thanks a lot.</p> <p>abstract class</p> <pre><code>abstract class User { function __construct() { $this-&gt;db= new Database('mysql','localhost','mvcdb','root',''); } abstract function checkUser(); function showAccountCredit(){ return $this-&gt;credits; } function getUserName(){ return $this-&gt;username; } } </code></pre> <p>I have 3 different user account types:</p> <p>Basic Account</p> <pre><code>class BasicUser extends User { function __construct($username) { parent::__construct(); $this-&gt;username=$username; $this-&gt;credit='10'; $this-&gt;accountType='Basic Account'; $data=$this-&gt;checkUser(); if(!empty($data)){ echo 'The username: '.$this-&gt;username.' already exists&lt;br&gt;'; return false; } $array=array('username'=&gt;$this-&gt;username, 'password'=&gt;'password','credit'=&gt; $this-&gt;credit,'accountType'=&gt;$this-&gt;accountType); $this-&gt;db-&gt;insert('user',$array); } function checkUser(){ $array=array(':username'=&gt;$this-&gt;username); $results=$this-&gt;db-&gt;select('SELECT * FROM USER WHERE username=:username',$array); if(!empty($results)){ $this-&gt;credit=$results[0]['credit']; $this-&gt;accountType=$results[0]['accountType']; } return $results; } function showAccountCredit() { echo 'Username: '.$this-&gt;username.'&lt;br&gt;'; echo 'Account Credit: '.$this-&gt;credit.'&lt;br&gt;'; echo 'Account Type: '.$this-&gt;accountType; } } </code></pre> <p>Premium Account</p> <pre><code>class PremiumUser extends User { function __construct($username) { parent::__construct(); $this-&gt;username=$username; $this-&gt;credit='100'; $this-&gt;accountType='Premium Account'; $data=$this-&gt;checkUser(); if(!empty($data)){ echo 'The username: '.$this-&gt;username.' already exists&lt;br&gt;'; return false; } $array=array('username'=&gt;$this-&gt;username, 'password'=&gt;'password','credit'=&gt; $this- &gt;credit,'accountType'=&gt;$this-&gt;accountType); $this-&gt;db-&gt;insert('user',$array); } function checkUser(){ $array=array(':username'=&gt;$this-&gt;username); $results=$this-&gt;db-&gt;select('SELECT * FROM USER WHERE username=:username',$array); if(!empty($results)){ $this-&gt;credit=$results[0]['credit']; $this-&gt;accountType=$results[0]['accountType']; } return $results; } function showAccountCredit() { echo 'Username: '.$this-&gt;username.'&lt;br&gt;'; echo 'Account Credit: '.$this-&gt;credit.'&lt;br&gt;'; echo 'Account Type: '.$this-&gt;accountType.'&lt;br&gt;'; } } </code></pre> <p>VIP account:</p> <pre><code>class VipUser extends User { function __construct($username) { parent::__construct(); $this-&gt;username=$username; $this-&gt;credit='1000'; $this-&gt;accountType='VIP Account'; $data=$this-&gt;checkUser(); if(!empty($data)){ echo 'The username: '.$this-&gt;username.' already exists&lt;br&gt;'; return false; } $array=array('username'=&gt;$this-&gt;username, 'password'=&gt;'password','credit'=&gt; $this-&gt;credit,'accountType'=&gt;$this-&gt;accountType); $this-&gt;db-&gt;insert('user',$array); } function checkUser(){ $array=array(':username'=&gt;$this-&gt;username); $results=$this-&gt;db-&gt;select('SELECT * FROM USER WHERE username=:username',$array); if(!empty($results)){ $this-&gt;credit=$results[0]['credit']; $this-&gt;accountType=$results[0]['accountType']; } return $results; } function showAccountCredit() { echo 'Username: '.$this-&gt;username.'&lt;br&gt;'; echo 'Account Credit: '.$this-&gt;credit.'&lt;br&gt;'; echo 'Account Type: '.$this-&gt;accountType; } } </code></pre> <p>UserFactory class</p> <pre><code>class UserFactory { static function create($username,$accountType){ $accountType = strtolower($accountType); switch($accountType){ case 'basic': return new BasicUser($username); case 'premium':return new PremiumUser($username); case 'vip': return new VipUser($username); default :return new BasicUser($username); } } </code></pre> <p>index.php</p> <pre><code>$user1= UserFactory::create('Jerry', 'Vip'); $user1-&gt;showAccountCredit(); $user2= UserFactory::create('Bob', 'Basic'); $user2-&gt;showAccountCredit(); $user3= UserFactory::create('Betty', 'premium'); $user3-&gt;showAccountCredit(); </code></pre>
[]
[ { "body": "<p><strong>Switch Statement</strong></p>\n\n<p>Inside your <code>UserFactory::create()</code> method I would do away with the \"basic\" case as it is the same as default. You can continue passing 'basic' as an argument with no change if you wish, or just stop passing the second argument for basic users. No need to replicate functionality that already exists :)</p>\n\n<p><strong>Edit:</strong> For clarification, you may still define that case if you wish. I know some people like covering every case they will use, even if they end up duplicating it as the default. Personally I just prefer defining it once.</p>\n\n<p><strong>Inheritance</strong></p>\n\n<p>I'm not sure you understand inheritance correctly... All your other classes (child classes) inherit methods and properties from your User class (parent class). So if you take all those methods that are the same in every class and give it to your parent class, you wont have to override them in the child class unless something changes in them. So essentially each child class should only have a construct method because the other two methods are the same and should be in the User class.</p>\n\n<p>Overriding a method is when you have a method defined in a parent class and then define that same method in the child class. The child method supercedes the parent method and then the only way to call the parent's version of that method would be to use the scope resolution operator <code>::</code> along with the class name followed by the method, so <code>parent::__construct()</code> as an example. This is useful if you have variables that change depending on the class but the rest of the functionality remains the same, or if you wish to add functionality to one class but not another.</p>\n\n<p>So taking this knowledge the construct method in each child should resemble this...</p>\n\n<pre><code>function __construct($username) {\n $this-&gt;credit='1000';\n $this-&gt;accountType='VIP Account';\n parent::__construct();\n}\n</code></pre>\n\n<p>And your construct method in your parent class should resemble this...</p>\n\n<pre><code>function __construct($username) {\n $this-&gt;db= new Database('mysql','localhost','mvcdb','root','');\n\n $this-&gt;username=$username;\n\n $data=$this-&gt;checkUser();\n if(!empty($data)){\n echo 'The username: '.$this-&gt;username.' already exists&lt;br&gt;';\n return false;\n }\n\n $array=array(\n 'username'=&gt;$this-&gt;username,\n 'password'=&gt;'password',\n 'credit'=&gt; $this-&gt;credit,'\n accountType'=&gt;$this-&gt;accountType\n );//don't have to do this, I just find this cleaner, you can also check out PHP's compart() function\n $this-&gt;db-&gt;insert('user',$array);\n}\n</code></pre>\n\n<p><strong>Defining Properties and Methods</strong></p>\n\n<p>You never define your class properties, so all of them are public by default :O This may not be a big issue as I don't see any secure information being set, but you should still define them before you use them. These properties should be defined within the class but outside of any methods and should be located at the top of your class.</p>\n\n<pre><code>public $username;\n//OR for a group\npublic\n $username,\n $credit = 100,\n $password\n;\n</code></pre>\n\n<p>None of your child methods appear to be called correctly either. They are not defined as either public or private. I am assuming this and the last point is because this is a \"demo\" and you simply neglected to add them, but in case it isn't I'm pointing it out here.</p>\n\n<pre><code>public function __construct()\n//OR\npublic static function create()\n//OR\nprivate function somePrivateFunc()\n</code></pre>\n\n<p><strong>Reusing Variables</strong></p>\n\n<p>Instead of continuously checking <code>$results[0]etc...</code> just make <code>$results[0]</code> a variable. Makes it cleaner.</p>\n\n<p><strong>Final Thoughts</strong></p>\n\n<p>Hope this helps, don't use the factory method myself so I can't say whether you are using it correctly. But my suggestions should still be valid.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-05-17T17:25:28.377", "Id": "11845", "ParentId": "11818", "Score": "1" } }, { "body": "<p>This question is pretty old, but I have a few things to add to showerhead's answer</p>\n\n<hr>\n\n<p><strong>new in a constructor</strong></p>\n\n<ul>\n<li>Creating an object in a constructor is an antipattern. It immediately introduces very tight coupling, and it makes testing absolutely impossible.</li>\n<li>You're needlessly creating database connections over and over again.</li>\n<li>A User class' only business is to model a User. It has no business creating database connections.</li>\n</ul>\n\n<p>What you should do instead is pass the database connection into the user object. (Or, if it's strictly a model, you might let some other type of object handle database interaction and let the User class essentially be for data storage/organisation.)</p>\n\n<p><strong>echoing in a constructor</strong></p>\n\n<p>A class should almost never output directly (unless the goal of the class is to handle rendering). What if you wanted to output a different message in a certain situation? What if you want to handle the error silently? It restricts you to handling things in one very specific way. </p>\n\n<p>Instead, make use of return values or exceptions.</p>\n\n<p><strong>returning in a constructor</strong></p>\n\n<p>Returning a value in a constructor does not work. Personally, I believe it should be a syntax error, but PHP has chosen to just ignore it.</p>\n\n<p>Where would the return value go? The variable receiving the instance? But then the reference to the object is lost. If you ever find yourself returning false in a constructor, it's probably a sign that exceptions should be used.</p>\n\n<p><strong>showAccountCredit</strong></p>\n\n<p>Nothing is being shown. Perhaps it should be <code>getAccountCredit</code>.</p>\n\n<p><strong>What is the user class?</strong></p>\n\n<p>Is it a model? Is it a controller? Is it a data persistence layer? It looks like a model to me, in which case whether or not it should be responsible for creating users is debatable.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-06-17T06:16:53.270", "Id": "12650", "ParentId": "11818", "Score": "2" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-05-16T20:50:39.633", "Id": "11818", "Score": "1", "Tags": [ "php", "object-oriented" ], "Title": "Simple Factory Pattern Demo" }
11818
<p>I feel that I am repeating myself a lot with this HTML/PHP code. Am I right, and is there a maintainable way of reducing the amount of repetition in the code?</p> <p>mydomain/index.php:</p> <pre><code>&lt;!DOCTYPE HTML&gt; &lt;?php $root="/mywebdir"; ?&gt; &lt;html&gt; &lt;head&gt; &lt;?php include("$root/inc/meta.php"); ?&gt; &lt;meta name="description" content="Some description" /&gt; &lt;meta name="keywords" content="some,home,page,keywords" /&gt; &lt;title&gt;Home - This Website&lt;/title&gt; &lt;/head&gt; &lt;body&gt; &lt;div id="main"&gt; &lt;?php include("$root/inc/header.php"); ?&gt; &lt;?php include("$root/inc/nav.php"); ?&gt; &lt;div&gt; &lt;h2&gt;Home&lt;/h2&gt; &lt;p&gt;Introduction.&lt;/p&gt; &lt;p&gt;Some content.&lt;/p&gt; &lt;p&gt;More content.&lt;/p&gt; &lt;/div&gt; &lt;?php include("$root/inc/footer.php"); ?&gt; &lt;/div&gt; &lt;/body&gt; &lt;/html&gt; </code></pre> <p>mydomain/somedir/index.php:</p> <pre><code>&lt;!DOCTYPE HTML&gt; &lt;?php $root="/mywebdir"; ?&gt; &lt;html&gt; &lt;head&gt; &lt;?php include("$root/inc/meta.php"); ?&gt; &lt;meta name="description" content="Some description" /&gt; &lt;meta name="keywords" content="some,keywords,about,this,page" /&gt; &lt;title&gt;Some Page - This Website&lt;/title&gt; &lt;/head&gt; &lt;body&gt; &lt;div id="main"&gt; &lt;?php include("$root/inc/header.php"); ?&gt; &lt;?php include("$root/inc/nav.php"); ?&gt; &lt;div&gt; &lt;h2&gt;Some Page&lt;/h2&gt; &lt;p&gt;Some content about this page.&lt;/p&gt; &lt;/div&gt; &lt;?php include("$root/inc/footer.php"); ?&gt; &lt;/div&gt; &lt;/body&gt; &lt;/html&gt; </code></pre>
[]
[ { "body": "<p>Consider using existing template systems to help you that support inheritance. Template inheritance isn't a strict requirement, but is a powerful feature that makes maintaining templates a lot easier. <a href=\"http://twig.sensiolabs.org/\" rel=\"nofollow\">Twig</a> is easy to use, and feature-rich.</p>\n\n<p>If you want to go it your own way, you could simply implement the use of layout files:</p>\n\n<p>layout_default.php</p>\n\n<pre><code>&lt;!DOCTYPE HTML&gt;\n&lt;?php $root=\"/mywebdir\"; ?&gt;\n&lt;html&gt;\n&lt;head&gt;\n&lt;?php include(\"$root/inc/meta.php\"); ?&gt;\n&lt;meta name=\"description\" content=\"&lt;?php echo $description ?&gt;\" /&gt;\n&lt;meta name=\"keywords\" content=\"&lt;?php echo keywords?&gt;\" /&gt;\n&lt;title&gt;&lt;?php echo $title ?&gt;&lt;/title&gt;\n&lt;/head&gt;\n&lt;body&gt;\n&lt;div id=\"main\"&gt;\n&lt;?php include(\"$root/inc/header.php\"); ?&gt;\n&lt;?php include(\"$root/inc/nav.php\"); ?&gt;\n&lt;div&gt;&lt;?php echo $contents ?&gt;&lt;/div&gt;\n&lt;?php include(\"$root/inc/footer.php\"); ?&gt;\n&lt;/div&gt;\n&lt;/body&gt;\n&lt;/html&gt;\n</code></pre>\n\n<p>example page.php</p>\n\n<pre><code>&lt;?php ob_start() ?&gt;\n&lt;p&gt; main body html&lt;/p&gt;\n&lt;?php\n$title = \"x\"; \n$description = \"x\"; \n$keywords = \"x\"; \n$contents = ob_get_clean();\nrequire 'layout_default.php'\n</code></pre>\n\n<p>This is a very crude implementation, simply enough to illustrate the principle.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-05-16T21:54:53.797", "Id": "18964", "Score": "0", "body": "Would it be bad to use a string to define the page contents? (Instead of ob_get_clean)" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-05-16T21:56:12.470", "Id": "18965", "Score": "0", "body": "I wouldn't say bad, but it won't make your life easy - output buffering simply makes it a lot easier to construct your main html body any way you wish (i.e. as .. plain html without `$contents .=\"<p>this..\"; $contents .= \"<p>that..\";` etc.) - but the above is just an example." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-05-16T21:59:25.710", "Id": "18966", "Score": "0", "body": "Well, I think I'll give it a try." } ], "meta_data": { "CommentCount": "3", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-05-16T21:48:23.730", "Id": "11822", "ParentId": "11819", "Score": "4" } } ]
{ "AcceptedAnswerId": "11822", "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-05-16T21:00:12.243", "Id": "11819", "Score": "4", "Tags": [ "php", "html", "html5" ], "Title": "Is this violating the DRY principle?" }
11819
<p>I'm teaching myself how to program Haskell, and I decided to make a find function in Haskell. What it does is it takes two strings, such as <code>"hello"</code> and <code>"he"</code>, and it counts how many times <code>"he"</code> appears in <code>"hello"</code>. In addition, it also uses the <code>*</code> character as a wildcard, so searching for <code>"he*o"</code> in <code>"hello"</code> will return <code>1</code>.</p> <h1>Latest Update</h1> <p>This update used pattern matching and less guards, and also outputs 1 if <code>ssearch "blah" "*"</code>.</p> <pre><code>ssearch _ [] = 0 ssearch [] _ = 0 ssearch ('*':_) _ = error "no '*' allowed in hay" ssearch _ ['*'] = 1 ssearch haystack ('*':needles) = ssearch haystack needles --removes '*', and then searches through hay for the char after the '*' ssearch (hay:haystack) (needle:needles) | needle == hay = search2 haystack needles + ssearch haystack (needle:needles) | otherwise = ssearch haystack (needle:needles) where search2 _ [] = 1 search2 [] _ = 0 search2 ('*':_) _ = error "no '*' allowed in hay" -- I need to declare this twice because search2 often jumps ahead of ssearch. search2 _ ['*'] = 1 search2 haystack ('*':needles) = ssearch haystack needles search2 (hay:haystack) (needle:needles) | needle == hay = search2 haystack needles | otherwise = 0 </code></pre> <h1>Update:</h1> <p>Thinking over <a href="https://codereview.stackexchange.com/a/11824/4253">dave4420's comments</a>, I decided to redo the entire algorithm. I think that it fixes most of the bugs.</p> <pre><code>ssearch _ [] = 0 ssearch [] _ = 0 ssearch (hay:haystack) (needle:needles) | hay == '*' = error "no '*' allowed in hay" --no confusion with wildcard things | needle == '*' = ssearch (hay:haystack) needles --removes '*', and then searches through hay for the char after the '*' | needle == hay = search2 haystack needles + ssearch haystack (needle:needles) | otherwise = ssearch haystack (needle:needles) where search2 _ [] = 1 search2 [] _ = 0 search2 (hay:haystack) (needle:needles) | hay == '*' = error "no '*' allowed in hay" -- I need to declare this twice because search2 often jumps ahead of ssearch. | (needle == '*') &amp;&amp; (needles /= []) = ssearch (hay:haystack) needles | (needle == '*') &amp;&amp; (needles == []) = 1 | needle == hay = search2 haystack needles | otherwise = 0 </code></pre> <p>I'm wondering if there are still any bugs, and also, if there is any way I can improve this code.</p> <h2>Old Code</h2> <pre><code>search :: String -&gt; String -&gt; Integer search x y = search1 x y y 0 -- n is set to 0, because nothing has been found yet :) where search1 :: String -&gt; String -&gt; String -&gt; Integer -&gt; Integer search1 _ _ [] n = n -- z can't be empty search1 x [] z n = search1 x z z (n+1) -- if y is empty but x isn't, it means the word was found, and y needs to be reset search1 [] _ _ n = n --end the program, bc if x is empty, the program has searched through the entire string search1 (x:xs) (y:ys) z n | x == '*' = error "you can not enter the character '*' in the first field: the '*' character is reserved for wildcard searches" | (y == '*') &amp;&amp; ((head ys) == '*') = error "You can not include two '**' in a row, that messes up the wildcard operator" | x == y = search1 xs (ys) z n | (y == '*') &amp;&amp; (ys /= []) = if (x == (head ys)) --this section is so search "hello" "h*llo" = 1 then search1 (x:xs) ys z n --if the string matches up with the rest of the string, excluding the '*', then redu the query, excluding the '*' else search1 xs (y:ys) z n --} --otherwise keep on searching for the wildcard thing | (y == '*') &amp;&amp; (ys == []) = n + 1 -- so search "hello" "*" = 1 | otherwise = search1 xs z z n -- don't include (y:ys), otherwise search "hihe" "hhe" = 1 </code></pre>
[]
[ { "body": "<h2>Update</h2>\n\n<p>Yes, that's better.</p>\n\n<p>Here is a version of your code that uses pattern matching more and guards less. I think it is clearer.</p>\n\n<pre><code>ssearch _ [] = 0\nssearch [] _ = 0\nssearch ('*' : _) _ = error \"no '*' allowed in hay\" --no confusion with wildcard things\nssearch haystack ('*' : needles) = ssearch haystack needles --removes '*', and then searches through hay for the char after the '*'\nssearch (hay:haystack) (needle:needles)\n | needle == hay = search2 haystack needles + ssearch haystack (needle:needles) \n where\n search2 _ [] = 1\n search2 [] _ = 0\n search2 ('*' : _) _ = error \"no '*' allowed in hay\" -- I need to declare this twice because search2 often jumps ahead of ssearch.\n search2 _ ['*'] = 1 \n search2 haystack ('*' : needles) = ssearch haystack needles \n search2 (hay:haystack) (needle:needles)\n | needle == hay = search2 haystack needles \n search2 _ _ = 0\nssearch (_:haystack) needles = ssearch haystack needles\n</code></pre>\n\n<p>There may still be bugs, but I can't see any :-)</p>\n\n<h2>Original</h2>\n\n<ol>\n<li><p>It appears to be buggy.</p>\n\n<ul>\n<li>I expect <code>search \"hello\" \"he*lo\"</code> to result in <code>1</code>, but it gives me <code>0</code>.</li>\n<li>I expect <code>search \"chanchance\" \"chance\"</code> to result in <code>1</code>, but it gives me <code>0</code>.</li>\n</ul>\n\n<p>Also</p>\n\n<ul>\n<li><code>search \"bobobob\" \"bob\"</code> results in <code>2</code>, but perhaps it should result in <code>3</code>. Whether or not you want your function to count overlapping matches, you should document that it does/doesn't.</li>\n</ul>\n\n<p>You need to rethink your algorithm. (Edit: as you are learning Haskell, I presume you'd rather get your function working yourself, rather than have us spoon-feed you a working version.)</p></li>\n<li><p><code>x</code> and <code>y</code> are not very descriptive names. They are suitable when you are writing generic code, but this code is more specific. I would call them <code>haystack</code> and <code>needle</code> instead (from the common English phrase).</p></li>\n<li><p>This line:</p>\n\n<pre><code> | (y == '*') &amp;&amp; ((head ys) == '*') = error \"You can not include two '**' in a row, that messes up the wildcard operator\"\n</code></pre>\n\n<ul>\n<li><code>ys</code> may be <code>[]</code>, so <code>head ys</code> may be an error. You should be using pattern matching instead of <code>head</code> (and often instead of comparing to <code>[]</code> as well).</li>\n<li>Why should a second <code>*</code> be an error anyway? The second <code>*</code> should successfully match a run of 0 characters, surely?</li>\n</ul></li>\n</ol>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-05-16T22:38:38.490", "Id": "18972", "Score": "0", "body": "Thanks for your feedback. Yes, I am learning Haskell, so thanks for not spoiling the answer for me. I was wondering, by \"You need to rethink your algorithm\" do you mean I should rewrite the entire thing, or that I should debug the current algorithm?" } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-05-16T22:20:23.253", "Id": "11824", "ParentId": "11820", "Score": "1" } } ]
{ "AcceptedAnswerId": "11824", "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-05-16T21:11:40.280", "Id": "11820", "Score": "1", "Tags": [ "haskell" ], "Title": "Search Function With Wildcard in Haskell" }
11820
<p>I have a linearized 2D array <code>u</code> (<code>block_height * block_width</code>) containing the values of a physical quantity over a regular 2D mesh. I need to downsample boundaries (top, bottom, left, right) of this array for communication with another process. I've refactored some code that does this, and I'd like people's thoughts on whether the new code is actually an improvement.</p> <p>Old code:</p> <pre><code>if (dir == LEFT) for(int j = 1; j &lt;= block_height; j += 2) left_edge[j/2] = (u[index(1,j)] + u[index(2,j)] + u[index(1,j+1)] + u[index(2,j+1)]) / 4; else if (dir == RIGHT) for(int j = 1; j &lt;= block_height; j += 2) right_edge[j/2] = (u[index(block_width-1, j)] + u[index(block_width,j)] + u[index(block_width-1, j+1)] + u[index(block_width, j+1)]) / 4; else if (dir == UP) for(int i = 1; i &lt;= block_width; i += 2) top_edge[i/2] = (u[index(i,1)] + u[index(i,2)] + u[index(i+1,1)] + u[index(i+1,2)]) / 4; else if (dir == DOWN) for(int i = 1; i &lt;= block_width; i += 2) bottom_edge[i/2] = (u[index(i,block_height-1)] + u[index(i,block_height)] + u[index(i+1,block_height-1)] + u[index(i+1,block_height)]) / 4; </code></pre> <p>New code:</p> <pre><code>double *boundary; int k, fixed_dim; int *x, *y; switch (dir) { case LEFT: case RIGHT: count = block_height; x = &amp;fixed_dim; y = &amp;k; break; case UP: case DOWN: count = block_width; y = &amp;fixed_dim; x = &amp;k; break; switch (dir) { case LEFT: boundary = left_edge; fixed_dim = 1; break; case RIGHT: boundary = right_edge; fixed_dim = block_width - 1; break; case UP: boundary = top_edge; fixed_dim = 1; break; case DOWN: boundary = bottom_edge; fixed_dim = block_height - 1; break; } for (k = 1; k &lt;= count; k += 2) boundary[k/2] = (u[index(*x, *y)] + u[index(*x+1, *y)] + u[index(*x, *y+1)] + u[index(*x+1, *y+1)] )/ 4; </code></pre> <p>So, I've factored out the repeated for loop and made the logic more declarative, at the expense of introducing some additional indirection (including over which direction the loop iterates through memory!) and the variables to support it.</p> <p>One obvious direction of future change for this code is increasing from 2 dimensions to 3 (and possible even more). I know which one I'd prefer to do that to, but if the old code is overwhelmingly clearer to people reading it, then the repetition may be worth retaining.</p>
[ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-05-16T23:56:06.993", "Id": "18974", "Score": "0", "body": "This should also be tagged 'pointer', but not enough rep transfered over from SO to let me create that." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-05-20T14:55:52.433", "Id": "19130", "Score": "0", "body": "So, I went whole-hog with the iterator approach, and it seems to be working out quite well. A lot of other code in the project was simplified using the same structure." } ]
[ { "body": "<p>I think the first one is more understandable to a reader, while the second is more efficient and or more easily adapted to higher dimensions. Have you thought about something like:</p>\n\n<pre><code>if (dir == LEFT || dir == RIGHT){ \n int x = dir == LEFT ? 1 : block_width-1;\n double *boundary = dir == LEFT ? left_edge : right_edge;\n for(int j = 1; j &lt;= block_height; j += 2)\n left_edge[j/2] = (u[index(x,j)] + u[index(x+1,j)] +\n u[index(x,j+1)] + u[index(x+1,j+1)]) / 4;\n}\nelse if (dir == UP || dir == DOWN){\n int y = dir == UP ? 1 : block_height-1\n double *boundary = dir == UP ? top_edge : bottom_edge;\n for(int i = 1; i &lt;= block_width; i += 2)\n boundary[i/2] = (u[index(i,y)] + u[index(i,y+1)] +\n u[index(i+1,y)] + u[index(i+1,y+1)]) / 4;\n}\n</code></pre>\n\n<p>Or if the second is more inclined I would recommend just clear comments to show the intention of each variables meaning.</p>\n\n<p>Also in the future adapting to more c++ style arrays (vectors), utilizing a c++ Matrix library, or making your own iterator (boundary iterator) would make for a very nice solution to this problem.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-05-17T06:06:26.647", "Id": "18988", "Score": "0", "body": "Thanks for the suggestion of an intermediate point between my two solutions; I hadn't thought of that." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-05-17T06:08:54.600", "Id": "18989", "Score": "0", "body": "I can clearly see how using a real matrix/multi-dimensional array library or an iterator would simplify this code. I'm less clear on what C++ `std::vector` changes about it, though. The only difference I see is that `boundary = foo` becomes `boundary = &foo[0]`." } ], "meta_data": { "CommentCount": "2", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-05-17T04:14:02.203", "Id": "11831", "ParentId": "11826", "Score": "1" } } ]
{ "AcceptedAnswerId": "11831", "CommentCount": "2", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-05-16T23:55:50.067", "Id": "11826", "Score": "1", "Tags": [ "c++", "array" ], "Title": "Downsampling boundaries of a 2D array" }
11826
<p>This function takes a URL structure which is most often a query string (but sometimes not) and generates filters to remove query variables from the URL.</p> <p>If you're looking at an archive like</p> <blockquote> <p><a href="http://example.com/?genre=rock&amp;band=deep-purple" rel="nofollow">http://example.com/?genre=rock&amp;band=deep-purple</a></p> </blockquote> <p>you'll get the following output:</p> <pre><code>[ROCK X] [DEEP PURPLE X] </code></pre> <p>so you can remove those "filters".</p> <p>I have a lot (too much maybe) of nested structure-- if anyone has any general optimization or refactoring pointers for me I'd really appreciate it!</p> <pre><code>&lt;?php function event_filters() { $output = ''; $filterclear = get_bloginfo('wpurl').'/events'; $filterclass = 'filter-clear cp block fl search-tag tdn pr con ic-right ic-x c2h btn bg1 c2'; $queryString = $_SERVER['QUERY_STRING']; $home = get_bloginfo('wpurl'); parse_str($queryString, $params); $filter_count = count($params); // IF IS SINGLE DAY VIEW if(tribe_is_day()) { $day_title = ucwords(strftime( '%e de %B ', strtotime( get_query_var('eventDate') ))); $output .= '&lt;a class="'.$filterclass.'" title="Remove filter: ' . $day_title . '" href="'.$filterclear.'"&gt;'.$day_title.'&lt;/a&gt;'; } foreach ($params as $key =&gt; $term) { $tags = explode(' ',$term); $tag_count = count($tags); $term = get_term_by('slug', $term, $key); $term_name = $term-&gt;name; if($filter_count == 1 &amp;&amp; $tag_count &lt;= 1) { // IF IS ONE KEY AND ONE TERM $output .= '&lt;a class="'.$filterclass.'" title="Remove filter: ' . $term_name . '" href="'.$filterclear.'"&gt;'.$term_name.'&lt;/a&gt;'; } else { if($tag_count &gt; 1) { foreach($tags as $tag) { // IF THERE IS MORE THAN ONE TERM PER KEY, LOOP THROUGH EACH TERM $the_tag = get_term_by('slug', $tag, $key); $tag_name = $the_tag-&gt;name; $filterclear = str_replace($tag, '', $queryString); $filterclear = str_replace(array('=+', '++', '+&amp;'), array('=', '+', '&amp;'), $filterclear); if(substr($filterclear, -1) == '+'){ $filterclear = substr($filterclear,0,-1); } $output .= '&lt;a class="'.$filterclass.'" title="Remove filter: ' . $tag_name . '" href="' . $home . '?'.$filterclear . '"&gt;'.$tag_name.'&lt;/a&gt;'; } } else { // OR ELSE THERES JUST ONE TERM PRESENT $filterclear = remove_query_arg($term,$queryString); $output .= sprintf("&lt;a class=\"$filterclass\" title=\"Remove filter: $term_name\" href=\"$blogurl/?%s\"&gt;%s&lt;/a&gt;", $filterclear, $term_name); } // END TAG_COUNT } // END FILTER_COUNT } // END FOR EACH return $output; } ?&gt; </code></pre>
[]
[ { "body": "<p><strong>Breaking Up Is Hard To Do</strong></p>\n\n<p>My first suggestion would be to break up your one function into many. No need to do all of that in just one function. The best way to do this would be to go about it logically. That is to say, break up your function by their purpose. For instance you could create a <code>get_params()</code> function like the following.</p>\n\n<pre><code>function getParams($queryString) {\n parse_str($queryString, $params);\n return $params;\n}\n</code></pre>\n\n<p>This is a poor example because it doesn't take much from your code, but it does show how your functions should be specialized. Break them up so that they do only one thing and do it well. Even if you don't find yourself reusing that function it will help you in the long run. Don't believe me? Try it and then run your program again. Where is that error coming from now? I am almost positive it will have narrowed the amount of code you need to look at and will probably tell you in which function to look through. Here's a couple more small functions for you. Not to say there aren't more, these are just some maybe not so obvious ones to get you started.</p>\n\n<pre><code>function getOutput($class, $title, $href) {\n return '&lt;a class=\"' . $class . '\" title=\"Remove filter: ' . $title . '\" href=\"' . $href . '\"&gt;' . $title . '&lt;/a&gt;';\n}\n\nfunction getTermBy($key, $term) {\n return get_term_by('slug', $term, $key);\n}\n</code></pre>\n\n<p>That last function might not be all that great, but if this were a class you could make it so that you'd only have to pass the $term to it, which would be better and cleaner. I tend to tell everyone to ignore OOP until they are ready for it, just as I am telling you. Work on the suggestions in this answer and once this all becomes second nature I think you'd be ready for it. For the time being, just breaking up your code will make it easier to transition into classes should you ever decide to convert this over to one.</p>\n\n<p><strong>What's This Now!</strong></p>\n\n<p>It may be common knowledge what some of these functions do ('get_bloginfo()`), but I haven't a clue. I'm assuming this is wordpress or something. Never got into it myself so I'm not sure. Never the less, you should be commenting your code to let people know what you're doing. You don't have to go into great detail, just enough to say what you expect the outcome to be. I do see that you have some comments, but they seem to be more structural rather than functional.</p>\n\n<p><strong>norunonfunctionsasitishardtoread</strong></p>\n\n<p>Look up, now look down, now back up at me. Sadly these run-on functions are hard to read.</p>\n\n<pre><code>$day_title = ucwords(strftime( '%e de %B ', strtotime( get_query_var('eventDate') )));\n</code></pre>\n\n<p>But with the power of good code separation your code could look as good as mine!</p>\n\n<pre><code>$eventDate = get_query_var('eventDate');\n$eventDateTime = strtotime($eventDate);\n$formattedTime = strftime('%e de %B', $eventDateTime);\n$day_title = ucwords($formattedTime);\n//OR\n$day_title = get_query_var('eventDate');\n$day_title = strtotime($day_title);\n$day_title = strftime('%e de %B', $day_title);\n$day_title = ucwords($day_title);\n</code></pre>\n\n<p>I've always wanted to do that :) Anyways, now that I've had my fun... It won't hurt anything to separate code like this, it will just increase the number of lines in your program. It will still run the same and the <em>slight</em> increase in filesize will be neglible and wont make it run any slower, or if it does, it will be so miniscule as to be unnoticeable.</p>\n\n<p><strong>Consistency</strong></p>\n\n<p>You seem to be struggling with how you want your code to look. This is very common in a new programmer who is still unsure as to what style they want to adopt. You should pick one and stick with it though. Right now you have oneword, camelCase, and under_score variables/functions with no consistency. The only other reason I could think of for code to look like this is if it were all copy-pasted in without fully understanding it, which should never be the case, nor do I think it is. This is not to say you need to pick just one. You can mix and match. Some people use camelcase for variables and underscore for functions, or vice-versa. Its entirely up to you, there is no right or wrong, just preference. But once you pick one you like you should stick with it.</p>\n\n<p>If you ever join a team this will become a big factor, though your preferences will mater little and you'll have to conform your style to the project lead's. They do this for consistency and being consistent with your own code will get you in the hang of this.</p>\n\n<p><strong>Final Thoughts</strong></p>\n\n<p>I've not found your issue, but implementing these suggestions might help you find it. I had a little fun with the answer, so my apologies, but it should still be helpful and understandable.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-05-17T16:45:07.690", "Id": "19008", "Score": "0", "body": "THANK YOU! I love feedback and love to learn. Really appreciate it!!!" } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-05-17T14:27:58.047", "Id": "11840", "ParentId": "11828", "Score": "2" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-05-17T02:40:18.287", "Id": "11828", "Score": "1", "Tags": [ "php", "url" ], "Title": "Generating filters to remove query variables from a URL" }
11828
<p>My application has a thread for handling database inserts and updates. Data is added by other threads to a generic queue in the DB thread. The contents of this queue is retrieved and is sequentially inserted to the database by the thread. </p> <p>To improve performance, I am planning to bring in a priority mechanism so that messages with higher priority should get inserted in the database before those with lower priority.</p> <p>I implemented a class with a <code>SortedDictionary</code> for handling the priority. An enum indicating the priority would be the key and a <code>Queue</code> containing the messages would be the value part of the dictionary.</p> <p>Please review the following code and provide suggestions on how to improve it. Also if there are any readily available solutions please provide the details.</p> <pre><code>public class PriorityQueue { private Object lockObj; private SortedDictionary&lt;PQMsgPriority, Queue&lt;PQMessage&gt;&gt; messageDictionary; public PriorityQueue() { lockObj = new object(); messageDictionary = new SortedDictionary&lt;PQMsgPriority, Queue&lt;PQMessage&gt;&gt;(); } public void Enqueue(PQMessage item) { lock (lockObj) { if (item != null) { if (messageDictionary.ContainsKey(item.MsgPriority)) { Queue&lt;PQMessage&gt; dataList = messageDictionary[item.MsgPriority]; dataList.Enqueue(item); } else { Queue&lt;PQMessage&gt; dataList = new Queue&lt;PQMessage&gt;(); dataList.Enqueue(item); messageDictionary.Add(item.MsgPriority, dataList); } } } } public PQMessage Dequeue() { lock (lockObj) { PQMessage messageData = null; PQMsgPriority prioKeyDeleteFlag = PQMsgPriority.None; //If no data available, throw an exception if (messageDictionary.Count == 0) throw new InvalidOperationException(); foreach (KeyValuePair&lt;PQMsgPriority, Queue&lt;PQMessage&gt;&gt; item in messageDictionary) { Queue&lt;PQMessage&gt; dataList = item.Value; if (dataList.Count &gt; 0) messageData = dataList.Dequeue(); else { prioKeyDeleteFlag = item.Key; continue; } break; } if (prioKeyDeleteFlag != PQMsgPriority.None) messageDictionary.Remove(prioKeyDeleteFlag); return messageData; } } public int Count() { lock (lockObj) { int totalCount = 0; foreach (KeyValuePair&lt;PQMsgPriority, Queue&lt;PQMessage&gt;&gt; item in messageDictionary) { if (item.Value != null) { if (item.Value.Count == 0) continue; else { totalCount = totalCount + item.Value.Count; continue; } } break; } return totalCount; } } public PQMessage Peek() { lock (lockObj) { PQMessage messageData = null; //If no data available, throw an exception if (messageDictionary.Count == 0) throw new InvalidOperationException(); foreach (KeyValuePair&lt;PQMsgPriority, Queue&lt;PQMessage&gt;&gt; item in messageDictionary) { Queue&lt;PQMessage&gt; dataList = item.Value; if (dataList.Count &gt; 0) messageData = dataList.Peek(); break; } return messageData; } } } </code></pre> <p>The priority enum is defined as follows:</p> <pre><code> public enum PQMsgPriority { High = 0, Medium = 1, Low = 2, None = 3 } </code></pre> <p>The priority message is defined as follows:</p> <pre><code>public class PQMessage { private PQMsgPriority msgPriority; private Object message; #region Properties public PQMsgPriority MsgPriority { get { return msgPriority; } set { msgPriority = value; } } public Object Message { get { return message; } set { message = value; } } #endregion public PQMessage(PQMsgPriority msgPriority, Object message) { this.msgPriority = msgPriority; this.message = message; } } </code></pre>
[]
[ { "body": "<ol>\n<li>I don't like that you're treat <code>PQMsgPriority.None</code> in a special way in <code>Dequeue()</code>. If somebody tried to enqueue something with this priority, the code wouldn't work as expected.</li>\n<li>I think your <code>Peek()</code> wouldn't work correctly in some cases. Specifically, <code>Dequeue()</code> can leave the queue with the highest priority empty, while other queues still have items. In this case <code>Peek()</code> would incorrectly return <code>null</code>.</li>\n<li>I think you're overusing <code>break</code> and <code>continue</code>. They can be useful, but I think the way you're using them makes your code harder to read. For example your (incorrect) code in <code>Peek()</code> could be simply rewritten using <code>First()</code>.</li>\n<li>Your <code>Count()</code> could be simplified to <code>messageDictionary.Values.Sum(q =&gt; q.Count)</code>. Especially the check for <code>0</code> seems completely useless here (possibly an attempt at nano-optimization?). The <code>null</code> check also seems useless, if the dictionary contained <code>null</code> values, that's a bug you're hiding by this.</li>\n<li>It would make sense to make this class generic in both the priority type and the message type.</li>\n</ol>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-05-17T13:26:57.733", "Id": "19002", "Score": "0", "body": "Btw, `Dictionary` cannot contain null keys - it will throw an exception." } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-05-17T11:11:08.650", "Id": "11837", "ParentId": "11836", "Score": "8" } }, { "body": "<h2>Enqueue</h2>\n\n<p>When <code>item</code> is <code>null</code>, it won't be inserted. I suggest that you check at the start, before the lock, whether <code>item</code> is <code>null</code>, and if it is, throw an <code>ArgumentNullException</code>.</p>\n\n<p>Your code for enqueuing an item is the same in both cases of the if-statement. Move that code out of it.</p>\n\n<pre><code>Queue&lt;PQMessage&gt; dataList;\nif (messageDictionary.ContainsKey(item.MsgPriority))\n{\n dataList = messageDictionary[item.MsgPriority];\n}\nelse\n{\n dataList = new Queue&lt;PQMessage&gt;();\n messageDictionary.Add(item.MsgPriority, dataList);\n}\n\ndataList.Enqueue(item);\n</code></pre>\n\n<h2>Dequeue</h2>\n\n<p>I'd move the check whether the number if items in the dictionary is zero to the top of the method. It does not need to be inside the lock.</p>\n\n<p>If you want, you may use <code>foreach(var item in messageDictionary)</code> instead, as it is cleaner (to me).</p>\n\n<p>Rethink how you delete an empty entry from the dictionary. The way it is now, if the dictionary contains two empty queues, only the last one gets deleted. Also note that you may use nullable types (e.g. <code>PQMsgPriority? prioKeyDeleteFlag = null;</code>) so that you don't need to assign special behavior to <code>PQMsgPriority.None</code>.</p>\n\n<p>Try to use the fact that the <code>foreach</code> will continue on its own. Remove the <code>continue</code> keyword, and this requires you to move the <code>break</code> closer to the code that requires it.</p>\n\n<h2>Count</h2>\n\n<p>You made <code>Count</code> a method, which is not common in collection classes. On the other hand, the rule is to make something a method when it performs many calculations. In this case you can go either way, altough I would prefer for <code>Count</code> to be a property. If you are concerned about performance, you could adjust the count on each enqueue or dequeue.</p>\n\n<p>For the <code>foreach</code>, reorder the <code>break</code> to be where you want it:</p>\n\n<pre><code>foreach (KeyValuePair&lt;PQMsgPriority, Queue&lt;PQMessage&gt;&gt; item in messageDictionary)\n{\n if (item.Value == null)\n break;\n else\n {\n if (item.Value.Count == 0)\n continue;\n else\n {\n totalCount = totalCount + item.Value.Count;\n continue;\n }\n }\n}\n</code></pre>\n\n<p>Again, use in your implementation the fact that <code>foreach</code> will continue on its own:</p>\n\n<pre><code>foreach (KeyValuePair&lt;PQMsgPriority, Queue&lt;PQMessage&gt;&gt; item in messageDictionary)\n{\n if (item.Value == null)\n break;\n else\n {\n if (item.Value.Count != 0)\n totalCount = totalCount + item.Value.Count;\n }\n}\n</code></pre>\n\n<p>And note that in your code it is not possible for <code>item.Value</code> to be <code>null</code>, so you don't have to check for that:</p>\n\n<pre><code>foreach (var item in messageDictionary)\n{\n if (item.Value.Count != 0)\n totalCount += item.Value.Count;\n}\n</code></pre>\n\n<p>Adding 0 is not a problem:</p>\n\n<pre><code>foreach (var item in messageDictionary)\n{\n totalCount += item.Value.Count;\n}\n</code></pre>\n\n<p>And did you know that LINQ is very useful for this kind of looping over collections?</p>\n\n<pre><code>public int Count\n{\n get \n {\n return messageDictionary\n .Sum(item =&gt; item.Value.Count);\n }\n}\n</code></pre>\n\n<h2>Peek</h2>\n\n<p>Again, move your <code>Count == 0</code> check to the top of the method. </p>\n\n<p>Your <code>foreach</code> is incorrect. It will only every iterate to the first <code>item</code> in the dictionary, as <code>break</code> is a statement that it will always encounter. You probably wanted to continue iterating the dictionary when you encounter an empty queue in the current <code>item</code>. For example:</p>\n\n<pre><code>foreach (var item in messageDictionary)\n{\n Queue&lt;PQMessage&gt; dataList = item.Value;\n if (dataList.Count &gt; 0)\n {\n messageData = dataList.Peek();\n break;\n }\n}\n</code></pre>\n\n<p>LINQ again may make your life easier here:</p>\n\n<pre><code>var messageData = messageDictionary // From each entry in the dictionary\n .Select(item =&gt; item.Value) // select the queue\n .First(queue =&gt; queue.Count &gt; 0) // and take the first queue with Count &gt; 0\n .Peek(); // and call Peek() on that.\n</code></pre>\n\n<hr>\n\n<p>In general: check all preconditions at the start of the method. Use the inherent qualities of the looping constructs instead of explicit <code>break</code> and <code>continue</code>. Especially <code>continue</code> is something you should almost never need. Try reading up on LINQ, it may solve many problems you'll encounter while programming.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-05-19T21:02:51.230", "Id": "11913", "ParentId": "11836", "Score": "5" } }, { "body": "<p>Your locking scope to too large. I only see one or two places in each method where locking is needed, yet the entire method is locked.</p>\n\n<p>Is there any reason a SortedDictionary is used? If there is not, have you considered a ConcurrentDictionary? From what I can tell this would eliminate your need to lock all together.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-05-20T17:56:13.093", "Id": "11930", "ParentId": "11836", "Score": "1" } }, { "body": "<p>That is actually a limited priority queue - at least according to the fact that you have an enum with a discrete amount of values. Due to the fact that it's limited you are wasting both CPU cycles and memory because you are dealing with a <code>Dictionary</code> - when an array will do:</p>\n\n<pre><code>private Queue&lt;PQMessage&gt;[] priorityQueue;\nprivate int maxPriority;\n\npublic PriorityQueue()\n{\n maxPriority = Enum.GetValues(typeof(PQMsgPriority)).Cast&lt;int&gt;().Max();\n priorityQueue = new Queue&lt;PQMessage&gt;[maxPriority + 1];\n for (var i = 0; i &lt;= maxPriority; i++)\n priorityQueue[i] = new Queue&lt;PQMessage&gt;();\n}\n</code></pre>\n\n<p>Now you can grab a queue by merely casting your <code>enum</code> value to an <code>int</code>. We never have to alter our array again we don't have to lock it (we are only retrieving elements from it) - so we only need to lock the queue in question.</p>\n\n<pre><code>public void Enqueue(PQMessage item)\n{\n if (item != null)\n {\n if ((int)item.MsgPriority &lt; 0 || (int)item.MsgPriority &gt; maxPriority)\n throw new ArgumentOutOfRangeException(\"item.MsgPriority\");\n\n var queue = priorityQueue[(int)item.MsgPriority];\n lock (queue) \n queue.Enqueue(item);\n }\n}\n\npublic PQMessage Dequeue()\n{\n for (var i = 0; i &lt;= maxPriority; i++)\n {\n var queue = priorityQueue[i];\n lock (queue)\n {\n if (queue.Count &gt; 0)\n return queue.Dequeue();\n }\n }\n return null;\n}\n</code></pre>\n\n<p>If you are using .Net 4.0 you can use the <code>ConcurrentQueue</code> (<code>System.Collections.Concurrent</code>) to eliminate locks altogether; as such:</p>\n\n<pre><code>class PriorityQueue\n{\n private ConcurrentQueue&lt;PQMessage&gt;[] priorityQueue;\n private int maxPriority;\n\n public PriorityQueue()\n {\n maxPriority = Enum.GetValues(typeof(PQMsgPriority)).Cast&lt;int&gt;().Max();\n priorityQueue = new ConcurrentQueue&lt;PQMessage&gt;[maxPriority + 1];\n for (var i = 0; i &lt;= maxPriority; i++)\n priorityQueue[i] = new ConcurrentQueue&lt;PQMessage&gt;();\n }\n\n public void Enqueue(PQMessage item)\n {\n if (item != null)\n {\n if ((int)item.MsgPriority &lt; 0 || (int)item.MsgPriority &gt; maxPriority)\n throw new ArgumentOutOfRangeException(\"item.MsgPriority\");\n\n var queue = priorityQueue[(int)item.MsgPriority];\n queue.Enqueue(item);\n }\n }\n\n public PQMessage Dequeue()\n {\n PQMessage result = null;\n for (var i = 0; i &lt;= maxPriority; i++)\n {\n var queue = priorityQueue[i];\n if (queue.TryDequeue(out result))\n break;\n }\n return result;\n }\n}\n</code></pre>\n\n<p>As a final step I would make it more re-usable:</p>\n\n<pre><code>class PQMsgPriorityQueue : PriorityQueue&lt;PQMsgPriority, PQMessage&gt;\n{\n public PQMsgPriorityQueue()\n : base(x =&gt; x.MsgPriority)\n {\n\n }\n}\n\nclass PriorityQueue&lt;TKey, TItem&gt;\n // struct (ValueType) so we can ignore null checks, and all enums are value types\n // IConvertible so that we can convert values to ints, and all enums are IConvertible\n where TKey : struct, IConvertible\n{\n private ConcurrentQueue&lt;TItem&gt;[] priorityQueue;\n private int maxPriority;\n private Func&lt;TItem, TKey&gt; extractKey;\n private int count;\n\n /// &lt;summary&gt;\n /// Gets the approximate amount of items in the queue.\n /// &lt;/summary&gt;\n public int Count\n {\n get { return Thread.VolatileRead(ref count); }\n }\n\n public PriorityQueue(Func&lt;TItem, TKey&gt; extractKey)\n {\n if (extractKey == null)\n throw new ArgumentNullException(\"extractKey\");\n\n this.extractKey = extractKey;\n // This will validate that the key type is an enum.\n maxPriority = Enum.GetValues(typeof(TKey)).Cast&lt;IConvertible&gt;().Select(x =&gt; x.ToInt32(null)).Max();\n priorityQueue = new ConcurrentQueue&lt;TItem&gt;[maxPriority + 1];\n for (var i = 0; i &lt;= maxPriority; i++)\n priorityQueue[i] = new ConcurrentQueue&lt;TItem&gt;();\n }\n\n public void Enqueue(TItem item)\n {\n if (item != null)\n {\n var key = extractKey(item).ToInt32(null);\n if (key &lt; 0 || key &gt; maxPriority)\n throw new ArgumentOutOfRangeException(\"item&gt;key\");\n\n var queue = priorityQueue[key];\n queue.Enqueue(item);\n Interlocked.Increment(ref count);\n }\n }\n\n public TItem Dequeue()\n {\n TItem result;\n TryDequeue(out result);\n return result;\n }\n\n public bool TryDequeue(out TItem result)\n {\n for (var i = 0; i &lt;= maxPriority; i++)\n {\n var queue = priorityQueue[i];\n if (queue.TryDequeue(out result))\n {\n Interlocked.Decrement(ref count);\n return true;\n }\n }\n result = default(TItem);\n return false;\n }\n\n // The presence of peek is indicative of race conditions\n // as such I have not implemented it.\n}\n</code></pre>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-05-24T16:32:12.820", "Id": "12037", "ParentId": "11836", "Score": "0" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-05-17T10:30:08.670", "Id": "11836", "Score": "5", "Tags": [ "c#", ".net", "priority-queue" ], "Title": "Priority queue implementation in C#" }
11836
<p>As this community is full of experienced JavaScript developers, and I'm a newbie in JavaScript, I would like if some of you could look over my code for a website I'm building (personal portfolio) and give some insight on how I can improve it, maybe make it more readable and clean, things I may be doing wrong or I missed.</p> <p>And here's the JavaScript (excluding plugins and other JavaScript libraries):</p> <pre><code>$(document).ready(function() { var default_cluster_options = { environment : "Development", local_storage_key : "Cluster", plugin_navigation_class : ".navigation", plugin_wrapper_id : "content-wrapper", headings : ['.heading-first h1', '.heading-second h1'], input_types : ['input', 'textarea'], info_iqns_class : ".iqn", preview_iqn_class : ".preview", limits : [ { min: 1224, items: 8 }, { min: 954, items: 6 }, { min: 624, items: 4 }, { min: 0, items: 2 } ], shop_local_storage_key : "Shop", }; var default_plugin_options = { containerID : "", first : false, previous : false, next : false, last : false, startPage : 1, perPage : 1, midRange : 6, startRange : 1, endRange : 1, keyBrowse : false, scrollBrowse: false, pause : 0, clickStop : true, delay : 50, direction : "auto", animation : "fadeIn", links : "title", fallback : 1000, minHeight : true, callback : function(pages, items) {} }; var Cluster = function(cluster_options, plugin_options) { var self = this; this.options = $.extend({}, default_cluster_options, cluster_options); this.plugin_options = $.extend({}, default_plugin_options, plugin_options); this.environment = this.options.environment; this.data_key = this.options.local_storage_key; this.shop_data_key = this.options.shop_local_storage_key; this.plugin_navigation_class = this.options.plugin_navigation_class; this.plugin_wrapper_id = this.options.plugin_wrapper_id; this.headings = this.options.headings; this.input_types = this.options.input_types; this.viewport = $(window); this.body = $('body'); this.viewport_width = this.viewport.width(); this.viewport_height = this.viewport.height(); this.info_iqns_class = this.body.find(this.options.info_iqns_class); this.preview_iqn_class = this.body.find(this.options.preview_iqn_class); this.limits = this.options.limits; this.current_shop_page = this.options.current_shop_page; this.total_shop_pages = this.options.total_shop_pages; this.initiate_cluster(self.plugin_navigation_class, { containerID : self.plugin_wrapper_id, startPage : +(self.get_local_storage_data(self.data_key) || 1), callback : function(pages){ self.set_local_storage_data(self.data_key, pages.current); } }); this.inititate_shop(); this.initiate_shop_touch_events(); }; Cluster.prototype.set_environment = function() { if(this.environment == "Development") { less.env = "development"; less.watch(); } }; Cluster.prototype.set_local_storage_data = function(data_key, data_val) { return localStorage.setItem(data_key, data_val); }; Cluster.prototype.get_local_storage_data = function(data_key) { return localStorage.getItem(data_key); }; Cluster.prototype.initiate_scalable_text = function() { for(var i in this.headings) { $(this.headings[i]).fitText(1.6); } }; Cluster.prototype.initiate_placeholder_support = function() { for(var i in this.input_types) { $(this.input_types[i]).placeholder(); } }; Cluster.prototype.initiate_iqn_selected_class = function() { if(this.viewport_width &lt; 980) { $(this.info_iqns_class).each(function(index, element) { var iqn = $(element).parent(); $(iqn).on('click', function() { if($(iqn).hasClass('selected')) { $(iqn).removeClass('selected'); } else { $(iqn).addClass('selected'); } }); }); } }; Cluster.prototype.initiate_preview_action = function() { $(this.preview_iqn_class).each(function(index, element) { var data = $(element).attr('data-image-link'); $(element).on('click', function(ev) { $.lightbox(data, { 'modal' : true, 'autoresize' : true }); ev.preventDefault(); }); }); }; Cluster.prototype.initiate_plugin = function(plugin_navigation, plugin_options) { var options = $.extend({}, this.plugin_options, plugin_options); return $(plugin_navigation).jPages(options); }; Cluster.prototype.initiate_shop_touch_events = function() { var self = this; return $("#shop-items-wrapper").hammer({prevent_default: true, drag_min_distance: Math.round(this.viewport_width * 0.1)}).bind("drag", function(ev) { var data = JSON.parse(self.get_local_storage_data(self.shop_data_key)); if (ev.direction == "left") { var next_page = parseInt(data.current_page + 1); if(next_page &gt; 0 &amp;&amp; next_page &lt;= data.total_pages) { $(".shop-items-navigation").jPages(next_page); } } if(ev.direction == "right") { var prev_page = parseInt(data.current_page - 1); if(prev_page &gt; 0 &amp;&amp; prev_page &lt;= data.total_pages) { $(".shop-items-navigation").jPages(prev_page); } } }); } Cluster.prototype.inititate_shop = function() { var self = this; for(var i = 0; i &lt; this.limits.length; i++) { if(this.viewport_width &gt;= this.limits[i].min) { this.initiate_plugin('.shop-items-navigation', { containerID : "shop-items-wrapper", perPage : self.limits[i].items, midRange : 8, animation : "fadeIn", links : "blank", keyBrowse : true, callback : function(pages) { var data = { current_page : pages.current, total_pages : pages.count } self.set_local_storage_data(self.shop_data_key, JSON.stringify(data)); } }); return false; } } }; Cluster.prototype.initiate_cluster = function(plugin_navigation, plugin_options) { this.set_environment(); this.initiate_scalable_text(); this.initiate_placeholder_support(); this.initiate_iqn_selected_class(); this.initiate_preview_action(); this.initiate_plugin(plugin_navigation, plugin_options); }; var cluster = new Cluster(); }); </code></pre>
[ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-05-18T15:26:49.100", "Id": "19066", "Score": "1", "body": "For a \"newbie in JavaScript\" your web page uses JavaScript awfully heavily. Most importantly it's completely broken with JavaScript disabled. If it were a \"web application\", I could understand that, but considering that it's a trivial \"content site\" and that I can't see any functionality that actually requires JS, I personally find that unacceptable. :-(" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-05-18T15:29:45.990", "Id": "19067", "Score": "1", "body": "Regarding your script: For a code review it would help to have a short explanation what it is supposed to do." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-05-18T15:30:18.533", "Id": "19068", "Score": "0", "body": "Perhaps your opinion it's a bit wrong, how can you say JS isn't necessary ? Do you know of any CSS techniques that could do what the jPages plugin does ? Or how about detecting CSS3 features with Modernizr ? And other fallbacks in JS that some browsers don't support ? And as a simple notice, what browser does not support JS now, 1% of the Earth's population ?" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-05-18T15:31:52.073", "Id": "19069", "Score": "0", "body": "@RoToRa I think it's pretty obvious what it does for someone who knows JS. Or should I describe what every plugin I use does ? I'm not sure I follow what you're suggesting" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-05-18T16:38:22.607", "Id": "19077", "Score": "0", "body": "Huh? What happend to \"as harsh as it would be\"? Anyway: I just don't see anything that **requires** JS. All of the basic functionality I can see can be done without any JS, and any \"extras\" don't require any big \"plugins\". And fallbacks are great, but you are not using the JS as a fallback, otherwise the site would work without JS. And the most important visitor doesn't support JS. Hint: It starts with \"G\" and ends with \"ooglebot\"." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-05-18T16:41:12.603", "Id": "19078", "Score": "0", "body": "Of course it's obvious what your script does. What I want to know is what **you** want it to do. These can be two very different things." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-05-18T17:01:32.477", "Id": "19079", "Score": "0", "body": "@RoToRa I don't have problems with your remarks, what strikes me is that you seem to think that the functionality that I have so far on the site can be acquired without JS, I find that hard to believe :) But if you seem to be so determined that you can make everything with just CSS and HTML, please do so :) I have already done all that can be done with CSS, but of course there may be more I can do, I'm still working on it. And why would I need gbot to index my JS ? I also don't care about where I am in Google's search. And what I want my JS to do is what it already does." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-05-18T17:05:43.047", "Id": "19082", "Score": "0", "body": "@RoToRa - Also, I was looking for improvements and clean ups, not someone trying to make me not use JS. I obviously don't know anything about you, neither you about me, so there's no reason for us to fight over an opinion :) I would though appreciate tips on how I can improve my coding and if you think I can achieve what I'm doing without JS I would like to hear about it, as I like CSS more than JS, because after all, what I'm developing is for exercise and for a better understanding of JS :) I hope I haven't offended you in anyway, if I did I'm sorry" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-05-18T21:00:56.717", "Id": "19094", "Score": "0", "body": "I tried visiting the site in Firefox 12 and got an \"unresponsive script\" warning at Script: https://raw.github.com/chaoscod3r/less.js/master/dist/less-1.3.0.min.js:8" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-05-18T22:04:27.177", "Id": "19095", "Score": "1", "body": "I'm not saying you shouldn't use any JS at all. I'm saying it's possible to have the site usable without JS and the functionality I currently see with much less JS. And gbot doesn't need to index the JS, but the content. Currently if a search engine sends someone to your site, they will get the \"homepage\" but most likely not the content they were looking for (for example the \"products\"). (NB the site seems to be currently broken. LESS seems to be missing. BTW the JS implementation of LESS should only be used for development not the live site)." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-05-19T07:44:59.353", "Id": "19100", "Score": "0", "body": "@RoToRa - Yes, sometimes throws that error, seems like it doesn't find the git source of the LESS.js , but there's fallback to local. Anyway, I'm using LESS because the website is under development, I'm not even half way there :) Of course after I developed it, I'll drop LESS and use the compiled CSS, but till then I have to use it because it's much easier to work with. There's a lot of work to do on it, so I'll try using as less JS as possible, but I still need to practice my JS skills too :) You were saying that some features can be meet with CSS, could you tell me what so I can try ? Thanks" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-05-19T07:46:12.707", "Id": "19101", "Score": "0", "body": "@CheranS - This is the link you were trying to reach : https://raw.github.com/chaoscod3r/less.js/master/dist/less-1.3.0.min.js . Sometimes it throws that error but I don't know why" } ]
[ { "body": "<p>Why is <code>Cluster</code> a function? You only instantiate it once, and you don't export anything (as far as I have seen). Use a simple object instead.</p>\n\n<p>If you want to export the <code>Cluster</code>, you should not do it onDOMReady, but as soon as your code executes.</p>\n\n<pre><code>var Cluster = (function(){\n // private static vars like default_options\n\n function Cluster() { ... }\n\n Cluster.prototype = ...\n\n return Cluster;\n})();\n// after that, you might instantiate one\njQuery(function(){\n var cluster = new Cluster;\n});\n</code></pre>\n\n<p>Also, it might be a good idea to put the onDOMready into the <code>.inititate_XY()</code> methods, if they need it. They seem to already use a callback, so it should be no problem - I'm not sure whether that matches your requirements.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-05-18T14:47:54.920", "Id": "19063", "Score": "0", "body": "I don't think that using onDOMReady inside the methods might be a good idea, I already have the entire prototype function wrapped inside `$(document).ready(function() {});` so there's no need to reuse it, just my opinion. Is it wrong if I'm using it as a function ? What impact will your method have on the website ? Oh, and for now it's only a piece of the entire project, there much more I need to do in fact, but I want to make sure I'm on the right track." } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-05-18T14:28:28.517", "Id": "11875", "ParentId": "11838", "Score": "2" } }, { "body": "<p>In the <code>Cluster.prototype.initiate_shop_touch_events</code> function, the only difference between \"left\" and \"right\" is the number that gets added to the current page. You can reduce duplication by pulling that out into a variable:</p>\n\n<pre><code> var step = (ev.direction == \"left\") ? 1 : -1;\n var new_page = parseInt(data.current_page + step);\n if(new_page &gt; 0 &amp;&amp; new_page &lt;= data.total_pages) {\n $(\".shop-items-navigation\").jPages(new_page);\n }\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-05-19T18:24:02.900", "Id": "19108", "Score": "0", "body": "I don't get the point here, what if the direction is right ? It actually needs the `ev.direction == \"right\"` to test which direction the drag event has been fired" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-05-19T22:35:27.447", "Id": "19117", "Score": "0", "body": "I was assuming that `direction` is only one of two values: \"left\" or \"right\". You can use whatever logic is appropriate to set the value of `step`, but the key point is to reduce unnecessary duplication." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-05-20T10:31:59.610", "Id": "19129", "Score": "0", "body": "Yes, I get the logic, only that the drag event can occur to whatever direction you drag your finger along the touch screen :) I'll try this one anyway :)" } ], "meta_data": { "CommentCount": "3", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-05-19T10:08:44.167", "Id": "11898", "ParentId": "11838", "Score": "1" } }, { "body": "<p>For places where you have an array of selectors (such as <code>this.headings</code>), you don't need to loop through each element of the array (never mind that <code>for...in</code> with arrays <a href=\"https://stackoverflow.com/questions/500504/javascript-for-in-with-arrays\">is a bad idea</a>). Instead, you can use jQuery's <a href=\"http://api.jquery.com/multiple-selector/\" rel=\"nofollow noreferrer\">multiple selector</a> to create one selector. This should perform slightly better since there will be less function calls to the plugins.</p>\n\n<p>Example</p>\n\n<pre><code>Cluster.prototype.initiate_scalable_text = function() {\n var selector = this.headings.join(\",\");\n $(selector).fitText(1.6);\n};\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-05-19T18:24:48.717", "Id": "19109", "Score": "0", "body": "Indeed, this might perform a bit faster. But why looping through an array like I do is not safe ?" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-05-19T22:36:55.807", "Id": "19118", "Score": "0", "body": "@Roland, did you read the linked SO question?" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-05-20T10:27:09.917", "Id": "19128", "Score": "0", "body": "I have now :) Seems like a good reason why not, even though in my case I don't think that something like that will occur. Anyway, using jQuery selectors might perform faster :)" } ], "meta_data": { "CommentCount": "3", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-05-19T10:20:52.170", "Id": "11899", "ParentId": "11838", "Score": "1" } } ]
{ "AcceptedAnswerId": "11898", "CommentCount": "12", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-05-17T11:35:30.450", "Id": "11838", "Score": "1", "Tags": [ "javascript", "jquery" ], "Title": "JavaScript initialization for a personal portfolio website" }
11838
<p>I've been programming in C++ again (after switching to web languages) for about 2 weeks now. I wrote this simple <code>Node</code> class from which all other objects within the Tree will be derived from. Any critique is very welcome here, however please use clear explanations, don't just point out flaws.</p> <pre><code>#include &lt;string&gt; #include &lt;vector&gt; using namespace std; // DEFINITION class Node { public: Node(string name_); virtual ~Node() = 0; string GetName() const; void SetParent(Node * parent); Node * GetParent() const; Node * AddChild(Node * child); vector&lt;Node*&gt; FindChildren(string name) const; Node * FindFirstChild(string name) const; Node * FindLastChild(string name) const; Node * FindNthChild(int nth, string name) const; vector&lt;string&gt; ChildrenNames() const; int Depth() const; bool IsLeaf() const; bool IsRoot() const; protected: string name; Node * parent; vector&lt;Node*&gt; children; private: }; // IMPLEMENTATION Node::Node(string name_) { name = name_; parent = NULL; } Node::~Node() { for(vector&lt;Node*&gt;::iterator it = children.begin(); it &lt; children.end(); it++) { if (*it) { delete * it; } } children.clear(); } string Node::GetName() const { return name; } void Node::SetParent(Node * parent_) { parent = parent_; } Node * Node::GetParent() const { return parent; } Node * Node::AddChild(Node * child) { child-&gt;SetParent(this); children.push_back(child); return child; } vector&lt;Node*&gt; Node::FindChildren(string name) const { vector&lt;Node*&gt; children; for(vector&lt;Node*&gt;::const_iterator it = children.begin(); it &lt; children.end(); it++) { if (name.compare((*it)-&gt;name) == 0) children.push_back(*it); } return children; } Node * Node::FindFirstChild(string name) const { for(vector&lt;Node*&gt;::const_iterator it = children.begin(); it &lt; children.end(); it++) { if (name.compare((*it)-&gt;name) == 0) return (*it); } return NULL; } Node * Node::FindNthChild(int nth, string name) const { int n = 0; for(vector&lt;Node*&gt;::const_iterator it = children.begin(); it &lt; children.end(); it--) { if (name.compare((*it)-&gt;name) == 0) { if (++n == nth) return (*it); } } return NULL; } vector&lt;string&gt; Node::ChildrenNames() const { vector&lt;string&gt; names; for(vector&lt;Node*&gt;::const_iterator it = children.begin(); it &lt; children.end(); it++) { names.push_back((*it)-&gt;name); } return names; } int Node::Depth() const { int d; Node * ancestor = parent; for (d = 0; ancestor != NULL; d++) { ancestor = ancestor-&gt;parent; } return d; } bool Node::IsLeaf() const { return (children.size() == 0) ? true : false; } bool Node::IsRoot() const { return (parent == NULL) ? true : false; } </code></pre>
[ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-05-17T19:06:31.480", "Id": "19019", "Score": "2", "body": "My immediate reaction is that the interface is at too low a level of abstraction for most purposes. What do you really want this to accomplish?" } ]
[ { "body": "<p>OK. I complain about this every time. Please don't do this.</p>\n\n<pre><code>using namespace std;\n</code></pre>\n\n<p>It may be in every C++ book but in real programs (more than 100) lines it causes more problems than it is worth. You can easily get tangled up in all sorts of problems with name look-up. The whole point of <code>std</code> being so short (not <code>standard</code>) is so that it is simple to prefix items in the standard library easily. You can also selectively use <code>using</code> to bring specific objects into the current namespace.</p>\n\n<pre><code>using std::cout; // now you can use cout\n // But try and scope it as much as possible\n // preventing pollution is a good thing.\n</code></pre>\n\n<p>But personally I have got used to typing std:: in-front of everything. </p>\n\n<p>When returning objects </p>\n\n<pre><code> string GetName() const;\n</code></pre>\n\n<p>prefer to return by reference. If you want to keep the object immutable return by const reference. Depending on usage it may be worth having two version a const and a non const version.</p>\n\n<pre><code> string&amp; GetName();\n string const&amp; GetName() const;\n</code></pre>\n\n<p>Why do you need a SetParent()?</p>\n\n<pre><code> void SetParent(Node * parent);\n</code></pre>\n\n<p>This seems like you are exposing the implementation via the interface. This is binding your interface and tightly binding your implementation to this interface. I would remove this method. Remember that Node is a friend of itself so methods in Node can access and manipulate other objects of type Node (you trust yourself don't you).</p>\n\n<p>There is absoilutely no reason to expose this.</p>\n\n<pre><code> Node * GetParent() const;\n</code></pre>\n\n<p>You pass pointers around too much.</p>\n\n<pre><code> Node * AddChild(Node * child);\n</code></pre>\n\n<p>OK. In a tree the ownership may seem obvious. But I would prefer to ownership explicitly defined by the code (this will prevent mistakes later). Thus you need to use smart pointers so that you explicitly define how ownership of pointers as they are passed around.</p>\n\n<pre><code> // No need to return anything.\n // Explicitly pass ownership of the pointer.\n void AddChild(std::auto_ptr&lt;Node&gt; child);\n</code></pre>\n\n<p>These are OK returning pointers. As here you are saying that there may be no result and you need to validate any result (checking for NULL) before it can be used. But you can pass string by const reference.</p>\n\n<pre><code> vector&lt;Node*&gt; FindChildren(string name) const;\n Node * FindFirstChild(string name) const;\n Node * FindLastChild(string name) const;\n Node * FindNthChild(int nth, string name) const;\n vector&lt;string&gt; ChildrenNames() const;\n</code></pre>\n\n<p>OK. Parent can be a pointer (as it potentially may be NULL).</p>\n\n<pre><code> Node * parent;\n</code></pre>\n\n<p>Children on the other hand are owned. </p>\n\n<ul>\n<li>One choice is a vector of smart pointers. </li>\n<li><p>An alternative is boost::ptr_vector.</p>\n\n<pre><code>vector&lt;Node*&gt; children;\n</code></pre></li>\n</ul>\n\n<p>Normally I would go with boost::ptr_vector (as it exposes its members as object references rather than pointers) but in this particular case I would go with a vector of smart pointers (because I want to manage the pointers in this case).</p>\n\n<p>No need to test for NULL before deleting\n if (*it) \n {\n delete * it;\n }\nJust use::\n delete (*it);</p>\n\n<p>No point in calling clear. The destructor is about to destroy this object any way. By putting this here you are making the mainter think that there is something none obvious going on here.</p>\n\n<pre><code> children.clear();\n\n\n// Just delete this function it is not required.\n// See below on how to replace it. \n/* void Node::SetParent(Node * parent_) \n{\n parent = parent_;\n}*/\n\n// No need for this. It is exposing internals without needing too.\n/*Node * Node::GetParent() const\n{\n return parent;\n}*/\n\n// Replace call to set parent\nvoid Node::AddChild(std::auto_ptr&lt;Node&gt; child)\n{\n // Check if the child is valid\n if (child.get() == NULL)\n { return;\n }\n\n // child-&gt;SetParent(this);\n // Check that the child is not already in a tree.\n if (child-&gt;parent != NULL)\n { throw std::runtime_error(\"Something bad happened this node is already in a tree\");\n }\n\n // Add it to the tree.\n child-&gt;parent = this;\n children.push_back(child);\n\n // No need to return this\n // You have to think why does this return the child\n // I see no reason for this.\n // return child;\n}\n</code></pre>\n\n<p>So you only check this node and its children!!!!!<br>\nIf so this function seems to be named incorrectly. Searching a tree is normally recursive. The function should check the current node then <strong>RECUSIVELY</strong> check each child.</p>\n\n<pre><code>vector&lt;Node*&gt; Node::FindChildren(string name) const\n</code></pre>\n\n<p>Iterators are <strong>not</strong> compared with <code>&lt;</code> you need to test against <code>!=</code>. While we are here prefer to use prefix ++ (here it does not make much difference but in other places it can so it is a nice habbit to get into (especially with iterators)).</p>\n\n<pre><code> for(vector&lt;Node*&gt;::const_iterator it = children.begin(); it &lt; children.end(); it++) \n</code></pre>\n\n<p>Is there a particular reason you use compare() rather than the more natural <code>==</code>?</p>\n\n<pre><code> if (name.compare((*it)-&gt;name) == 0)\n</code></pre>\n\n<p>Try this:</p>\n\n<pre><code>std::vector&lt;Node*&gt; Node::FindChildren(std::string const&amp; name) const\n{\n std::vector&lt;Node*&gt; children;\n if (name == this-&gt;name)\n {\n children.push_back(this);\n }\n for(vector&lt;Node*&gt;::const_iterator it = children.begin(); it != children.end(); ++it) \n {\n if (*it)\n { it-&gt;FindChildren(name);\n }\n }\n return children;\n}\n</code></pre>\n\n<p>Again. Only checking the children. See notes above. Same comments as last function.</p>\n\n<pre><code>Node * Node::FindFirstChild(string name) const\n</code></pre>\n\n<p>Does this really have any meaning for a tree? The nth child in this tree. What about the next tree down. Seems like a very strange interface.</p>\n\n<pre><code>Node * Node::FindNthChild(int nth, string name) const\n</code></pre>\n\n<p>Why are you looping over the vector.<br>\nstd::vector has direct element access with <code>operator[]</code> if you want to make sure you don't exceed the size of the array then use <code>at()</code> and it will validate the index before use.</p>\n\n<p>What about granchildren?</p>\n\n<pre><code>vector&lt;string&gt; Node::ChildrenNames() const\n</code></pre>\n\n<p>Sure it works. But initialize variables on declaration (<code>d</code>). And scope your variables (<code>ancestor</code>) so there lifespan does not exceed their need. Also your control loop is all messed up (you are incrementing d not the value you are testing in the condition!!!!</p>\n\n<pre><code>int Node::Depth() const\n{\n int d;\n Node * ancestor = parent;\n for (d = 0; ancestor != NULL; d++)\n {\n ancestor = ancestor-&gt;parent;\n }\n return d;\n}\n</code></pre>\n\n<p>Try this:</p>\n\n<pre><code>int Node::Depth() const\n{\n // I hate single letter variables.\n // Make the name meaningful and represent what you are going to do with it.\n //\n // Short functions it does not matter. But for larger functions it makes\n // it so much easier to search see all the usage of the variable.\n\n int result = 0;\n for (Node * ancestor = parent; ancestor;ancestor = ancestor-&gt;parent)\n {\n ++result;\n }\n return result;\n}\n\n\nbool Node::IsLeaf() const\n{\n return (children.size() == 0) ? true : false;\n\n // Easier to read/write as\n\n return children.size() == 0;\n}\n\nbool Node::IsRoot() const\n{\n return (parent == NULL) ? true : false;\n\n // Easier to read/write as\n\n return parent == NULL;\n}\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-05-17T17:12:40.970", "Id": "19009", "Score": "1", "body": "Thank you VERY much! I will take all of your advice. I'm still a C++ newbie, as I said. I hadn't expected such a great answer. So once again: THANK YOU!" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2015-04-09T20:53:19.950", "Id": "155848", "Score": "0", "body": "One adjustment: change it->FindChildren(name); to (*it)->FindChildren(name);." } ], "meta_data": { "CommentCount": "2", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-05-17T16:16:54.900", "Id": "11843", "ParentId": "11841", "Score": "12" } } ]
{ "AcceptedAnswerId": "11843", "CommentCount": "1", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-05-17T14:56:29.690", "Id": "11841", "Score": "7", "Tags": [ "c++", "tree" ], "Title": "C++ tree base node" }
11841
<p>These days I read a lot here on SO about password hashing and data encryption. It's a real mess, I mean, deciding what the best practice is. I need a very simple class that can be reused anywhere and that provide a <strong><em>decent-but-not-paranoic</em></strong> security level for my PHP applications (I do not handle bank data). Additionally, I want to rely as much as possible on PHP standard libs. I came up with this:</p> <pre><code>class Security { public static function hashPassword($plain) { $salt = md5(rand(0, 1023) . '@' . time()); // Random salt return crypt($plain, '$2a$07$' . $salt); // '$2a$07$' is the Blowfish trigger } public static function checkPassword($plain, $hash) { return (crypt($plain, $hash) === $hash); } public static function generateIv() { $iv_size = mcrypt_get_iv_size(MCRYPT_RIJNDAEL_256, MCRYPT_MODE_CBC); // It's 32 return mcrypt_create_iv($iv_size, MCRYPT_RAND); } public static function encrypt($key, $data, $iv = null, $base64 = true) { if (is_null($iv)) $iv = md5($key); $ret = mcrypt_encrypt(MCRYPT_RIJNDAEL_256, $key, $data, MCRYPT_MODE_CBC, $iv); return ($base64 ? base64_encode($ret) : $ret); } public static function decrypt($key, $data, $iv = null, $base64 = true) { if (is_null($iv)) $iv = md5($key); return rtrim(mcrypt_decrypt(MCRYPT_RIJNDAEL_256, $key, $base64 ? base64_decode($data) : $data, MCRYPT_MODE_CBC, $iv), "\0"); } } </code></pre> <p>As you can see, I choose to hash passwords with <a href="http://us.php.net/manual/en/function.crypt.php" rel="nofollow"><strong><code>crypt()</code></strong></a> using <strong>Blowfish hashing algorithm</strong>. The return value of <code>hashPassword()</code> is the salt + hash that then I store in the DB. I made this choice because <code>crypt()</code> is available on every server, provides a confortable way to check hash regardless of algorithm used (it's based on salt prefix) and, I read, <em>bcrypt</em> is a decent hashing method.</p> <p>Then, for data encryption I used <a href="http://www.php.net/manual/en/book.mcrypt.php" rel="nofollow"><strong><code>mcrypt()</code></strong></a> <strong>Rijndael 256</strong> algorithm with <strong>CBC mode</strong>. As you can see, I can use encryption methods in two way. I can pass a IV (and <code>generateIv()</code> helps me to create one) that I will store in the DB along crypted data, or, if I don't, a basic IV is derived from key in both crypt and decrypt process.</p> <p>What do you think about it? Am I missing something? Can I be finally relaxed about hashing and encryption in my PHP applications?</p>
[]
[ { "body": "<p>Your salt generation mechanism does not seem sufficiently random. You will end up with a very small set of salts.</p>\n\n<p>First of all, <code>time()</code> is not random at all. In second place, <code>rand(0, 1023)</code> is not only a relatively weak random number generator, but also generates too few bits to be enough.</p>\n\n<p>All this - combined with the use of the relatively unsafe <code>md5</code> algorithm - means that there's a higher-than-ideal risk of salt collision.</p>\n\n<p>Will all of this still cause trouble? Frankly, I don't know. This is definitely better than storing passwords in plain text, or using unsalted hashes, but it's not perfect. Generally, I'm nervous about using not-exactly-random data for security algorithms that are meant to use random data.</p>\n\n<p>For a starting point, try to look at <a href=\"https://stackoverflow.com/questions/4795385/how-do-you-use-bcrypt-for-hashing-passwords-in-php\">this stackoverflow question</a>. This is what the author does for salt generation:</p>\n\n<ol>\n<li>Use OpenSSL random pseudo bytes, if available. Using a security library to get random data for use in another security function makes me far less nervous than ordinary <code>rand()</code>.</li>\n<li>Try a *NIX-specific method</li>\n<li>If not possible, then use a mix of <code>md5</code>, <code>microtime</code>(better than <code>time</code> since it changes more often) and even the PID.</li>\n</ol>\n\n<p>In particular, note than PHP's <code>md5</code> normally returns a hexadecimal string with a 32-byte length, but <code>bcrypt</code> expects a string with a length of <code>22</code>, so that might cause troubles (namely, the salt will not be as secure as it could be)</p>\n\n<p>Also, in your case this won't be a problem, but <code>$2a</code> is ambiguous (but sadly, the correct, unambiguous way might be incompatible with older PHP versions). If you can, consider using <code>$2y</code> instead and see if that works for you.</p>\n\n<p>The PHP documentation <a href=\"http://php.net/manual/en/function.mcrypt-get-iv-size.php\" rel=\"nofollow noreferrer\">recommends</a> using <code>mcrypt_enc_get_iv_size</code> instead of <code>mcrypt_get_iv_size</code> and using that in combination with <code>mcrypt_module_open</code> (although strangely, the <a href=\"http://php.net/manual/en/function.mcrypt-encrypt.php\" rel=\"nofollow noreferrer\">documentation for <code>mcrypt_encrypt</code></a> does use <code>mcrypt_get_iv_size</code>)</p>\n\n<p>Again, you are using not-really-random data for a function that seems to expect random data (specifically, the IV when the supplied IV is \"null\"). This makes me nervous.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-09-26T22:30:27.170", "Id": "25950", "Score": "0", "body": "Thank you @luiscubal for your remarks. It's all little changes I can do without class skeleton modifications and, most important, without break compatibility for already-used cases (that means, ok, salts and IVs will be better than previous from now, but old stuff will continue to work with updated class too). I will try to use `mt_rand()` with no args (that means, *0 to 2^31* on 32 bits systems) instead of `rand(0, 1023)` and `microtime()` instead of time. I think that will be sufficient." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-03-30T15:54:37.027", "Id": "79876", "Score": "0", "body": "@lorenzo-s Please consider using SSL random pseudo bytes, if available, or reading from `/dev/urandom`. Rely on the other options (`mt_rand` and `microtime`) only if *really* necessary. Better safe than sorry." } ], "meta_data": { "CommentCount": "2", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-09-26T21:33:26.873", "Id": "15964", "ParentId": "11842", "Score": "4" } } ]
{ "AcceptedAnswerId": "15964", "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-05-17T15:48:42.330", "Id": "11842", "Score": "4", "Tags": [ "php", "security", "cryptography" ], "Title": "Am I using crypt and mcrypt well in this simple encryption class?" }
11842
<p>I'm developing applications using Qt which highly make usage of the JSON language to communicate, store and load data of different types. I often need a simple viewer similar to the <a href="http://www.softwareishard.com/blog/firebug/json-explorer-for-firebug/" rel="noreferrer">Firebug JSON explorer</a> to <strong>view this data</strong>. I already had a JSON parser and serializer called QJson. (update: I also posted my <a href="https://codereview.stackexchange.com/q/11927/13353">QJson class on Code Review</a>.)</p> <p>I think this code snippet might be of public interest and there are some open problems (see below) which might be solved by you. I for myself would be glad if the problems get solved or the code will be improved in another point, but I don't need it really. So it is up to you (of course) if you want to review / test / improve the code and contribute.</p> <p><strong>Features / Preview</strong></p> <p>QJsonView is a QWidget so you can embed it in any other widget. You can set the value as a JSON-serialized string or as a hierarchical QVariant. It performs <strong>syntax-highlighting</strong> using HTML and displays this HTML using a QLabel.</p> <p>An example usage might look like this:</p> <pre><code>QString data = "{" "\"test\" : [\"this\", \"is\", \"a\", " "{\"test\" : [\"with\", \"nested\", \"items\"]}]," "\"types\" : [1337, 13.37, true, null]" "}"; QJsonView *jsonView = new QJsonView(this); jsonView-&gt;setJsonValue(data); </code></pre> <blockquote> <p><img src="https://i.stack.imgur.com/TtzUO.png" alt="Preview: Initial view"><br> <em>Preview: Initial view</em></p> </blockquote> <p>You can <strong>expand</strong> a JSON object or array (QVariantMap or QVariantList respectively) by clicking on the [+] sign. This can also be done from within your code. The entries then are displayed one below another and can be expanded again if they are objects or arrays. Expanding a nested element from within your code is currently not supported.</p> <pre><code>jsonView-&gt;expand(); </code></pre> <p>By enabling <strong>hover effects</strong>, QJsonView highlights the entry the mouse is currently over:</p> <pre><code>jsonView-&gt;setHoverEffects(true); </code></pre> <blockquote> <p><img src="https://i.stack.imgur.com/a2hbx.png" alt="Preview: Expanded view with hover effects"><br> <em>Preview: Expanded view with hover effects</em></p> </blockquote> <p>From within the <strong>context menu</strong>, the user can copy the JSON-serialized representation into the clipboard. If this is performed on a string, it doesn't get serialized but copied 1:1.</p> <blockquote> <p><img src="https://i.stack.imgur.com/TmhkJ.png" alt="Preview: Context menu: copy to clipboard"><br> <em>Preview: Context menu: copy to clipboard</em></p> </blockquote> <p>When shown as a stand-alone QWidget, it looks like this (here: fully expanded):</p> <blockquote> <p><img src="https://i.stack.imgur.com/HB6cF.png" alt="Preview: Windowed, fully expanded"><br> <em>Preview: Windowed, fully expanded</em></p> </blockquote> <p><strong>Known problems / Possible improvements</strong></p> <p>The following things are not implemented well, but I didn't have the time and/or motivation to do it better:</p> <ul> <li>The font family is set to <code>monospaced</code> by QJsonView.</li> <li>The custom paint event expects a fixed font size.</li> <li>The spacing expects a fixed font size.</li> <li>When using hover effects, the palette gets manipulated and reset to the palette of the parent widget. Two problems occur: (1) If there is no such parent widget, <em>boom</em>. (2) If you assign a custom palette, it will be reset to the parent palette when the mouse leaves the widget.</li> </ul> <p><strong>qjsonview.h:</strong></p> <pre><code>#ifndef QJSONVIEW_H #define QJSONVIEW_H #include &lt;QWidget&gt; #include &lt;QVariant&gt; #include &lt;QLabel&gt; /** Widget to display JSON or QVariant data. This widget will display any JSON-encoded string or a hierarchically nested QVariant tree in an expandable way. Per default, the whole data gets displayed in one single (non-wrapped) line, which can be expanded using a button if the JSON / QVariant data is of type JSON-array (QVariantList) or JSON-object (QVariantMap). */ class QJsonView : public QWidget { Q_OBJECT Q_PROPERTY(bool hoverEffects READ hoverEffects WRITE setHoverEffects); Q_PROPERTY(bool expandable READ isExpandable); Q_PROPERTY(bool expanded READ isExpanded WRITE setExpanded); public: /** Constructor for QJsonView, taking the parent widget as a single argument. */ explicit QJsonView(QWidget *parent = 0); /** Static and public helper function returning the HTML code which will be used to visualize the data (by applying syntax highlighting rules). This function is kept public since you may want to use this to layout some other QVariant data the same way like QJsonView does. */ static QString variantToHtml(QVariant data); signals: /** Emitted whenever this widget or one of its children has been expanded or collapsed. (The signal gets propagated to the root QJsonView object.) */ void resized(); public slots: /** Set the value to be displayed to a QVariant value. The only supported QVariant-types are Invalid, Bool, Int, LongLong, List, Map. Any other types are untested! */ void setValue(QVariant value); /** Set the value to be displayed to a JSON serialized string, which will be decoded before being viewed. */ void setJsonValue(QString json); /** Enables or disables hover effects. */ void setHoverEffects(bool enabled = true); /** Returns true if hover effects are enabled. */ bool hoverEffects(); /** Returns true if this QJsonView is expandable. This is the case for JSON-objects and JSON-arrays having at least one entry. */ bool isExpandable(); /** Returns true if this QJsonView is currently expanded. */ bool isExpanded(); /** Expands or collapses this view (convenient slot for expand() or collapse(), depending on the argument). */ void setExpanded(bool expanded); /** Expands this view if it is expandable and not expanded. */ void expand(); /** Collapses this view if it is expanded. */ void collapse(); protected: /** \reimp */ void mousePressEvent(QMouseEvent *); /** \reimp */ void paintEvent(QPaintEvent *); /** \reimp */ void contextMenuEvent(QContextMenuEvent *); /** \reimp */ void enterEvent(QEvent *); /** \reimp */ void leaveEvent(QEvent *); /** Called by a child in order to inform this widget that the mouse cursor is now over the child instead of this widget. */ void childEntered(); /** Called by a child in order to inform this widget that the mouse cursor isn't over the child anymore. */ void childLeaved(); private: // value to be displayed, as a QVariant QVariant v; // if this is no container type, this points to the QLabel representing the single value QLabel *lblSingle; // if this is a container type, these point to child widgets QList&lt;QWidget*&gt; childWidgets; // true if this is a container type and is currently in expanded view bool expanded; // true if hover effects are enabled bool hoverEffectsEnabled; // apply hover effect void hover(); // revert hover effect void unhover(); }; #endif // QJSONVIEW_H </code></pre> <p><strong>qjsonview.cpp:</strong></p> <pre><code>#include "qjsonview.h" #include "qjson.h" #include &lt;QGridLayout&gt; #include &lt;QPainter&gt; #include &lt;QVariantMap&gt; #include &lt;QContextMenuEvent&gt; #include &lt;QMenu&gt; #include &lt;QClipboard&gt; #include &lt;QApplication&gt; #include &lt;QMouseEvent&gt; #include &lt;QTextDocument&gt; #include &lt;QDebug&gt; #include &lt;QToolTip&gt; #define EXPANDABLE_MARGIN_LEFT 14 #define EXPANDED_MARGIN_LEFT 21 QJsonView::QJsonView(QWidget *parent) : QWidget(parent), lblSingle(new QLabel(this)), expanded(false), hoverEffectsEnabled(false) { //needed for hover effects setAutoFillBackground(true); QGridLayout *layout = new QGridLayout; layout-&gt;setContentsMargins(0, 0, 0, 0); layout-&gt;setSpacing(0); setLayout(layout); //default: show one single QLabel with the whole value as its content layout-&gt;addWidget(lblSingle); lblSingle-&gt;setAutoFillBackground(true); lblSingle-&gt;setCursor(Qt::ArrowCursor); setValue(QVariant()); } void QJsonView::setValue(QVariant value) { if(expanded) collapse(); v = value; lblSingle-&gt;setText(QString("&lt;span style=\"font-family: monospace; overflow: hidden\"&gt;%1&lt;/span&gt;") .arg(variantToHtml(v))); layout()-&gt;setContentsMargins(isExpandable() ? EXPANDABLE_MARGIN_LEFT : 0, 0, 0, 0); //show hand cursor if expandable Qt::CursorShape cursor; if(isExpandable()) cursor = Qt::PointingHandCursor; else cursor = Qt::ArrowCursor; setCursor(cursor); lblSingle-&gt;setCursor(cursor); update(); emit resized(); } void QJsonView::setJsonValue(QString json) { setValue(QJson::decode(json)); } void QJsonView::setHoverEffects(bool enabled) { hoverEffectsEnabled = enabled; if(!hoverEffectsEnabled) unhover(); } bool QJsonView::hoverEffects() { //if my parent is also a QJsonView, return its property QJsonView *p = qobject_cast&lt;QJsonView*&gt;(parentWidget()); if(p) return p-&gt;hoverEffects(); else return hoverEffectsEnabled; } QString QJsonView::variantToHtml(QVariant data) { if(data.type() == QVariant::String || data.type() == QVariant::ByteArray) return "&lt;span style=\"color: #006000\"&gt;\"" + Qt::escape(data.toString()) + "\"&lt;/span&gt;"; else if(data.type() == QVariant::Int || data.type() == QVariant::LongLong) return "&lt;span style=\"color: #800000\"&gt;" + Qt::escape(data.toString()) + "&lt;/span&gt;"; else if(data.type() == QVariant::Double) return "&lt;span style=\"color: #800080\"&gt;" + Qt::escape(data.toString()) + "&lt;/span&gt;"; else if(data.type() == QVariant::Bool || data.isNull() || !data.isValid()) { QString str = "null"; if(data.type() == QVariant::Bool) str = data.toBool() ? "true" : "false"; return "&lt;span style=\"color: #000080\"&gt;" + str + "&lt;/span&gt;"; } else if(data.type() == QVariant::List) { QString str = "&lt;span style=\"color: #606060\"&gt;&lt;b&gt;[&lt;/b&gt;&lt;/span&gt;"; bool first = true; foreach(QVariant e, data.toList()) { if(!first) str += "&lt;span style=\"color: #606060\"&gt;&lt;b&gt;, &lt;/b&gt;&lt;/span&gt;"; first = false; str += variantToHtml(e); } str += "&lt;span style=\"color: #606060\"&gt;&lt;b&gt;]&lt;/b&gt;&lt;/span&gt;"; return str; } else if(data.type() == QVariant::Map) { QString str = "&lt;span style=\"color: #606060\"&gt;&lt;b&gt;{&lt;/b&gt;&lt;/span&gt;"; QVariantMap map(data.toMap()); //special entry: "children" =&gt; tree view bool containsChildren = false; QVariant children; if(map.contains("children")) { children = map.take("children"); containsChildren = true; } //normal entries QVariantMap::iterator i; for(i = map.begin(); i != map.end(); ++i) { if(i != map.begin()) str += "&lt;span style=\"color: #606060\"&gt;&lt;b&gt;, &lt;/b&gt;&lt;/span&gt;"; str += Qt::escape(i.key()) + ": " + variantToHtml(i.value()); } //entry "children" if(containsChildren) { if(!map.isEmpty()) str += "&lt;span style=\"color: #606060\"&gt;&lt;b&gt;, &lt;/b&gt;&lt;/span&gt;"; str += "children: " + variantToHtml(children); } str += "&lt;span style=\"color: #606060\"&gt;&lt;b&gt;}&lt;/b&gt;&lt;/span&gt;"; return str; } else return data.toString(); } void QJsonView::paintEvent(QPaintEvent *) { QPainter p(this); // i designed the graphics using a pixel font size of 15, so this should be scalable now. qreal scale = fontMetrics().height() / 15.0; p.scale(scale, scale); int h = height() / scale; p.drawRect(2, 2, 10, 10); p.drawLine(5, 7, 9, 7); if(!expanded) p.drawLine(7, 5, 7, 9); if(expanded) { QColor color(96, 96, 96); if(v.type() == QVariant::List) { p.fillRect(16, 2, 4, 1, color); p.fillRect(16, 3, 2, h - 6, color); p.fillRect(16, h - 3, 4, 1, color); } else { int mid = h / 2; p.fillRect(18, 2, 4, 1, color); p.fillRect(17, 3, 2, mid - 4, color); p.fillRect(16, mid - 1, 3, 1, color); p.fillRect(15, mid , 3, 1, color); p.fillRect(16, mid + 1, 3, 1, color); p.fillRect(17, mid + 2, 2, h - mid - 5, color); p.fillRect(18, h - 3, 4, 1, color); } } } void QJsonView::mousePressEvent(QMouseEvent *e) { if(isExpandable() &amp;&amp; e-&gt;button() == Qt::LeftButton &amp;&amp; (!expanded || e-&gt;x() &lt; EXPANDED_MARGIN_LEFT)) { if(!expanded) expand(); else collapse(); } } void QJsonView::contextMenuEvent(QContextMenuEvent *e) { QMenu menu(this); //copy value to clipboard QAction *copy; if(v.type() == QVariant::List || v.type() == QVariant::Map) copy = menu.addAction(tr("Copy value (JSON encoded)")); else if(v.type() == QVariant::String || v.type() == QVariant::ByteArray) copy = menu.addAction(tr("Copy string value")); else copy = menu.addAction(tr("Copy value")); //execute menu QAction *triggeredAction = menu.exec(e-&gt;globalPos()); if(triggeredAction == copy) { QClipboard *clipboard = QApplication::clipboard(); if(v.type() == QVariant::List || v.type() == QVariant::Map || v.type() == QVariant::Bool || v.isNull() || !v.isValid()) clipboard-&gt;setText(QJson::encode(v, QJson::EncodeOptions(QJson::Compact | QJson::EncodeUnknownTypesAsNull))); else clipboard-&gt;setText(v.toString()); } } void QJsonView::enterEvent(QEvent *) { hover(); //if my parent is also a QJsonView, i inform it that i have been entered QJsonView *p = qobject_cast&lt;QJsonView*&gt;(parentWidget()); if(p) p-&gt;childEntered(); } void QJsonView::leaveEvent(QEvent *) { unhover(); //if my parent is also a QJsonView, i inform it that i have been leaved QJsonView *p = qobject_cast&lt;QJsonView*&gt;(parentWidget()); if(p) p-&gt;childLeaved(); } bool QJsonView::isExpandable() { return (v.type() == QVariant::List &amp;&amp; !v.toList().isEmpty()) || (v.type() == QVariant::Map &amp;&amp; !v.toMap().isEmpty()); } bool QJsonView::isExpanded() { return expanded; } void QJsonView::setExpanded(bool expanded) { if(expanded) expand(); else collapse(); } void QJsonView::expand() { if(isExpandable()) { lblSingle-&gt;setVisible(false); layout()-&gt;removeWidget(lblSingle); if(v.type() == QVariant::List) { foreach(QVariant e, v.toList()) { QJsonView *w = new QJsonView(this); w-&gt;setValue(e); layout()-&gt;addWidget(w); childWidgets &lt;&lt; w; //propagate signals to parent connect(w, SIGNAL(resized()), SIGNAL(resized())); } } else if(v.type() == QVariant::Map) { QVariantMap map(v.toMap()); //normal entries QVariantMap::iterator i; int index = 0; QSizePolicy sizePolicy(QSizePolicy::Expanding, QSizePolicy::Preferred); sizePolicy.setHorizontalStretch(0); sizePolicy.setVerticalStretch(0); for(i = map.begin(); i != map.end(); ++i) { QLabel *k = new QLabel(this); k-&gt;setText("&lt;span style=\"font-family: monospace\"&gt;" + Qt::escape(i.key()) + ": &lt;/span&gt;"); k-&gt;setAlignment(Qt::AlignTop | Qt::AlignLeft); k-&gt;setCursor(Qt::ArrowCursor); k-&gt;setAutoFillBackground(true); ((QGridLayout*)layout())-&gt;addWidget(k, index, 0); childWidgets &lt;&lt; k; QJsonView *w = new QJsonView(this); w-&gt;setValue(i.value()); ((QGridLayout*)layout())-&gt;addWidget(w, index, 1); w-&gt;setSizePolicy(sizePolicy); childWidgets &lt;&lt; w; //propagate signals to parent connect(w, SIGNAL(resized()), SIGNAL(resized())); index++; } } layout()-&gt;setContentsMargins(EXPANDED_MARGIN_LEFT, 0, 0, 0); expanded = true; update(); emit resized(); } } void QJsonView::collapse() { if(isExpandable()) { foreach(QWidget *w, childWidgets) { w-&gt;deleteLater(); layout()-&gt;removeWidget(w); } childWidgets.clear(); lblSingle-&gt;setVisible(true); layout()-&gt;addWidget(lblSingle); layout()-&gt;setContentsMargins(isExpandable() ? EXPANDABLE_MARGIN_LEFT : 0, 0, 0, 0); expanded = false; update(); emit resized(); } } void QJsonView::childEntered() { unhover(); } void QJsonView::childLeaved() { hover(); } void QJsonView::hover() { if(hoverEffects()) { QPalette pal = palette(); pal.setColor(backgroundRole(), Qt::white); setPalette(pal); } } void QJsonView::unhover() { setPalette(parentWidget()-&gt;palette()); } </code></pre>
[ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2015-01-23T21:10:24.080", "Id": "142129", "Score": "0", "body": "With Qt5 , QJson module are embedded inside the framework. I made a treemodel from Qt model view perspective. https://github.com/dridk/QJsonmodel" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2015-08-01T05:58:30.250", "Id": "180963", "Score": "0", "body": "JSON isn't a language :)" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2016-06-09T21:26:57.923", "Id": "245399", "Score": "1", "body": "What version to `c++` do you plan to use for your code?" } ]
[ { "body": "<p>I only see minor suggestions so far.</p>\n\n<pre><code>bool hoverEffects();\n</code></pre>\n\n<p>should be</p>\n\n<pre><code>bool hoverEffects() const;\n</code></pre>\n\n<p>and likewise for <code>isExpandable</code>, <code>isExpanded</code>.</p>\n\n<p>Depending on your version of C++, there is some syntactic sugar to simplify your map iterator in <code>variantToHtml</code>; do some reading about <code>auto</code>.</p>\n\n<p>Otherwise I don't see anything glaring.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2017-07-25T18:42:40.193", "Id": "171148", "ParentId": "11849", "Score": "2" } }, { "body": "<p>I see a few other minor things:</p>\n\n<p>This code:</p>\n\n<blockquote>\n<pre><code>if(data.type() == QVariant::String || data.type() == QVariant::ByteArray)\n return \"&lt;span style=\\\"color: #006000\\\"&gt;\\\"\" + Qt::escape(data.toString()) + \"\\\"&lt;/span&gt;\";\nelse if(data.type() == QVariant::Int || data.type() == QVariant::LongLong)\n return \"&lt;span style=\\\"color: #800000\\\"&gt;\" + Qt::escape(data.toString()) + \"&lt;/span&gt;\";\nelse if(data.type() == QVariant::Double)\n return \"&lt;span style=\\\"color: #800080\\\"&gt;\" + Qt::escape(data.toString()) + \"&lt;/span&gt;\";\nelse if(data.type() == QVariant::Bool || data.isNull() || !data.isValid())\n</code></pre>\n</blockquote>\n\n<p>should be a <code>switch(data.type())</code> making use of a <code>default:</code> section. (Split off <code>QVariant::Bool</code>; it's categorically different than null and invalid)</p>\n\n<p>However, this code has a lot of repetition. The only differences between the three THEN clauses is the color and whether or not they're quoted. They all start and end the same. Maybe use some string formatting with a string similar to <code>\"&lt;span style=\\\"color: %1\\\"&gt;%2%3%2&lt;/span&gt;\"</code></p>\n\n<blockquote>\n<pre><code>if(!first)\n ...\nfirst = false;\n</code></pre>\n</blockquote>\n\n<p>Try not to put conditionals inside the loop. This makes it harder for the processor to pipeline. Instead, go ahead and put the wrong info in as a suffix then delete or fix it up the final one after the loop closes. (change the <code>\", \"</code> to \"]\", easy since you know right where it is) Again this should use the format string from before to reduce the amount of duplicated data.</p>\n\n<blockquote>\n<pre><code>if(i != map.begin())\n</code></pre>\n</blockquote>\n\n<p>Same thing, add the string as a suffix then delete the extra one at the end.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2017-12-21T18:25:05.843", "Id": "183368", "ParentId": "11849", "Score": "2" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "3", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-05-17T19:30:20.293", "Id": "11849", "Score": "25", "Tags": [ "c++", "json", "gui", "qt" ], "Title": "QJsonView: A QWidget-based json explorer for Qt" }
11849
<p>This is a class that downloads files in a smart way: it tries to download from different sessions. This do speed up things. How can I Improve it?</p> <pre><code>import os import urllib2 import time import multiprocessing import string, random import socket from ctypes import c_int import dummy from useful_util import retry import config from logger import log "Smart Downloading Module." shared_bytes_var = multiprocessing.Value(c_int, 0) # a ctypes var that counts the bytes already downloaded @retry(socket.timeout, tries=2, delay=1, backoff=1, logger=log) def DownloadFile(url, path, startByte=0, endByte=None, ShowProgress=True): ''' Function downloads file. @param url: File url address. @param path: Destination file path. @param startByte: Start byte. @param endByte: End byte. Will work only if server supports HTTPRange headers. @param ShowProgress: If true, shows textual progress bar. @return path: Destination file path. ''' url = url.replace(' ', '%20') headers = {} if endByte is not None: headers['Range'] = 'bytes=%d-%d' % (startByte,endByte) req = urllib2.Request(url, headers=headers) try: urlObj = urllib2.urlopen(req, timeout=4) except urllib2.HTTPError, e: if "HTTP Error 416" in str(e): # HTTP 416 Error: Requested Range Not Satisfiable. Happens when we ask # for a range that is not available on the server. It will happen when # the server will try to send us a .html page that means something like # "you opened too many connections to our server". If this happens, we # will wait for the other threads to finish their connections and try again. log.warning("Thread didn't got the file it was expecting. Retrying...") time.sleep(5) return DownloadFile(url, path, startByte, endByte, ShowProgress) else: raise Exception("urllib2.HTTPError: %s" % e) f = open(path, 'wb') meta = urlObj.info() try: filesize = int(meta.getheaders("Content-Length")[0]) except IndexError: log.warning("Server did not send Content-Length.") ShowProgress=False filesize_dl = 0 block_sz = 8192 while True: try: buff = urlObj.read(block_sz) except socket.timeout, e: dummy.shared_bytes_var.value -= filesize_dl raise e if not buff: break filesize_dl += len(buff) try: dummy.shared_bytes_var.value += len(buff) except AttributeError: pass f.write(buff) if ShowProgress: status = r"%.2f MB / %.2f MB %s [%3.2f%%]" % (filesize_dl / 1024.0 / 1024.0, filesize / 1024.0 / 1024.0, ProgressBar(1.0*filesize_dl/filesize), filesize_dl * 100.0 / filesize) status += chr(8)*(len(status)+1) print status, if ShowProgress: print "\n" f.close() return path @retry(urllib2.URLError, tries=2, delay=1, backoff=1, logger=log) def DownloadFile_Parall(url, path=None, processes=config.DownloadFile_Parall_processes, minChunkFile=1024**2, nonBlocking=False): ''' Function downloads file parally. @param url: File url address. @param path: Destination file path. @param processes: Number of processes to use in the pool. @param minChunkFile: Minimum chunk file in bytes. @param nonBlocking: If true, returns (mapObj, pool). A list of file parts will be returned from the mapObj results, and the developer must join them himself. Developer also must close and join the pool. @return mapObj: Only if nonBlocking is True. A multiprocessing.pool.AsyncResult object. @return pool: Only if nonBlocking is True. A multiprocessing.pool object. ''' from HTTPQuery import Is_ServerSupportHTTPRange global shared_bytes_var shared_bytes_var.value = 0 url = url.replace(' ', '%20') if not path: path = r"%s\%s.TMP" % (config.temp_dir, "".join(random.choice(string.letters + string.digits) for i in range(16))) if not os.path.exists(os.path.dirname(path)): os.makedirs(os.path.dirname(path)) log.debug("Downloading to %s..." % path) urlObj = urllib2.urlopen(url) meta = urlObj.info() filesize = int(meta.getheaders("Content-Length")[0]) if filesize/processes &gt; minChunkFile and Is_ServerSupportHTTPRange(url): args = [] pos = 0 chunk = filesize/processes for i in range(processes): startByte = pos endByte = pos + chunk if endByte &gt; filesize-1: endByte = filesize-1 args.append([url, path+".%.3d" % i, startByte, endByte, False]) pos += chunk+1 else: args = [[url, path+".000", None, None, False]] log.debug("Running %d processes..." % processes) pool = multiprocessing.Pool(processes, initializer=_initProcess,initargs=(shared_bytes_var,)) mapObj = pool.map_async(_DownloadFile_ArgsList, args) if nonBlocking: return mapObj, pool while not mapObj.ready(): status = r"%.2f MB / %.2f MB %s [%3.2f%%]" % (shared_bytes_var.value / 1024.0 / 1024.0, filesize / 1024.0 / 1024.0, ProgressBar(1.0*shared_bytes_var.value/filesize), shared_bytes_var.value * 100.0 / filesize) status = status + chr(8)*(len(status)+1) print status, time.sleep(0.1) file_parts = mapObj.get() pool.terminate() pool.join() combine_files(file_parts, path) def combine_files(parts, path): ''' Function combines file parts. @param parts: List of file paths. @param path: Destination path. ''' with open(path,'wb') as output: for part in parts: with open(part,'rb') as f: output.writelines(f.readlines()) os.remove(part) def ProgressBar(progress, length=20): ''' Function creates a textual progress bar. @param progress: Float number between 0 and 1 describes the progress. @param length: The length of the progress bar in chars. Default is 20. ''' length -= 2 # The bracket are 2 chars long. return "[" + "#"*int(progress*length) + "-"*(length-int(progress*length)) + "]" def _DownloadFile_ArgsList(x): "Function gets args for DownloadFile as a list and executes it" return DownloadFile(*x) def _initProcess(x): dummy.shared_bytes_var = x </code></pre> <ul> <li><code>dummy</code> class is a blank file.</li> <li><code>from useful_util import retry</code> is this function: <a href="http://www.saltycrane.com/blog/2009/11/trying-out-retry-decorator-python/" rel="nofollow">http://www.saltycrane.com/blog/2009/11/trying-out-retry-decorator-python/</a></li> <li><code>config</code> has config about the project. config.DownloadFile_Parall_processes is 6.</li> <li><p>The <code>Is_ServerSupportHTTPRange</code> from <code>HTTPQuery</code> is:</p> <p>@retry(urllib2.URLError, tries=4, delay=3, backoff=2, logger=log) def Is_ServerSupportHTTPRange(url, timeout=config.Is_ServerSupportHTTPRange_timeout): " Function checks if a server allows HTTP Range " url = url.replace(' ', '%20')</p> <pre><code>fullsize = GetFileSize(url) headers = {'Range': 'bytes=0-4'} req = urllib2.Request(url, headers=headers) try: urlObj = urllib2.urlopen(req, timeout=timeout) except urllib2.HTTPError as e: log.error(e) return False except urllib2.URLError as e: log.error(e) return False meta = urlObj.info() filesize = int(meta.getheaders("Content-Length")[0]) return (filesize != fullsize) </code></pre></li> </ul> <p>Thanks!</p>
[]
[ { "body": "<pre><code> url = url.replace(' ', '%20')\n</code></pre>\n\n<p>has codesmell. You probably want to use the general-case URL encoding method here.</p>\n\n<pre><code> f = open(path, 'wb')\n</code></pre>\n\n<p>should probably be using the 'with' context manager to make sure the filehandle gets closed automatically in the case of exceptions or the like.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-05-21T14:06:03.543", "Id": "11944", "ParentId": "11850", "Score": "3" } } ]
{ "AcceptedAnswerId": "11944", "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-05-17T20:15:34.653", "Id": "11850", "Score": "2", "Tags": [ "python", "optimization" ], "Title": "How to improve this SmartDownloader?" }
11850
<p>I was looking to do this with <code>sizeof()</code> and I just gave up. As minimal as I can make it, I was wondering if there was a less crude way of doing the <code>const char *</code> as a convenience. I thought about doing this as a template, but I thought having another bit of generated code every time it is called seemed kinda dumb for me.</p> <pre><code>#include "misc.hh" namespace mlcppl { int cpl(char * c) { char ct; int i = 0; while (ct = *(c+i)) { if (ct == '\0') { break; } else { i++; } } return i; } int cpl(const char * c) { char * ct = (char*) c; return cpl(ct); } } </code></pre>
[]
[ { "body": "<p>What about:</p>\n\n<pre><code>std::cout &lt;&lt; ::strlen(\"Plop Poop\") &lt;&lt; \"\\n\";\n</code></pre>\n\n<p>While we are at it:</p>\n\n<pre><code>// use std::size_t to represent a size of something in memory\n// It is non negative and is explicitly designed so it can represent\n// the biggest in memory object.\n//\n// Pass C-String as 'char const*' (or const char* (samething))\n// The compiler will automatically add a const to objects if required.\n// BUT it will never remove a const (apart from 1 special case see below).\n// Also the type of a string literal is 'char const*` (for the language lawyers yes it is an array but not relevant here as by the time we will see it is a pointer).\n//\n// Also, because you don't want to mutate the underlying string it gives\n// you some slight protection from accidental assignment into the string.\nstd::size_t martinStringLen(char const* start)\n{\n char const* end = start;\n\n // Look for the end of the string.\n // Your code increments two objects. I would just increment a single object\n // looking for the end of the string.\n for(;*end;++end){/*Empty*/}\n\n // The size is then just subtraction.\n return end - start;\n}\n\n// Unfortunately the special case is string literals: which is allowed to decay\n// to char* for compatibility with old C code.\n</code></pre>\n\n<p>Other notes on your code:</p>\n\n<pre><code>int cpl(char * c) // does work\nint cpl(const char * c) // converts to char* so it can do work.\n</code></pre>\n\n<p>You have these two the wrong way around.<br>\nMake the <code>int cpl(const char * c)</code> version do the work. As noted above you are not mutating the object so it provides some slight protection from simple mistakes.</p>\n\n<p>Also you will find the <code>int cpl(char * c)</code> version becomes unnecessary. As the compiler will automatically add const (ness) to parameters for you so you don't actually need the this version.</p>\n\n<p>Other comments are same as @Konrad Rudolph</p>\n\n<p>Note on the use of const.</p>\n\n<p>If you put const on the right or left is a style thing. Peronally I always put it on the right. As there are a couple of corner cases (with typedef) were it does make a difference and I want to be consistent.</p>\n\n<p>Note: cost always binds to the type on its <code>left</code>. unless it is the left-most part of a type declaration then it binds right. Read type right to left.</p>\n\n<pre><code>char const* str1; // const binds left to char =&gt; (char const)*\n // Read as: pointer to 'const char'\n\nchar const *const str2; // const binds left =&gt; (char const) (* const)\n // Read as: 'const pointer' to 'const char'\n\n// From the C world (and it has leaked into C++) so a lot of people still us it\nconst char* str3; // const as left-most part binds right =&gt; (const char) *\n // Read as: pointer to 'char const'\n</code></pre>\n\n<p>Basically str1 and str3 are identical. But the consistency of always thinking that const binds to the left makes it neater in my mind.</p>\n\n<p>One place where it can make a difference is typedefs. This is because the typedef has already formed a type so any external const are applied to the typedef type as a whole thing (not as individual parts).</p>\n\n<pre><code>typedef char* String;\nconst String str4; // const is the left-most item so binds right.\n // So you may expect this to be the same as str3\n\n // unfortunately this is not correct as the typedef\n // String a whole type so the const applies to `String`\n // not to the char.\n\n // Thus this is like const (char*)\n // Which is the same as (char*) const\n // Read: const 'pointer to char' so once set the pointer\n // can not be moved.\n // If on the other hand you never put const in the left-most position then\n // this problem never even comes up.\n</code></pre>\n\n<p>So two reasons not to put const as the left-most part of the type.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-05-18T03:44:08.933", "Id": "19033", "Score": "1", "body": "I now i could use strlen, god knows wjat else goes into that function, and i wanted to try my hand at it myself" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-05-18T04:51:55.377", "Id": "19042", "Score": "1", "body": "@alexhairyman Wait, what are you up to? Are you doing an academic assignment writing `strlen` from scratch? If yes, look into Keith's answer and understand the principles behind it, because your original posted code looks very un-C (and un-C++, for that matter). If, on the other hand, you're doing production work, then you **should** use stock `strlen` unless you have a very, very solid argument against doing that. Otherwise, it's a dangerous case of Not Invented Here (http://en.wikipedia.org/wiki/Not_invented_here)." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-05-18T17:57:41.220", "Id": "19085", "Score": "0", "body": "I dunno, I have just a little project I am using to learn c++ features @ [mlcppl](https://github.com/alexhairyman/mlcppl) Don't make fun of me bros!" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-05-18T18:14:47.953", "Id": "19088", "Score": "0", "body": "Okay, I get the first example using the for, but I don't think it is as staightforward as counting, although it is another way. Upvote for you too!" } ], "meta_data": { "CommentCount": "4", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-05-18T03:24:17.757", "Id": "11856", "ParentId": "11853", "Score": "9" } }, { "body": "<p><code>std::strlen</code> will give you the length a zero-terminated string, like Loki said. If you want to know how it’s implemented, just look up its implementation.</p>\n\n<p>And Keith has given a short, albeit slightly cryptic, implementation.</p>\n\n<p>But since this is <em>Code Review</em>, let’s go over your code, shall we. We’ll start at the end.</p>\n\n<pre><code>int cpl(const char * c)\n{\n char * ct = (char*) c;\n return cpl(ct);\n}\n</code></pre>\n\n<p>Two things to note:</p>\n\n<ol>\n<li>Don’t use C-style casts, they hide bugs and are generally strongly discouraged; use C++ casts instead – <code>const_cast</code> in this case.</li>\n<li>Don’t use <code>const_cast</code> unless you really have to, it’s also quite dangerous. In particular, it can easily lead to undefined behaviour. And it’s unnecessary in your case: your code will never actually modify the string so why un-<code>const</code> it?</li>\n</ol>\n\n<p>In fact, your non-<code>const</code> variant of the function is unnecessary since there’s an implicit conversion from <code>char*</code> to <code>char const*</code>.</p>\n\n<p>Next, what does “<code>cpl</code>” actually stand for? I have no idea. Use a meaningful name and avoid abbreviations in general.</p>\n\n<p>Now to the main function. I’ll note right at the start that <code>c</code> is a bad name for the argument. Single-letter names are sometimes OK but <code>c</code> suggests that the type of the variable is actually <code>char</code>. If you insist on a single-letter identifier, use <code>s</code> for “string”.</p>\n\n<p>The return type and the loop variable in your code are <code>int</code> but they will never be negative. C++ provides a type for this – <code>unsigned int</code> – which is more suitable here.</p>\n\n<p>Next,</p>\n\n<pre><code>while (ct = *(c+i))\n</code></pre>\n\n<p>This is cryptic. First off, why do you write <code>*(c+1)</code> instead of <code>c[i]</code>? Secondly, while C++ allows assignments inside expressions, and some developers encourage this, it should still be used sparingly. You don’t really need the variable <code>ct</code> here anyway. It certainly doesn’t help readability (especially not with the once again cryptic name).</p>\n\n<p>Thirdly, C++ is once again forgiving and lets you test a character value for “truthiness”. But just because C++ understands this doesn’t make it understandable. I’d argue that testing a char for truthiness is a nonsensical operation. Use an explicit comparison instead, this is more readable.</p>\n\n<p>The body of the loop contains nothing as much as redundancy. (I’ll note in passing that even with the <code>if</code> in it, this could be <em>two lines</em> instead of <em>eight</em>, and would be more readable).</p>\n\n<p>The <code>if</code> is totally redundant. You are testing <strong>the same</strong> condition as in the loop head, and the condition inside the loop will <em>never</em> be true. You probably missed that because, as I noted above, the loop head is cryptic.</p>\n\n<p>Finally, it’s convention in C++ to use prefix-<code>++</code> instead of postfix unless necessary. The reason for this is that the prefix operation is <em>sometimes faster, and never slower</em>, than the postfix operation. Now, this is irrelevant in your case since you are incrementing an integer but it may play a role for user-defined types.</p>\n\n<p>Your whole code can be condensed to this simple, readable code:</p>\n\n<pre><code>unsigned int length(char const* s) {\n unsigned int i = 0;\n while (s[i] != '\\0')\n ++i;\n\n return i;\n}\n</code></pre>\n\n<p>Some people would instead write it as follows; the result is more or less indistinguishable:</p>\n\n<pre><code>unsigned int length(char const* s) {\n unsigned int i = 0;\n while (*s++ != '\\0')\n ++i;\n\n return i;\n}\n</code></pre>\n\n<p>(And note that here, we <em>do</em> need postfix increment.)</p>\n\n<p>Finally, here’s a recursive implementation, just to get a one-liner:</p>\n\n<pre><code>unsigned int length(char const* s) {\n return *s == '\\0' ? 0 : 1 + length(s + 1);\n}\n</code></pre>\n\n<p>Note that although this is recursive, and not even tail recursive, modern compilers will very likely recognise this and produce efficient code that doesn’t overflow the stack for long strings (tested on GCC 4.7 with <code>-O2</code>, works; but doesn’t without optimisations – not surprisingly).</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-05-18T18:12:01.593", "Id": "19087", "Score": "0", "body": "I thought, why not *(c+i)? I can see how that behavior works, it simply gives the value pointed to c with an offset of +i. I don't know much about memory allocation in c++\\" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-12-29T21:07:30.807", "Id": "136646", "Score": "0", "body": "maybe another comment to the terseness of `while (ct = *(c+i))` would be to focus on making the code readable and let the compiler worry about the optimization." } ], "meta_data": { "CommentCount": "2", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-05-18T09:53:41.547", "Id": "11863", "ParentId": "11853", "Score": "5" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-05-18T02:32:52.797", "Id": "11853", "Score": "3", "Tags": [ "c++", "strings" ], "Title": "Determining length of a char* string in C++" }
11853
<p>I currently have a selection sorting algorithm, but need some help turning it into a insertion sort, I understand a insertion sort if faster? The hand array is full, and it needs to sort from lowest to highest rank. </p> <pre><code>private void sort(PlayingCard[] hand) { PlayingCard temp; for(int i = 0; i &lt; hand.length ; i++) { for(int j = i+1; j &lt; hand.length ; j++) { int compareRank = hand[j].getRank().compareTo(hand[i].getRank()); if(compareRank &lt; 0){ temp = hand[i]; hand[i] = hand[j]; hand[j] = temp; } } } } </code></pre>
[ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-05-18T10:37:39.587", "Id": "19045", "Score": "5", "body": "While it’s true that insertion sort is generally faster, both algorithms are inefficient except on almost-sorted or very small input. I’d therefore like to ask what your use-case is. Maybe another algorithm would be altogether more appropriate. Furthermore, are you aware that Java provides an extremely efficient [`Arrays.sort`](http://docs.oracle.com/javase/6/docs/api/java/util/Arrays.html#sort%28T[],%20java.util.Comparator%29) implementation?" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-05-18T14:46:15.173", "Id": "19062", "Score": "1", "body": "I am sorting a poker hand from smallest rank to largest, and if the deck is < 5 then inserting a new card, and sorting as needed. I am aware of a few sorting implementation but this is for a class project, and we are not allowed to use any of them." } ]
[ { "body": "<p>Here is a sort that I put together after some research:</p>\n\n<pre><code>private void sort(PlayingCard[] hand)\n{\n int i, j;\n PlayingCard temp; \n for (i = 1; i &lt; hand.length; i++) {\n temp = hand[i];\n j = i;\n while (j &gt; 0 &amp;&amp; hand[j - 1].getRank().compareTo(temp.getRank()) &gt; 0) {\n hand[j] = hand[j - 1];\n j--;\n } \n hand[j] = temp;\n }\n}\n</code></pre>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-05-18T12:49:11.183", "Id": "11873", "ParentId": "11855", "Score": "1" } }, { "body": "<p>So there are a few ways of making this into an insertion sort. One way would be similar to the following code (which is adapted from the pseudo code on wikipedia):</p>\n\n<pre><code>//insert each item into the sorted part of the list\nfor(int i = 1; i&lt;hand.length(); i++){\n //make sure to save a temporary\n PlayingCard card = hand[i];\n int j = i;\n //now we search through the already sorted part \n //of the list looking for insertion point\n while(j &gt; 0 &amp;&amp; hand[j-1].getRank().compareTo(card.getRank()) &lt; 0){ //make sure comparator is correct\n //we know item is less than hand[j-1]. so we need to move it to hand[j] \n hand[j] = hand[j-1];\n j -= 1;\n }\n //now we insert j\n hand[j] = card;\n}\n</code></pre>\n\n<p>Now this is not the most efficient way of implementing an insertion sort, but rather one of the simplest. I will let you ponder on ways to improve this. One thing to think about is how to more quickly find the insertion point. As in we can use a binary search to find the insertion point (meaning less comparisons are taking place). Other items that can be done, though this is much more difficult, is to regulate the amount of swaps (probably beyond your course). Work with this code and the data structures to see what you come up with. Good luck!</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-05-19T16:48:50.973", "Id": "19106", "Score": "0", "body": "I figured out how to change the order of the sort and also made some adjustments to simplify the code a bit. Let me know what you think:" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-05-19T23:38:07.440", "Id": "19119", "Score": "0", "body": "Yes that code is an insertion sort. Good work." } ], "meta_data": { "CommentCount": "2", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-05-19T04:43:06.167", "Id": "11892", "ParentId": "11855", "Score": "1" } }, { "body": "<p>There are only 120 possible permutations of five items; if one starts by ordering items 1 and 2, and items 3 and 4, that will leave 30 permutations, which can then be sorted using five more comparisons. If you're worried about speed, use explicit operations on the five items rather than using loops.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-10-17T23:38:17.247", "Id": "17657", "ParentId": "11855", "Score": "1" } }, { "body": "<p>Two small notes about the original code:</p>\n\n<ol>\n<li><p>About the <code>temp</code> variable: try to minimize the scope of local variables. It's not necessary to declare them at the beginning of the method, declare them where they are first used. (<em>Effective Java, Second Edition, Item 45: Minimize the scope of local variables</em>)</p></li>\n<li><p>Furthermore, </p>\n\n<pre><code>temp = hand[i];\nhand[i] = hand[j];\nhand[j] = temp;\n</code></pre>\n\n<p>could be extracted out to a <code>swap</code> method:</p>\n\n<pre><code>public void swap(final PlayingCard[] arr, final int pos1, final int pos2) {\n final PlayingCard temp = arr[pos1];\n arr[pos1] = arr[pos2];\n arr[pos2] = temp;\n}\n</code></pre></li>\n</ol>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-10-18T00:17:59.133", "Id": "17658", "ParentId": "11855", "Score": "1" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "2", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-05-18T03:18:54.337", "Id": "11855", "Score": "1", "Tags": [ "java", "homework", "sorting" ], "Title": "Insertion vs Selection" }
11855
<p>These are the steps to determine coordinates of the 4 points (P1, P2, P3, P4) that make up a tangential trapezoid connecting to circles. Another way of looking at it is to think of the tangential segments of being the parts of a belt that would not be wrapped around the pulleys. The math should work regardless of the orientation of the two circles in coordinate space.</p> <p><img src="https://i.stack.imgur.com/EqdpH.png" alt="diagram of shapes and points"></p> <p>Code (usage @ bottom):</p> <pre><code>internal class TrapezoidBuilder { private const double RadiansToDegrees = 180/Math.PI; private readonly double _bufferDistanceC0; private readonly double _bufferDistanceC1; private readonly Point _pointC0; private readonly Point _pointC1; public TrapezoidPoints TrapezoidPoints; public TrapezoidBuilder(Point pointC0, Point pointC1, double bufferDistanceC0, double bufferDistanceC1) { _pointC0 = pointC0; _pointC1 = pointC1; _bufferDistanceC0 = bufferDistanceC0; _bufferDistanceC1 = bufferDistanceC1; TrapezoidPoints = new TrapezoidPoints(); CalculateTrapezoidPoints(); } public void CalculateTrapezoidPoints() { // Get the angle of the line C0-C1 in degrees. This will be used in conjunction with angleA to determine the vector of these points double angleRelativeToPositiveXAxis = CalculateAngleRelativeToXAxis(_pointC0, _pointC1); // Get angleA double angleA = CalculateAngleA(_pointC0, _pointC1, _bufferDistanceC0, _bufferDistanceC1); //// Calculate P1 and P2 coordinates first double positiveAngle = angleRelativeToPositiveXAxis + angleA; double cosPositiveAngle = Math.Cos(positiveAngle/RadiansToDegrees); double valueToAddToC0X = cosPositiveAngle*_bufferDistanceC0; // Set P1's X coordinate TrapezoidPoints.P1.X = _pointC0.X + valueToAddToC0X; double valueToAddToC1X = cosPositiveAngle*_bufferDistanceC1; // Set P2's X coordinate TrapezoidPoints.P2.X = _pointC1.X + valueToAddToC1X; double sinPositiveAngle = Math.Sin(positiveAngle/RadiansToDegrees); double valueToAddToC0Y = sinPositiveAngle*_bufferDistanceC0; // Set P1's Y coordinate TrapezoidPoints.P1.Y = _pointC0.Y + valueToAddToC0Y; double valueToAddToC1Y = sinPositiveAngle*_bufferDistanceC1; // Set P2's Y coordinate TrapezoidPoints.P2.Y = _pointC1.Y + valueToAddToC1Y; //// Calculate P3 and P4 coordinates double negativeAngle = angleRelativeToPositiveXAxis - angleA; double cosNegativeAngle = Math.Cos(negativeAngle/RadiansToDegrees); valueToAddToC0X = cosNegativeAngle*_bufferDistanceC0; // Set P4's X coordinate TrapezoidPoints.P4.X = _pointC0.X + valueToAddToC0X; valueToAddToC1X = cosNegativeAngle*_bufferDistanceC1; // Set P3's X coordinate TrapezoidPoints.P3.X = _pointC1.X + valueToAddToC1X; double sinNegativeAngle = Math.Sin(negativeAngle/RadiansToDegrees); valueToAddToC0Y = sinNegativeAngle*_bufferDistanceC0; // Set P4's Y coordinate TrapezoidPoints.P4.Y = _pointC0.Y + valueToAddToC0Y; valueToAddToC1Y = sinNegativeAngle*_bufferDistanceC1; // Set P3's Y coordinate TrapezoidPoints.P3.Y = _pointC1.Y + valueToAddToC1Y; Debug.WriteLine("C0 " + _pointC0.X + " " + _pointC0.Y); Debug.WriteLine("C1 " + _pointC1.X + " " + _pointC1.Y); Debug.WriteLine("P1 " + TrapezoidPoints.P1.X + " " + TrapezoidPoints.P1.Y); Debug.WriteLine("P2 " + TrapezoidPoints.P2.X + " " + TrapezoidPoints.P2.Y); Debug.WriteLine("P3 " + TrapezoidPoints.P3.X + " " + TrapezoidPoints.P3.Y); Debug.WriteLine("P4 " + TrapezoidPoints.P4.X + " " + TrapezoidPoints.P4.Y); } private double CalculateAngleA(Point pointC0, Point pointC1, double radius0, double radius1) { double xDistance = pointC1.X - pointC0.X; double yDistance = pointC1.Y - pointC0.Y; double distance = Math.Sqrt((xDistance*xDistance) + (yDistance*yDistance)); double radius2 = radius0 - radius1; double cosA = radius2/distance; double angleAInRadians = Math.Acos(cosA); double angleAInDegrees = angleAInRadians*RadiansToDegrees; return angleAInDegrees; } private double CalculateAngleRelativeToXAxis(Point point0, Point point1) { try { // In order to use ATAN2, point C1 has to be considered as the origin, i.e. 0, 0. // So C1x is subtracted from C2x and C1y from C2y. Note that it’s important to subtract // the 1st value from the 2nd to help determine which quadrant the angle is in. double x = point1.X - point0.X; double y = point1.Y - point0.Y; // Get the angle in radians double angleInRadians = Math.Atan2(x, y); // Convert to degrees double angleInDegrees = angleInRadians*RadiansToDegrees; // Subtract from 90 to get the angle relative to the positive X-axis double relativeAngleInDegrees = 90 - angleInDegrees; // Return result return relativeAngleInDegrees; } catch (Exception err) { Debug.WriteLine(err.Message); } // If no result, return zero return 0; } } internal class TrapezoidPoints { public Point P1; public Point P2; public Point P3; public Point P4; } // Usage Point C1 = new Point(5,7); Point C2 = new Point(6.516, 7.875); double buffer0 = 1; double buffer1 = .375; var trapezoidBuilder = new TrapezoidBuilder(C1, C2, buffer0, buffer1); </code></pre>
[ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-05-18T10:59:52.807", "Id": "19047", "Score": "0", "body": "Great question but [pseudo code is off-topic](http://codereview.stackexchange.com/faq#im-confused-what-questions-are-on-topic-for-this-site)" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-05-18T13:06:10.913", "Id": "19057", "Score": "1", "body": "With all due respect (and I should have read the rules first), this policy isn't helpful. While I'm capable of posting actual code, it will become very specific (harder to wade through), will not provide a concrete example and would result in wasted effort if my general approach is wrong." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-05-18T13:23:33.770", "Id": "19058", "Score": "0", "body": "I'm just a member, but pseudo code has one huge disadvantage - you can't check if the code actually works or run it to ensure the changes you proposed would actually work." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-05-18T14:58:00.570", "Id": "19065", "Score": "0", "body": "That's a good point." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-05-18T17:32:48.317", "Id": "19084", "Score": "0", "body": "I've updated this post with code. So far, as much as I've been able to test it, it's doing what I want. I've been able to switch the circle sizes or make them the same and get the desired results." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-05-18T20:27:29.903", "Id": "19092", "Score": "1", "body": "This problem is perfect for F#. I would start out by writing out the formulas in LaTeX." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-05-20T01:06:32.387", "Id": "19122", "Score": "0", "body": "@Leonid Hmm. May have to take a look @ F#...always good to learn another language...just gotta find time." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-05-20T01:09:50.707", "Id": "19123", "Score": "0", "body": "One thing I caught in real world testing is that the distance between the circle centers has to be greater than the radius of the smaller circle. Otherwise, an error is thrown because the COS is outside the limits of -1 to 1. Also, the operation would be unnecessary anyway because one circle would be completely inside the other." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-05-20T04:33:29.390", "Id": "19125", "Score": "0", "body": "I have a suspicion that the math could be simpler..." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-05-30T17:06:58.217", "Id": "19488", "Score": "0", "body": "You are using lots of unnecessary comments. Comment should explain why not what?" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-07-11T16:12:30.303", "Id": "21943", "Score": "1", "body": "Uhm, what's the question being asked here?" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-07-13T08:42:42.993", "Id": "22052", "Score": "0", "body": "As @miniBill asked, can you clarify what problem exactly you are having? Is the code not working properly? Are you seeking to shorten it? Refactor? Optimize for performance? Did you manage to solve it in the end?" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-08-30T15:40:51.013", "Id": "24676", "Score": "0", "body": "@Stonetip, which software/script did you use to draw these pictures?" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-05-22T19:21:06.027", "Id": "41033", "Score": "0", "body": "@Leonid I drew the picture in Adobe Illustrator." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-05-22T19:22:36.330", "Id": "41035", "Score": "0", "body": "Just revisiting this and have to say thanks for comments and answer from Ron. When I have time, I'll try to refactor. I'll also make sure to be clearer on what I'm asking next time. In this case, just hoping for a general review." } ]
[ { "body": "<ol>\n<li>It's not clear to me what are <code>buffer0</code> and <code>buffer1</code>? If these represent the radius values (like C1-P1 line for <code>buffer1</code>), then perhaps <code>radius0</code> (and <code>radius1</code>) would be a better name here.</li>\n<li>I'd create and use a data class for each point-radius pair. Say, <code>InputPoint</code> class with <code>Point</code> and <code>Radius</code> or something similar.</li>\n<li>I'd separate constructor and results. The results are calculations that should not be part of the constructor. Take, for example, the class named <a href=\"http://msdn.microsoft.com/en-us/library/system.uribuilder.aspx\" rel=\"nofollow\"><code>UriBuilder</code></a> in .NET: you can construct it, change the inputs, and only when you call the property named <code>Uri</code> - you get the calculated uri. The same should apply here, too. Constructing a class gives us an instance with a valid state. Calculations - in their own methods or property-getters (that are practically methods, by the way). So <code>TrapezoidPoints</code> should be the returned type of a <code>GetTrapezoid</code> method (or maybe <code>TryGetTrapezoid</code> if this pattern apply here), and not part of the class' state.</li>\n</ol>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-10-09T23:47:23.433", "Id": "16380", "ParentId": "11858", "Score": "2" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "15", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-05-18T05:41:40.023", "Id": "11858", "Score": "8", "Tags": [ "c#", "computational-geometry" ], "Title": "C# code to derive tangential points between two circles to create a trapezoid" }
11858
<p>I have a function named <code>InserUpdateRecords(int flag)</code> to which I pass integer variable which indicates the type of operation it has to perform , if <code>flag==1</code> then insert , if <code>flag==2</code> then update. Here is my code:</p> <pre><code>public void InsertUpdateRecords(int flag) { Data_Customer_Log customer_log=new Data_Customer_Log(); try { if(flag==2) { customer_log = (from cust in dt.Data_Customer_Logs where cust.cApplicationNo == Request.QueryString["ApplicationNO"] select cust).SingleOrDefault(); } customer_log.cCustomerType = NewCustomerddlCustomerType.Text; customer_log.cBranchName = NewCustomerddlBranchName.Text; customer_log.nBranchNo = Convert.ToDecimal(Global.gBranchNo); . . . . } catch{} } </code></pre> <p>So when I create <code>Data_Customer_Log customer_log=new Data_Customer_Log();</code> and then depending on the value of flag I use it , is it an appropriate approach, what are the possible downsides to my approach.</p>
[ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-05-18T10:58:32.190", "Id": "19046", "Score": "0", "body": "Using `catch{}` is a terrible idea. You should only catch exceptions that you know about." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-05-18T11:04:32.153", "Id": "19049", "Score": "0", "body": "@svick could you elaborate a bit more thanks" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-05-18T13:26:15.310", "Id": "19059", "Score": "1", "body": "Like I said, you should only catch specific exceptions that you know about. If an unknown exception is thrown, your `catch` is just hiding a bug. And most of the time, operation shouldn't silently fail. If I call `InsertUpdateRecords()` and it returns successfully, I will expect that it succeeded. You should only catch an exception is you know what to do with it." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-05-18T13:57:07.963", "Id": "19061", "Score": "2", "body": "`int flag` is a bad data type to use and a bad parameter name. Consider creating an `enum` called something like `Operation` with `Insert` and `Update` as enumeration sub-values. Make that the parameter type to your method." } ]
[ { "body": "<p>I would probably pass in the customer log as a parameter to the method and then have it deal with just the database insertion. If you wanted to keep a InsertOrUpdate type of approach I would branch on perhaps something like the object ID if it has one. This way you can have a variety of ways that your object is created and the method is only responsible for the persistance of that object not also it's creation and populating.</p>\n\n<p>A couple of problems I see in your approach:</p>\n\n<ol>\n<li>The method is doing too many things. It's responsible for querying for your record, instantiating the record and populating as well as performing the persistance.</li>\n<li>The method has too many dependencies. It looks like you have made it subject to both an external UI component in the .Text objects as well as the database layer. What happens if you had multiple ways of populating the object. You would have to duplicate this method?</li>\n</ol>\n\n<p>Something like this (without knowing a bit more of your setup):</p>\n\n<pre><code>// a method higher up the chain\nvoid CreateCustomerLog()\n{\n Data_Customer_Log record = new Data_Customer_Log();\n record.cCustomerType = NewCustomerddlCustomerType.Text;\n record.cBranchName = NewCustomerddlBranchName.Text;\n record.nBranchNo = Convert.ToDecimal(Global.gBranchNo);\n\n InsertOrUpdate(record);\n}\n\nvoid UpdateCustomerLog(string applicationNo)\n{\n Data_Customer_Log record = GetCustomerLog(applicationNo);\n\n if(record == null)\n {\n // handle record not existing here or filter it up the chain\n }\n else\n {\n InsertOrUpdate(record);\n }\n}\n\nData_Customer_Log GetCustomerLog(string applicationNo)\n{\n return (from cust in\n dt.Data_Customer_Logs\n where cust.cApplicationNo.Equals(applicationNo)\n select cust).SingleOrDefault(); \n}\n\nData_Customer_Log InsertOrUpdate(Data_Customer_Log record)\n{\n if(record.ID &gt; 0)\n { \n return Insert(record);\n }\n else \n {\n return Update(record);\n }\n}\n\nData_Customer_Log Insert(Data_Customer_Log record)\n{\n // TODO: perform insertion and throw exception if there is a problem\n}\n\nData_Customer_Log Update(Data_Customer_Log record)\n{\n // TODO: perform update and throw exception if there is a problem\n}\n</code></pre>\n\n<p>I would probably point out that these methods would probably be in different classes. For example the Update, Insert and/or Get might be in some sort of repository class. The CreateCustomerLog and UpdateCustomerLog might be at the higher level, maybe your UI level as it interacts directly with the UI elements.</p>\n\n<p>Just my thoughts.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-05-18T09:14:03.817", "Id": "19043", "Score": "0", "body": "thanks a lot , you mean to say that I should insert and update records in different function and only pass the type of object which would let it know if it is insert or update , I could no understand your use of InserOrUpdate() , could you explain." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-05-18T09:25:53.290", "Id": "19044", "Score": "0", "body": "in Insert and Update methods should I only do dt.insertOnSubmit() and dt.SubmitChanges() respectively ." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-05-18T20:39:13.623", "Id": "19093", "Score": "0", "body": "@freebird yes, that was what i was trying to get at" } ], "meta_data": { "CommentCount": "3", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-05-18T09:07:00.927", "Id": "11861", "ParentId": "11859", "Score": "3" } }, { "body": "<pre><code>// Add/Update or CustomerLog for the given Application number.\npublic bool StoreCustomerLog(string applicationNO)\n{\n bool result = false;\n\n using(CustomerEntities context = new CustomerEntities())\n {\n\n // See if our record is already there.\n Data_Customer_Log record = (from row in context.Data_Customer_Logs\n where row.cApplicationNo == applicationNO\n select row).FirstOrDefault();\n\n // If we didn't get a record back, it's an insert\n bool isNew = (record == null);\n\n if(isNew)\n {\n // Create an instance of the entity\n record = context.Data_Customer.CreateObject();\n\n // Add any other fields that are created on insert only.\n }\n\n // Fields that are set on insert and updates ...\n\n // -- FYI: I wouldn't do this directly, but pass these values\n // ------- as parameters so they could be validated prior to \n // ------- storing in the database to avoid insert/update exceptions.\n record.cCustomerType = NewCustomerddlCustomerType.Text;\n record.cBranchName = NewCustomerddlBranchName.Text;\n\n // Other fields ...\n\n // If it's new, we add it to the entity collection\n if(isNew) { context.Data_Customer.AddObject(record); }\n\n // If we affected a row, then we were successful!\n result = (context.SaveChanges() &gt; 0);\n }\n\n return result;\n}\n</code></pre>\n\n<p>That's how I'd do it.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-05-23T05:19:11.440", "Id": "19223", "Score": "0", "body": "thanks for the idea , but I am no very clear how would I go about this , may be I have not posted the entire code , should I post full code so that you could help me better." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-05-29T15:00:30.443", "Id": "19417", "Score": "0", "body": "Yep - that would help." } ], "meta_data": { "CommentCount": "2", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-05-22T16:08:12.237", "Id": "11976", "ParentId": "11859", "Score": "0" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "4", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-05-18T06:57:23.670", "Id": "11859", "Score": "3", "Tags": [ "c#", "linq" ], "Title": "Inserting and updating record using LINQ by calling a common function" }
11859
<p>I'm very new to C++ and would like you all to review the source code I wrote for a program that calculates the user's BMI and loops the program back to the start if the user needs to do additional calculations.</p> <pre><code>#include &lt;iostream&gt; #include &lt;stdlib.h&gt; using namespace std; float bmiNumber(float pounds, float inches) //BMI calculation { return ((pounds/inches)*703); } void chart(int mF) { if(mF==2) { cout&lt;&lt;"\nHere is some info you might find useful...\n" &lt;&lt;"At the same BMI, women tend to have more body fat than men."&lt;&lt;endl &lt;&lt;"From cdc.gov\n"&lt;&lt;endl; } } void history() { cout&lt;&lt;"Version History"&lt;&lt;endl; cout&lt;&lt;"\tVersion 1.0.1(05/18/2012)"&lt;&lt;endl &lt;&lt;"Optimized source code for better program flow,\nImproved calculation algorithms,\n" &lt;&lt;"Introduded looping capabilities for\nmultiple calculations without restarting the program."&lt;&lt;endl; cout&lt;&lt;"\tVersion 1.0.0(05/15/2012)"&lt;&lt;endl &lt;&lt;"Creation of the program, very rough outline of the basic structure."&lt;&lt;endl; system ("pause"); } int main() { int changes; int m; m=1; cout&lt;&lt;"Hello and welcome to the BMI Calculation Tool 1.0.1, or BMICT1.0.1 for short."&lt;&lt;endl; cout&lt;&lt;"If you would like to see the changes from the previous version(1.0.0)\nplease press 3..."&lt;&lt;endl; cout&lt;&lt;"If not press any other key."; cin&gt;&gt;changes; if(changes==3) { history(); } cout&lt;&lt;endl&lt;&lt;endl&lt;&lt;endl; cout&lt;&lt;"Why don't you first tell me a little bit about yourself,\nby answering just one simple question."&lt;&lt;endl; cout&lt;&lt;"Are you a man or a woman?"; while(m==1) { cout&lt;&lt;"If you are a man, please press 1,\nif you are a woman, please press 2."&lt;&lt;endl; cout&lt;&lt;"Please make your selection now..."&lt;&lt;endl; cin&gt;&gt;m; if(m==1) { cout&lt;&lt;"Our sources have indicated that you are in fact a man,\n" &lt;&lt;"please check to confirm this and continue with the program"&lt;&lt;endl; } else if(m==2) { cout&lt;&lt;"Our sources have indicated that you are a woman,\n" &lt;&lt;"if this is true please continue with the program"&lt;&lt;endl; } else { cout&lt;&lt;"You have entered an incorrect key..."&lt;&lt;endl; cout&lt;&lt;"The program will now close.\n"; system ("pause"); return 0; } chart(m); float feet; float inch; float totalinches; cout&lt;&lt;"Please enter your height as follows..."&lt;&lt;endl; cout&lt;&lt;"Number of feet: "&lt;&lt;endl; cin&gt;&gt;feet; cout&lt;&lt;"\nNumber of inches: "&lt;&lt;endl; cin&gt;&gt;inch; totalinches=(feet*12)+inch; cout&lt;&lt;"Your total height in inches is: "&lt;&lt;totalinches&lt;&lt;endl; float inchSqd; float lbs; float BMI; inchSqd=(totalinches*totalinches); cout&lt;&lt;"Please enter your weight in pounds: \n"; cin&gt;&gt;lbs; cout&lt;&lt;"Okay, we will now calculate your BMI\n"; BMI=bmiNumber(lbs, inchSqd); cout&lt;&lt;endl &lt;&lt;"Your Body Mass Index Number is: "&lt;&lt;BMI&lt;&lt;endl; cout&lt;&lt;endl&lt;&lt;"Once again your BMI is "&lt;&lt;BMI&lt;&lt;", and here is a chart for review."&lt;&lt;endl; cout&lt;&lt;endl &lt;&lt; "\tWeight Status"&lt;&lt;endl &lt;&lt;" Below 18.5 Underweight"&lt;&lt;endl &lt;&lt;" 18.5 to 24.9 Normal"&lt;&lt;endl &lt;&lt;" 25.0 to 29.9 Overweight"&lt;&lt;endl &lt;&lt;" 30.0 and Above Obese"&lt;&lt;endl; cout&lt;&lt;"If you would like to make another calculation press 1, if not press 2..."&lt;&lt;endl; cin&gt;&gt;m; } cout&lt;&lt;endl&lt;&lt;"Thank you for using the BMICT1.0.1 and have a great day.\n"; system ("pause"); return 0; } </code></pre>
[]
[ { "body": "<ul>\n<li><p><code>stdlib.h</code> doesn’t exist in C++. The correct header is <code>cstdlib</code> although most (but not all!) compilers will also find the former.</p></li>\n<li><p><code>using namespace std</code> is generally discouraged since it may cause prolific name clashes. Instead, import just the names you need, at small scope (i.e. not at file level but in individual functions).</p></li>\n<li><p>Parenthetical: if there is <em>any</em> chance that this code may be reused (not likely, since it’s a toy example) use SI units, not Imperial ones, for the calculation. If you want to support Imperial input, convert the units to SI on input, and convert back before output, but use standard units internally. Incidentally, this also makes the calculation easier.</p></li>\n<li><p>Your <code>bmiNumber</code> calculation is wrong: the function claims that it has <code>inches</code> as input. But this is a lie: the input is actually <em>inches squared</em>. This is a recipe for bugs.</p></li>\n<li><p>What does the <code>mF</code> parameter in <code>chart</code> exactly do?</p></li>\n<li><p>The calculation of <code>totalinches</code> might be better off in function which takes whole feet and inches as arguments.</p></li>\n<li><p>Extensive text data, such as that printed in <code>chart</code> and <code>history</code> are probably better off in a separate file.</p></li>\n<li><p>The <code>main</code> function is crowded.</p></li>\n</ul>\n\n<p>But more importantly, you are using the C++ stream library as an interactive input library, and that’s not what it was designed for, and doesn’t work well for. Unfortunately, C++ doesn’t ship with an interactive console input library. If you insist on the interactivity, use a library such as <a href=\"https://stackoverflow.com/q/544280/1968\">Curses for C++</a>.</p>\n\n<p>However, console applications are usually designed to be non-interactive, and controlled by command line arguments or config files.</p>\n\n<p>If this were a <em>real</em> program, I’d probably design it to be used as follows:</p>\n\n<pre><code>bmi --male --size=6ft2 --weight=160lb\n</code></pre>\n\n<p>Or, to output the history:</p>\n\n<pre><code>bmi --history\n</code></pre>\n\n<p>Once again, C++ does’t offer great support for this in its standard library, but once again, there are libraries for that. The default on Unix systems os <a href=\"http://www.gnu.org/software/libc/manual/html_node/Getopt.html\" rel=\"nofollow noreferrer\">getopt</a> but for C++ a better library is <a href=\"http://www.boost.org/doc/libs/1_44_0/doc/html/program_options.html\" rel=\"nofollow noreferrer\">Boost.ProgramOptions</a>.</p>\n\n<p><strong>The real secret to C++ is to use libraries for everything but the most trivial tasks.</strong> Bjarne Stroustrup, the inventor of C++, once said that,</p>\n\n<blockquote>\n <p>Without a good library, most interesting tasks are hard to do in C++; but given a good library, almost any task can be made easy.</p>\n</blockquote>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-05-18T15:49:03.587", "Id": "19073", "Score": "1", "body": "`<stdlib.h>` certainly *does* exist in C++ (§D.5). It's officially deprecated, but the chances of its ever going further than that are essentially nonexistent." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-06-16T13:28:42.420", "Id": "20368", "Score": "0", "body": "@Jerry My compiler installation (GCC) actually did *not* have this header, that’s why I wrote this. Turns out, I had accidentally nuked the C part of the installation." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-05-18T20:45:41.957", "Id": "22511", "Score": "0", "body": "the use of stdlib.h is there because I was looking for ways to keep the program open on the compilers website. also I was thinking about including a feature that lets the user input si units if they want to so that is a good idea also I would love to be able to put the history in a separate file/program and be able to call on it from this one though i have no idea where to start on that." } ], "meta_data": { "CommentCount": "3", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-05-18T10:21:17.953", "Id": "11864", "ParentId": "11860", "Score": "5" } }, { "body": "<p>I'll try not to repeat too many of @Konrad Rudolph's points:</p>\n\n<ul>\n<li><p>Very important here: <em>clean up the indentation</em>. It's all over the place, making your code hard to read for others. I cannot even tell which level of indentation you're <em>trying</em> to use, but whichever it is, just stick with that one.</p></li>\n<li><p>The <code>703</code> looks like a magic number that should be a constant (with <code>const</code>). This will allow you to use this value anywhere while its use in this program will be known.</p></li>\n<li><p>It doesn't appear that <code>chart()</code> is doing anything useful, nor does its name make much sense here, so it could be removed. Functions shouldn't solely print some hardcoded text, as that is not considered useful work.</p></li>\n<li><p>You're mixing <code>std::endl</code> and <code>\"\\n\"</code>, but you really just need the latter as no flushing is specifically needed.</p></li>\n<li><p>Be aware that <code>system(\"PAUSE\")</code> is Windows-only, thus is non-portable. If you want to do a portable pause, do something like <code>std::cin.get()</code>. It does work a bit differently, but it is still better to use here.</p></li>\n</ul>\n\n<p>Overall, it was still hard to review this due to the indentation, and there's probably more that can be addressed here. Focus on cleaning this up, and it should look better.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-11-02T19:28:37.157", "Id": "68673", "ParentId": "11860", "Score": "2" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-05-18T08:25:20.407", "Id": "11860", "Score": "5", "Tags": [ "c++", "beginner" ], "Title": "BMI calculation" }
11860
<p>I have some data in a database, organized like (time, category, value), and basically, I want to show it in a histogram. But the library I use to draw historgrams only works properly if every value is filled. </p> <p>For instance, this does not work:</p> <pre><code>bin category value 1 A 5 2 B 3 </code></pre> <p>But this is ok:</p> <pre><code>bin category value 1 A 5 2 A 0 1 B 0 2 B 3 </code></pre> <p>So I have to insert zeros for every time/category combination that are not in the database. I came up with the following code:</p> <pre><code>List&lt;Info&gt; allCategories = GetAllCategories(cnn); //select distinct ... var data = new List&lt;Info&gt;(); using (var cmd = cnn.CreateCommand()) { cmd.CommandText = sqlSelect; while (blah blah) { [setting command parameters] //prepare a copy of reference values var valuesToAdd = new List&lt;Info&gt;(allCategories.Count); foreach (var x in allCategories) valuesToAdd.Add(x.Clone()); int bin = [get bin] foreach (var info in valuesToAdd) info.Bin = bin; using (var reader = cmd.ExecuteReader()) while (reader.Read()) { int category = reader.GetInt32(1); Info info = valuesToAdd.Find(i =&gt; i.category == category); //get the the object to modify info.value = reader.GetInt64(2); } data.AddRange(valuesToAdd); } } return data; </code></pre> <p>So, basically I make a copy of the list of possible combination for each bin of the graph, and then I update the values found in the database.</p> <p>I'm not really fond of this solution, partly because it involves a <code>.Clone</code>, and I'm looking for a more elegant solution...</p>
[ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-05-19T19:29:08.787", "Id": "19111", "Score": "0", "body": "You might want to do it all in the database with the help of a view ... for example http://stackoverflow.com/questions/2033535/creating-view-from-complicated-select" } ]
[ { "body": "<p>Have you considered linq? Something like:</p>\n\n<pre><code> var j = from i in new[] {1, 2}\n from s in new[] {\"a\", \"b\"}\n select new {i, s};\n</code></pre>\n\n<p>or in method syntax:</p>\n\n<pre><code> var j = new[] {1, 2}.SelectMany(i =&gt; new[] {\"a\", \"b\"}, (i, s) =&gt; new {i, s});\n</code></pre>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-05-18T12:31:35.033", "Id": "11872", "ParentId": "11862", "Score": "1" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "1", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-05-18T09:45:44.123", "Id": "11862", "Score": "2", "Tags": [ "c#" ], "Title": "Fill a collection from a database with all values filled" }
11862
<p>My code does what I need it to do, but I think I am missing the "right" way to do this with comparing the arrays. Essentially what I need this to do is compare a textbox entry against two different arrays and redirect based on which value matches. </p> <pre><code>Protected void Button1_Click(object sender, EventArgs e) { string[] str1 = new string[] {"87002", "87001", "87005"}; string[] str2 = new string[] {"97002", "97003", "97004"}; for (int i = 0; i &lt; str1.Length; i++) { string comp1 = str1[i]; if (comp1 == TextBox1.Text.ToString()) { Response.Redirect("Page1.aspx"); } } for (int i = 0; i &lt; str2.Length; i++) { string comp2 = str2[i]; if (comp2 == TextBox1.Text.ToString()) { Response.Redirect("Page2.aspx"); } } Response.Redirect("Unknown.aspx"); } </code></pre>
[ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-05-17T23:41:49.850", "Id": "19050", "Score": "1", "body": "I'd prefer `List<string>` to arrays, and use the [`Contains`](http://msdn.microsoft.com/en-us/library/bhkz42b3.aspx) method instead of looping. Other than that... what *exactly* are you asking? Is there something wrong with your code?" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-05-17T23:42:33.920", "Id": "19051", "Score": "1", "body": "I think OP may be looking for the Array.Exists method?" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-05-17T23:43:33.360", "Id": "19052", "Score": "0", "body": "basically, what is the right way to compare two strings? nothing wrong with the code, I just feel uncomfortable with it." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-05-17T23:48:09.823", "Id": "19053", "Score": "1", "body": "Is the question \"how to determine whether a string is in an array?\" or \"how to compare two strings?\"" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-05-17T23:51:03.093", "Id": "19054", "Score": "0", "body": "how to determine whether a string is in an array" } ]
[ { "body": "<p>Would you not be better using the array.Contains(..) method?\nFor example: str1.Contains(TextBox1.Text); should suffice to check whether the string is within the array.\nIt might be worth also storing the two string arrays as HashSet also for speed.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-05-18T15:46:53.020", "Id": "19072", "Score": "0", "body": "+1 for mentioning `HashSet`, but I don't understand \"for speed if they're not *very* big\". The benefit of using `HashSet` will be *greater* for a larger set of values; that phrase seems to imply that `HashSet` would only be useful for a relatively small set of values." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-05-18T15:53:50.580", "Id": "19074", "Score": "0", "body": "I'm also unsure what I meant by that..removed it now." } ], "meta_data": { "CommentCount": "2", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-05-17T23:43:22.573", "Id": "11866", "ParentId": "11865", "Score": "3" } }, { "body": "<p>You are right that should work, however there is a cleaner way to write this using Linq. Now if you are not using 3.5+ then you will stick with your way.</p>\n\n<p>Try below.</p>\n\n<pre><code>protected void btn1_Click(object sender, EventArgs e)\n {\n string[] str1 = new string[] { \"87002\", \"87001\", \"87005\" },\n str2 = new string[] { \"97002\", \"97003\", \"97004\" };\n\n string txt = txtBox1.Text.Trim();\n\n if (str1.Any(x =&gt; x.Equals(txt)))\n Response.Redirect(\"Page1.aspx\");\n else if (str2.Any(x =&gt; x.Equals(txt)))\n Response.Redirect(\"Page2.aspx\");\n else\n Response.Redirect(\"Unknown.aspx\");\n }\n</code></pre>\n\n<p>Unfortunatly we cant avoid a loop here but what we have done is used the \"ANY\" method of the string array. The \"any\" method returns a boolean (true\\false) if any of the values in the Collection matches your lambada expression. In this instance we are simply saying does x (the item in the collection) match the txt (from txtBox1).</p>\n\n<p>If it does we can redirect to the correct location.</p>\n\n<p>I hope this helps</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-05-17T23:44:44.937", "Id": "11868", "ParentId": "11865", "Score": "2" } }, { "body": "<p>I would do this:</p>\n\n<pre><code>protected void Button1_Click(object sender, EventArgs e)\n{ \n string[] str1 = new string[] {\"87002\", \"87001\", \"87005\"};\n string[] str2 = new string[] {\"97002\", \"97003\", \"97004\"};\n\n if (str1.Contains(TextBox1.Text))\n Response.Redirect(\"Page1.aspx\");\n\n if (str2.Contains(TextBox1.Text))\n Response.Redirect(\"Page2.aspx\");\n\n Response.Redirect(\"Unknown.aspx\");\n}\n</code></pre>\n\n<p>You don't need the <code>ToString()</code> calls - <code>TextBox.Text</code> should already be a <code>string</code>.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-05-17T23:56:50.023", "Id": "19055", "Score": "1", "body": "I would do this, but also use arrays of `int` (assuming those values are not just for demonstration.) If `TextBox1.Text` does not parse as an `int`, you can go straight to Unknown.aspx without searching." } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-05-17T23:44:56.283", "Id": "11869", "ParentId": "11865", "Score": "14" } }, { "body": "<p>How about using <code>Switch</code></p>\n\n<pre><code> switch(input)\n {\n case foo: do something;\n break;\n\n case bar: do something;\n break;\n }\n</code></pre>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-05-18T02:20:46.297", "Id": "11871", "ParentId": "11865", "Score": "2" } }, { "body": "<p>I would have used a <code>Dictionary&lt;string, string&gt;</code>:</p>\n\n<pre><code>private Dictionary&lt;string, string&gt; redirects = new Dictionary&lt;string, string&gt;\n{\n { \"87002\", \"Page1.aspx\" },\n { \"87001\", \"Page1.aspx\" },\n { \"87005\", \"Page1.aspx\" },\n { \"97002\", \"Page2.aspx\" },\n { \"97003\", \"Page2.aspx\" },\n { \"97004\", \"Page2.aspx\" },\n};\n\nprotected void Button1_Click(object sender, EventArgs e)\n{ \n if (redirects.ContainsKey(TextBox1.Text))\n {\n Response.Redirect(redirects[TextBox1.Text]);\n }\n else\n { \n Response.Redirect(\"Unknown.aspx\");\n }\n}\n</code></pre>\n\n<p>This solution separates the data from the algorithm, which I think is a good idea.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-05-24T17:33:12.553", "Id": "19305", "Score": "1", "body": "This could be improved with `TryGetValue` so you only need to do the lookup once." } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-05-18T16:29:52.593", "Id": "11882", "ParentId": "11865", "Score": "2" } } ]
{ "AcceptedAnswerId": "11869", "CommentCount": "5", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-05-17T23:37:26.903", "Id": "11865", "Score": "7", "Tags": [ "c#", "asp.net", "array" ], "Title": "Comparing string arrays" }
11865
<p>We developed a potential solution for the double form submit prevention and we need some review on it. To be able to execute this code on asp.net we needed to add our function call directly into the <code>onsubmit</code> event of the form. This cannot be handled by jQuery because asp.net use a <code>dopostback</code> function and called <code>form.submit()</code>. If <code>onsubmit</code> attribute of the form is empty then it will not execute the code. We don't want to depend on a bloq-UI or disabled button actions.</p> <p>This is our form tag</p> <pre><code> &lt;form id="form1" runat="server" onsubmit="return preventDoubleSubmit(event);"&gt; </code></pre> <p>And this is our javascript that handles the double submit prevention:</p> <pre><code>//Double submit preventions var _preventDoubleSubmit = false; function preventDoubleSubmit(e) { if (_preventDoubleSubmit) { return cancelDoubleSubmit(e); } else { _preventDoubleSubmit = true; return true; } } function cancelDoubleSubmit(e) { if (!e) { e = window.event; } if (e.returnValue != undefined) { e.returnValue = false; } if (e.cancelBubble != undefined) { e.cancelBubble = true; } if (e.stopPropagation) { e.stopPropagation(); } if (e.stopImmediatePropagation) { e.stopImmediatePropagation(); } if (e.preventDefault) { e.preventDefault(); } return false; } //END - Double submit prevention </code></pre> <p>Any review on this would be appreciated.</p>
[ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-05-18T15:40:56.920", "Id": "19071", "Score": "1", "body": "Couldn't you just disable the Submit button after the user clicks on it?" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-05-18T16:07:40.657", "Id": "19075", "Score": "0", "body": "It is more complicated with Asp.net controls that does a autopostback like a checkbox, dropdownlist, imagebutton, linkbutton, etc... You need to consider each type of controls that can submit the form." } ]
[ { "body": "<p>Can't you just overwrite the <code>onsubmit</code> handler with the first submission?</p>\n\n<pre><code>function preventDoubleSubmit(e) {\n e = e || window.event;\n var form = e.target || e.srcElement;\n\n form.onsubmit = function() {\n return false;\n };\n}\n</code></pre>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-08-01T11:28:34.220", "Id": "14196", "ParentId": "11874", "Score": "2" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "2", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-05-18T13:43:30.350", "Id": "11874", "Score": "4", "Tags": [ "javascript", "asp.net", "form", "event-handling", "cross-browser" ], "Title": "Cross-browser double form submit prevention" }
11874
<p>I am implementing the Factory pattern for creating my objects and am trying to compose the factories using the <code>AssemblyCatelog</code> from MEF.</p> <p>The problem I have is that while the Import of the <code>InspectionFactory</code> works the Import of the <code>InspectionPhotoFactory</code> does not.</p> <p>If I call the <code>AddPhoto</code> method on an <code>InspectionFault</code> object I can see that the <code>PhotoFactory</code> is null. I can see from looking at the container object after the composition completes <code>( _container.ComposeParts(Me))</code> that there is a <code>IInspectionPhotoFactory</code> part in the collection but it does not get assigned to the Import on the <code>InspectionFault.PhotoFactory</code> property.</p> <p>Any ideas what I am missing? Should I really be using a single factory for both objects and not having a <code>PhotoFactory</code> in each instance of the <code>InspectionFault</code> collection?</p> <p><strong>Form 1</strong></p> <pre><code>&lt;Import(GetType(IInspectionFactory))&gt; Public Property InspectionFactory As IInspectionFactory Public Sub New() ' This call is required by the designer. InitializeComponent() ' Add any initialization after the InitializeComponent() call. _catelog = New AssemblyCatalog(Assembly.GetExecutingAssembly) _container = New CompositionContainer(_catelog) Try _container.ComposeParts(Me) Catch ex As CompositionException Stop Catch ex As Reflection.ReflectionTypeLoadException Stop Catch ex As Exception Stop End Try End Sub Private Sub GetInspectionObject() Dim ins As InspectionFault = InspectionFactory.CreateInspection Try Dim by(10) As Byte ins.AddPhoto(by) Catch ex As Exception Stop End Try Stop End Sub Private Sub SimpleButton1_Click(sender As System.Object, e As System.EventArgs) Handles SimpleButton1.Click GetInspectionObject() End Sub </code></pre> <p><strong>IInspectionFactory</strong></p> <pre><code>Public Interface IInspectionFactory Function CreateInspection() As InspectionFault End Interface </code></pre> <p><strong>IInspectionPhotoFactory</strong></p> <pre><code>Public Interface IInspectionPhotoFactory Function CreateInspectionPhoto() As IList(Of InspectonPhoto) End Interface </code></pre> <p><strong>InspectionFactory</strong></p> <pre><code>Imports System.ComponentModel.Composition &lt;Export(GetType(IInspectionFactory))&gt; Public Class InspectionFactory Implements IInspectionFactory Public Function CreateInspection() As InspectionFault Implements IInspectionFactory.CreateInspection Return New InspectionFault End Function End Class </code></pre> <p><strong>InspectionFault</strong></p> <pre><code>Imports System.ComponentModel.Composition Public Class InspectionFault Public Property PartCentreID() As Int16 Public Property PartNumberID() As Int32 Public Property FaultCodeID() As Int16 Public Property FaultCodeDetailID() As Int16 Public Property SuplierID() As Int32 Public Property CreatedByID() As Int32 Public Property AdviceNumber() As String Public Property InspectionNotes() As String Public Property Quantity() As Int16 Public Property InspectionPhotos() As IList(Of InspectonPhoto) &lt;Import(GetType(IInspectionPhotoFactory))&gt; Public Property PhotoFactory As IInspectionPhotoFactory Public Sub AddPhoto(img As Byte()) If img Is Nothing Then Throw New ArgumentNullException("img", "Parameter Can Not Be Null") If InspectionPhotos Is Nothing Then InspectionPhotos = PhotoFactory.CreateInspectionPhoto InspectionPhotos.Add(New InspectonPhoto With {.Photo = img}) End Sub End Class </code></pre> <p><strong>InspectionPhotoFactory</strong></p> <pre><code>Imports System.ComponentModel.Composition &lt;Export(GetType(IInspectionPhotoFactory))&gt; Public Class InspectionPhotoFactory Implements IInspectionPhotoFactory Public Function CreateInspectionPhoto() As IList(Of InspectonPhoto) Implements IInspectionPhotoFactory.CreateInspectionPhoto Return New List(Of InspectonPhoto) End Function End Class </code></pre> <p><strong>InspectonPhoto</strong></p> <pre><code>Public Class InspectonPhoto Public Property Photo() As Byte() End Class </code></pre> <hr> <p><strong>Possible Resolution</strong></p> <p>I can make the changes as shown below and it does work but I still don't understand why the above does not</p> <p><strong>InspectionFactory</strong></p> <pre><code>Imports System.ComponentModel.Composition &lt;Export(GetType(IInspectionFactory))&gt; Public Class InspectionFactory Implements IInspectionFactory &lt;Import(GetType(IInspectionPhotoFactory))&gt; Public Property PhotoFactory As IInspectionPhotoFactory Public Function CreateInspection() As InspectionFault Implements IInspectionFactory.CreateInspection Return New InspectionFault With {.InspectionPhotos = PhotoFactory.CreateInspectionPhoto} End Function End Class </code></pre> <p><strong>InspectionFault</strong></p> <pre><code>Public Class InspectionFault Public Property PartCentreID() As Int16 Public Property PartNumberID() As Int32 Public Property FaultCodeID() As Int16 Public Property FaultCodeDetailID() As Int16 Public Property SuplierID() As Int32 Public Property CreatedByID() As Int32 Public Property AdviceNumber() As String Public Property InspectionNotes() As String Public Property Quantity() As Int16 Public Property InspectionPhotos() As IList(Of InspectonPhoto) Public Sub AddPhoto(img As Byte()) If img Is Nothing Then Throw New ArgumentNullException("img", "Parameter Can Not Be Null") InspectionPhotos.Add(New InspectonPhoto With {.Photo = img}) End Sub End Class </code></pre> <p>Anyone have any opinions of this solution? It doesn't feel right having the PhotoFactory inside the InspectionFactory and calling the <code>New InspectonPhoto</code> in the InspectionFault class.</p>
[]
[ { "body": "<blockquote>\n <p>If I call the AddPhoto method on an InspectionFault object I can see that the PhotoFactory is null.</p>\n</blockquote>\n\n<p>MEF will never silently fail to compose an object in this way. It will either create the object with all required imports, or fail with a <code>CompositionException</code>.</p>\n\n<p>Therefore, if you see an object instance which has a missing import, it must mean that you did not construct it with MEF, but just called the constructor directly. And indeed, you don't have an export attribute on the <code>InspectionFault</code> class so it is not even possible to ask MEF to construct it.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-05-21T08:55:06.360", "Id": "19159", "Score": "0", "body": "Very good point Wim. No idea how I missed that :-)" } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-05-18T21:02:00.413", "Id": "11885", "ParentId": "11876", "Score": "1" } } ]
{ "AcceptedAnswerId": "11885", "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-05-18T08:58:49.720", "Id": "11876", "Score": "2", "Tags": [ "design-patterns", ".net", "vb.net" ], "Title": "MEF composition with nested factories" }
11876
<p>So this is a lot more confusing than it has to be (I could just stick all of this in the main class with the ui event handlers) but I wanted to decouple this class for learning purposes.</p> <p><strong>Basic information:</strong></p> <p>I pulled out a bunch of code and put it in a separate class. This separate class opens files so I used exception handling. When an exception is thrown it should update the UI with an error message. To decouple this class I created an event handler and event listeners. </p> <p><strong>Questions:</strong></p> <ol> <li><p>Is this a common way to decouple classes?</p></li> <li><p>Is this too loosely coupled where it creates too much overhead</p></li> <li><p>Is this so decoupled that it makes it completely too complicated?</p></li> <li><p>My friend suggested passing Form1 to the function, but I would still need to use the name of the label. So it would be less coupled, but not completely decoupled. Is this an acceptable approach?</p></li> <li><p>Are there some other approaches that would work better?</p></li> </ol> <p><strong>Original class with UI event handlers:</strong></p> <pre><code>using System; using System.Collections.Generic; using System.ComponentModel; using System.Data; using System.Drawing; using System.Linq; using System.Text; using System.Windows.Forms; using System.IO; namespace compiler { public partial class Form1 : Form { CompilerControls controls = new CompilerControls(); bool ErrorFlag = false; public Form1() { InitializeComponent(); //add an event listener to handle exceptions controls.HandleException += new ExceptionCaught(CatchException); } private void Form1_Load(object sender, EventArgs e) { } public void CatchException(CustomEventArgs e) { UpdateStatus(e.Message, Color.Red); ErrorFlag = true; } private void ctrlOpenFile_Click(object sender, EventArgs e) { DialogResult sourceFile = openFileDialog1.ShowDialog(); if (sourceFile == DialogResult.OK) { // Read the lines into a list from the file controls.ReadFile(openFileDialog1.FileName); //Print the source file to the text box txtMainBox.Clear(); txtMainBox.Text = controls.GetSourceFile(); if (!ErrorFlag) { //Show status message and move forward UpdateStatus("File Opened Successfully", Color.Green); ctrlCreateChFile.Enabled = true; ctrlOpenFile.Enabled = false; } else ErrorFlag = false; } } private void UpdateStatus(string message, Color color) { lblStatus.ForeColor = color; lblStatus.Text = message; } private void ctrlCreateChFile_Click(object sender, EventArgs e) { //delete everything in the main text box and get/create the contents of the character file txtMainBox.Clear(); txtMainBox.Text = controls.GetChFile(); //deslect all of the text in the main text box txtMainBox.GotFocus += delegate { txtMainBox.Select(0, 0); }; //if there wasn't an exception thrown if (!ErrorFlag) { //Show status message and move forward UpdateStatus("Successfully Created Character File", Color.Green); ctrlCreateChFile.Enabled = false; ctrlCreateTokens.Enabled = true; } else ErrorFlag = false; //if there was an exception thrown, ignore the above statements only ONCE } } } </code></pre> <p><strong>Decoupled class with exception handling:</strong></p> <pre><code>using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.IO; namespace compiler { public delegate void ExceptionCaught(CustomEventArgs e); class CompilerControls { private List&lt;String&gt; fileLines = new List&lt;string&gt;(); //add an event handler public event ExceptionCaught HandleException; //handle the event of an exception being thrown private void OnCaught(CustomEventArgs e) { if (HandleException != null) HandleException(e); } public void ReadFile(String FileName) { try { using (StreamReader sr = new StreamReader(FileName)) { string line; while ((line = sr.ReadLine()) != null) fileLines.Add(line); } } catch (IOException) { OnCaught(new CustomEventArgs("File could not be Opened")); } catch (OutOfMemoryException) { fileLines.Clear(); OnCaught(new CustomEventArgs("File too large")); } } public string GetSourceFile() { string text; text = "/*******************************************************************" + Environment.NewLine; text += "/ Stephen Granet" + Environment.NewLine; text += "/ CS 451 Compiler" + Environment.NewLine; text += "/" + Environment.NewLine; try { //Format each line from the file and print it to the text box for (int i = 0; i &lt; fileLines.Count(); i++) { text += "/ " + (i + 1) + ": " + fileLines[i] + Environment.NewLine; } } catch (OutOfMemoryException) { OnCaught(new CustomEventArgs("File too large")); return ""; } //Print footer information to the text box text += "/******************************************************************/"; return text; } public String GetChFile() { String text = ""; //Convert the fileLines into one long string, and split each character into its own array element char[] symbols = (string.Join("", fileLines)).ToCharArray(); //cycle through each symbol and print it to the text box foreach (char symbol in symbols) { if ((symbol != '\n') &amp;&amp; (symbol != ' ') &amp;&amp; (symbol != '\t')) text += symbol + Environment.NewLine; } CreateChFile(text); return text; } private void CreateChFile(string content) { //Write the data to the ch.txt file try { File.WriteAllText("ch.txt", content); } catch (IOException) { OnCaught(new CustomEventArgs("Could not create Character File")); } } } } </code></pre> <p>Note: This is a homework assignment. However, I'm not asking a question on the homework part of the program. This is for my own practice. </p>
[ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-05-18T15:37:41.503", "Id": "19070", "Score": "2", "body": "Not a direct answer to your question, so a comment: your approach hides useful information from the caller. You handle the exception, which has lots of information in it, by passing *much less information* to an event. For example, an IOException will tell you *why* the file couldn't be opened; the event does not. Exceptions have a stack trace; the event does not. Sometimes it's best to let the caller handle the exception, since the caller knows best how to react to a given exceptional condition." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-05-18T17:03:23.103", "Id": "19081", "Score": "0", "body": "So I should just not check for exceptions in the decoupled class, and make whoever calls it check for exceptions?" } ]
[ { "body": "<p>Answer to question 5: you should use <code>Stringbuilder</code> to create your strings.</p>\n\n<p>Because strings are immutable, whenever you concatenate two strings you create a third. This will quickly ramp up the resources used, as you duplicate longer and longer strings.<br>\nSo, for more than a handful of concatenations, you want to use StringBuilder. (For a few, <a href=\"http://www.codinghorror.com/blog/2009/01/the-sad-tragedy-of-micro-optimization-theater.html\">it does not matter</a>.)</p>\n\n<p>Additionally, StringBuilder has methods to concatenate line-ends.<br>\nI find it deliciously ironic that lazyness can be an incentive for excellence. :)</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-05-18T16:28:00.620", "Id": "11881", "ParentId": "11880", "Score": "5" } }, { "body": "<p>Thanks to ANeves for pointing out that I could also submit my comments as an answer by invoking question 5 :)</p>\n\n<p>Original comment:</p>\n\n<p><s>Not a direct answer to your question, so a comment:</s> your approach hides useful information from the caller. You handle the exception, which has lots of information in it, by passing much less information to an event. For example, an IOException will tell you why the file couldn't be opened; the event does not. Exceptions have a stack trace; the event does not. Sometimes it's best to let the caller handle the exception, since the caller knows best how to react to a given exceptional condition.</p>\n\n<blockquote>\n <p>So I should just not check for exceptions in the decoupled class, and make whoever calls it check for exceptions? – Stephen Granet 8 mins ago</p>\n</blockquote>\n\n<p>Most likely, yes. The ReadFile method takes a file path and fills a collection of strings with the lines of the file. That's pretty simple. By using the event-based pattern you've developed, you require the consumer of the method to subscribe to an event if they want to know about exceptions. The built-in exception handling mechanism, on the other hand, comes for free.</p>\n\n<p>Indeed, the direct caller of ReadFile might not need to catch the exception. It might be appropriate to allow the exception to bubble up to a higher point in the call stack. In general, any given method should only handle exceptions that it knows about, and for which it has some specific course of action. (Such a course of action could be, for example, informing the user that the path was invalid and asking for new input.)</p>\n\n<p>At the entry point of your application (the entry point of each thread, actually), you'll usually want a general exception handler for logging exceptions that weren't handled more specifically.</p>\n\n<p>Back to your program: to decouple the ReadFile logic from the calling class, you could <em>have the method return a <code>List&lt;string&gt;</code> rather than operate on a private member of the class.</em> This has many advantages: easier testing and greater reusability come to mind.</p>\n\n<p>Another suggestion: Since you concatenate all the lines in the end, you could skip a lot of this and use the <a href=\"http://msdn.microsoft.com/en-us/library/system.io.file.readalltext.aspx\" rel=\"nofollow\"><code>File.ReadAllLines</code></a> method instead.</p>\n\n<p>In general, it seems, you might want to focus on the <a href=\"http://en.wikipedia.org/wiki/Single_responsibility_principle\" rel=\"nofollow\">single responsibility principle</a> as a way of arriving at a decoupled design.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-05-18T18:08:12.597", "Id": "19086", "Score": "0", "body": "I'd give a +1 but I don't have the rep yet. This makes a lot of sense. Later on in the program I need to read the lines individually which is why I didn't use FIle.ReadAllLines. Thanks again for the wonderful answer!" } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-05-18T17:24:06.260", "Id": "11883", "ParentId": "11880", "Score": "4" } } ]
{ "AcceptedAnswerId": "11883", "CommentCount": "2", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-05-18T15:34:28.450", "Id": "11880", "Score": "3", "Tags": [ "c#", "mvc" ], "Title": "Best practices for decouple classes in C#" }
11880
<p>After hours of working, I've finally finished my first C log parsing program! (previously was a bash script, now it is C).</p> <p>Although I think I've gotten most everything, I was just wondering if you saw any possible buffer/memory overflow dangers in the coding?</p> <pre><code>#include &lt;stdio.h&gt; #include &lt;stdlib.h&gt; #include &lt;string.h&gt; #include &lt;ctype.h&gt; #ifndef max #define max(a, b) ((a)&gt;(b))? (a) : (b) #endif long GetFileSize(FILE *fp){ long fsize = 0; fseek(fp,0,SEEK_END); fsize = ftell(fp); fseek(fp,0,SEEK_SET);//reset stream position!! return fsize; } char *lastline(char *filepath){ FILE *fp; char buff[4096+1]; int size,i; long fsize; if(NULL==(fp=fopen(filepath, "r"))){ printf("You have not died recently enough for any information to be recorded."); return NULL; } fsize= -1L*GetFileSize(fp); if(size=fseek(fp, max(fsize, -4096L), SEEK_END)){ perror("cannot seek"); exit(0); } size=fread(buff, sizeof(char), 4096, fp); fclose(fp); buff[size] = '\0'; i=size-1; if(buff[i]=='\n'){ buff[i] = '\0'; } while(i &gt;=0 &amp;&amp; buff[i] != '\n') --i; ++i; return strdup(&amp;buff[i]); } int main(int argc, char *argv[], char *envp[]){ typedef char * string; char *last; char *name; char field_x[128]; char field_y[128]; char field_z[128]; char field_world[128]; char field_cause[128]; char field_killer[128]; name = getenv("MCEXEC_PLAYERNAME"); char *filename; char *p; char *ispvp; int i; char *f; char output[200] = {0x00}; int index = 0; char field_year[128]; char field_month[128]; char field_mix[128]; char field_mix2[128]; char field_day[128]; char field_hour[128]; char field_minute[128]; char field_seconds[128]; char *hummonth; int dmon; int dy; char *cause_string; int x; char *deathtype; string dtypes[15] = { "unknown", "water", "fire", "explosion", "lava", "fall", "cactus", "creeper", "skeleton", "spider", "zombie", "pigzombie", "slime", "ghast", "suicide" }; string dstrings[15] = { "You died for unknown reasons", "You Drowned", "You were burnt to death", "You were blown to pieces", "You tried to swim in lava", "You fell to your death", "You tried to hug a cactus", "You were killed by a (more to this but not needed for this post) string realm[12] = { "Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug", "Sep", "Oct", "Nov", "Dec" }; filename = malloc(sizeof "/home/minecraft/freedonia/playerdata/deathlog-.txt" - 1 + strlen(name) + 1); if (!filename) exit(EXIT_FAILURE); snprintf(filename,4096,"/home/minecraft/freedonia/playerdata/deathlog-%s.txt",name); last = lastline(filename); if( last != NULL ) { printf( "%s\n", last ); sscanf(last, "%*[^:]:%*[^:]:%*[^:]:%127[^:]:", field_x); sscanf(last, "%*[^:]:%*[^:]:%*[^:]:%*[^:]:%127[^:]:", field_y); sscanf(last, "%*[^:]:%*[^:]:%*[^:]:%*[^:]:%*[^:]:%127[^:]:", field_z); sscanf(last, "%*[^:]:%*[^:]:%*[^:]:%*[^:]:%*[^:]:%*[^:]:%127[^:]:", field_world); sscanf(last, "%*[^:]:%*[^:]:%*[^:]:%*[^:]:%*[^:]:%*[^:]:%*[^:]:%127[^:]:", field_cause); sscanf(last, "%127[^ ] ", field_mix); sscanf(field_mix, "%127[^-]-", field_year); sscanf(field_mix, "%*[^-]-%127[^-]-", field_month); sscanf(field_mix, "%*[^-]-%*[^-]-%127[^-]-", field_day); sscanf(last, "%127[^:]:", field_mix2); sscanf(field_mix2, "%*[^ ] %127[^ ] ", field_hour); sscanf(last, "%*[^:]:%127[^:]:", field_minute); sscanf(last, "%*[^:]:%*[^:]:%127[^:]:", field_seconds); dmon = atoi(field_month); hummonth = realm[dmon-1]; p = strchr(field_cause, '_'); printf( "X coord: %s\n", field_x); printf( "Y coord: %s\n", field_y); printf( "Z coord: %s\n", field_z); printf( "World: %s\n", field_world); printf( "Cause: %s\n", field_cause); printf( "Year: %s\n", field_year ); printf( "Month: %s\n", field_month ); printf( "Day: %s\n", field_day ); printf( "Hour: %s\n", field_hour ); printf( "Minute: %s\n", field_minute ); printf( "Second: %s\n", field_seconds ); printf( "Human Month: %s\n", hummonth ); while (p != NULL) { ispvp = "true"; sscanf(field_cause, "%*[^_]_%128[^_]_", field_killer); printf( "Killer: %s\n", field_killer); cause_string = malloc(sizeof "You were killed by §f\n" - 1 + strlen(field_killer) + 1); snprintf(cause_string,128,"You were killed by §f%s\n",field_killer); printf( "%s", cause_string); p = NULL; } f = field_cause; while( *f ) { if (isalnum(*f) || *f == '_') { output[index++] = *f; } f++; } if (strcmp(ispvp,"true")!=0) { for ( x = 0; x &lt; 15; x++ ) { deathtype = dtypes[x]; if (strcmp(field_cause,deathtype)==0) { cause_string = dstrings[x]; printf( "%s\n", cause_string ); {break;} } } } dy = atoi(field_y); if ( 0 &gt; dy ) { printf( "§eYou suffocated in the void §6at§f%s:%s §6on§f %s %s", field_hour, field_minute, hummonth, field_day ); printf("§6Coords: §f%s %s\n", field_x, field_z ); } else if (strcmp(field_world,"normal")==0) { printf("§e%s §6at§f%s:%s §6on§f %s %s\n", cause_string, field_hour, field_minute, hummonth, field_day ); printf("§6Coords: §f%s %s %s\n", field_x, field_y, field_z ); } else if (strcmp(field_world,"normal")==0) { printf("§e%s §6at§f%s:%s §6on§f %s %s\n", cause_string, field_hour, field_minute, hummonth, field_day ); printf("§6Coords: §f%s %s %s §6in the §fnether\n", field_x, field_y, field_z ); } } // printf("\"%s\"\n", last); free(last); return 0; } </code></pre>
[]
[ { "body": "<p>An even quicker way to find buffer overflow or memory issues would be to use something like <a href=\"http://valgrind.org\" rel=\"nofollow\">valgrind</a> (Linux, free, open source) or <a href=\"http://www-01.ibm.com/software/awdtools/purify/\" rel=\"nofollow\">Purify</a> (multiplatform, not free) </p>\n\n<p>Im not suggesting that this is meant to replace a good code-review, but it should serve as an additional helper. After all, we all are only human, and even the best of us miss things in the code review. With a good set of requirements and good understanding of the problem, it should be possible to create a robust unit test-suite (I prefer test driven design) that should catch many/most issues. </p>\n\n<p>A static code analyzer, like <a href=\"http://www.coverity.com/\" rel=\"nofollow\">coverity</a> or <a href=\"http://cccc.sourceforge.net/\" rel=\"nofollow\">cccc</a> (more oriented towards sw metrics) is often helpful as well. At work, we have both coverity and valgrind integrated into our nightly builds and unit testing.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-05-20T16:55:28.317", "Id": "19134", "Score": "0", "body": "That only finds actual overflows not potential overflows and thus you need comprehensive test data which is imposable to get before the fact. Thus valgrind is great when you have input that is causing a problem but of only limited use otherwise." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-05-20T18:39:20.233", "Id": "19137", "Score": "0", "body": "@LokiAstari, that's the first time Ive ever heard someone call Valgrind \"limited\" (and I dont think suggesting its use is worth a down vote). I updated my answer with more details as to why I think its helpful. With a good understanding of the problem, it shouldnt be so difficult to get a decent data-set. Thanks at least for helping me to improve my answer." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-06-14T04:07:46.243", "Id": "20236", "Score": "0", "body": "Valgrind's memcheck is limited in a way because it lulls you into a false sense of security. Memcheck allows you to get extra output from unit tests. Whatever you don't unit test, memcheck won't catch. No magic there. A static tester uses formal methods to ensure that the leak/invalid access won't happen no matter what the input was." } ], "meta_data": { "CommentCount": "3", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-05-19T17:41:42.297", "Id": "11907", "ParentId": "11886", "Score": "2" } }, { "body": "<p>There are several things to improve in the code before looking for buffer overflows:</p>\n\n<ol>\n<li>Don't duplicate constant strings. E.g. <code>sizeof(\"You were killed by §f\\n\")</code> and then <code>snprintf(..., \"You were killed by §f\\n\", ...)</code>)</li>\n<li>Avoid raw constants (and duplicated) in the code. E.g. <code>char buff[4096+1]; ... fread(buff, sizeof(char), 4096, fp);</code> In this case you can define a constant/macro for <code>4096</code> or just use <code>sizeof(buff)</code> in <code>fread(buff, sizeof(char), sizeof(buff)-1, fp);</code>.</li>\n<li><p>In the code:</p>\n\n<pre><code>while(i &gt;=0 &amp;&amp; buff[i] != '\\n')\n --i;\n ++i;\n</code></pre>\n\n<p>The <code>++i;</code> has a invalid indentation which can confuse the reader.</p></li>\n<li><p>Your macro <code>max</code> should have some parenthesis to enclose the whole result:</p>\n\n<p><code>#define max(a, b) ( ((a)&gt;(b))? (a) : (b) )</code></p>\n\n<p>Without those parenthesis a call like <code>(max(2,1)+3)</code> will give you 2 (instead of 5).</p></li>\n<li>You've defined <code>string</code> type like <code>typedef char * string</code> but you're using the <code>string</code> type like <code>const char*</code>.</li>\n<li>You're calling several times <code>snprintf</code> function with an invalid 2nd argument (which is the same as calling <code>sprintf</code> directly). If you are creating a buffer with a specific size in <code>malloc</code>, remember to use that size in <code>snprintf()</code>.</li>\n<li><p>In</p>\n\n<pre><code>dmon = atoi(field_month);\nhummonth = realm[dmon-1];\n</code></pre>\n\n<p>The <code>atoi</code> is generally deprecated, because it's not required to set <code>errno</code> -- when it returns a zero, you won't know why. You should use <code>strtol</code> and ensure that <code>dmon</code> has sensible value. If <code>dmon</code> is zero, then <code>errno</code> will indicate whether it was really zero, or was there an error. In this case simply checking dmon to be between 1 and 12 inclusive will do the trick, as the zero value is not allowed.</p></li>\n</ol>\n\n<p>There are more things, but anyway, generally I would recommend you to create tiny functions to do specific tasks: instead of having mallocs/snprints/scanfs all mixed together, write functions with minimal objectives which you can ensure that they don't contain bugs/memory buffer overflow. Then you are safe to use them in your main() function.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-05-19T18:18:16.917", "Id": "11908", "ParentId": "11886", "Score": "6" } }, { "body": "<p>Adding to comments from @dacap:</p>\n\n<ul>\n<li>Open bracket in functions normall starts at column 0</li>\n<li>be kind to readers on small screens/windows: restrict lines to 80 chars</li>\n</ul>\n\n<p><strong><code>lastline()</code></strong></p>\n\n<ul>\n<li><code>filepath</code> should be <code>const</code></li>\n<li>should the error message on failure to open the file be to <code>stderr</code>?</li>\n<li>message lacks <code>\\n</code></li>\n<li><code>size=fseek</code> assignment in condition geta compiler warning and is unnecessary. The value is not used. Just check <code>if (fseek(...) &lt; 0)</code></li>\n<li><p>Negative <code>fsize</code> and <code>fseek</code> is too clever by half. Results in a redundant call to <code>fseek</code> if file size &lt;= 4096. Prefer</p>\n\n<pre><code>fsize = GetFileSize(fp);\nif (fsize &gt; (long) sizeof buff) \n{\n if (fseek(fp, fsize - sizeof buff, SEEK_SET) &lt; 0) {\n perror(\"cannot seek\");\n exit(EXIT_FAILURE);\n }\n }\n</code></pre></li>\n<li><p>Use <code>EXIT_FAILURE</code> instead of <code>0</code> for an exit code.</p></li>\n<li>Only one of <code>size</code>, <code>fsize</code> and <code>i</code> is needed.</li>\n<li><code>sizeof(char)</code> is 1 by definition</li>\n<li><code>if (buff[i])=='\\n')</code> accesses outside the buffer if file size is zero</li>\n</ul>\n\n<p><strong><code>main()</code></strong></p>\n\n<ul>\n<li>Types are normally defined at file scope.</li>\n<li>string type is pointless</li>\n<li>creation of filename allocates a buffer and then assumes its size is 4096</li>\n<li>creation of filename should be a function</li>\n<li>snprintf return value needs checking to make sure the string was not truncated</li>\n<li><p>use <code>PATH_MAX</code>:</p>\n\n<pre><code>static char * make_filename(const char *name) \n{\n char *path = malloc(PATH_MAX+1);\n if (snprintf(path, PATH_MAX, \"/home/...\", name) &gt;= PATH_MAX) {\n ... /* error handling */\n }\n return path;\n}\n</code></pre></li>\n<li><p>No idea whether the <code>scanf</code> calls are ok. Prefer to see them hidden away in a helper function.</p></li>\n<li><code>p = strchr(field_cause, '_');</code> should be later, where p is used.</li>\n<li><code>while (p != NULL)</code> should be <code>if (...)</code>. Bizarre.</li>\n<li>cause_string leaks</li>\n<li>Why not just print what you want instead of <code>malloc</code>ing a buffer and then printing it? Really strange.</li>\n<li>... baling out there. Too many problems.</li>\n</ul>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-05-20T23:57:40.247", "Id": "11933", "ParentId": "11886", "Score": "4" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-05-18T23:21:59.570", "Id": "11886", "Score": "4", "Tags": [ "c", "strings", "parsing", "logging" ], "Title": "Possible buffer overflow dangers in C log parsing program" }
11886
<p>I'd like to improve the readability of the following code. The aim of this code is to apply formatting to row(s) in a <code>WinForms DataGridView</code> based on the Priority of an item, determined either by its <code>currentPriorityValue</code> or its <code>dueDate</code> property.</p> <p>Because I've got tiger striped rows in the grid I used the modulo ternary to get the background to use by default. Then test for the High or Medium priority conditions and set the rowStyles conditionally. </p> <p>I refactored <em>to</em> use a Tuple because it seemed to tidy the code up bit and let me assign values in my conditional logic, so there was just a single call to <code>FormatRowStyle</code> after the <code>if</code>/<code>else</code> <code>if</code>/<code>else</code>, but in the call to <code>FormatRowStyle</code> I think it no longer clearly expresses what it is doing. Specifically I don't like the <code>if</code>/<code>else</code> block and I don't like the call to <code>FormatRowStyle</code> with the nested Tuple properties showing as Item2.Item1...</p> <p>Currently this logic is at the UI level. It is a presentational decision but I feel that it <em>should</em> be possible to have the logic handled elsewhere and that would make it easier to test.</p> <pre><code>private void ConditionallyFormatRowsForUrgency(int rowIndex, DateTime dueDate, string currentPriorityValue) { var defaultBackColour = rowIndex % 2 == 0 ? VisualSettings.DefaultBackColour : VisualSettings.AlternateBackColour; var rowStyles = new Tuple&lt;int, Tuple&lt;Color, Color, Font&gt;&gt;(rowIndex, new Tuple&lt;Color, Color, Font&gt;(defaultBackColour, Color.Black, VisualSettings.RegularFont)); if (ToDoUrgency(currentPriorityValue, "High", dueDate, 2)) rowStyles = new Tuple&lt;int, Tuple&lt;Color, Color, Font&gt;&gt;(rowIndex, VisualSettings.HighPriorityStyle); else if (ToDoUrgency(currentPriorityValue, "Medium", dueDate, 7)) rowStyles = new Tuple&lt;int, Tuple&lt;Color, Color, Font&gt;&gt;(rowIndex, VisualSettings.MediumPriorityStyle); FormatRowStyle(rowStyles.Item1, rowStyles.Item2.Item1, rowStyles.Item2.Item2, rowStyles.Item2.Item3); } private static bool ToDoUrgency(string currentPriorityValue, string priorityLevel, DateTime dueDate, int daysGrace) { return currentPriorityValue == priorityLevel || dueDate &lt;= DateTime.Now.AddDays(daysGrace); } private void FormatRowStyle(int rowIndex, Color backColour, Color foreColour, Font font) { dataGridView1.Rows[rowIndex].DefaultCellStyle.BackColor = backColour; dataGridView1.Rows[rowIndex].DefaultCellStyle.ForeColor = foreColour; dataGridView1.Rows[rowIndex].DefaultCellStyle.Font = font; } </code></pre>
[]
[ { "body": "<p>Concentrating on the <code>ConditionallyFormatRowsForUrgency</code> method, I see three times <code>rowStyles = new Tuple&lt;int, Tuple&lt;Color, Color, Font&gt;&gt;(rowIndex, ...)</code> so that is something I would move to a common place. In fact, only its last argument -- lets call it <code>style</code> -- changes.</p>\n\n<p>The initial value for <code>style</code> is actually the default for when the two <code>if</code>-statements don't fire. So I would put that initial value as an <code>else</code> to that <code>if</code>-statement.</p>\n\n<p>Last but not least: <code>Tuple&lt;Color, Color, Font&gt;</code> accounts for most of the clutter. By specifying an alias (<code>using Style = Tuple&lt;Color, Color, Font&gt;</code> at the top) it conveys more meaning and makes it all more readable.</p>\n\n<p>The end result would be like this:</p>\n\n<pre><code>using Style = Tuple&lt;Color, Color, Font&gt;;\n\nprivate void ConditionallyFormatRowsForUrgency(int rowIndex, DateTime dueDate, string currentPriorityValue)\n{\n var defaultBackColour = rowIndex % 2 == 0 ? VisualSettings.DefaultBackColour : VisualSettings.AlternateBackColour;\n\n Style style;\n if (ToDoUrgency(currentPriorityValue, \"High\", dueDate, 2))\n style = VisualSettings.HighPriorityStyle;\n else if (ToDoUrgency(currentPriorityValue, \"Medium\", dueDate, 7))\n style = VisualSettings.MediumPriorityStyle;\n else\n style = new Style(defaultBackColour, Color.Black, VisualSettings.RegularFont);\n\n var rowStyles = new Tuple&lt;int, Style&gt;(rowIndex, style);\n\n FormatRowStyle(rowStyles.Item1, rowStyles.Item2.Item1, rowStyles.Item2.Item2, rowStyles.Item2.Item3);\n}\n</code></pre>\n\n<p>You could consider moving <code>defaultBackColor</code> into the <code>else</code> as that is the only place it is relevant.</p>\n\n<hr>\n\n<p>In response to your latest edits: I think that your <code>ToDoUrgency</code> method is quite short, concise and easy to read. Maybe the length of the if-conditions make you think it is ugly, but there is not much you can do about it.</p>\n\n<p>One important remark: in <code>ConditionallyFormatRowsForUrgency</code> the <code>style</code> variable should <em>never</em> be null, or you'll get a <code>NullReferenceException</code> later on, somewhere else. I therefore strongly recommend that you throw a <code>NotImplementedException</code> in the switch <code>default</code> case and remove the <code>= null</code> from the line <code>Tuple&lt;Color, Color, Font&gt; style = null</code>. Two reasons: if you ever add a new enum member to <code>Urgency</code> and you forget to add the appropriate <code>case</code> to the switch, you'll get an exception right there in your switch instead of in some other method (e.g. <code>FormatRowStyle</code>). If you then do add the case but forget to set the <code>style</code> variable to something valid, you'll get a compiler error stating that <code>style</code> might be used while it has not been assigned a value. This way you ensure that <code>style</code> is never null and that your switch covers all cases.</p>\n\n<p>Further, on more personal preferences: I'd rename <code>ConditionallyFormatRowsForUrgency</code> to something like <code>FormatRowForUrgency</code>. The fact that it is conditional is an implementation detail: you might later on change how the formatting is done and this should not require you to change the name of the method. And it formats only one row, so use singular <code>Row</code> instead of <code>Rows</code>. You could also rename <code>ToDoUrgency</code> to just <code>ToUrgency</code> as that's what it does.</p>\n\n<p>Lastly, your method <code>ConditionallyFormatRowsForUrgency</code> does not care about <code>DateTime dueDate</code> or <code>string currentPriorityValue</code>, yet is asks for them. Your method cares about <code>Urgency urgency</code> so that's what I would put in the parameters. This also makes your testing easier, as you can just put a single <code>Urgency</code> value in the method and see how it works. The conversion from <code>dueDate</code> and <code>currentPriorityValue</code> to an <code>Urgency</code> enumeration member may then be done somewhere else, and tested separately.</p>\n\n<pre><code>private void FormatRowForUrgency(int rowIndex, Urgency urgency)\n{ ... }\n</code></pre>\n\n<hr>\n\n<p>In regards to the switch-statement: essentially there are four ways to accomplish what you want to do: as a switch-statement, as multiple if-statements, using inheritance, or as an index into a delegate array of functions. Multiple if-statements are probably uglier in this case than a switch-statement, and inheritance would require a complete rewrite of the Urgency enum to a class hierarchy. The index into a delegate array of functions would look like this:</p>\n\n<pre><code>private static readonly Func&lt;int, Tuple&lt;Color, Color, Font&gt;&gt;[] styleDelegates = new Func&lt;int, Tuple&lt;Color, Color, Font&gt;&gt;[]\n{\n rowIndex =&gt; VisualSettings.HighPriorityStyle, // assuming ToDo.Urgency.High = 0\n rowIndex =&gt; VisualSettings.MediumPriorityStyle, // assuming ToDo.Urgency.Medium = 1\n rowIndex =&gt; // assuming ToDo.Urgency.Normal = 2\n {\n var defaultBackColour = rowIndex % 2 == 0 ? VisualSettings.DefaultBackColour : VisualSettings.AlternateBackColour;\n return new Tuple&lt;Color, Color, Font&gt;(defaultBackColour, Color.Black, VisualSettings.RegularFont);\n }\n};\n\nprivate void FormatRowForUrgency(int rowIndex, ToDo.Urgency urgencyLevel)\n{\n var rowToStyle = dataGridView1.Rows[rowIndex].DefaultCellStyle;\n\n Tuple&lt;Color, Color, Font&gt; style = styleDelegates[(int)urgencyLevel](rowIndex);\n\n FormatRowStyle(rowToStyle, style);\n}\n</code></pre>\n\n<p>However, I would <em>not</em> recommend it. It is very likely that it severly reduces performance. There is just not much you can do about the switch statement and I would not mind seeing it there where it is now. But an alternative might be to move the switch statement altogether into another method, with the added benefit that it is possible to <code>return</code> early out of the switch.</p>\n\n<pre><code>private Tuple&lt;Color, Color, Font&gt; GetStyleByUrgency(int rowIndex, ToDo.Urgency urgencyLevel)\n{\n switch (urgencyLevel)\n {\n case ToDo.Urgency.High: return VisualSettings.HighPriorityStyle;\n case ToDo.Urgency.Medium: return VisualSettings.MediumPriorityStyle;\n case ToDo.Urgency.Normal:\n var defaultBackColour = rowIndex % 2 == 0 ? VisualSettings.DefaultBackColour : VisualSettings.AlternateBackColour;\n return new Tuple&lt;Color, Color, Font&gt;(defaultBackColour, Color.Black, VisualSettings.RegularFont);\n default:\n throw new InvalidOperationException();\n }\n}\n\nprivate void FormatRowForUrgency(int rowIndex, ToDo.Urgency urgencyLevel)\n{\n var rowToStyle = dataGridView1.Rows[rowIndex].DefaultCellStyle;\n\n Tuple&lt;Color, Color, Font&gt; style = GetStyleByUrgency(rowIndex, urgencyLevel);\n\n FormatRowStyle(rowToStyle, style);\n}\n</code></pre>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-05-19T12:05:53.600", "Id": "11900", "ParentId": "11887", "Score": "4" } }, { "body": "<p>In response to your \"<em>I still feel there's a better way of handling this than the switch\"</em> sometimes when I see switches I think polymorphism and is there a way to handle this via OOP. I typically don't do anything about it but at times it's hinting that I have a problem in my design and I should think a bit more deeper to put the necessary abstractions in place etc</p>\n\n<p>In your case, although this might be needless complexity you could change your enum into a class hierachy of Urgencies. Maybe something like.</p>\n\n<pre><code> public abstract class Urgency\n {\n public Color ForeColor { get; private set; }\n public Font Font { get; private set; }\n private Color _defaultBackColor { get; }\n\n protected Urgency(Color color, VisualSettings.RegularFont font, VisualSettings.RegularFont defaultBackColor)\n {\n this.ForeColor = color;\n this.Font = font;\n this._defaultBackColor = defaultBackColor;\n }\n\n public virtual Color GetBackColor(int rowIndex)\n {\n return this.DefaultBackColor;\n } \n\n }\n\n public class HighUrgency : Urgency\n {\n public HighUrgency(Tuple&lt;Color, Color, Font&gt; priority)\n : this(priority.item2, priority.item3, priority.item1)\n {\n\n }\n\n public HighUrgency(Color color, Font font)\n : base(color, font)\n { \n }\n }\n\n public class NormalUrgency : Urgency\n { \n public NormalUrgency(Color color, Font font)\n : base(color, font, VisualSettings.DefaultBackColour)\n { \n }\n\n public override Color GetBackColor(int rowIndex)\n { \n if(rowIndex % 2 == 0) \n {\n return VisualSettings.AlternateBackColour;\n }\n else\n {\n return base.GetBackColor(rowIndex);\n }\n }\n</code></pre>\n\n<p>Then I would remove the switch and adjust your priority property to something like:</p>\n\n<pre><code>public virtual Urgency UrgencyLevel\n{\n get\n {\n if (Priority.PriorityName == Urgency.High.ToString() || DueDate &lt;= DateTime.Now.AddDays(2))\n {\n return new HighUrgency( VisualSettings.HighPriorityStyle);\n }\n else if (Priority.PriorityName == Urgency.Medium.ToString() || DueDate &lt;= DateTime.Now.AddDays(7))\n {\n return new MediumUrgency( VisualSettings.MediumPriorityStyle);\n }\n else\n {\n // what about passing in VisualSettings.NormalPriorityStyle here??\n return new NormalUrgency(Color.Black, VisualSettings.RegularFont);\n }\n }\n} \n</code></pre>\n\n<p>Then your method with the switch becomes something like:</p>\n\n<pre><code>private void FormatRowForUrgency(int rowIndex, ToDo.Urgency urgencyLevel)\n{\n var rowToStyle = dataGridView1.Rows[rowIndex].DefaultCellStyle;\n\n cellStyle.BackColor = urgency.GetBackColor(rowIndex);\n cellStyle.ForeColor = urgency.ForeColor;\n cellStyle.Font = urgency.Font; \n}\n</code></pre>\n\n<p>Adding a new Urgency then becomes a matter of adding a new class and adjusting the if else in the Urgency property.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-05-19T22:11:15.277", "Id": "11914", "ParentId": "11887", "Score": "1" } } ]
{ "AcceptedAnswerId": "11900", "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-05-18T23:41:15.680", "Id": "11887", "Score": "3", "Tags": [ "c#", "unit-testing", "formatting" ], "Title": "Formatting rows based on priority" }
11887
<p>I'm working with two remote APIs: one which manages customers and the other (a Paypal API interface) which manages billing. To delete an account, I must delete the records from both.</p> <pre><code>function deleteAccount($account_id) { try { $api1-&gt;deleteAccount( $account_id ); } catch (Exception $e) { Logger::log(...); return false; } try { $api2-&gt;cancelBilling( $account_id ); } catch (Exception $e) { Logger::log(...); return false; } } </code></pre> <p>Suppose that the first operation (with <code>api1</code>) succeeds but the second operation (with <code>api2</code>) fails. This could happen, for example, if the <code>api2</code> server was down - a factor which is out of my control.</p> <p>I would then have deleted the account in <code>api1</code>, but would still be billing the user, which would lead to a corruption in my data (and some unhappy users!).</p> <p>I have one idea on how to maximise the possibility of success, by doing various checks for errors:</p> <pre><code>function deleteAccount($account_id) { //Check that servers are up if(!$api1-&gt;canConnectToServer() || !$api2-&gt;canConnectToServer()) { return false; } if (!$api1-&gt;isAccountIDValid($account_id ) || !$api2-&gt;isAccountIDValid($account_id ) ) { return false; } try { $api1-&gt;deleteAccount( $account_id ); } catch (Exception $e) { Logger::log(...); return false; } try { $api2-&gt;cancelBilling( $account_id ); } catch (Exception $e) { Logger::log(...); return false; } } </code></pre> <p>However, this seems a little flimsy and doesn't guarantee data integrity. Is there a better way to handle this? I'm also not sure whether I should <code>return false</code> or throw an exception.</p>
[]
[ { "body": "<p>Do you have access to the customer API? If so, I think the deletion of the Paypal account should be handled by it.</p>\n\n<p>If you do not have access to it, it seems the most important call is the Paypal one, so you should first make sure that one succeeds. Once it does, you can delete the customer account. But no matter how you delete it, there will be some time, even if only a few seconds, when the customer account will be without a Paypal account. The customer API needs to handle this situation gracefully.</p>\n\n<p>To make sure the customer account gets eventually deleted, I would add this account to some table and have a cron job process it every X seconds. The cron job should delete all the account in that table. It means that if deletion fails, it will try again a few seconds later, so it's safe to assume the account will eventually get deleted.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-05-19T08:08:02.383", "Id": "19102", "Score": "0", "body": "I'd do this as well. But everything that requires a valid account, e.g. placing a new order, would have to check \"is this account deleted?\" prior to placing that order or viewing the store at all." } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-05-19T05:43:19.177", "Id": "11893", "ParentId": "11889", "Score": "4" } }, { "body": "<p>I agree with @Laurent about the cron jobs. A better solution would be a <a href=\"http://en.wikipedia.org/wiki/Two-phase_commit_protocol\" rel=\"nofollow noreferrer\">two-phase commit protocol</a> but I don't know whether your APIs support it or not. </p>\n\n<p>I'd prefer exceptions. Actually, I'd use two <code>if</code>s instead of conditions like this:</p>\n\n<pre><code>if(!$api1-&gt;canConnectToServer() || !$api2-&gt;canConnectToServer()) {\n return false;\n}\n</code></pre>\n\n<p>For example:</p>\n\n<pre><code>if (!$api1-&gt;canConnectToServer()) {\n throw new MyException('Unable to connect to API1.');\n}\nif (!$api2-&gt;canConnectToServer()) {\n throw new MyException('Unable to connect to API2.');\n}\n</code></pre>\n\n<p>It provides detailed error messages which the caller could log or handle (different exception types could be helpful here for this). A simple <code>false</code> value does not say anything about the cause of the error and does not help debugging too much.</p>\n\n<p>This answer could be helpful: <a href=\"https://stackoverflow.com/a/307508/843804\">to throw, to return or to errno?</a></p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-05-19T18:40:01.263", "Id": "19110", "Score": "0", "body": "Two-phase commit protocol would be the ideal solution if you have access to the API." } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-05-19T09:48:21.773", "Id": "11897", "ParentId": "11889", "Score": "1" } }, { "body": "<p>For a few reasons, your best option is to <strong>use delayed job execution</strong></p>\n\n<p>That means setting up a job queue such as <a href=\"http://gearman.org/\" rel=\"nofollow\">gearman</a>, and <em>instead</em> of trying to do things all at once and in serial - you simply register a request to perform the job later.</p>\n\n<p>The benefits of working this way are numerous and include:</p>\n\n<ul>\n<li>The user doesn't have to sit their waiting while (potentially) slow processes run</li>\n<li>You disassociate the user request from the api calls. If the api calls fail you can simply try again</li>\n<li>Generally speaking you end up with much leaner and easier to maintain/test code in this way.</li>\n</ul>\n\n<p>Therefore your code would become similar to:</p>\n\n<pre><code>function deleteAccount($account_id) {\n ... your code return early to abort ...\n $delayedExecution-&gt;do('delete from api one', $account_id);\n $delayedExecution-&gt;do('cancel billing', $account_id);\n return true;\n}\n</code></pre>\n\n<p>I use gearman as an example - but you can implement it any way you wish. Just ensure your solution account for jobs that fail intermittently (job fails once, reschedule for later) <em>and</em> for jobs that fail consistently (something wrong, job fails 3 times - flag for action).</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-05-19T19:53:20.240", "Id": "11912", "ParentId": "11889", "Score": "3" } } ]
{ "AcceptedAnswerId": "11893", "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-05-19T01:22:10.967", "Id": "11889", "Score": "1", "Tags": [ "php", "error-handling", "api", "finance" ], "Title": "Fail-safe remote API operations for managing customers and billing" }
11889
<p>I try to avoid using classes in Python as much as possible; if I don't plan on building on it, I don't build it in the first place. It helps me avoid Java-like classes like <code>FileDownloader()</code>, when I could build <code>download_file()</code> instead.</p> <p>That being said, I wanted to discuss getter and setter methods -- particularly getter methods. Instead of using class methods, I typically make them <em>module</em> methods (and use the module as others might use a class).</p> <p>For example:</p> <pre><code>package/ | | __init__.py | constants.py | main.py | helpers.py </code></pre> <p>How this might be used:</p> <pre><code>#constants.py import os def get_default_directory(): return os.path.join(os.expanduser('~'), 'Desktop', 'files') def get_server_name(): return '127.0.0.1' def get_url_template(site, timezone): ... </code></pre> <p>And so on. This is the <em>go here and change stuff if something changes</em> area of the code.</p> <p>For <code>helpers.py</code>, you might have some convenience functions that work well as one liners here and there, but duplicating them in each script might be a stretch while you're still formulating a final draft.</p> <p>For instance, I had something like this, but ended up copying it into a second file later on:</p> <pre><code>def filename_from_path(path): return os.path.split(path)[-1] def trimext(filename): return os.path.splitext(filename)[0] def raw_filename(path): return trimext(filename_from_path(path)) </code></pre> <p>This replaced <code>return os.path.splitext(os.path.split(path)[-1])[0]</code>, which ended up in a couple of places (and looked ugly).</p> <p><code>main()</code> simply holds all of my high level convenience functions, my "dumb functions", as they were. They just carry out a task, and make it take the least amount of keystrokes possible. Like a main method, but you have many different arrangements available to you.</p> <pre><code>#main.py import constants import helpers def admin_dry_run(safe_mode=True): do_main_a(safe_mode) do_main_b(safe_mode) do_main_c(safe_mode) def dry_run(safe_mode=False): if safe_mode: #even this code could be defined in `helpers` to use #the login credentials in `constants`, saving space here if helpers.login(constants.get_credentials()): do_main_a() else: do_main_b() else: do_main_c() def do_main_a(): pass #... </code></pre> <p>Is this typical? Is there anyone who does this, or might be able to suggest a different approach to structuring programs that stretch across multiple files in a similar manner? </p>
[]
[ { "body": "<p>Well, this kind of stuff is usually context dependent and all, but in general your approach is pretty good. Many times I'd put my package's top level functions in it's <code>__init__.py</code> (if it's small) or reimport them there from the package submodules, like your <code>main.py</code> (only, the names are content dependent, again).</p>\n\n<p>I'm having that helpers-like file for functions that don't belong to any other particular file yet, and take them out when I figure where to put them. Only it's called <code>utils.py</code> in my case, usually.</p>\n\n<p>As for the code you provided, couple of notes:</p>\n\n<ul>\n<li><p><code>constants.py</code>:</p>\n\n<p>I'd make it look like this:</p>\n\n<pre><code>import os\n\nget_default_directory = lambda: os.path.join(os.expanduser('~'), 'Desktop', 'files')\nget_server_name = lambda: '127.0.0.1'\nget_url_template = lambda site, timezone: ...\n</code></pre>\n\n<p>Replacing the functions with lambdas reduces overall code noise and the constants look more like constants, not some functions. :-)</p>\n\n<p>Talking about functional programming, the <code>get_default_directory</code> function is not really a good constant, because it has a side effect of interacting with outside world by getting $HOME environment, but we can leave it this way, I guess.</p></li>\n<li><p><code>helpers.py</code>:</p>\n\n<pre><code>def filename_from_path(path):\n return os.path.split(path)[-1]\n</code></pre>\n\n<p>This functions is exactly <a href=\"http://docs.python.org/library/os.path.html#os.path.basename\" rel=\"nofollow\"><code>os.path.basename(path)</code></a>.</p></li>\n</ul>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-05-21T03:38:48.620", "Id": "19153", "Score": "1", "body": "I like your point about `lambda`s, however, in my examples I'd like to take advantage of docstrings...is it possible to self-document a `lambda` expression?" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-05-21T04:32:51.193", "Id": "19154", "Score": "1", "body": "Well yeah, it is possible, though it looks a bit hacky:\n\n some = lambda: 1;\n some.__doc__ = \"\"\" Do some serious stuff. \"\"\"\n\n(Damn these comments, I can't have newlines here)" } ], "meta_data": { "CommentCount": "2", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-05-20T11:28:28.677", "Id": "11919", "ParentId": "11890", "Score": "4" } }, { "body": "<p>So one thing about not using objects is that it makes getters/setters a bit less flexible in that you can't start them out as pure properties and then move them to <code>property()</code> values later. </p>\n\n<p>Also, by using something like <code>helpers.login(..)</code>, you're implicitly limiting yourself to one login at a time since the helpers namespace isn't managed like an object namespace would be. That may or may not be a problem for you now, but it's definitely a corner you may not be aware you're coding yourself into. If in the future you had two things you wanted to log into using the same code, you'd have to restructure quite a bit.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-05-22T17:37:42.150", "Id": "19219", "Score": "0", "body": "What about assigning the [`@property`](http://adam.gomaa.us/blog/2008/aug/11/the-python-property-builtin/) decorator to the getters in `helpers.py`? Would that ease any of your concerns? Your second point is definitely a concern I hadn't thought of." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-05-23T15:22:51.113", "Id": "19243", "Score": "0", "body": "Will @property work for variables in a module namespace? I don't know - I've only ever used them on object-variables. It's nice to be able to start with 'somevalue = 1' and then later be able to attach behavior to the assignment event." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-05-24T11:37:52.827", "Id": "19272", "Score": "0", "body": "Yeah I tried it...it doesn't work. I'll try rolling out my own decorator that assigns the function to some junk class, and see if I can get the effect." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-05-24T14:02:18.180", "Id": "19297", "Score": "0", "body": "At the risk of being obvious: If you're having to use a 'junk class', you're working against the language, which is almost never what you want. If you don't want to use objects, use another language. Something functional, perhaps?" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-05-25T03:01:00.420", "Id": "19323", "Score": "0", "body": "I think you already know what I'm going to say: it didn't work. I think I have a better idea of what your point is, but for this specific script I'm writing, it's not an issue. I will add that, in the future, I will probably use a very bland class to represent constants...based on the task they are a part of." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-05-26T02:36:56.370", "Id": "19360", "Score": "0", "body": "I think if you pay more attention to my second paragraph you'll find that the constants you have naturally either have a place to live (on the task object) or even become configuration arguments to the task object's constructor and so are just parameters to it in the main block." } ], "meta_data": { "CommentCount": "6", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2012-05-21T13:57:59.500", "Id": "11942", "ParentId": "11890", "Score": "10" } } ]
{ "AcceptedAnswerId": "11942", "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-05-19T03:06:09.913", "Id": "11890", "Score": "18", "Tags": [ "python", "functional-programming" ], "Title": "Replacing Python Classes with Modules" }
11890
<p>I made an object wrapper/parameter injector and I hope it will be useful. I made it for a project I am working on but then decided to try polishing it a bit.</p> <p>The use case is for wrapping objects such that you can inject parameters into their methods by calling the wrapper as a function. I was heavily inspired by AngularJS and their use of parameter injection to almost create a DSL with their framework.</p> <p>Questions:</p> <ol> <li>Is this a well-designed module?</li> <li>Is my code legible?</li> <li>Am I over looking something that might lead to bugs later?</li> <li>Is something like this safe to use?</li> </ol> <p><a href="https://github.com/KGZM/negotiator.js" rel="nofollow">Repo</a></p> <p><strong>negotiator.js</strong></p> <pre><code># A small tool for proxying objects behind a wrapper that can inject # parameters into their methods. # Extract parameter names from a function, # position is given by position this array. if module _ = require('underscore'); else _ = window._ utils = {}; utils.parameterNames = (func) -&gt; funcArgs = func.toString().split('(')[1].split(')')[0].split(',') return (k.trim() for k in funcArgs) # Inject parameters from a context object into a function. # Passed parameters are supplied by the 'params' argument. utils.injectAndApply =(func, parameters, context, target) -&gt; signature = utils.parameterNames func parameters = [] if _.isEmpty(parameters) for position, name of signature parameters[position] = context[name] if context[name]? parameters.length = signature.length; return func.apply target ? {}, parameters # Constructor for proxy object. utils.Proxy = (real) -&gt; @$real = real self = this for key, method of real when typeof method is 'function' do (method, key) -&gt; self[key] = -&gt; utils.injectAndApply method, arguments, @$context ? {}, @$real return this # Build a context object from an arguments list. utils.buildContextFromParams = (func, parameters) -&gt; signature = utils.parameterNames func context = {} for key, value of parameters context[signature[key]] = value return context # This is the circular wrapper that returns a version of itself with # a set context. utils.innerWrapper = (proxy, templateFunction, parameters) -&gt; wrapper = -&gt; utils.innerWrapper(proxy,templateFunction,arguments); context = utils.buildContextFromParams templateFunction, parameters context.$real = proxy.$real context.$wrapper = wrapper context.$proxy = proxy context.$context = context; utils.injectAndApply templateFunction, parameters, context, proxy wrapper.$context = context; wrapper.__proto__ = proxy; return wrapper # Returns a function that wraps object. # not intended to be called as a constructor utils.makeWrapper = (real, templateFunction) -&gt; proxy = new utils.Proxy real return utils.innerWrapper proxy, templateFunction, [] negotiator = utils.makeWrapper negotiator.utils = utils; if module module.exports = negotiator else window.negotiator = negotiator return </code></pre>
[ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-02-23T23:42:30.527", "Id": "35575", "Score": "0", "body": "I don't know if this is useful advice but you could use some common CoffeeScript conventions like implicit returns, and `=>` to bind a function to the current value of `this`. You also don't need to end lines with semicolons. I highlighted some of these with `#CR:` in this Gist: https://gist.github.com/wildlyinaccurate/5021863" } ]
[ { "body": "<p>Looks quite good.\nNevertheless here are some thoughts:</p>\n\n<h2>Parameter Names</h2>\n\n<p>You might get problems when calling <code>utils.parameterNames</code> without arguments. E.g. <code>func.toString()</code> would fail if <code>func</code> is undefined.\nMoreover you'll get an array with one entry (<code>['']</code>) if you pass a function with no arguments (<code>utils.parameterNames(-&gt;)</code>) where you might expect an empty array.\nYou could change your implementation to this:</p>\n\n<pre><code>utils.parameterNames = (func=-&gt;) -&gt;\n funcArgs = func.toString().split('(')[1].split(')')[0].split(',')\n (t for k in funcArgs when (t=k.trim()) isnt '')\n</code></pre>\n\n<p>Here is an other implementation (<a href=\"https://github.com/flosse/scaleApp/blob/master/src/Util.coffee\" rel=\"nofollow\">source</a>) using an regular expression</p>\n\n<pre><code>getArgumentNames = (fn=-&gt;) -&gt;\n args = fn.toString().match ///\n function # start with 'function'\n [^(]* # any character but not '('\n \\( # open bracket = '(' character\n ([^)]*) # any character but not ')'\n \\) # close bracket = ')' character\n ///\nreturn [] if not args? or (args.length &lt; 2)\nargs = args[1]\nargs = args.split /\\s*,\\s*/\n(a for a in args when a.trim() isnt '')\n</code></pre>\n\n<p>We could also write s.th. like this:</p>\n\n<pre><code>fnRgx = ///\n function # start with 'function'\n [^(]* # any character but not '('\n \\( # open bracket = '(' character\n ([^)]*) # any character but not ')'\n \\) # close bracket = ')' character\n///\n\nargRgx = /([^\\s,]+)/g\n\nparameterNames = (fn) -&gt;\n (fn?.toString().match(fnRegex)?[1] or '').match(argRgx) or []\n</code></pre>\n\n<p>The performance depend on the browser but the last one seems to be pretty fast (see <a href=\"http://jsperf.com/getparameternames\" rel=\"nofollow\">benchmarks</a>)</p>\n\n<h2>Expressions</h2>\n\n<p>In CoffeeScript every thing is an expression so you can turn this</p>\n\n<pre><code>if module\n _ = require('underscore');\nelse\n _ = window._\n</code></pre>\n\n<p>into this</p>\n\n<pre><code>_ = if module then require('underscore') else window._\n</code></pre>\n\n<h2>Iteration</h2>\n\n<p>This:</p>\n\n<pre><code>for position, name of signature\n parameters[position] = context[name] if context[name]?\n</code></pre>\n\n<p>could also be written in that way:</p>\n\n<pre><code>for position, name of signature when context[name]?\n parameters[position] = context[name]\n</code></pre>\n\n<p>or even:</p>\n\n<pre><code>parameters[position] = context[name] for position, name of signature when context[name]?\n</code></pre>\n\n<p>It compiles all to the same JS. I'd prefer the second variant.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-10-04T23:31:36.277", "Id": "32265", "ParentId": "11891", "Score": "3" } } ]
{ "AcceptedAnswerId": "32265", "CommentCount": "1", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-05-19T04:34:45.997", "Id": "11891", "Score": "3", "Tags": [ "javascript", "coffeescript" ], "Title": "Object wrapper/parameter injection module" }
11891
<p>For practice I tried implementing a bubble sort algorithm in Ruby. I'm especially interested in creating clean DRY and KISS code and keeping things readable, but efficient. Any hints to improve things would be very much appreciated. The code looks like this:</p> <pre><code>class Sorter def initialize end def sort(stack) if stack.length == 0 return stack else checkArguments(stack) if stack.length == 1 return stack else newstack = [] stackIsSorted = false while !stackIsSorted newstack = iterateThroughStack(stack) if newstack == stack stackIsSorted = true else stack = newstack end end return newstack end end end def checkArguments(stack) stack.each do |element| if element.class != Float &amp;&amp; element.class != Fixnum raise ArgumentError, "element detected in stack that is not an integer or double" end end end def iterateThroughStack(stack) newstack = [] currentElement = stack[0] for i in (1...stack.length) if currentElement &lt; stack[i] newstack.push(currentElement) currentElement = stack[i] else newstack.push(stack[i]) end end newstack.push(currentElement) end end </code></pre> <p>Then, after reading about Test Driven Development, I started using this practice and since then, I think code makes more sense with unit tests. So below are the unit test I wrote:</p> <pre><code>require 'test/unit' require 'lib/Sorter' class Test_Sorter &lt; Test::Unit::TestCase def setup @sorter = Sorter.new end def test_emptyStack stack = [] assert_equal(stack, @sorter.sort(stack), "sorting empty stack failed") end def test_StackWithOneElement stack = [1] assert_equal(stack, @sorter.sort(stack), "sorting stack with one element: 1 failed") stack = ["a"] assert_raise (ArgumentError) { @sorter.sort(stack) } end def test_StackWithTwoElements stack = [2, 1] sorted_stack = [1, 2] assert_equal(sorted_stack, @sorter.sort(stack), "sorting stack with two elements: 1, 2 failed") stack = [2, "a"] assert_raise (ArgumentError) { @sorter.sort(stack) } end def test_StackWithThreeElements stack = [2, 3, 1] sorted_stack = [1, 2, 3] assert_equal(sorted_stack, @sorter.sort(stack), "sorting stack with three elements: 1, 2, 3 failed") end def test_StackWithFourElements stack = [4, 2, 3, 1] sorted_stack = [1, 2, 3, 4] assert_equal(sorted_stack, @sorter.sort(stack), "sorting stack with four elements: 1, 2, 3, 4 failed") end end </code></pre>
[]
[ { "body": "<p>Just a note about the tests: I'd create a test method for every assert call. For example, </p>\n\n<pre><code> def test_StackWithTwoElements\n stack = [2, 1]\n sorted_stack = [1, 2]\n assert_equal(sorted_stack, @sorter.sort(stack), \"sorting stack with two elements: 1, 2 failed\")\n stack = [2, \"a\"]\n assert_raise (ArgumentError) { @sorter.sort(stack) }\n end\n</code></pre>\n\n<p>would be</p>\n\n<pre><code> def test_StackWithTwoElements\n stack = [2, 1]\n sorted_stack = [1, 2]\n assert_equal(sorted_stack, @sorter.sort(stack), \"sorting stack with two elements: 1, 2 failed\")\n end\n\n\n def test_StackWithInvalidElement\n stack = [2, \"a\"]\n assert_raise (ArgumentError) { @sorter.sort(stack) }\n end\n</code></pre>\n\n<p>Too many asserts in one test is a bad smell. It's <a href=\"http://xunitpatterns.com/Assertion%20Roulette.html\" rel=\"nofollow\">Assertion Roulette</a> and you lost <a href=\"http://xunitpatterns.com/Goals%20of%20Test%20Automation.html#Defect%20Localization\" rel=\"nofollow\">Defect Localization</a>. If the first <code>assert_equal</code> throws an exception you don't know anything about the results of the other assert calls which could be important because they could help debugging and defect localization.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-05-21T13:24:22.883", "Id": "19164", "Score": "1", "body": "That's a nice suggestion. Thanks for sharing the links too. Interesting stuff." } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-05-19T09:18:03.823", "Id": "11896", "ParentId": "11894", "Score": "1" } }, { "body": "<p>There are few things I would do differently:</p>\n\n<ol>\n<li>Using <code>class</code> without instance variables doesn't make much sense, you can use <code>module</code> for that if the only thing you want is to limit scope. Of course it had been useful if you would have initialized class with some parameters like <code>Sorter.new(Float, Fixnum)</code> and saved them for later use,</li>\n<li>When you iterate through the stack you know for sure if you swapped items or not, so I would say it's a good idea to save this information inside <code>iterateThroughStack</code> and pass it back so you don't need to compare arrays in <code>sort</code>,</li>\n<li>Duck typing in Ruby means you normally don't check types, who cares what type of element is if it allows comparison, so I would remove <code>checkArguments</code> unless you have some special requirements,</li>\n<li>I would use <code>each</code> instead of <code>for</code>,</li>\n<li>Don't use <code>return</code> unless you want to return from the middle of a function (which is presumably bad thing to do).</li>\n</ol>\n\n<p>So it all comes down to this:</p>\n\n<pre><code>class Sorter\n def initialize\n end\n\n def sort(stack)\n if stack.length &gt; 1\n stackIsSorted = false\n while !stackIsSorted\n stackIsSorted, stack = iterateThroughStack(stack)\n end\n end\n stack\n end\n\n def iterateThroughStack(stack)\n stackIsSorted = true\n newstack = []\n currentElement, *tail = stack\n tail.each do |element|\n if currentElement &lt; element\n newstack.push(currentElement)\n currentElement = element\n else\n newstack.push(element)\n stackIsSorted = false\n end\n end\n [stackIsSorted, newstack.push(currentElement)]\n end\nend\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-05-24T07:33:41.000", "Id": "19269", "Score": "0", "body": "Thanks Victor! I never heard of the `*tail` syntax, but found it [here](http://stackoverflow.com/questions/918449/what-does-the-unary-operator-do-in-this-ruby-code). Your code would require a test to be changed: `sort([\"a\"])` will now return `[\"a\"]` in stead of raising an error. Isn't that an issue?" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-05-24T13:42:40.783", "Id": "19294", "Score": "0", "body": "It depends on your requirements, strings can be sorted too." } ], "meta_data": { "CommentCount": "2", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-05-21T14:56:41.963", "Id": "11947", "ParentId": "11894", "Score": "1" } } ]
{ "AcceptedAnswerId": "11947", "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-05-19T08:31:36.473", "Id": "11894", "Score": "3", "Tags": [ "ruby", "unit-testing", "sorting" ], "Title": "Bubble sort implementation with tests" }
11894
<p>Some time ago I've written a small parser (about 250 LoC) which is capable of executing the four arithmetic operators <code>+-*/</code> as well as a dice-roll operator, <code>NdM</code>, which "rolls a dice", DnD style. The source contains only integers, but of course due to division, not only integers are handled. Floating-point errors are silently ignored and mocked.</p> <p>Now that I've come across it again today, I feel a bit meh about it. It's not horrible, but it definitely could be better.</p> <p>Since it's a bit longish, I'll only paste here the two functions I feel most uncomfortable about: The one which goes through the token lists and decides which to execute, and the one which actually executes the operators.</p> <p>To clear up some details if you don't wish to see the entire source: The parser tokenizes input left->right, inserting numbers and operators into <code>numberStack</code> and <code>operatorStack</code> respectively. The "executer" (don't have a clue what's the proper name for it) goes right->left on the operator stack, and uses the simple operator-precedence logic to see which ones to execute. All these functions exist on one object. The rest should be straightforward from the variable/property names.</p> <pre><code>execute : function () { var idx; while ( (idx = this.operatorStack.length) ) { //execute, BACKWARDS! OH THE INSANITY while ( 0 &lt;=-- idx ) { execute.call( this, this.operatorStack[idx], idx ); } } function execute ( token, index ) { var last = this.operatorStack[ index + 1 ]; //last one is more important than we are if ( last &amp;&amp; last.precedence &gt; token.precedence ) { //execute it this.operate( index + 1 ); } //we're about to finish and the last one isn't as all-mighty as we // thought else if ( !index ) { //execute za operator! this.operate( index ); } } } //snip operate : function ( index ) { //grab the two numbers we care about //since the source string looks like: 2 + 1 // and the index param is actually the index of the operator to use, // we grab the index-th number and the index-th+1 number //in the above example, index = 0, we grab numberStack[0] and // numberStack[1] var couplet = this.numberStack.slice( index, index + 2 ); //in addition to the numbers we operate on, there's also a dice-roll // operator, so we take it into consideration couplet.push( this.rolls ); //arr.splice removes items and returns the removed items as an array //we remove the index-th item from the operatorStack and grab its // "value", which is the operator symbol (+, * etc) //when we have that value, we grab the corresponding operator object var op = operators[ this.operatorStack.splice(index, 1)[0].value ]; //arr.splice, as well as removing items, can also add items //so, we slice-n-dice at the two numbers, grab the result of executing // the operator, and add that result where we finished slicing //for example: // [0, 1, 2].splice( 0, 2, 42 ) //will make the array look like // [42, 2] this.numberStack.splice( index, 2, op.exec.apply(null, couplet) ); } </code></pre> <p>Full code can be found here: <a href="https://gist.github.com/1761880" rel="nofollow">https://gist.github.com/1761880</a></p>
[ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-05-20T00:07:48.987", "Id": "19121", "Score": "0", "body": "Why is \"2d3d4\" considered illegal? Wouldn't that just mean \"roll two 3-sided dice, sum the results, roll that many 4-sided dice, and sum the results\"?" } ]
[ { "body": "<p>There are a couple of issues I notice when I look at the code style of your code.</p>\n\n<p>You could hide your internal variables by using the <a href=\"http://www.adequatelygood.com/2010/3/JavaScript-Module-Pattern-In-Depth\" rel=\"nofollow\">module pattern</a>. Information hiding is a very important concept. Although you have hidden the fields already by putting everything in a function, this will allow more fine grained control. It will also remove the need to use the <code>call</code> function on inner functions.</p>\n\n<p>There are two functions that have the same name <code>execute</code> (<code>parser.execute</code> and the function within). This confusing. It would be better if you would pick two unique names for that.</p>\n\n<p>The names <code>execute</code> and <code>operate</code> are very generic and these two words have a similar meaning. By looking at the names I cannot determine what these functions do. A more clear name would be better.</p>\n\n<p>Abbreviating variables is confusing. Using <code>idx</code> instead of <code>index</code> isn't a real saving, since you should optimize for reading, not for writing. (You will read your code more often than you write it) <code>index</code> is still vague. Describing what kind of index it is makes the variable name more clear.</p>\n\n<p>Comments like</p>\n\n<pre><code>//execute it\n</code></pre>\n\n<p>are useless. You shouldn't use comments for these straight forward things. Explaining how the other functions work, as is done with <code>array.splice</code>, is also something that isn't common to do.</p>\n\n<p>Using </p>\n\n<pre><code>else if ( !index ) {\n</code></pre>\n\n<p>for checking whether a index is 0 is confusing. Better would be</p>\n\n<pre><code>else if ( index == 0 ) {\n</code></pre>\n\n<p>, because then it is instantly clear you are checking whether it is zero instead of not initialized.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-05-19T23:53:21.640", "Id": "19120", "Score": "1", "body": "I agree with everything you said, except for `!index` vs `index == 0`. The concept of falsey vs actually false is a critical part of the javascript language - if constructs like this confuse the reader, chances are the reader is going to be confused no matter what you write. Besides, in this case, the variable has a name that already tells you it's a number." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-05-20T03:07:26.477", "Id": "19124", "Score": "0", "body": "I agree with Mark about the `!index` part. The `!` should only be used to do binary tests (true/false, exists/doesn't exist, etc.). For any variable that might have more than 2 states, using comparison operators makes the statements clearer and more consistent." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-05-21T05:28:14.507", "Id": "19155", "Score": "0", "body": "@laurent except that `[] == 0` so therefore if you are really checking if it is 0 you want a `index === 0` right? Well `index` really couldn't be `[]` in this case so we achieve nothing really. I personally think this more of a coding style decision more than anything and both ways seem valid." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-05-27T23:58:57.477", "Id": "19374", "Score": "0", "body": "Sorry for lateness and thanks for your comments. For the information hiding part, I have to disagree - I'm not a big fan of privacy. The inner execute function is indeed very stupid, I don't know what I was thinking. Their names can also be improved, but I just don't know what the \"proper\" technical names for them are. Regarding variable names, these abbreviations are made clear by context, but I otherwise agree. Regarding comments, I like to explain non-obvious parts of my code (using splice this way is uncommon.) boost provided my view on `!index`." } ], "meta_data": { "CommentCount": "4", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-05-19T23:23:57.667", "Id": "11915", "ParentId": "11895", "Score": "3" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "1", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-05-19T09:01:13.433", "Id": "11895", "Score": "4", "Tags": [ "javascript", "parsing", "dice" ], "Title": "DnD dice roll parser" }
11895
<p>I'm building a form dynamically in a web app where I'm using <code>product_id</code> to keep track which product I'm reading and then <code>product_&lt;id&gt;_property</code> to grab the value of it. Then in my view I end up with this:</p> <pre><code>for product_id in request.POST.getlist('product_id'): ProductPlacement.objects.create( product = Product.objects.get(id=product_id), board = board, x = request.POST.get('product_{0}_x'.format(product_id)), y = request.POST.get('product_{0}_y'.format(product_id)), width = request.POST.get('product_{0}_width'.format(product_id)), height = request.POST.get('product_{0}_height'.format(product_id)), rotation = request.POST.get('product_{0}_rotation'.format(product_id)), z = 0 ) </code></pre> <p>It's not very pretty, is there a nicer more readable way of doing it?</p>
[]
[ { "body": "<p>Your code is quite ok and I have no idea how to improve this particular piece. </p>\n\n<p>You have used several identical forms and processed it manually. Django have <a href=\"http://django.me/formsets\" rel=\"nofollow\">formsets</a> for this purpose. Why don't you use them?</p>\n\n<p>Then I don't see validation in your code. What happens when <code>product_0_width</code> contains not-numeric or empty value? Formsets would solve this problem.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-05-19T19:20:57.877", "Id": "11910", "ParentId": "11902", "Score": "1" } }, { "body": "<p>If your list of attributes varies, the below might be a bit more future-proof:</p>\n\n<pre><code>for product_id in request.POST.getlist('product_id'):\n attribs = { 'product' : Product.objects.get(id=product_id),\n 'board' = board,\n 'z' = 0\n }\n for attrib in [ 'x', 'y', 'width', 'height', 'rotation' ]:\n attribs[attrib] = request.POST.get('product_{0}_{1}'.format(product_id, attrib))\n ProductPlacement.objects.create(**attribs)\n}\n</code></pre>\n\n<p>but overall what you've got is quite legible and easily understandable, if a bit repetitive. Note that what @San4ez said is true: there's no validation in the above, so it may need to be added.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-05-21T13:50:54.457", "Id": "11941", "ParentId": "11902", "Score": "1" } }, { "body": "<p>Maybe you might consider this to be somewhat more readable?</p>\n\n<pre><code># for Python 3.x\nclass Getter:\n\n def __init__(self, request, product_id):\n self.get = request.POST.get\n self.pid = product_id\n\n def __getattr__(self, name):\n return self.get('product_{}_{}'.format(self.pid, name))\n\nfor product_id in request.POST.getlist('product_id'):\n get = Getter(request, product_id)\n ProductPlacement.objects.create(\n product=Products.objects.get(id=product_id),\n board=board,\n x=get.x,\n y=get.y,\n width=get.width,\n height=get.height,\n rotation=get.rotation,\n z=0\n )\n</code></pre>\n\n<p>If you like it, more of your code might be structured similarly.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-05-21T19:19:20.447", "Id": "11953", "ParentId": "11902", "Score": "1" } } ]
{ "AcceptedAnswerId": "11910", "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-05-19T14:29:11.050", "Id": "11902", "Score": "2", "Tags": [ "python", "html", "django" ], "Title": "Building and getting a form of objects that have multiple properties" }
11902
<p>I have a hierarchy of types in my program and need to be able to create them dynamically at runtime. The solution I've come up with below is not the most elegant solution. Are there ways of improving it?</p> <p>Specifically would it be possible to have the method <code>getBuilderFor(...)</code> not need to instantiate the type it's trying to create in order to get a builder for that type?</p> <pre><code>public class Main { public interface E { } public class EImpl implements E { } public interface C&lt;V&gt; extends E { interface Builder&lt;T&gt; { T build(); } } public abstract class CImpl&lt;T&gt; extends EImpl implements C&lt;T&gt; { public abstract class BuilderImpl&lt;V extends C&lt;?&gt;&gt; implements Builder&lt;V&gt;{ } } public interface B extends C&lt;String&gt; { } public class BImpl extends CImpl&lt;String&gt; implements B { public class BuilderImpl extends CImpl&lt;B&gt;.BuilderImpl&lt;B&gt; { @Override public B build() { return new BImpl(); } } } public interface D extends C&lt;Double&gt; { } public class DImpl extends CImpl&lt;Double&gt; implements D { public class BuilderImpl extends CImpl&lt;D&gt;.BuilderImpl&lt;D&gt; { @Override public D build() { return new DImpl(); } } } public class Factory { public &lt;R extends C&lt;?&gt;, K extends C.Builder&lt;R&gt;&gt; K getBuilderFor(final Class&lt;R&gt; type) { if (BImpl.class.equals(type)) { // I would ideally like to just have return BImpl.BuilderImpl() here - is it possible? return (K) new BImpl().new BuilderImpl(); } else if (DImpl.class.equals(type)) { // I would ideally like to just have return DImpl.BuilderImpl() here - is it possible? return (K) new DImpl().new BuilderImpl(); } return null; } } } </code></pre>
[]
[ { "body": "<p>Why not use a map of types (<code>CImpl</code> concrete instances) that are instantiated upon <code>Factory</code> initialization? The values of the map would be instances of <code>BImpl</code>, <code>DImpl</code>, etc, and the respective keys would be the types. The function <code>getBuilderFor()</code> would just do a map lookup and on the value returned from the map, call <code>BuilderImpl()</code> and return the result.</p>\n\n<p>This approach would allow to avoid the if/else block. Additionally, it would make it easier and more elegant to add more types in the future.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-05-19T17:33:41.137", "Id": "11905", "ParentId": "11903", "Score": "3" } }, { "body": "<ol>\n<li><p>The <code>BuilderImpl</code> classes can't be an inner (i.e. non-static) class of the class what it build. You have to create the builder first, then the builder will create the actual class. If the builder is an inner class it's not possible.</p>\n\n<p>(To make the <code>BuilderImpl</code> classes static you need to make static some other classes too.)</p></li>\n<li><p>The <code>V</code> type parameter on <code>C</code> looks unnecessary since the interface does not use it.</p>\n\n<pre><code>public interface C&lt;V&gt; extends E {\n interface Builder&lt;T&gt; { \n T build(); \n }\n}\n</code></pre></li>\n</ol>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-05-20T00:09:41.160", "Id": "11916", "ParentId": "11903", "Score": "1" } } ]
{ "AcceptedAnswerId": "11905", "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-05-19T14:56:28.500", "Id": "11903", "Score": "3", "Tags": [ "java" ], "Title": "Factory-like pattern implementation" }
11903
<p>I'm a JavaScript newbie who was first introduced to JavaScript by jQuery. I'm trying to switch over some of the small things I've written in jQuery to JavaScript as a way of learning. I was wondering how I could make my code cleaner and if there were any bad habits which I am guilty of doing.</p> <pre><code>function getTweets(user) { //Adds a little animation to the body when function is executed $('.container').html('&lt;div class="loading"&gt;&lt;/div&gt;'); var container = document.getElementsByClassName('container')[0]; container.innerHTML = "&lt;div class='loading'&gt;&lt;/div&gt;"; $.getJSON("https://twitter.com/statuses/user_timeline.json?screen_name=" + user + "&amp;callback=?&amp;count=50", function(data) { var date = { Sun : 'Sunday, ', Sat : 'Saturday, ', Mon : 'Monday, ', Tue : 'Tuesday, ', Wed : 'Wednesday, ', Fri : 'Friday, ', Thu : 'Thursday, ', }; // Creates a box and puts JSON data into it. for ( var i = 0 ; i &lt; data.length; i++) { // Makes the dates readable and links work. data[i].text = data[i].text.replace(/(http[s]*:\/\/[\w/\.]+)/, '&lt;a href=\"$1\"&gt;$1&lt;/a&gt;') day = date[ data[i].created_at.match(/\w+/)[0] ]; data[i].created_at = data[i].created_at.replace(/(\+\d+)/g, '').replace(/\w+/, day); var art = document.createElement('article'); art.innerHTML = "&lt;h3&gt;" + data[i].user.name + "&lt;/h3&gt;&lt;span class='date'&gt;" + data[i].created_at + "&lt;/span&gt;&lt;p&gt;" + data[i].text + "&lt;/p&gt;"; container.appendChild(art); }; //Everything after this is to dynamically create a Pinterest type layout var width = Math.floor( ( $(window).width() - 200 )/225), col = [], small = 0, articleArray = document.getElementsByTagName('article'); while ( col.length &lt; width ) { col.push(0) }; for (var o = 0; o &lt; articleArray.length; o++) { articleArray[o].style.top = col[small] + "px"; articleArray[o].style.left = small*225 + "px"; col[small] += articleArray[o].clientHeight + 5; for ( var j = 0; j &lt; width; j++ ) { if (col[j] &lt; col[small]) { small = j } }; }; container.style.height = col[small] + 'px'; container.style.width = col.length * 225 - 5 + 'px'; $('.container .loading').fadeOut(); $('article').fadeIn(); }); }; </code></pre>
[]
[ { "body": "<ul>\n<li><p>First step to making the code look good is proper indentation. <a href=\"http://jsbeautifier.org/\" rel=\"nofollow\">JSBeautifier</a> can do that for you. </p></li>\n<li><p>Next is consistency. If you use jQuery, you can go all-out with jQuery to make it as neat and uniform. Of course, you can do vanilla JS if you want to for optimization.</p></li>\n<li><p>Then remove duplicate code or code that does the same thing over and over again.</p></li>\n<li><p>Watch out for missed <code>var</code>s. This can make variables to globals which isn't good.</p></li>\n<li><p>When declaring, follow this order:</p>\n\n<ul>\n<li>variables</li>\n<li>functions</li>\n<li>\"prep code\" like initializers, code to fill arrays, fetching values etc.</li>\n<li>actual operation of the function</li>\n</ul></li>\n</ul>\n\n<p>The rest are commented so keep a sharp eye. Can't really debug the code but the idea of what to do are there:</p>\n\n<pre><code>function getTweets(user) {\n\n //cache an object if it's to be used more than once\n var container = $('.container').html('&lt;div class=\"loading\"&gt;&lt;/div&gt;'),\n\n //put the url up here so it does not clutter the getJSON below\n //i prefer using single quotes than double quotes for a cleaner look\n url = 'https://twitter.com/statuses/user_timeline.json?screen_name=' + user + '&amp;callback=?&amp;count=50';\n\n $.getJSON(url, function (data) {\n\n //it's logical to only put things where they are needed\n //in this case, the following variables are only needed\n //when the callback completes\n var date = {\n Sun: 'Sunday, ',\n Sat: 'Saturday, ',\n Mon: 'Monday, ',\n Tue: 'Tuesday, ',\n Wed: 'Wednesday, ',\n Fri: 'Friday, ',\n Thu: 'Thursday, '\n },\n width = Math.floor(($(window).width() - 200) / 225),\n col = [],\n small = 0,\n articleArray = $('article');\n\n //prep codes after vars\n while(col.length &lt; width) {\n col.push(0)\n };\n\n //consistency and ease, use jQuery instead.\n $.each(data, function (i, value) {\n //watch out for missed \"vars\"\n var day = date[value.created_at.match(/\\w+/)[0]],\n //shorthand notation for creating a variable, appending it to the container directly\n //we can hand it over to a reference to do more on it\n art = $('&lt;article&gt;').appendTo(container);\n value.text = value.text.replace(/(http[s]*:\\/\\/[\\w/\\.]+)/, '&lt;a href=\\\"$1\\\"&gt;$1&lt;/a&gt;')\n value.created_at = value.created_at.replace(/(\\+\\d+)/g, '').replace(/\\w+/, day);\n art.html('&lt;h3&gt;' + value.user.name + '&lt;/h3&gt;&lt;span class=\"date\"&gt;' + value.created_at + '&lt;/span&gt;&lt;p&gt;' + value.text + '&lt;/p&gt;');\n });\n\n\n container.css({\n width : col.length * 225 - 5,\n height : col[small]\n })\n\n //using the built in each to loop through DOM\n articleArray.each(function (i, article) {\n $(article).css({\n 'top': col[small],\n 'left': small * 225\n });\n col[small] += article.clientHeight + 5;\n for(var j = 0; j &lt; width; j++) {\n if(col[j] &lt; col[small]) {\n small = j\n }\n }\n }).fadeIn(); //chain whenever necessary\n\n //using context to limit the scope of the selector search\n $('.loading', container).fadeOut();\n });\n}\n</code></pre>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-05-19T18:28:09.727", "Id": "11909", "ParentId": "11906", "Score": "2" } }, { "body": "<p>Just a small note: </p>\n\n<ol>\n<li><p><code>225</code> should be constant, the code uses it three times. (<a href=\"http://en.wikipedia.org/wiki/Magic_number_%28programming%29#Unnamed_numerical_constants\" rel=\"nofollow\">Unnamed numerical constants</a> on Wikipedia)</p></li>\n<li><p>Comments often could be function names and the commented code could be extracted out to these functions. For example:</p>\n\n<ul>\n<li><code>// Creates a box and puts JSON data into it.</code>: <code>createBoxWithFilledData(...)</code>,</li>\n<li><code>// Makes the dates readable and links work.</code>: <code>makeDatesReadable(...)</code>, <code>fixLinks(...)</code>,</li>\n<li><code>// Everything after this is to dynamically create a Pinterest type layout</code>: <code>createLayout(...)</code>.</li>\n</ul>\n\n<p>Reference:</p>\n\n<ul>\n<li><em>Clean Code</em> by <em>Robert C. Martin</em>, <em>Bad Comments, p67</em>: <em>Don’t Use a Comment When You Can Use a Function or a Variable</em>.</li>\n<li><em>Refactoring</em> by <em>Martin Fowler</em>, <em>Chapter 3. Bad Smells in Code</em>, <em>Long Method</em></li>\n</ul></li>\n<li><p>In the <code>for</code> loop I'd create a local variable for <code>data[i]</code>. I'd make the code readable and shorter.</p></li>\n</ol>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-05-20T13:27:10.440", "Id": "11923", "ParentId": "11906", "Score": "0" } } ]
{ "AcceptedAnswerId": "11909", "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-05-19T17:33:42.673", "Id": "11906", "Score": "1", "Tags": [ "javascript" ], "Title": "getTweets in JavaScript" }
11906
<p>So, first time I try PHP. Thought I'd set a goal for myself, divide it up in smaller problems and start googling. So yes I got it to work, very happy.</p> <p>But, it is rather crude and ugly. So now I would like to know how it should look. Proper regex, proper formatting in the array, keeping the links as links and any other tips.</p> <p>Just to be clear, what it does: You place this on a server you have, browse to the url where the file is, it scrapes Pirate Bay, and emails you the names and magnets. It could be used by one person on his web domain as private 'proxy'. No one else can see or use it and it is all in one simple file.</p> <p>I miss-posted earlier but they did say using cache would be smart.</p> <pre><code>$data = file_get_contents('http://thepiratebay.se/top/201'); $selected = '/Details.for.(.+?)"|magnet:.+?"/'; preg_match_all($selected,$data,$matches, PREG_OFFSET_CAPTURE); $to = "me@domain.com"; $subject = "Pirate Mail"; if (mail($to, $subject, print_r($matches, 1), 'From: BlackBeard@piratemail.com')) { echo("&lt;p&gt;Message successfully sent!&lt;/p&gt;"); } else { echo("&lt;p&gt;Message delivery failed...&lt;/p&gt;"); } </code></pre>
[ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-05-20T05:57:53.210", "Id": "19126", "Score": "1", "body": "I really can't see any problem with this code. What it does is clear, the variable names are good, etc." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-05-21T19:15:46.707", "Id": "19180", "Score": "0", "body": "Well for example the magnet link doesnt present as link when printed. And to me it all looks messy in the array. But then again i haven't seen many arrays. How do i get some more control over what is printed and what is not?" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-05-22T01:15:13.020", "Id": "19197", "Score": "0", "body": "this is more a question for StackOverflow, but basically if you want to have clickable links in the email, you need to format it as HTML. Some example there - http://css-tricks.com/sending-nice-html-email-with-php/ You will have to loop through your array and print the links one by one." } ]
[ { "body": "<p>Generally, RegExps are a bad choice to deal with HTML code. You're better of with DOM parser: parse the tree and then use XPath to find desired elements, i.e. the ones containing the torrent name and the magnet link. I'm not posting any code because I've never done it in PHP though, but as a pointer...</p>\n\n<p>Anyway, if you just wanted a simple script that just works, you're good, and if you wanted to do some self-education, you can try parsing the DOM.</p>\n\n<p>The first search result from Google gives me this: <a href=\"http://simplehtmldom.sourceforge.net/\" rel=\"nofollow\">http://simplehtmldom.sourceforge.net/</a></p>\n\n<p>And some points on the code style:</p>\n\n<p>You have some weird (IMO) indentation in the <code>if</code> statement. Usually the closing bracket is on the same level as <code>if</code> is, i.e.:</p>\n\n<pre><code>if (mail($to, $subject, print_r($matches, 1), 'From: BlackBeard@piratemail.com')) {\n echo(\"&lt;p&gt;Message successfully sent!&lt;/p&gt;\");\n} else {\n echo(\"&lt;p&gt;Message delivery failed...&lt;/p&gt;\");\n}\n</code></pre>\n\n<p>And you have inconsistent spaces-after-arguments:</p>\n\n<pre><code>preg_match_all($selected,$data,$matches, PREG_OFFSET_CAPTURE);\n....\nmail($to, $subject, print_r($matches, 1), 'From: BlackBeard@piratemail.com')\n</code></pre>\n\n<p>Second one (with spaces after commas) is usually a preferred one.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-05-20T07:54:44.817", "Id": "11918", "ParentId": "11917", "Score": "4" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "3", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-05-20T03:25:32.373", "Id": "11917", "Score": "1", "Tags": [ "php", "regex" ], "Title": "Pirate Bay name and magnet mailer" }
11917
<p>I am looking for a more efficient or shorter way to achieve the following output using the following code:</p> <pre><code>timeval curTime; gettimeofday(&amp;curTime, NULL); int milli = curTime.tv_usec / 1000; time_t rawtime; struct tm * timeinfo; char buffer [80]; time(&amp;rawtime); timeinfo = localtime(&amp;rawtime); strftime(buffer, 80, "%Y-%m-%d %H:%M:%S", timeinfo); char currentTime[84] = ""; sprintf(currentTime, "%s:%d", buffer, milli); printf("current time: %s \n", currentTime); </code></pre> <p>Sample output:</p> <blockquote> <p>current time: 2012-05-16 13:36:56:396</p> </blockquote> <p>I would prefer not to use any third-party library like Boost.</p>
[ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-05-24T00:49:02.690", "Id": "19266", "Score": "2", "body": "You want to use `%03d` to format `milli` so you get leading zeros. And since your format is so close to ISO-8601, you might want to continue with it and use \".\" instead of \":\" to separate the seconds and milliseconds." } ]
[ { "body": "<p>When you call <code>gettimeofday</code> it gives you the number of seconds since EPOCH too, so you don't need to call <code>time</code> again. And when you use output of <code>localtime</code> as input of <code>strftime</code>, you may omit the intermediate variable (not a very useful point though). So your code could be written like:</p>\n\n<pre><code>timeval curTime;\ngettimeofday(&amp;curTime, NULL);\nint milli = curTime.tv_usec / 1000;\n\nchar buffer [80];\nstrftime(buffer, 80, \"%Y-%m-%d %H:%M:%S\", localtime(&amp;curTime.tv_sec));\n\nchar currentTime[84] = \"\";\nsprintf(currentTime, \"%s:%03d\", buffer, milli);\nprintf(\"current time: %s \\n\", currentTime);\n</code></pre>\n\n<p>an important note to be considered is that functions like <code>localtime</code> are not thread-safe, and you'd better use <code>localtime_r</code> instead.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2018-02-28T07:46:26.960", "Id": "360085", "Score": "0", "body": "It's worth to note that on Windows `timeval::tv_sec` is a `long`, while `localtime` expects a `time_t`. You might want explicitly convert it to the right type first." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-01-22T21:51:46.943", "Id": "409974", "Score": "0", "body": "`sprintf(currentTime, \"%s:%d\", buffer, milli);` will be wrong when milli<100. Use `\"%s:03d\"` to add zero-padding." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-01-08T17:40:16.983", "Id": "460436", "Score": "0", "body": "@michaelmoo Perhaps it should be `\"%s:%03d\"` :)" } ], "meta_data": { "CommentCount": "3", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2012-05-20T12:57:44.093", "Id": "11922", "ParentId": "11921", "Score": "11" } }, { "body": "<p>You can remove the necessity to use two buffers, and also they are too large (80? why?). The actual string will be something like 23 characters long.</p>\n<p>If you want to be cool and expect your program to last until end of 64bit Unix timestamp, which is the year 292277026596, then we need 8 additional characters to fit. So 31 bytes for the actual characters in total.</p>\n<p>And + 1 byte for <code>\\0</code> which makes it nice and round 32 bytes.</p>\n<pre><code>timeval curTime;\nchar buffer[32];\n\ngettimeofday(&amp;curTime, NULL);\nsize_t endpos = strftime(buffer, sizeof buffer,\n &quot;%Y-%m-%d %H:%M:%S&quot;, localtime(&amp;curTime.tv_sec));\nsnprintf(buffer + endpos, sizeof buffer - endpos,\n &quot;:%03d&quot;, (int) (curTime.tv_usec / 1000));\n</code></pre>\n<p>This code is not thread safe (use <code>localtime_r()</code>).</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-07-30T21:36:30.280", "Id": "524531", "Score": "1", "body": "To make it portable, just cast the result of `curTime.tv_usec / 1000` to `int` and format it with `%03d`. I would also use `snprintf()` just to be safe, and use `sizeof buffer` instead of repeating `32`." } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-07-29T14:51:26.630", "Id": "265520", "ParentId": "11921", "Score": "1" } }, { "body": "<p>There's a serious problem here:</p>\n<blockquote>\n<pre><code>gettimeofday(&amp;curTime, NULL);\n⋮\ntime(&amp;rawtime);\n</code></pre>\n</blockquote>\n<p>Suppose the system time is approximately HH:MM:00.999 when <code>curTime</code> is assigned, but a few microseconds later at HH:MM:01.000 when <code>rawtime</code> is assigned. This means that we'll print HH:MM:01.999, which is quite far from either value.</p>\n<p>Swapping the two calls won't help - that would result in HH:MM:00.000, which is also wrong. We need to get a single precise value, and use that for the whole of the formatting.</p>\n<p>Instead of writing out <code>%Y-%m-%d</code> and <code>%H:%M:%S</code>, it's easier and arguably clearer to use the shorter forms <code>%F</code> and <code>%T</code>. And we can use the return value from <code>std::strftime()</code> to determine the position at which the fractional seconds should be formatted.</p>\n<p>We can use the size of the longest expected output to determine how large the buffer needs to be:</p>\n<pre><code> char buffer[sizeof &quot;9999-12-31 23:59:59.999&quot;];\n</code></pre>\n<p>In modern C++, we would use <code>std::chrono</code> for time access, rather than the C library:</p>\n<pre><code>#include &lt;chrono&gt;\n#include &lt;iostream&gt;\n\nint main()\n{\n using namespace std::chrono;\n auto timepoint = system_clock::now();\n auto coarse = system_clock::to_time_t(timepoint);\n auto fine = time_point_cast&lt;std::chrono::milliseconds&gt;(timepoint);\n\n char buffer[sizeof &quot;9999-12-31 23:59:59.999&quot;];\n std::snprintf(buffer + std::strftime(buffer, sizeof buffer - 3,\n &quot;%F %T.&quot;, std::localtime(&amp;coarse)),\n 4, &quot;%03lu&quot;, fine.time_since_epoch().count() % 1000);\n\n std::cout &lt;&lt; buffer &lt;&lt; '\\n';\n}\n</code></pre>\n<p>If you have a C++ environment that implements C++20's <a href=\"https://en.cppreference.com/w/cpp/utility/format/format\" rel=\"nofollow noreferrer\"><code>std::format</code></a>, then it becomes much, much simpler:</p>\n<pre><code>#include &lt;chrono&gt;\n#include &lt;format&gt;\n#include &lt;iostream&gt;\n\n// UNTESTED!!\nint main()\n{\n auto timepoint = std::chrono::system_clock::now();\n\n auto buffer = std::format(&quot;%F %R:%06.3S&quot;, timepoint.time_since_epoch());\n\n std::cout &lt;&lt; buffer &lt;&lt; '\\n';\n}\n</code></pre>\n<p>I'm not yet sure whether we can supply a precision specifier with <code>%T</code> conversion, so I split the time representation. I may try that out when I have access to a GCC with sufficient support.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-07-29T16:04:41.790", "Id": "265523", "ParentId": "11921", "Score": "2" } } ]
{ "AcceptedAnswerId": "11922", "CommentCount": "1", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-05-20T12:45:01.930", "Id": "11921", "Score": "10", "Tags": [ "c++", "datetime" ], "Title": "Getting current time with milliseconds" }
11921
<h2>I was asked to submit my request for code review on <a href="https://stackoverflow.com/questions/10672046/defining-transpose-on-a-collection-of-irregular-collections">https://stackoverflow.com/questions/10672046/defining-transpose-on-a-collection-of-irregular-collections</a> here.</h2> <p>This is a follow-up to the post I made in <a href="https://stackoverflow.com/questions/1683312/is-there-a-safe-way-in-scala-to-transpose-a-list-of-unequal-length-lists/10663749#10663749">https://stackoverflow.com/questions/1683312/is-there-a-safe-way-in-scala-to-transpose-a-list-of-unequal-length-lists/10663749#10663749</a>. I want to propose a definition of transpose for a list of unequal-sized lists by viewing List[A] as a mapping from Int to A. First, here's why I think the transpose defined in the referenced post is problematic.</p> <pre><code>scala&gt; val l = List(List(1, 2, 3), List(4, 5), List(6, 7, 8)) l: List[List[Int]] = List(List(1, 2, 3), List(4, 5), List(6, 7, 8)) scala&gt; val lt = transpose( l ) lt: List[List[Int]] = List(List(1, 4, 6), List(2, 5, 7), List(3, 8)) scala&gt; val ltt = transpose( lt ) ltt: List[List[Int]] = List(List(1, 2, 3), List(4, 5, 8), List(6, 7)) scala&gt; l == ltt res0: Boolean = false </code></pre> <p>So, transpose( transpose( l ) ) is not the same as l. The problem arises from the fact that this definition of transpose does not respect the precise indices associated with the elements (there is implicit "shifting" of elements when preparing the inner lists).</p> <p>So I am proposing that transpose on a list of unequal-sized lists (List[List[A]]) be more abstractly viewed as an operation on a Map[Int,Map[Int,A]] (because a List[A] can be viewed as a Map[Int,A]). This operation is well-defined and can be further abstracted to operate on a Map[A,Map[B,C]] as follows:</p> <pre><code>def transpose[A,B,C]( mapOfMaps: Map[A,Map[B,C]] ) : Map[B,Map[A,C]] = { val innerKeys = ( mapOfMaps map { p =&gt; ( p._2.keys ) toList } ) flatten val outerKeys = ( mapOfMaps keys ) toList val allValues = innerKeys map { ik =&gt; outerKeys filter { ok =&gt; mapOfMaps( ok ).contains( ik ) } map { ok =&gt; ( ok, mapOfMaps( ok )( ik ) ) } toMap } ( innerKeys zip allValues ) toMap } </code></pre> <p>To transform a list of lists to the more-abstract map of maps, zipping is convenient.</p> <pre><code>def listOfListsToMapOfMaps[A]( l : List[List[A]] ) : Map[Int,Map[Int,A]]= { val listOfMaps = l map { x =&gt; ( x.indices zip x ) toMap } ( listOfMaps.indices zip listOfMaps ) toMap } </code></pre> <p>Now, things are clean:</p> <pre><code>scala&gt; val m = listOfListsToMapOfMaps( l ) m: Map[Int,Map[Int,Int]] = Map(0 -&gt; Map(0 -&gt; 1, 1 -&gt; 2, 2 -&gt; 3), 1 -&gt; Map(0 -&gt; 4, 1 -&gt; 5), 2 -&gt; Map(0 -&gt; 6, 1 -&gt; 7, 2 -&gt; 8)) scala&gt; val mt = transpose( m ) mt: Map[Int,Map[Int,Int]] = Map(0 -&gt; Map(0 -&gt; 1, 1 -&gt; 4, 2 -&gt; 6), 1 -&gt; Map(0 -&gt; 2, 1 -&gt; 5, 2 -&gt; 7), 2 -&gt; Map(0 -&gt; 3, 2 -&gt; 8)) scala&gt; val mtt = transpose( mt ) mtt: Map[Int,Map[Int,Int]] = Map(0 -&gt; Map(0 -&gt; 1, 1 -&gt; 2, 2 -&gt; 3), 1 -&gt; Map(0 -&gt; 4, 1 -&gt; 5), 2 -&gt; Map(0 -&gt; 6, 1 -&gt; 7, 2 -&gt; 8)) scala&gt; m == mtt res1: Boolean = true </code></pre> <p>I see plenty of use for this generalized transpose operation in my work (and I'm sure for many others - across languages). But I'd like for people to review my transpose definition and implementation before I put it into my core library and start using it (I'm relatively new to Scala and am sure my implementation can be improved).</p>
[]
[ { "body": "<p>Yes, <code>traspose</code> defined such that it shrings the result to the size of the shortest list isn't an <a href=\"https://en.wikipedia.org/wiki/Involution_%28mathematics%29\" rel=\"nofollow\">involution</a>. Your idea of viewing lists as maps is nice, but I suppose once you leave <code>List</code>s, there are other easier options.</p>\n\n<p>As you observed, <code>List[A]</code> is also a <code>PartialFunction[Int,A]</code> that works on integers that are between <code>0</code> and the size of the list. Now if we have a list of lists, it's <code>PartialFunction[Int,PartialFunction[Int,A]]</code>. Now we can convert such functions into a single function by a process called <a href=\"https://en.wikipedia.org/wiki/Currying\" rel=\"nofollow\">un-currying</a>. While Scala has <a href=\"http://www.scala-lang.org/api/current/index.html#scala.Function%24\" rel=\"nofollow\"><code>uncurried</code></a> for plain functions, it lacks it for <code>PartialFunction</code>s. But it's not difficult to define it:</p>\n\n<pre><code>def uncurried[A,B,C](f: PartialFunction[A,PartialFunction[B,C]]):\n PartialFunction[(A,B),C] =\n Function.unlift((x: (A,B)) =&gt; f.lift(x._1).flatMap(_.lift(x._2)));\n</code></pre>\n\n<p>So we can apply <code>uncurried</code> immediately on <code>List[List[A]]</code> (or rather to <code>Seq[Seq[A]]</code> to avoid <em>O(n)</em> access for lists) and we get a functional representation that accepts a pair of indices and gives the result. If we swap the indices in a pair, we get a transposed view.</p>\n\n<p>The problem with this representation is that we can't enumerate all matching indices easily. If this is required, we could instead convert a list of lists into <code>Map[(Int,Int),A]</code>, perhaps a <code>SortedMap</code> so that we can enumerate the indices in a proper order. Again, this will be a <code>PartialFunction[(Int,Int),A]</code>, but also with this additional ability.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-07-26T18:45:29.497", "Id": "29039", "ParentId": "11924", "Score": "3" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-05-20T13:30:57.190", "Id": "11924", "Score": "3", "Tags": [ "functional-programming", "scala", "collections" ], "Title": "Defining transpose on a collection of irregular collections" }
11924
<p>When we select the 'info' list in the select field, the article with type 'info' characteristic automatically showed up, and when we select 'Berita' list in the select field, the articles with type 'Berita' characteristic automatically show up.</p> <p>This is a long script that uses a post method. Can you help me make it simpler, perhaps using functions?</p> <pre><code>&lt;form method=&quot;post&quot; name=&quot;form2&quot;&gt; &lt;select name=&quot;type&quot; id=&quot;type&quot;&gt; &lt;option value=&quot;Semua&quot;&gt;Semua&lt;/option&gt; &lt;option value=&quot;Berita&quot;&gt;Berita&lt;/option&gt; &lt;option value=&quot;Info&quot;&gt;Info&lt;/option&gt; &lt;/select&gt; &lt;input type=&quot;submit&quot; id=&quot;type&quot; /&gt; &lt;/form&gt; &lt;table width=&quot;200&quot; border=&quot;1&quot; class=&quot;tbl_art_content&quot; id=&quot;results&quot;&gt; &lt;tbody&gt; &lt;tr&gt; &lt;/tr&gt; &lt;?php $i=0; $no=0; if($_POST['type'] == 'Semua') { $query_art = mysql_query(&quot;SELECT * FROM artikel_tbl ORDER BY id&quot;) or die(mysql_error()); } else if ($_POST['type'] == 'Berita') { $query_art = mysql_query(&quot;SELECT * FROM artikel_tbl WHERE type = 'Berita' ORDER BY id&quot;) or die(mysql_error()); } else if ($_POST['type'] == 'Info') { $query_art = mysql_query(&quot;SELECT * FROM artikel_tbl WHERE type = 'Info' ORDER BY id&quot;) or die(mysql_error()); } else { $query_art = mysql_query(&quot;SELECT * FROM artikel_tbl ORDER BY id&quot;) or die(mysql_error()); } while($show=mysql_fetch_array($query_art)) { $no++; if(($no%2)==0) $color = '#f2f2f2'; else $color = '#f9f9f9'; ?&gt; &lt;tr bgcolor=&quot;&lt;?php echo $color; ?&gt;&quot; class=&quot;rows&quot;&gt; &lt;td class=&quot;chk_content&quot;&gt;&lt;input type=&quot;checkbox&quot; name=&quot;checked&lt;?php echo $i; ?&gt;&quot; value=&quot;&lt;?php echo $show['id']; ?&gt;&quot;/&gt;&lt;/td&gt; &lt;td class=&quot;no_content&quot;&gt;&lt;?php echo $no; ?&gt;&lt;/td&gt; &lt;td class=&quot;middle_content&quot;&gt;&lt;?php echo $show['judul']; ?&gt;&lt;/td&gt; &lt;td class=&quot;middle_content&quot;&gt;&lt;?php echo $show['penulis']; ?&gt;&lt;/td&gt; &lt;td class=&quot;middle_content&quot;&gt;&lt;?php echo $show['type']; ?&gt;&lt;/td&gt; &lt;td class=&quot;middle_content&quot;&gt;&lt;img src=&quot;.././upload/artikel/&lt;?php echo $show['foto']; ?&gt;&quot; width=&quot;144&quot; height=&quot;88&quot;/&gt;&lt;/td&gt; &lt;td class=&quot;middle_content&quot;&gt;&lt;?php echo $show['tanggal']; ?&gt;&lt;/td&gt; &lt;td class=&quot;aksi_content&quot;&gt;&lt;div id=&quot;aksi_table&quot;&gt; &lt;ul&gt; &lt;li&gt;&lt;a href=&quot;table_artikel.php?edit=&lt;?php echo $show['id']; ?&gt;&quot;&gt;&lt;img src=&quot;images/Apps-text-editor-icon.png&quot; width=&quot;20&quot; height=&quot;20&quot; /&gt;&lt;/a&gt;&lt;/li&gt; &lt;li&gt;&lt;a href=&quot;table_artikel.php?delete=&lt;?php echo $show['id']; ?&gt;&quot; onclick=&quot;return confirm('Hapus artikel?')&quot;;&gt;&lt;img src=&quot;images/Remove-icon.png&quot; width=&quot;20&quot; height=&quot;20&quot;/&gt;&lt;/a&gt;&lt;/li&gt; &lt;/ul&gt; &lt;/div&gt;&lt;!-- end of aksi_table --&gt;&lt;/td&gt; &lt;/tr&gt; &lt;?php $i++; } ?&gt; &lt;input type=&quot;hidden&quot; name=&quot;n&quot; value=&quot;&lt;?php echo $i; ?&gt;&quot; /&gt; &lt;/tbody&gt; &lt;/table&gt; </code></pre>
[]
[ { "body": "<p>Well... First we can shorten your if-construct a lot:</p>\n\n<pre><code>$sql = 'SELECT * FROM artikel_tbl';\nif ($_POST['type'] == 'Info' || $_POST['type'] == 'Berita')\n $sql .= \" WHERE type = '{$_POST['type']}'\";\n$sql .= ' ORDER BY id';\n</code></pre>\n\n<p>In my opinion this also increases readability, because it is clear that the query is basically everytime the same, you are just including a condition in one case.</p>\n\n<p>Next thing the <code>if(($no%2)==0)</code>-part. Do you know about the nth-child of css? Here is an example for that: <a href=\"http://jsfiddle.net/2ZR2U/\" rel=\"nofollow\">http://jsfiddle.net/2ZR2U/</a></p>\n\n<p>For these things: <code>&lt;?php echo $show['judul']; ?&gt;</code> change this to read <code>&lt;?php echo htmlspecialchars($show['judul']); ?&gt;</code>. Unless you are very sure that the input is just a number or something that is guaranteed to not contain any of [&lt;>\"] this is very important to prevent display bugs or in worst case cross site scripting attacks.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-05-20T17:43:08.680", "Id": "11929", "ParentId": "11925", "Score": "2" } }, { "body": "<ol>\n<li><p>When you are merely &quot;reading&quot; data from the server/database, the appropriate way to pass data with this request is generally <code>$_GET</code>. <code>$_POST</code> is used when you are &quot;writing&quot; data to the server/database. Your search form should be using <code>method=&quot;get&quot;</code> instead of <code>method=&quot;post&quot;</code>. (not that it is breaking anything, just a better practice) Using <code>$_GET</code> will also allow your users to bookmark the actual selection and navigate directly to specific selection which is a better UX.</p>\n</li>\n<li><p>There is absolutely no benefit in repeating the <code>&lt;option&gt;</code>'s text as the <code>value</code> attribute value. It doesn't even matter if you are employing javascript processes on the element. Simply omit the <code>value</code> attribute declarations from all option tags.</p>\n</li>\n<li><p><code>mysql_</code> functions should no longer exist in any code, here's why: <a href=\"https://stackoverflow.com/a/12860046/2943403\">https://stackoverflow.com/a/12860046/2943403</a></p>\n</li>\n<li><p>Extending the advice in that answer to this page, you should be using a prepared statement with a placeholder for cases when you want to include user-supplied data into your query. Sure, you can validate the incoming values to ensure the safety of your query, but when you are using the best practice throughout your application, you can confidently and interchangeably copy-paste snippets from any of your projects.</p>\n</li>\n<li><p>I recommending keeping processing code at the top of your file and all of the markup generation at the bottom. This separation should help to make your script easier to maintain.</p>\n</li>\n<li><p>If the user did select a specific option, it will be expected to present that selection in the <code>&lt;select&gt;</code> field when the page is loaded.</p>\n</li>\n<li><p>Declare an options array which can be used as a validating whitelist AND to populate the extra options of your select field.</p>\n</li>\n<li><p>To alternate the styling (in this case, background color) of html table rows, use css only. This is a much more sleak technique than bloating your php code. Please see: <a href=\"https://stackoverflow.com/q/3084261/2943403\">https://stackoverflow.com/q/3084261/2943403</a></p>\n</li>\n<li><p>Do not use <code> or die(mysql_error())</code> in production, this will present potentially usable details about your database to &quot;bad actors&quot; who may attempt to infiltrate your system.</p>\n</li>\n<li><p><code>aksi_table</code> is an <code>id</code> value that is declared inside a loop. This is a no-no. Element <code>id</code> values must be unique within an html document. Unless you have another alternative solution, this attribute should be declared as a <code>class</code>. To be honest, I don't see any benefit in wrapping your <code>&lt;ul&gt;</code> element in a <code>&lt;div&gt;</code> container. It is best to try to minimize the number of elements that your html document needs.</p>\n</li>\n<li><p>Your inline javascript should be translated into &quot;listeners&quot; which should be written in a <code>&lt;script&gt;</code> section or in an external javascript file. This will make the row template less bloated and easier to read. The same is true for the inline styling -- move anything that can be moved to a css file.</p>\n</li>\n<li><p>I have to assume that I am not looking at all the vital code for this script. There seems to be no second form, so I don't what the purpose of the hidden input is.</p>\n</li>\n<li><p>As stated in #1, <code>table_artikel.php?edit=</code> and <code>table_artikel.php?delete=</code> are bad ideas. These actions should be triggered by a form submission or ajax process and only with <code>post</code> as the method. You don't want a crawler to find your &quot;data writing&quot; scripts and wipe out or modify all of the data in your database table. I'll include your technique in my snippet, but you need to fundamentally change these processes.</p>\n</li>\n</ol>\n<p>Code:</p>\n<pre><code>&lt;?php\n$conn = new mysqli(&quot;localhost&quot;, &quot;root&quot;, &quot;&quot;, &quot;myDB&quot;);\n\n$options = ['Berita', 'Info'];\n\nif (isset($_GET['type']) &amp;&amp; in_array($_GET['type'], $options)) {\n $selected = $_GET['type'];\n $stmt = $conn-&gt;prepare(&quot;SELECT * FROM artikel_tbl WHERE `type` = ? ORDER BY id&quot;);\n $stmt-&gt;bind_param('s', $_GET['type']);\n $stmt-&gt;execute();\n $result = $stmt-&gt;get_result();\n} else {\n $selected = '';\n $result = $conn-&gt;query(&quot;SELECT * FROM artikel_tbl ORDER BY id&quot;);\n}\n\n?&gt;\n&lt;form method=&quot;get&quot; name=&quot;form2&quot;&gt;\n &lt;select name=&quot;type&quot; id=&quot;type&quot;&gt;\n &lt;option&gt;Semua&lt;/option&gt;\n &lt;?php\n foreach ($options as $option) {\n printf(\n &quot;&lt;option%s&gt;%s&lt;/option&gt;&quot;,\n $selected === $option ? ' selected' : '',\n $option\n );\n }\n ?&gt;\n &lt;/select&gt;\n &lt;input type=&quot;submit&quot; /&gt;\n&lt;/form&gt;\n\n&lt;?php\n$rowTemplate = '\n &lt;tr class=&quot;rows&quot;&gt;\n &lt;td class=&quot;chk_content&quot;&gt;\n &lt;input type=&quot;checkbox&quot; name=&quot;id&quot; value=&quot;%1$d&quot;/&gt;\n &lt;/td&gt;\n &lt;td class=&quot;no_content&quot;&gt;%2$d&lt;/td&gt;\n &lt;td class=&quot;middle_content&quot;&gt;%3$s&lt;/td&gt;\n &lt;td class=&quot;middle_content&quot;&gt;%4$s&lt;/td&gt;\n &lt;td class=&quot;middle_content&quot;&gt;%5$s&lt;/td&gt;\n &lt;td class=&quot;middle_content&quot;&gt;\n &lt;img src=&quot;.././upload/artikel/%6$s&quot; width=&quot;144&quot; height=&quot;88&quot;/&gt;\n &lt;/td&gt;\n &lt;td class=&quot;middle_content&quot;&gt;%7$s&lt;/td&gt;\n &lt;td class=&quot;aksi_content&quot;&gt;\n &lt;div class=&quot;aksi_table&quot;&gt;\n &lt;ul&gt;\n &lt;li&gt;\n &lt;a href=&quot;table_artikel.php?edit=%1$d&quot;&gt;\n &lt;img src=&quot;images/Apps-text-editor-icon.png&quot; width=&quot;20&quot; height=&quot;20&quot; /&gt;\n &lt;/a&gt;\n &lt;/li&gt;\n &lt;li&gt;\n &lt;a href=&quot;table_artikel.php?delete=%1$d&quot; onclick=&quot;return confirm(\\'Hapus artikel?\\')&quot;;&gt;\n &lt;img src=&quot;images/Remove-icon.png&quot; width=&quot;20&quot; height=&quot;20&quot;/&gt;\n &lt;/a&gt;\n &lt;/li&gt;\n &lt;/ul&gt;\n &lt;/div&gt;\n &lt;/td&gt;\n &lt;/tr&gt;\n';\n?&gt;\n\n&lt;table width=&quot;200&quot; border=&quot;1&quot; class=&quot;tbl_art_content&quot; id=&quot;results&quot;&gt;\n &lt;tbody&gt;\n &lt;?php\n foreach ($result as $row) {\n printf(\n $rowTemplate,\n $row['id'], // %1$d -- used multiple times\n $i + 1, // %2$d\n $row['judul'], // %3$s\n $row['penulis'], // %4$s\n $row['type'], // %5$s\n $row['foto'], // %6$s\n $row['tanggal'] // %7$s\n );\n }\n ?&gt;\n &lt;/tbody&gt;\n&lt;/table&gt;\n</code></pre>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-01-30T02:16:17.360", "Id": "255401", "ParentId": "11925", "Score": "2" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2012-05-20T14:47:18.370", "Id": "11925", "Score": "2", "Tags": [ "php", "mysql" ], "Title": "Present database results based on form submission" }
11925
<p>I have following code for a content scroller. This has been implemented with basic jquery. Iam trying to convert the same using advanced javascript concepts. Guide me to implement the same.</p> <p>Working Code : </p> <pre><code>$(document).ready(function() { var currentPosition = 0, slideWidth = 112, slides = $('#scroller ul li'), numberOfSlides = slides.length; scrollerContainer = $('#scroller ul'); $(scrollerContainer).css('width', slideWidth * numberOfSlides); manageControls(currentPosition); $('.control').click(function(){ currentPosition = ($(this).attr('id')=='rightControl') ? currentPosition+1 : currentPosition-1; manageControls(currentPosition); $(scrollerContainer).animate({ 'marginLeft' : slideWidth*(-(currentPosition*3)) }); }); function manageControls(position){ if(position==0){ $('#leftControl').hide() } else{ $('#leftControl').show() } if((position*3)==numberOfSlides-1 || (position*3)==numberOfSlides-3 || (position*3)==numberOfSlides-2) { $('#rightControl').hide() } else{ $('#rightControl').show() } } }); </code></pre> <p>Advanced Code Structure : Initial understanding</p> <pre><code>if(!scroller) { var scroller = {}; } scroller = { videos : { moveThumbnails : function() { }, gotonextThumbnails : function() { var obj = this; }, gotopreviousThumbnails : function() { var obj = this; }, init : function() { var obj = this; } }, init : function() { var obj = this; this.videos.init(); } } </code></pre> <p>Working example : <a href="http://jsfiddle.net/ylokesh/9EyEu/" rel="nofollow">http://jsfiddle.net/ylokesh/9EyEu/</a></p>
[ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-05-20T18:34:33.867", "Id": "19136", "Score": "2", "body": "I don't intend to troll, but do you have a definition of what's _advanced_ and what's not in JavaScript?" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-05-21T17:08:19.737", "Id": "19176", "Score": "0", "body": "@Tharabas at a beginner level, we used to write javascript where we marely use Object communication. Advanced javascript concpets like modular javascript so that later on same code can be converted to plugin easily. Just trying yo get my hands dirty with how object communicates and how we can achieve optimization." } ]
[ { "body": "<p>I can't post a full answer about the \"advanced JavaScript\" part of your question, but here's what I would change in the actual code:</p>\n\n<ul>\n<li><p><strong>Use <code>jQuery.fn.find</code> method</strong></p>\n\n<p>You could optimize this <code>$('#scroller ul li')</code> with this <code>$('#scroller').find('ul li')</code>. When using a selector like <code>#someidname</code>, jQuery can use directly the native method <code>document.getElementById</code>. When using <code>#someidname something</code>, then jQuery has to parse the selector, and only after this it can say \"oh there's an id string in there !\".</p></li>\n<li><p><strong>Don't recreate jQuery objects</strong></p>\n\n<p>When doing <code>var scrollerContainer = $('#scroller ul');</code>, <code>scrollerContainer</code> becomes a jQuery object. Then, you <strong>don't need</strong> to do <code>$(scrollerContainer).someMethodName()</code> but you could directly write <code>scrollerContainer.someMethodName()</code>.</p></li>\n<li><p><strong>Always use triple equals sign</strong></p>\n\n<p>You should (almost) always prefer <code>===</code> over <code>==</code>. The double equal sign may have some unexpected behavior such as <code>\"\\t \\n\" == 0</code> which evaluate to <code>true</code>.</p></li>\n<li><p><strong>Don't use jQuery when it's not needed</strong></p>\n\n<p><code>$(this).attr('id')</code> could be simplified in <code>this.id</code>. This way, you don't construct a new jQuery object (this can be costly when done in loops for example), and the <code>id</code> property is supported in a cross-browser way so you don't have to worry about it.</p></li>\n<li><p><strong>Cache your DOM selections</strong></p>\n\n<p><code>$('#leftControl')</code> and <code>$('#rightControl')</code> should be cached in variables in the same way as <code>$('#scroller ul')</code> is. We should avoid doing the same DOM query wherever it's possible.</p></li>\n<li><p><strong>Prefer <code>jQuery.fn.on</code> or <code>jQuery.fn.bind</code> methods over traditional ones</strong></p>\n\n<p>Because:</p>\n\n<ul>\n<li>they are <strong>faster</strong>: internally <code>$('whatever').click(fn)</code> calls <code>$('whatever').on('click', fn)</code>, so you can use it directly and avoid a function call,</li>\n<li>they are <strong>more flexible</strong>: you can bind the same function to <em>different events</em> (<code>$('whatever').on('click mouseenter mouseleave', fn)</code>), you can <em>namespace your events</em> (<code>$('whatever').on('click.myPlugin', fn)</code>) which IMO would be useful in your case (your doing some sort of namespacing)</li>\n</ul></li>\n<li><p><strong>Simplify (Math) expressions</strong></p>\n\n<p>IMO, the code <code>slideWidth*(-(currentPosition*3))</code> is not really readable. Why using such parenthesis ? And what about this inner <code>-</code> sign ?</p>\n\n<p>What about writing it this way <code>-slideWidth*currentPosition*3</code> ?</p>\n\n<p>Also, the part <code>(position*3)==numberOfSlides-1 || (position*3)==numberOfSlides-3 || (position*3)==numberOfSlides-2</code> can be simplified. Have a look (shorter variable names for the example):</p>\n\n<pre><code>(p*3)==n-1 || (p*3)==n-3 || (p*3)==n-2\n// which is equivalent to\n1==n-p*3 || 3==n-p*3 || 2==n-p*3\n// which is equivalent to\n1 &lt;= n-p*3 &amp;&amp; n-p*3 &lt;= 3\n// and also equivalent to\n(n-p*3-1) in [0,0,0]\n</code></pre>\n\n<p>so you end up with this:</p>\n\n<pre><code>if( (numberOfSlides-position*3-1) in [0,0,0] ) {\n ...\n}\n</code></pre>\n\n<p>That <code>(n-p*3-1) in [0,0,0]</code> part is quite interesting. When doing <code>a in b</code> you'll search if the array <code>b</code> has the index <code>a</code>. This only happens in our case because <code>b</code> <strong>is</strong> an array. So we use a array <code>b = [0,0,0]</code> which has 3 elements. <strong>3</strong> comes from the expression <code>n-p*3</code>, this is the maximum X of the three <code>n-p*X</code> forms seen above. Then, since <code>[0,0,0]</code> has 3 elements, its index are 0, 1, and 2. So the test if the expression <code>n-p*3</code> equals to one of 1, 2, or 3, we have to subtract <code>-1</code>.</p>\n\n<p>To explain it on another way, we can say that <code>0 in [0,0,0]</code>, <code>1 in [0,0,0]</code>, and <code>2 in [0,0,0]</code> will both be true (because we're using the array indexes and not its values), and all others numerical values will evaluate the expression to <code>false</code>. Since what you want you is to check if <code>n-p*3</code> is of one 1, 2 or 3, if we remove 1 to this expression, we retrieve our values 0, 1, and 2 from above which will evaluate the expression to <code>true</code>.</p>\n\n<p>If you think this one is too tricky (and to be honest, it is !), you can do the following, which avoid code repetition and where <strong>the intent is explicit and readable</strong> (I would recommend this technique over the <code>index i [0,0,0]</code> one which is implicit and less readable IMO)</p>\n\n<pre><code>var temp = numberOfSlides - position * 3;\nif( 1 &lt;= temp &amp;&amp; temp &lt;= 3 ) {\n ...\n}\n</code></pre></li>\n</ul>\n\n<p>Hope that helps :)</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-05-20T23:26:52.867", "Id": "19149", "Score": "0", "body": "Nice in on array of index trick." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-05-21T14:22:45.030", "Id": "19167", "Score": "2", "body": "The `in [0,0,0]` \"trick\" is terribly unreadable. I wouldn't recommend it." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-05-21T19:46:58.153", "Id": "19182", "Score": "0", "body": "I'd support @RoToRa here. The _trick_ will trick yourself after not having read that line of code for a while. Better extract the value and compare it in a more readable fashion like `var v = numberOfSlides - position * 3 - 1; if (v >= 0 && v <= 2) ...` as @pomeh recommended the line before the _trick_." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-05-21T19:54:09.217", "Id": "19183", "Score": "0", "body": "@RoToRa you're right. This is the kind of \"high level\" optimization, or the \"art\" to use JavaScript's leakiness to achieve a unexpected behavior. While I'm agree with you that this not readable and unclear (I've updated the answer to point it out), this **could** be the kind of trick used in \"high level\" optimization or \"high level\" of code compression, but that may represent a very low percentage or real-world applications ;) Anyway, I think this kind of JavaScript trick is funny, and that's why I've included it, but I would say **don't use it unless you really know what're doing** :)" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-05-22T06:28:31.367", "Id": "19202", "Score": "0", "body": "Maybe add use function binding instead of `var that = this`, etc? +1 for using `.on()` instead of `.click()`." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-05-22T16:35:21.290", "Id": "19218", "Score": "0", "body": "@Cobby how would you write the function binding here ?" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-05-23T23:32:50.237", "Id": "19261", "Score": "0", "body": "I'd probably use [underscore](http://underscorejs.org/), it has `_.bind()` and my personal favourite `_.bindAll()`." } ], "meta_data": { "CommentCount": "7", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-05-20T22:48:00.343", "Id": "11932", "ParentId": "11926", "Score": "4" } } ]
{ "AcceptedAnswerId": "11932", "CommentCount": "2", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-05-20T17:04:47.570", "Id": "11926", "Score": "1", "Tags": [ "javascript", "jquery" ], "Title": "basic javascript to advanced javascript" }
11926
<p>I wrote <code>QJson</code>, a utility class in/for Qt, I need you to take a look at. It is both a JSON parser and serializer, but with extended functionality (going beyond the <a href="http://json.org" rel="nofollow">JSON specification</a>) (see first section of this post).</p> <h2>Features</h2> <p>QJson uses QVariants for parsed values and QStrings for serialized JSON data.</p> <p>The <strong>parser</strong> not only understands the JSON language but optionally also this modificatons for "lazy" writers, providing the ability to write the data in a simpler way:</p> <ul> <li>Allow unquoted strings (e.g. <code>{foo: bar}</code> instead of <code>{"foo": "bar"}</code>. The end of a string is assumed when either a new-line, non-escaped colon, comma, <code>]</code> or <code>}</code> is following. The whole string is then trimmed. Strings starting with digits are not allowed. Escaping within the string is allowed, even <code>\</code> followed by <em>any</em> character is treated like the character itself (if it isn't a special escape sequence like <code>\n</code>). The keywords <code>true</code>, <code>false</code>, <code>null</code> are still parsed as a boolean / null values, not as strings.</li> <li>Allow arrays and objects with whitespaces instead of commas as their separator, also mixed (e.g. <code>{whitespaces only: [1 2 3], commas only: [1,2,3], mixed: [1, 2 3]}</code>.</li> <li>Allow any type for the whole JSON (JSON spec only allows objects and arrays as root values), even <em>empty</em> to simplify error handling.</li> <li>Parse errors are (optionally) reported in a human-readable output (e.g. <code>{foo: bar</code> => "Unexpected end of JSON input.", <code>[foo: bar]</code> => "Unexpected character at index 4").</li> </ul> <p>The <strong>serializer</strong> has the following features:</p> <ul> <li><p>Format output either compact or nice indented, e.g. compact: <code>[1,2,3,{"foo":"bar"}]</code> vs. indented:</p> <pre><code>[ 1, 2, 3, { "foo" : "bar" } ] </code></pre></li> <li><p>Treat unknown types either as an error (cancel serialization and return <code>""</code>) or encode them as <code>null</code>.</p></li> </ul> <p>The <strong>interface</strong> is similar to PHP's functions <code>json_encode</code>, <code>json_decode</code>:</p> <pre><code>QString QJson::encode(const QVariant &amp;data, (...) ); QVariant QJson::decode(const QString &amp;json, (...) ); </code></pre> <p>where the optional <code>(...)</code> can contain options to control the parser / serlaizer features from above and out-parameters for error reporting. For details see the code.</p> <hr> <h2>Possible improvements</h2> <p>For the following I'm looking for solutions / improvements / reviews:</p> <ul> <li><strong>Improving code style:</strong> The serializer understands both QVariantList and QStringList, which will be encoded in exactly the same way. So the codes look exactly the same, too. I want to put them in one <code>case</code>, but don't know how.</li> <li><strong>Testing:</strong> I don't have enough "evil" input to test my parser (and serializer, but this isn't that problematic, I think). Do you have some?</li> <li><strong>Additional feature:</strong> Provide an abstract <code>Serializable</code> interface / helper class for QObjects which can then be serialized and restored using QJson. Either use the properties of the QObject or use manual registration of attributes to the serializer engine, using macros for example: <code>JSON_OBJECT_ATTRIBUTE(foo);</code> => <code>registerJsonObjectAttribute(foo, "foo");</code>. The object is then serialized like <code>{"foo": ...}</code>.</li> </ul> <hr> <p><strong>qjson.h:</strong></p> <pre><code>#ifndef QJSON_H #define QJSON_H #include &lt;QString&gt; #include &lt;QVariant&gt; class QJson { Q_FLAGS(EncodeOption EncodeOptions) Q_FLAGS(DecodeOption DecodeOptions) public: enum EncodeOption { EncodeUnknownTypesAsNull = 0x01, Compact = 0x02 }; Q_DECLARE_FLAGS(EncodeOptions, EncodeOption) enum DecodeOption { DecodeObjectsAsHash = 0x01, AllowUnquotedStrings = 0x02, AllowMissingComma = 0x04, AllowLazyJSON = AllowUnquotedStrings | AllowMissingComma }; Q_DECLARE_FLAGS(DecodeOptions, DecodeOption) static QString encode(const QVariant &amp;data, QString *errorMessage = 0, int indentation = 4); static QString encode(const QVariant &amp;data, EncodeOptions options, QString *errorMessage = 0, int indentation = 4); static QVariant decode(const QString &amp;json, QString *errorMessage = 0); static QVariant decode(const QString &amp;json, DecodeOptions options, QString *errorMessage = 0); private: QJson(); static QString encodeData(const QVariant &amp;data, EncodeOptions options, QString *errorMessage, int indentation, QString currentLinePrefix); static QString encodeString(QString data); static QString encodeByteArray(QByteArray data); static QVariant parseValue(const QString &amp;json, int &amp;index, DecodeOptions options, bool &amp;success, QString *errorMessage); template&lt;typename ContainerType&gt; static QVariant parseObject(const QString &amp;json, int &amp;index, DecodeOptions options, bool &amp;success, QString *errorMessage); static QVariant parseArray(const QString &amp;json, int &amp;index, DecodeOptions options, bool &amp;success, QString *errorMessage); static QVariant parseString(const QString &amp;json, int &amp;index, bool &amp;success, QString *errorMessage); static QVariant parseUnquotedString(const QString &amp;json, int &amp;index, bool &amp;success, QString *errorMessage); static QVariant parseNumber(const QString &amp;json, int &amp;index, bool &amp;success, QString *errorMessage); static QVariant parseBool(const QString &amp;json, int &amp;index, bool &amp;success, QString *errorMessage); static QVariant parseNull(const QString &amp;json, int &amp;index, bool &amp;success, QString *errorMessage); static int skipWhitespace(const QString &amp;json, int &amp;index); static bool checkAvailable(const QString &amp;json, int &amp;index, bool &amp;success, QString *errorMessage, int minAvailable = 1); static bool checkToken(const QString &amp;json, int &amp;index, bool &amp;success, QString *errorMessage, QString token); }; #endif // QJSON_H </code></pre> <p><strong>qjson.cpp:</strong></p> <pre><code>#include "qjson.h" #include &lt;QStringList&gt; QJson::QJson() { } /* ----------------------------------------------------------------------------------------------------------------- */ // ENCODER / SERIALIZER /* ----------------------------------------------------------------------------------------------------------------- */ QString QJson::encode(const QVariant &amp;data, QString *errorMessage, int indentation) { return encodeData(data, EncodeOptions(), errorMessage, indentation, QString()); } QString QJson::encode(const QVariant &amp;data, EncodeOptions options, QString *errorMessage, int indentation) { return encodeData(data, options, errorMessage, indentation, QString()); } QString QJson::encodeData(const QVariant &amp;data, EncodeOptions options, QString *errorMessage, int indentation, QString currentLinePrefix) { QString indentedLinePrefix = options.testFlag(Compact) ? QString::fromAscii("") : (currentLinePrefix + QString::fromAscii(" ").repeated(indentation)); QString optionalNewLine = options.testFlag(Compact) ? QString::fromAscii("") : (QString::fromAscii("\n") + currentLinePrefix); QString optionalIndentedNewLine = options.testFlag(Compact) ? QString::fromAscii("") : (QString::fromAscii("\n") + indentedLinePrefix); QString encoded; switch(data.type()) { case(QVariant::Bool): encoded += QString::fromAscii(data.toBool() ? "true" : "false"); break; case(QVariant::Int): case(QVariant::UInt): case(QVariant::LongLong): case(QVariant::ULongLong): Q_ASSERT(data.canConvert(QVariant::String)); encoded = data.toString(); break; case(QVariant::Double): encoded = QString::number(data.toDouble(), 'g', 16); if(!encoded.contains(QString::fromAscii(".")) &amp;&amp; !encoded.contains(QString::fromAscii("e"))) encoded += ".0"; break; case(QVariant::String): encoded = encodeString(data.toString()); break; case(QVariant::ByteArray): encoded = encodeByteArray(data.toByteArray()); break; case(QVariant::List): { encoded = QString::fromAscii("[") + optionalIndentedNewLine; QVariantList list = data.toList(); for(int i = 0; i &lt; list.count(); ++i) { if(i) encoded += QString::fromAscii(",") + optionalIndentedNewLine; encoded += encodeData(list.at(i), options, errorMessage, indentation, indentedLinePrefix); if(errorMessage &amp;&amp; !errorMessage-&gt;isNull()) return QString(); } encoded += optionalNewLine + QString::fromAscii("]"); } break; case(QVariant::StringList): { encoded = QString::fromAscii("[") + optionalIndentedNewLine; QStringList list = data.toStringList(); for(int i = 0; i &lt; list.count(); ++i) { if(i) encoded += QString::fromAscii(",") + optionalIndentedNewLine; encoded += encodeData(list.at(i), options, errorMessage, indentation, indentedLinePrefix); if(errorMessage &amp;&amp; !errorMessage-&gt;isNull()) return QString(); } encoded += optionalNewLine + QString::fromAscii("]"); } break; case(QVariant::Map): { encoded = QString::fromAscii("{") + optionalIndentedNewLine; QVariantMap map = data.toMap(); QVariantMap::iterator i; bool first = true; for (i = map.begin(); i != map.end(); ++i) { if(!first) encoded += QString::fromAscii(",") + optionalIndentedNewLine; first = false; encoded += encodeString(i.key()); encoded += options.testFlag(Compact) ? QString::fromAscii(":") : QString::fromAscii(" : "); encoded += encodeData(i.value(), options, errorMessage, indentation, indentedLinePrefix); if(errorMessage &amp;&amp; !errorMessage-&gt;isNull()) return QString(); } encoded += optionalNewLine + QString::fromAscii("}"); } break; case(QVariant::Hash): { encoded = QString::fromAscii("{") + optionalIndentedNewLine; QVariantHash hash = data.toHash(); QVariantHash::iterator i; bool first = true; for (i = hash.begin(); i != hash.end(); ++i) { if(!first) encoded += QString::fromAscii(",") + optionalIndentedNewLine; first = false; encoded += encodeString(i.key()); encoded += options.testFlag(Compact) ? QString::fromAscii(":") : QString::fromAscii(" : "); encoded += encodeData(i.value(), options, errorMessage, indentation, indentedLinePrefix); if(errorMessage &amp;&amp; !errorMessage-&gt;isNull()) return QString(); } encoded += optionalNewLine + QString::fromAscii("}"); } break; case(QVariant::Invalid): encoded = QString::fromAscii("null"); break; default: if(!options.testFlag(EncodeUnknownTypesAsNull)) { if(errorMessage) *errorMessage = QString::fromAscii("Can't encode this type of data to JSON: %1") .arg(data.typeName()); return QString(); } encoded = QString::fromAscii("null"); break; } return encoded; } QString QJson::encodeString(QString data) { QString encoded; encoded.append(QChar::fromAscii('"')); for(int i = 0; i &lt; data.length(); ++i) { QChar ch = data.at(i); // printable ASCII character? if(ch.unicode() &gt;= 32 &amp;&amp; ch.unicode() &lt; 128) encoded.append(ch); else { switch(ch.unicode()) { case(8): encoded.append(QString::fromAscii("\\b")); break; case(9): encoded.append(QString::fromAscii("\\t")); break; case(10): encoded.append(QString::fromAscii("\\n")); break; case(12): encoded.append(QString::fromAscii("\\f")); break; case(13): encoded.append(QString::fromAscii("\\r")); break; case('"'): encoded.append(QString::fromAscii("\\\"")); break; case('\\'): encoded.append(QString::fromAscii("\\\\")); break; case('/'): encoded.append(QString::fromAscii("\\/")); break; default: encoded.append(QString::fromAscii("\\u") + QString::number(ch.unicode(), 16) .rightJustified(4, QChar::fromAscii('0'))); } } } encoded.append(QChar::fromAscii('"')); return encoded; } QString QJson::encodeByteArray(QByteArray data) { return encodeString(QString::fromLocal8Bit(data)); } /* ----------------------------------------------------------------------------------------------------------------- */ // DECODER / PARSER /* ----------------------------------------------------------------------------------------------------------------- */ QVariant QJson::decode(const QString &amp;json, QString *errorMessage) { return decode(json, DecodeOptions(), errorMessage); } QVariant QJson::decode(const QString &amp;json, DecodeOptions options, QString *errorMessage) { //there are currently no options defined Q_UNUSED(options); bool success = true; if(!json.isNull() &amp;&amp; !json.isEmpty()) { int index = 0; return parseValue(json, index, options, success, errorMessage); } else // To simplify things, this is not treated as an error but as valid input. return QVariant(); } QVariant QJson::parseValue(const QString &amp;json, int &amp;index, DecodeOptions options, bool &amp;success, QString *errorMessage) { skipWhitespace(json, index); if(!checkAvailable(json, index, success, errorMessage)) { success = false; if(errorMessage) *errorMessage = QString("Expected more input at position %1").arg(index); return QVariant(); } switch(json[index].toAscii()) { case '"': return QJson::parseString(json, index, success, errorMessage); case '{': if(options &amp; DecodeObjectsAsHash) return QJson::parseObject&lt;QVariantHash&gt;(json, index, options, success, errorMessage); else return QJson::parseObject&lt;QVariantMap&gt;(json, index, options, success, errorMessage); case '[': return QJson::parseArray(json, index, options, success, errorMessage); case 't': case 'f': if(options &amp; AllowUnquotedStrings) return QJson::parseUnquotedString(json, index, success, errorMessage); else return QJson::parseBool(json, index, success, errorMessage); case 'n': if(options &amp; AllowUnquotedStrings) return QJson::parseUnquotedString(json, index, success, errorMessage); else return QJson::parseNull(json, index, success, errorMessage); case '0': case '1': case '2': case '3': case '4': case '5': case '6': case '7': case '8': case '9': case '-': return QJson::parseNumber(json, index, success, errorMessage); default: if(options &amp; AllowUnquotedStrings) return QJson::parseUnquotedString(json, index, success, errorMessage); else { success = false; if(errorMessage) *errorMessage = QString("Unexpected character at position %1").arg(index); return QVariant(); } } } template&lt;typename ContainerType&gt; QVariant QJson::parseObject(const QString &amp;json, int &amp;index, DecodeOptions options, bool &amp;success, QString *errorMessage) { Q_ASSERT(json[index] == '{'); index++; skipWhitespace(json, index); ContainerType object; while(checkAvailable(json, index, success, errorMessage)) { if(json[index] == QChar::fromAscii('}')) { index++; return object; } else { QString key = QJson::parseValue(json, index, options, success, errorMessage).toString(); if(!success) return QVariant(); skipWhitespace(json, index); checkAvailable(json, index, success, errorMessage); if(json[index] == QChar::fromAscii(':')) index++; else { success = false; if(errorMessage) *errorMessage = QString("Expected colon at position %1").arg(index); return QVariant(); } skipWhitespace(json, index); QVariant value = QJson::parseValue(json, index, options, success, errorMessage); if(!success) return QVariant(); // Add the key / value pair to the object object.insert(key, value); int skippedWhitespaces = skipWhitespace(json, index); checkAvailable(json, index, success, errorMessage); switch(json[index].toAscii()) { case ',': index++; skipWhitespace(json, index); break; case '}': //'}' will be processed in the next iteration break; default: // Only allow missing comma if there is at least one whitespace instead of the comma! if((options &amp; AllowMissingComma) &amp;&amp; skippedWhitespaces &gt; 0) break; else { success = false; if(errorMessage) *errorMessage = QString("Unexpected character at index %1").arg(index); return QVariant(); } } } } return QVariant(); } QVariant QJson::parseArray(const QString &amp;json, int &amp;index, DecodeOptions options, bool &amp;success, QString *errorMessage) { Q_ASSERT(json[index] == '['); index++; skipWhitespace(json, index); QVariantList array; while(checkAvailable(json, index, success, errorMessage)) { if(json[index] == QChar::fromAscii(']')) { index++; return array; } else { QVariant value = QJson::parseValue(json, index, options, success, errorMessage); if(!success) return QVariant(); // Add the value pair to the array array.append(value); int skippedWhitespaces = skipWhitespace(json, index); checkAvailable(json, index, success, errorMessage); switch(json[index].toAscii()) { case ',': index++; skipWhitespace(json, index); break; case ']': //']' will be processed in the next iteration break; default: // Only allow missing comma if there is at least one whitespace instead of the comma! if((options &amp; AllowMissingComma) &amp;&amp; skippedWhitespaces &gt; 0) break; else { success = false; if(errorMessage) *errorMessage = QString("Unexpected character at index %1").arg(index); return QVariant(); } } } } return QVariant(); } QVariant QJson::parseString(const QString &amp;json, int &amp;index, bool &amp;success, QString *errorMessage) { Q_ASSERT(json[index] == '"'); index++; QString string; QChar ch; while(checkAvailable(json, index, success, errorMessage)) { ch = json[index++]; switch(ch.toAscii()) { case '\\': // Escaped character if(!checkAvailable(json, index, success, errorMessage)) return QVariant(); ch = json[index++]; switch(ch.toAscii()) { case 'b': string.append('\b'); break; case 'f': string.append('\f'); break; case 'n': string.append('\n'); break; case 'r': string.append('\r'); break; case 't': string.append('\t'); break; case 'u': if(!checkAvailable(json, index, success, errorMessage, 4)) return QVariant(); string.append(QChar(json.mid(index, 4).toInt(0, 16))); index += 4; break; default: string.append(ch); } break; case '"': // End of string return QVariant(string); default: string.append(ch); } } return QVariant(); } QVariant QJson::parseUnquotedString(const QString &amp;json, int &amp;index, bool &amp;success, QString *errorMessage) { QString string; QChar ch; bool end = false; while(!end &amp;&amp; checkAvailable(json, index, success, errorMessage)) { ch = json[index++]; switch(ch.toAscii()) { case '\\': // Escaped character if(!checkAvailable(json, index, success, errorMessage)) return QVariant(); ch = json[index++]; switch(ch.toAscii()) { case 'b': string.append('\b'); break; case 'f': string.append('\f'); break; case 'n': string.append('\n'); break; case 'r': string.append('\r'); break; case 't': string.append('\t'); break; case 'u': if(!checkAvailable(json, index, success, errorMessage, 4)) return QVariant(); string.append(QChar(json.mid(index, 4).toInt(0, 16))); index += 4; break; default: string.append(ch); } break; case ':': case ',': case ']': case '}': case '\n': // End of string (was one character before this!) end = true; index--; break; default: string.append(ch); } } //trim string string = string.trimmed(); //handle keywords if(string == "true") return QVariant(true); if(string == "false") return QVariant(false); if(string == "null") return QVariant(); return QVariant(string); } QVariant QJson::parseNumber(const QString &amp;json, int &amp;index, bool &amp;success, QString *errorMessage) { int end = index; bool endFound = false; while(!endFound &amp;&amp; end &lt; json.length()) { switch(json[end].toAscii()) { case '0': case '1': case '2': case '3': case '4': case '5': case '6': case '7': case '8': case '9': case '.': case 'e': case 'E': case '+': case '-': end++; break; default: endFound = true; break; } } QString numberStr = json.mid(index, end - index); index = end; QVariant result; bool ok; // is floating point number? if(numberStr.contains(QChar::fromAscii('.')) || numberStr.contains(QChar::fromAscii('e')) || numberStr.contains(QChar::fromAscii('E'))) result = QVariant(numberStr.toDouble(&amp;ok)); else result = QVariant(numberStr.toLongLong(&amp;ok)); if(ok) return result; else { success = false; if(errorMessage) *errorMessage = QString("Can't parse number at position %1: %2").arg(index).arg(numberStr); return QVariant(); } } int QJson::skipWhitespace(const QString &amp;json, int &amp;index) { int skipped = 0; while(index &lt; json.size()) { switch(json[index].toAscii()) { case ' ': case '\t': case '\n': case '\r': index++; skipped++; break; default: return skipped; } } return skipped; } QVariant QJson::parseBool(const QString &amp;json, int &amp;index, bool &amp;success, QString *errorMessage) { if(checkToken(json, index, success, errorMessage, "true")) { index += 4; return QVariant(true); } else if(checkToken(json, index, success, errorMessage, "false")) { index += 5; return QVariant(false); } else { success = false; if(errorMessage) *errorMessage = QString("Can't parse value at position %1").arg(index); return QVariant(); } } QVariant QJson::parseNull(const QString &amp;json, int &amp;index, bool &amp;success, QString *errorMessage) { if(checkToken(json, index, success, errorMessage, "null")) { index += 4; return QVariant(true); } else { success = false; if(errorMessage) *errorMessage = QString("Can't parse value at position %1").arg(index); return QVariant(); } } bool QJson::checkAvailable(const QString &amp;json, int &amp;index, bool &amp;success, QString *errorMessage, int minAvailable) { if(index + minAvailable &gt; json.length()) { success = false; if(errorMessage) *errorMessage = QString("Unexpected end of JSON input."); return false; } else return true; } bool QJson::checkToken(const QString &amp;json, int &amp;index, bool &amp;success, QString *errorMessage, QString token) { return checkAvailable(json, index, success, errorMessage, token.length()) &amp;&amp; json.mid(index, token.length()) == token; } </code></pre>
[]
[ { "body": "<h2>In general</h2>\n<p>I like that you didn't try and force OO on something that works very well without it, but it would be simpler, cleaner if you were to just put all those functions in a namespace instead of a class (IIRC the metadata-generating macros for enums work outside classes, too). you can use global static functions or anonymous namespaces in your .cpp file for the private stuff. And also, it is very nice that you don't try to handle I/O and some other stuff that library writers are so keen on doing. SRP all the way, it's great :)</p>\n<h2>Error handling</h2>\n<p>There is one thing I don't particularly like about your code:</p>\n<pre><code>QString *errorMessage\n</code></pre>\n<p>I can tell by your coding style that you try to follow the Qt coding guidelines, which is fantastic for a Qt library, but this kind of error handling is not particularly useful. You should stick to the <code>qWarning</code>/<code>qDebug</code> etc. kind of error reporting, since Q_ASSERT does that anyway (they can be redirected from external code, without modifying your library if your user wants to). Or even: use exceptions - Qt is huge, so avoiding exceptions does result in a great size reduction for them, but your little library would not suffer that much. The problem with the current approach is that it limits the caller to one way of handling the error: presenting the (by the way <strong>not localized</strong>) string to the user.</p>\n<h2>Possible improvements</h2>\n<p>There is some unneeded duplication, for example <code>parseString</code> and <code>parseUnquotedString</code> looks quite similar, and I noticed other parts, too.</p>\n<p>Consistency in style: it's pretty good, and again, props for sticking to the Qt guidleines. One thing I noticed though, is that you use parentheses around case labels (which is alright, if somewhat alien to me personally), but you forget it in some places.</p>\n<h2>Other</h2>\n<blockquote>\n<p>The serializer understands both QVariantList and QStringList, which\nwill be encoded in exactly the same way. So the codes look exactly the\nsame, too. I want to put them in one case, but don't know how.</p>\n</blockquote>\n<p>Simple (if I understood your intention correctly):</p>\n<pre><code>case(QVariant::List):\ncase(QVariant::StringList):\n {\n encoded = QString::fromAscii(&quot;[&quot;) + optionalIndentedNewLine;\n QStringList list = data.toStringList();\n for(int i = 0; i &lt; list.count(); ++i)\n {\n if(i) encoded += QString::fromAscii(&quot;,&quot;) + optionalIndentedNewLine;\n encoded += encodeData(list.at(i), options, errorMessage, indentation, indentedLinePrefix);\n if(errorMessage &amp;&amp; !errorMessage-&gt;isNull())\n return QString();\n }\n encoded += optionalNewLine + QString::fromAscii(&quot;]&quot;);\n }\n break;\n</code></pre>\n<h2>Additional features</h2>\n<p>I think the QObject-serialization is already possible with QScriptEngine (although you can probably implement it smaller). One thing I would love to see is an implementation of <a href=\"https://datatracker.ietf.org/doc/html/draft-zyp-json-schema-03\" rel=\"nofollow noreferrer\">json-schema</a>. It is still a draft, but there are already some implementations out there (you can google them). It adds validation capability to JSON (probably not as powerful as XML schemas and DTD, but it's something).</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-05-20T19:49:27.457", "Id": "19138", "Score": "0", "body": "Error handling: Q_ASSERT is for internal asserts (things my code really asserts != input should be like). I tried to follow Qt's way to handle *conversion* errors; see: `QString::toInt(int base, bool *ok = 0)`. What do you mean by \"not localized string\"? That I don't present where the error occured? --- Parentheses around cases: I do so when I define new variables (compiler warning if I omitted {}). --- Code for QStringList + QVariantList: your version is wrong, since QStringLists contain strings (`encodeData(QString)`) and QVariantList contain variants (`encodeData(QVariant)` in case line 6)." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-05-20T19:54:08.493", "Id": "19139", "Score": "0", "body": "(continuation of previous comment) --- Code duplication `parseString` + `parseUnquotedString`: The problem is, that some parts of the code differ from each other, for example the exit condition and escaping (in JSON strings, one can't escape *any* character, e.g. `\\:`, which I allow in unquoted strings since `:` would terminate the string). --- Namespace vs. utility class: Thanks, I'm not very familiar with namespaces; I use them very rarely. So I just didn't see that it's a nice alternative to a utility class. --- Json-scheme: maybe :) --- Summarizing, thank you for your review & comments!" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-05-20T20:21:48.323", "Id": "19141", "Score": "0", "body": "By \"not localized\" I mean that if I were to use your library in an application that supports multiple languages I would have a hard time using the messages provided this way. Parentheses: I did mean parentheses, not curly braces. See `case('\"'):` vs. `case '\"':`. To solve the code duplication, you should extract the common parts and call it from both, then deal with the differences in each one." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-05-20T20:25:20.127", "Id": "19142", "Score": "0", "body": "Also, I'm familiar with that way of error handling all around Qt, but it does not work well with strings. It would be better if you could use an enum for error codes in a similar fashion. Regarding assert, I was just pointing out that it will report the error in qDebug(), so it would not be the same as your other way of reporting errors." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-05-20T20:32:13.720", "Id": "19143", "Score": "0", "body": "Thanks for the hint with enum errors. That should solve the localisation problem. Misunderstanding with the parenthesis thing in case labels; I will change that. I only use asserts where I am sure that the assersion has to be true, even for *wrong* inputs. I never use assertions to check user input. That's what I tried to make clear by saying \"things my code really asserts != input should be like\". Regarding code duplicates: The problem is that the code parts look like the same (same code) but are different (different types / overloads of the same method). I maybe could use macros..." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-05-20T21:59:26.367", "Id": "19144", "Score": "0", "body": "I think you can keep your sanity with a function template there :)" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-05-20T22:07:48.083", "Id": "19145", "Score": "0", "body": "Thank you for this. While writing the template, I noticed that distinguishing between `QVariant::List` and `QVariant::StringList` isn't needed at all, since `QVariant::StringList` gets converted to QVariantList when doing `toList()`. ;) But I now try to merge the codes for maps and hashes." } ], "meta_data": { "CommentCount": "7", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-05-20T19:39:01.717", "Id": "11931", "ParentId": "11927", "Score": "4" } }, { "body": "<h3>Extensions to the standard.</h3>\n<p>I know you mean well with the additional features.</p>\n<ul>\n<li>Allow unquoted strings (e.g. {foo: bar} instead of {&quot;foo&quot;: &quot;bar&quot;}.</li>\n<li>Allow arrays and objects with whitespaces instead of commas as their separator</li>\n<li>Allow any type for the whole JSON</li>\n</ul>\n<p>But these to me are just bugs. Stick to the standard otherwise your code will not spot bugs that the standard was designed to explicitly prevent.</p>\n<p>We had similar home grown json parser at work (that we had to eventually throw out) because it led to so many other problems along the way. Extending the standard (because you think it is not required as a bad way to go in coding).</p>\n<h3>Design:</h3>\n<p>You are converting from a QString into a JSON DOM (and vice versa). In C++ I would have expected you to convert to from a stream.</p>\n<p>I find the use of QString quite limiting as I must convert all sources into a string first before use. This feels very error prone as I must convert the incoming stream to UTF-16 (the type held by the QChar character). Not a horrendous task but one that you must remember to do (designing software is about designing it so that it <strong>can not be used incorrectly</strong>).</p>\n<h3>Character encoding</h3>\n<p>QChar is UTF-16. But in a lot of places in your code you are converting to ascii() before appending to the QString. This is distracting and seems like an unnecessary round trip. Just add UTF-16 characters to the string.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-05-21T20:20:17.437", "Id": "19184", "Score": "0", "body": "The extensions are optional. You need to explicitly enable them when using QJson. When you use QJson::parse without any arguments but the json string, it behaves (at least it *should*) with respect to the specification. Thanks for the feedback about character encoding. Maybe I add an interface for binary <-> JSON conversion and use binary data internally." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-05-21T20:22:40.103", "Id": "19185", "Score": "0", "body": "Note: The JSON RFC explicitly states that all JSON is from Unicode files (no other formats are supported). So there should be no need to transcode. But you do need to support UTF-8/UTF-16/UTF-32 encoding." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-05-21T20:29:11.920", "Id": "19186", "Score": "0", "body": "When I translate my code to use binary data internally instead of QStrings, should I assume that the input is UTF-8 encoded? And another question about encoding: Is it possible to encode real-binary data in JSON? I currently use `encodeString(QString::fromLocal8Bit(data))` to encode QByteArrays. If `data` hasn't to be UTF-8 encoded binary data, I can't do `QString::fromUtf8(data)` or treat it like an already encoded string. I hope you understand, I'm a bit confused about my own question right now :D" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-05-21T20:41:16.473", "Id": "19187", "Score": "0", "body": "See my last comment." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-05-21T20:53:49.360", "Id": "19188", "Score": "0", "body": "\"But you do need to support UTF-8/UTF-16/UTF-32 encoding\" => Do I really need to detect this by my own? I guess QString is far more straightforward in this circumstance." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-05-21T21:06:10.920", "Id": "19189", "Score": "0", "body": "At the point it is in QString it should already be in UTF-16 (as QT says that QChar is UTF-16 encoded). The problem for users of your library is that **they** must make sure that reading a stream correctly decodes to UTF-16." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-05-21T21:19:30.717", "Id": "19190", "Score": "0", "body": "Ok, I just saw that the UTF-X detection isn't that hard. I may consider implementing it, but as I currently only need to support UTF-8 encoded QByteArrays or QStrings, this is at the bottom of my wish-list. But thanks a lot for making this problem clear. ;)" } ], "meta_data": { "CommentCount": "7", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-05-21T19:49:26.087", "Id": "11954", "ParentId": "11927", "Score": "2" } } ]
{ "AcceptedAnswerId": "11931", "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-05-20T17:17:04.790", "Id": "11927", "Score": "6", "Tags": [ "c++", "parsing", "json", "qt" ], "Title": "Yet another JSON parser and serializer for Qt, but with additional features" }
11927
<p>Quite some time ago I started this question: <a href="https://codereview.stackexchange.com/questions/5856/looking-for-more-knowledge-on-how-to-make-my-c-vector2-class-better">Mathematical Vector2 class implementation</a> and have since improved on it. I've been using it and it seems to work fine, but I'm always looking for ways to improve on code. I also have a question, should I force inline for all my operator overloads or should i just leave them as inline and hope they inline?</p> <p>Edit 1: Ok, so I don't need inline it looks like. Also I see the benefit of related operations now and have changed my operations and functions to reflect that principle. Did not know that the compiler had better routines for handling assignment operators (though the more I think about it the more it makes sense).</p> <p>I don't think its a vary good idea to rid my code of const return types, and here is the reason why.</p> <pre><code>//this operator format Vector2 Vector2::operator + (Vector2 const &amp; v) const { Vector2 r(*this); return r +=v; } //allows this (v1 + v2) = v3 //tested it to be safe //this operator format const Vector2 Vector2::operator + (const Vector2 &amp; v) const { Vector2 r(*this); return r += v; } //does not allow this (v1 + v2) = v3 //also tested //this made me realize that, in fact, these are valid as well Vector2::Add(v1, v2) = v3; Vector2::Max(v1, v2) = v3; //But not this Vector2::Dot(v1, v2) = fval; //to be on the safe side I changed some more functions return to const //when I change them to const its true, the qualifer gets thrown out //but only after the assignment, which is what I want. </code></pre> <p>Your advice was extremely helpful. Thank you Loki!</p> <p>Edit 2: Fixed bad operator> code.</p> <p>fogbit pointed out that I needed to check for division by zero in my Normalize method. But doesn't checking that 'len &lt; FLT_EPSILON' prevent such mishap already?</p> <p>Second Edit: dsrVector2.hpp</p> <pre><code>//namespace namespace dsr { //vector2 class Vector2 { public: //members float32 x, y; //ctor Vector2(float32 xVal = 0.0, float32 yVal = 0.0); //methods float32 LengthSq() const; float32 Length() const; const Vector2 &amp; Skew(); const Vector2 &amp; Normalize(); //assingment operators Vector2 &amp; Vector2::operator = (const Vector2 &amp; v) { x = v.x; y = v.y; return *this; } Vector2 &amp; Vector2::operator = (const float32 &amp; s) { x = s; y = s; return *this; } Vector2 &amp; Vector2::operator - (void) { x = -x; y = -y; return *this; } //equality operators bool Vector2::operator == (const Vector2 &amp; v) const { return (x == v.x) &amp;&amp; (y == v.y); } bool Vector2::operator != (const Vector2 &amp; v) const { return !(*this == v); } //comparison operators bool Vector2::operator &lt; (const Vector2 &amp; v) const { return (x &lt; v.x) || ((x == v.x) &amp;&amp; (y &lt; v.y)); } bool Vector2::operator &gt; (const Vector2 &amp; v) const { return !(*this &lt; v) &amp;&amp; !(*this == v); } //vector2 to this operators Vector2 &amp; Vector2::operator += (const Vector2 &amp; v) { x += v.x; y += v.y; return *this; } Vector2 &amp; Vector2::operator -= (const Vector2 &amp; v) { x -= v.x; y -= v.y; return *this; } Vector2 &amp; Vector2::operator *= (const Vector2 &amp; v) { x *= v.x; y *= v.y; return *this; } Vector2 &amp; Vector2::operator /= (const Vector2 &amp; v) { x /= v.x; y /= v.y; return *this; } //vector2 to vector2 operators const Vector2 Vector2::operator + (const Vector2 &amp; v) const { Vector2 r(*this); return r += v; } const Vector2 Vector2::operator - (const Vector2 &amp; v) const { Vector2 r(*this); return r -= v; } const Vector2 Vector2::operator * (const Vector2 &amp; v) const { Vector2 r(*this); return r *= v; } const Vector2 Vector2::operator / (const Vector2 &amp; v) const { Vector2 r(*this); return r /= v; } //scaler to this operators Vector2 &amp; Vector2::operator += (float32 s) { x += s; y += s; return *this; } Vector2 &amp; Vector2::operator -= (float32 s) { x -= s; y -= s; return *this; } Vector2 &amp; Vector2::operator *= (float32 s) { x *= s; y *= s; return *this; } Vector2 &amp; Vector2::operator /= (float32 s) { x /= s; y /= s; return *this; } //scaler to vector2 operators const Vector2 Vector2::operator + (float32 s) const { Vector2 r(*this); return r += s; } const Vector2 Vector2::operator - (float32 s) const { Vector2 r(*this); return r -= s; } const Vector2 Vector2::operator * (float32 s) const { Vector2 r(*this); return r *= s; } const Vector2 Vector2::operator / (float32 s) const { Vector2 r(*this); return r /= s; } //static arithmetic static const Vector2 Add (const Vector2 &amp; v1, const Vector2 &amp; v2) { return v1 + v2; } static const Vector2 Sub (const Vector2 &amp; v1, const Vector2 &amp; v2) { return v1 - v2; } static const Vector2 Mul (const Vector2 &amp; v1, const Vector2 &amp; v2) { return v1 * v2; } static const Vector2 Div (const Vector2 &amp; v1, const Vector2 &amp; v2) { return v1 / v2; } //static methods static float32 DistanceSq (const Vector2 &amp; v1, const Vector2 &amp; v2) { return ((v1.x - v2.x) * (v1.x - v2.x)) + ((v1.y - v2.y) * (v1.y - v2.y)); } static float32 Distance (const Vector2 &amp; v1, const Vector2 &amp; v2) { return sqrt(DistanceSq(v1, v2)); } static float32 Dot (const Vector2 &amp; v1, const Vector2 &amp; v2) { return ((v1.x * v2.x) + (v1.y * v2.y)); } static const Vector2 Min (const Vector2 &amp; v1, const Vector2 &amp; v2) { return Vector2(v1.x &lt; v2.x ? v1.x : v2.x, v1.y &lt; v2.y ? v1.y : v2.y); } static const Vector2 Max (const Vector2 &amp; v1, const Vector2 &amp; v2) { return Vector2(v1.x &gt; v2.x ? v1.x : v2.x, v1.y &gt; v2.y ? v1.y : v2.y); } static const Vector2 Clamp (const Vector2 &amp; v, const Vector2 &amp; min, const Vector2 &amp; max) { return Min(Max(v, min), max); /*because lifes too short*/ } //friend operators friend std::ostream &amp; Vector2::operator &lt;&lt; (std::ostream &amp; os, const Vector2 &amp; v) { return os &lt;&lt; "{" &lt;&lt; v.x &lt;&lt; ", " &lt;&lt; v.y &lt;&lt; "}"; } }; //end vector2 //prototype void TestVector2(); }//end namespace </code></pre> <p>Second Edit: dsrVector2.cpp</p> <pre><code>//namespace namespace dsr { //vector2 ctor Vector2::Vector2(float32 xVal, float32 yVal) : x(xVal), y(yVal) { } //vector2 methods float32 Vector2::LengthSq() const { return x * x + y * y; } float32 Vector2::Length() const { return sqrt(LengthSq()); } const Vector2 &amp; Vector2::Skew() { x -= y; y += x; x -= y; return *this; } const Vector2 &amp; Vector2::Normalize() { float32 len = Length(); if(len &lt; FLT_EPSILON) { x = y = 0; return *this; } else { float32 invLen = 1.0f / len; x *= invLen; y *= invLen; return *this; } } //test vector2 void TestVector2() { //using using std::cout; using std::endl; //locals Vector2 v1 = Vector2(20, 20); Vector2 v2 = Vector2(10, 10); Vector2 v3 = Vector2(); //test cout &lt;&lt; "-&gt; Vector2 Class Testing" &lt;&lt; endl &lt;&lt; endl; //value cout &lt;&lt; "-&gt; Testing Vector2 Starting Values" &lt;&lt; endl; cout &lt;&lt; "v1 = " &lt;&lt; v1 &lt;&lt; endl; cout &lt;&lt; "v2 = " &lt;&lt; v2 &lt;&lt; endl; cout &lt;&lt; "v3 = " &lt;&lt; v3 &lt;&lt; endl; cout &lt;&lt; endl; //vector2 arithmetic cout &lt;&lt; "-&gt; Testing Vector2 Arithmetic" &lt;&lt; endl; cout &lt;&lt; "v1 + v2 = " &lt;&lt; v1 + v2 &lt;&lt; endl; cout &lt;&lt; "v1 - v2 = " &lt;&lt; v1 - v2 &lt;&lt; endl; cout &lt;&lt; "v1 * v2 = " &lt;&lt; v1 * v2 &lt;&lt; endl; cout &lt;&lt; "v1 / v2 = " &lt;&lt; v1 / v2 &lt;&lt; endl; cout &lt;&lt; endl; //vector2 assingment arithmetic cout &lt;&lt; "-&gt; Testing Vector2 Arithmetic to Assingment" &lt;&lt; endl; v3 += v1; cout &lt;&lt; "v3 += v1; v3 = " &lt;&lt; v3 &lt;&lt; endl; v3 -= v2; cout &lt;&lt; "v3 -= v2; v3 = " &lt;&lt; v3 &lt;&lt; endl; v3 *= v1; cout &lt;&lt; "v3 *= v1; v3 = " &lt;&lt; v3 &lt;&lt; endl; v3 /= v2; cout &lt;&lt; "v3 /= v2; v3 = " &lt;&lt; v3 &lt;&lt; endl; cout &lt;&lt; endl; //vector2 assingment cout &lt;&lt; "-&gt; Testing Vector2 Assingment" &lt;&lt; endl; v3 = v2; cout &lt;&lt; "v3 = v2; v3 = " &lt;&lt; v3 &lt;&lt; "; v2 = " &lt;&lt; v2 &lt;&lt; endl; cout &lt;&lt; "-(v3) = " &lt;&lt; -v3 &lt;&lt; endl; v3 = 0; cout &lt;&lt; "v3 = 0; v3 = " &lt;&lt; v3 &lt;&lt; endl; cout &lt;&lt; endl; //vector2 comparison cout &lt;&lt; "-&gt; Testing Vector2 Comparison" &lt;&lt; endl; if(!(v1 == v2)) { cout &lt;&lt; "v1 == v2 is False" &lt;&lt; endl; } if(v1 != v2) { cout &lt;&lt; "v1 != v2 is True" &lt;&lt; endl; } if(!(v1 &lt; v2)) { cout &lt;&lt; "v1 &lt; v2 is False" &lt;&lt; endl; } if(v1 &gt; v2) { cout &lt;&lt; "v1 &gt; v2 is True" &lt;&lt; endl; } cout &lt;&lt; endl; //scaler arithmetic cout &lt;&lt; "-&gt; Testing Vector2 Scaler Arithmetic" &lt;&lt; endl; cout &lt;&lt; "v1 + 10 = " &lt;&lt; v1 + 10 &lt;&lt; endl; cout &lt;&lt; "v1 - 10 = " &lt;&lt; v1 - 10 &lt;&lt; endl; cout &lt;&lt; "v2 * 10 = " &lt;&lt; v2 * 10 &lt;&lt; endl; cout &lt;&lt; "v2 / 10 = " &lt;&lt; v2 / 10 &lt;&lt; endl; cout &lt;&lt; endl; //scaler assingment arithmetic cout &lt;&lt; "-&gt; Testing Vector2 Scaler Arithmetic to Assingment" &lt;&lt; endl; v3 += 20; cout &lt;&lt; "v3 += 20; v3 = " &lt;&lt; v3 &lt;&lt; endl; v3 -= 10; cout &lt;&lt; "v3 -= 10; v3 = " &lt;&lt; v3 &lt;&lt; endl; v3 *= 20; cout &lt;&lt; "v3 *= 20; v3 = " &lt;&lt; v3 &lt;&lt; endl; v3 /= 10; cout &lt;&lt; "v3 /= 10; v3 = " &lt;&lt; v3 &lt;&lt; endl; cout &lt;&lt; endl; //static arithmetic cout &lt;&lt; "-&gt; Testing Vector2 Static Arithmetic" &lt;&lt; endl; cout &lt;&lt; "Vector2::Add(v1, v2) = " &lt;&lt; Vector2::Add(v1, v2) &lt;&lt; endl; cout &lt;&lt; "Vector2::Sub(v1, v2) = " &lt;&lt; Vector2::Sub(v1, v2) &lt;&lt; endl; cout &lt;&lt; "Vector2::Mul(v1, v2) = " &lt;&lt; Vector2::Mul(v1, v2) &lt;&lt; endl; cout &lt;&lt; "vector2::Div(v1, v2) = " &lt;&lt; Vector2::Div(v1, v2) &lt;&lt; endl; cout &lt;&lt; endl; //static member functions cout &lt;&lt; "-&gt; Testing Vector2 Static Member Functions" &lt;&lt; endl; cout &lt;&lt; "Vector2::Distance(v2, v1) = " &lt;&lt; Vector2::Distance(v2, v1) &lt;&lt; endl; cout &lt;&lt; "Vector2::DistanceSq(v2, v1) = " &lt;&lt; Vector2::DistanceSq(v2, v1) &lt;&lt; endl; cout &lt;&lt; "Vector2::Dot(v2, v1) = " &lt;&lt; Vector2::Dot(v2, v1) &lt;&lt; endl; cout &lt;&lt; "Vector2::Min(v1, v2) = " &lt;&lt; Vector2::Min(v1, v2) &lt;&lt; endl; cout &lt;&lt; "Vector2::Max(v1, v2) = " &lt;&lt; Vector2::Max(v1, v2) &lt;&lt; endl; cout &lt;&lt; "Vector2::Clamp(Vector2(5, 30), v2, v1) = " &lt;&lt; Vector2::Clamp(Vector2(5, 30), v2, v1) &lt;&lt; endl; cout &lt;&lt; endl; //member functions cout &lt;&lt; "-&gt; Testing Vector2 Member Functions" &lt;&lt; endl; cout &lt;&lt; "v1.Length() = " &lt;&lt; v1.Length() &lt;&lt; endl; cout &lt;&lt; "v1.LengthSquared() = " &lt;&lt; v1.LengthSq() &lt;&lt; endl; cout &lt;&lt; "v2.Skew() = " &lt;&lt; v2.Skew() &lt;&lt; endl; cout &lt;&lt; "v2.Normalize() = " &lt;&lt; v2.Normalize() &lt;&lt; endl; cout &lt;&lt; endl; //testing cpp copy cout &lt;&lt; "-&gt; Testing Vector2 Default Copy Ctor" &lt;&lt; endl; Vector2 * vec = new Vector2(v2); cout &lt;&lt; "v2 = " &lt;&lt; v2 &lt;&lt; endl; cout &lt;&lt; "Vector2 * vec = new Vector2(v2);" &lt;&lt; endl; cout &lt;&lt; "v4 = " &lt;&lt; *vec &lt;&lt; endl; cout &lt;&lt; endl; //free delete vec; } }//end namespace </code></pre> <p>BTW, I know this is not the same account. I lost my info for that account and have since been using this account.</p>
[ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-05-21T13:39:51.100", "Id": "19165", "Score": "0", "body": "How are you planning on forcing the inlining? Via compiler options?" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-05-21T21:51:56.513", "Id": "19192", "Score": "0", "body": "Yes, but I guess it wont make a difference anyway. It sounds like the compiler has taken care of that for me http://stackoverflow.com/q/1759300/14065 Thanks Loki." } ]
[ { "body": "<pre><code>float32 Vector2::Length() const { return sqrt(x * x + y * y); }\nfloat32 Vector2::LengthSq() const { return x * x + y * y; }\n</code></pre>\n\n<p>Don't dup the code. You already have the functionality for calculating LenSq use it instead of writing it again.</p>\n\n<pre><code>float32 Vector2::Length() const { return sqrt( LengthSq() ); }\nfloat32 Vector2::LengthSq() const { return x * x + y * y; }\n</code></pre>\n\n<p>upd:</p>\n\n<pre><code>Vector2 &amp; Vector2::Normalize()\n{\n float32 invLen = 1.0f / len;\n}\n</code></pre>\n\n<p>what if <code>len</code> is <code>0</code>?</p>\n\n<p>upd2:</p>\n\n<p>General recommendation, use <code>+=</code> instead of <code>+</code>. It's shorter and in this case the new object isn't created. If you have deal with native types (ints etc), then creation of a new object isn't a problem, but the user defined objects might be very big. Compare strings below.</p>\n\n<pre><code>Vector2 &amp; Vector2::Skew() { x = x - y; y = x + y; x = x - y; return *this; }\nVector2 &amp; Vector2::Skew() { x -= y; y += x; x -= y; return *this; }\n</code></pre>\n\n<p>upd3:\nDon't use <code>endl</code> so often, i don't think you need this. Check Google/Stackoverflow for the question \"\\n vs endl\"</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-05-21T22:19:30.830", "Id": "19193", "Score": "0", "body": "Thanks, I changed my Skew method and will change my Normalize to prevent division by zero when I get back. Also I use 'endl', because I like typing it more that '\\n' and don't use 'cout' and 'cin' for more than testing purposes so I choose to use 'endl' because it feels better to me. Thanks for the help!" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-05-22T11:23:41.373", "Id": "19205", "Score": "0", "body": "Wait, doesn't my 'len < FLT_ESPILON' make sure I won't have division by zero or a really small number by the time it reaches my else block?" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-05-23T08:41:18.793", "Id": "19227", "Score": "0", "body": "I'm not sure, what if a ``len`` will be a very small negative one? Argument \"it won't because it can't be\" isn't convincing because one part of code must not rely on other part." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-06-23T00:35:34.593", "Id": "20930", "Score": "0", "body": "@fogbit FLT_EPSILON is always positive." } ], "meta_data": { "CommentCount": "4", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-05-21T13:06:42.740", "Id": "11938", "ParentId": "11934", "Score": "1" } }, { "body": "<p>Don't delcare members inline:</p>\n\n<pre><code>inline Vector2 &amp; Vector2::operator = (const Vector2 &amp; v) { x = v.x; y = v.y; return *this; }\n</code></pre>\n\n<p>It is already inline. This provides no information for humans (and the compiler ignores this keyword) so best not to use this keyword except in places where you must. <a href=\"https://stackoverflow.com/q/1759300/14065\">https://stackoverflow.com/q/1759300/14065</a></p>\n\n<p>Define related operations in terms of each other.<br>\nThis prevents subtle bugs:</p>\n\n<pre><code>inline bool Vector2::operator != (const Vector2 &amp; v) const { return (x != v.x) || (y != v.y); }\n\n// Much better to write as:\n\nbool Vector2::operator != (Vector2 const&amp; v) const { return !(*this == v);}\n//or\nbool Vector2::operator != (Vector2 const&amp; v) const { return !this-&gt;operator==(v);}\n</code></pre>\n\n<p>Define the standard operators in terms of their assignment versions.<br>\nAgain this helps in preventing simple mistakes by reducing repeated code.<br>\nThis case is also widely used and compilers have routines to optimize this.</p>\n\n<pre><code>inline const Vector2 Vector2::operator + (const Vector2 &amp; v) const { return Vector2(x + v.x, y + v.y); }\n\n// Much better to write as\n\nVector2 Vector2::operator + (Vector2 const&amp; v) const { Vector2 r(*this); return r += v;}\n</code></pre>\n\n<p>Also Note: Returning by <code>const value</code> is meaningless.</p>\n\n<pre><code>inline const Vector2 Vector2::operator +(/*STUFF*/)\n// ^^^^^^^^^^^^^\n</code></pre>\n\n<p>Its a value once at the call site it is a temporary value thus its const is removed.</p>\n\n<p>Again with the static version of standard operators. Define them in terms of normal operators. Prevent copy and paste bugs.</p>\n\n<pre><code>static Vector2 Add (const Vector2 &amp; v1, const Vector2 &amp; v2) { return Vector2(v1.x + v2.x, v1.y + v2.y); }\n\n// Much better as:\n\nstatic Vector2 Add (Vector2 const&amp; v1, Vector2 const&amp; v2) { return v1 + v2; }\n</code></pre>\n\n<p>Define related operators in terms of each other.<br>\nReduce repeated code and subtle bugs:</p>\n\n<pre><code>static float32 Distance (const Vector2 &amp; v1, const Vector2 &amp; v2)\n{ return sqrt(DistanceSq(v1,v2)); }\n</code></pre>\n\n<p>If you define the output operator also define the input operator (that can read what was generated by output). Also there is no need to add an extra statement to <code>return os;</code>. Just return the expression.</p>\n\n<pre><code>friend std::ostream &amp; Vector2::operator &lt;&lt; (std::ostream &amp; os, const Vector2 &amp; v)\n{ \n return os &lt;&lt; \"{\" &lt;&lt; v.x &lt;&lt; \", \" &lt;&lt; v.y &lt;&lt; \"}\";\n}\nfriend std::istream &amp; Vector2::operator &gt;&gt; (std::istream &amp; is, Vector2 &amp; v)\n{\n char tmp1=' ';\n char tmp2=' ';\n char tmp3=' ';\n is &gt;&gt; tmp &gt;&gt; v.x &gt;&gt; tmp2 &gt;&gt; v.y &gt;&gt; tmp3;\n\n if ((tmp1 != '{' ) || (tmp2 != ',') || (tmp3 != '}'))\n { is.setstate(std::ios::failbit);\n }\n\n return os;\n}\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-05-21T22:20:30.673", "Id": "19194", "Score": "0", "body": "Did some major edits in main post in light of what you said. Thanks!" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-05-21T22:28:13.173", "Id": "19195", "Score": "0", "body": "Note sure this update is correct: `bool Vector2::operator > (const Vector2 & v) const { return !(*this < v); }` . What happens if they are equal?" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-05-22T11:25:06.347", "Id": "19207", "Score": "0", "body": "Thank you, fixed above. That's what I get for trying to fix it quickly. :)" } ], "meta_data": { "CommentCount": "3", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-05-21T20:05:43.320", "Id": "11955", "ParentId": "11934", "Score": "1" } }, { "body": "<p>Most binary operators are best defined outside the class in order to make them more symmetric. I would recommend using the following pattern:</p>\n\n<pre><code>Vector2 const operator+(Vector2 lhs, Vector2 const&amp; rhs) {\n return lhs += rhs;\n}\n</code></pre>\n\n<p>Idem for all similar operators. Feel free to make the return type const if you'd like, although that's not always desired (<code>(v1 + v2).Normalize()</code> may be useful).</p>\n\n<p>Most of your static functions look like they should be free functions to me. I don't see a use-case for <code>Add</code>.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-11-18T13:24:43.677", "Id": "18765", "ParentId": "11934", "Score": "1" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "2", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-05-21T10:28:42.983", "Id": "11934", "Score": "5", "Tags": [ "c++", "optimization" ], "Title": "C++ Vector2 Class Review" }
11934
<p>I messed a little bit with pthreads and needed an alternative to the C++11 function <code>std::lock</code> (2 args are enough), and this is what I came up with: </p> <pre><code>void lock(pthread_mutex_t* m1, pthread_mutex_t* m2) { while(1) { pthread_mutex_lock(m1); if(pthread_mutex_trylock(m2) == 0) { // if lock succesfull break; } pthread_mutex_unlock(m1); sched_yield(); } } </code></pre> <p>It works fine so far. I am just not sure whether I missed some potential deadlock.</p> <p>In addition, I am interested if I should do some more error checking. I am especially not that firm with C-style error checking.</p>
[ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2015-07-17T15:00:33.860", "Id": "177874", "Score": "1", "body": "Downvoter please explain!" } ]
[ { "body": "<p>It does not look like your code will deadlock.<br />\nThat said, I am not very keen on the spin lock like attempt, as I can see situations where it may not be great in efficiency.</p>\n<p>It (<code>std::lock</code>) guarantees that no matter what order you specify the locks in the parameter list you will not fall into a deadlock situation.</p>\n<p>A common technique (simple enough you could use (but the standard does not specify whether this technique is used by <code>std::lock</code>)) is to make sure the locks are ordered in some way. This basically means that the order you lock the mutexes in must be consistent (thus independent of the order they are in the parameter list).</p>\n<ul>\n<li>The actual order should be defined in terms of some immutable property of the underlying mutex (such as its address).</li>\n<li>This also means that if a lock in the list is already locked it must be released so that the locks are acquired in the correct order (Note: not all lockables can safely call <code>try_lock()</code> so you can't always determine if you should unlock).</li>\n</ul>\n<p>Example of deadlock occurring when locks are not acquired in order:</p>\n<pre><code> Time: Thread-1 Thread-2\n lock(g2, g1) lock(g1, g2)\n\n\n 0 lock(&amp;g2)\n \n 1 lock(&amp;g1)\n\n 2 lock(&amp;g1) // Can never succeed\n \n 3 lock(&amp;g2) // Can never succeed\n</code></pre>\n<p>Metal deadlock.</p>\n<p>Thread 1 is now waiting for <code>g1</code> (held by thread 2), while thread 2 is waiting for <code>g2</code> (held by thread 1).</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-05-21T21:40:16.617", "Id": "19191", "Score": "0", "body": "Ok, thanks for the hints. Starting with your example, this is of course something I didn't think of as I didn't know that `std::lock` handles this, I supposed that it acts like a normal `mutex::lock` which gets double locked. While I can see that a proper ordering would fix the problem in the upper example, would the ordering still matter if we'd assume that the mutexs are both unlocked? I can't come up with a test which would deadlock in that case." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-05-22T04:30:36.833", "Id": "19200", "Score": "0", "body": "To be more precise - assuming that a thread doesn't try to lock a mutex again which it already owns." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-06-14T15:43:48.090", "Id": "20256", "Score": "0", "body": "@bamboon: If it already owns a lock. Then it **must** be release. If the locks are not acquired in the correct order you run the risk of deadlock. This is why std::lock imposes a strict ordering on lock acquisition." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-04-03T17:41:06.973", "Id": "510850", "Score": "1", "body": "I know almost 10 years have passed since this was written, but I believe this answer to be incorrect. Whether the naïve \"try-and-back-off\" strategy to lock multiple mutexes is good in terms of performance is debateable, but it is correct and does not generate deadlocks. It can theoretically generate live-locks and eat a lot of CPU. See: https://www.justsoftwaresolutions.co.uk/threading/acquiring-multiple-locks-without-deadlock.html" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-04-05T02:39:14.067", "Id": "510932", "Score": "0", "body": "@gd1 I don't say this implementation will potentially deadlock. I say it does not meet the requirements imposed by std::lock. Then I explain how std::locks implementation guarantees that deadlock does not happen." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-04-05T15:45:16.363", "Id": "510959", "Score": "0", "body": "Sorry but that's as clear as mud. Leaving aside for a moment that the OP's function is very naïve, inefficient, and notably not compliant with the std::lock interface due to it not even being C++, it captures std::lock's general idea of locking more than one mutex while avoiding a deadlock. The standards says something along the lines of \"arguments are locked via sequence of calls to lock(), try_­lock(), or unlock(). The sequence of calls does not result in deadlock, but is otherwise unspecified\", which doesn't exclude a \"try-and-back-off\" strategy whereby the order is an emergent property." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-04-05T15:59:57.137", "Id": "510960", "Score": "0", "body": "If the non-compliance of the OP's approach, according to you, is due to this: \"if a lock in the list is already locked it must be released so that the locks are acquired in the correct order\", I'm not aware of such requirement and neither is this user on SO: https://stackoverflow.com/questions/47637815/may-a-call-to-stdlock-pass-a-resource-that-is-already-locked-by-the-calling-th\nAt the very least, this 2012 dated answer of yours is most unclear." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-04-05T20:43:32.337", "Id": "510982", "Score": "1", "body": "@gd1 OK cleaned up the lanaguage a bit." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-04-05T20:48:05.013", "Id": "510984", "Score": "0", "body": "The code does not deadlock, but @gd1 is correct and the code can [livelock](https://en.wikipedia.org/wiki/Deadlock#Livelock), which is of course just as bad for the application." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-04-05T22:45:59.817", "Id": "510997", "Score": "0", "body": "Thanks @MartinYork. It's worth underlining, for the benefit of whoever is reading this in 2021, that while it is absolutely true that \"This also means that if a lock in the list is already locked it must be released so that the locks are acquired in the correct order.\", `std::lock` does not and cannot do that for you. If you pass it a `std::mutex` that is already locked by the current thread, it's going to be deadlock, or kaboom (`std::terminate`, `std::system_error` or whatever), or some more dangerous form of undefined behaviour." } ], "meta_data": { "CommentCount": "10", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2012-05-21T20:40:25.710", "Id": "11956", "ParentId": "11935", "Score": "7" } }, { "body": "<p>If you swap pointers to the mutexes after a failed iteration, you can get better performance than either your original code, or the ordered solution shown in the currently accepted answer.</p>\n<pre><code>void lock(pthread_mutex_t* m1, pthread_mutex_t* m2) {\n while(1) {\n pthread_mutex_lock(m1);\n\n if(pthread_mutex_trylock(m2) == 0) { // if lock succesfull\n break;\n }\n pthread_mutex_unlock(m1);\n sched_yield();\n pthread_mutex_t* tmp = m1;\n m1 = m2;\n m2 = tmp;\n }\n}\n</code></pre>\n<p>Without swapping, the code works, but burns cpu cycles in highly contested situations.</p>\n<p>The ordering solution works, doesn't burn cpu cycles, but can sometimes block on a mutex while holding the lock on another mutex. This can reduce parallel execution on a multicore platform.</p>\n<p>By inserting the swap you eliminate both of those problems:</p>\n<ol>\n<li>You never hold a locked mutex while blocking on another.</li>\n<li>You don't &quot;spin&quot; because on all iterations but the first, you try to lock a mutex that just failed a <code>try_lock</code>. Thus you are likely to block (without holding a locked mutex), allowing other threads to run with both mutexes available.</li>\n</ol>\n<p>I've published <a href=\"http://howardhinnant.github.io/dining_philosophers.html\" rel=\"nofollow noreferrer\">a paper that goes into more detail</a>, and supplies C++ code demonstrating these algorithms.</p>\n<p>The paper terms the original solution &quot;Persistent&quot;. The ordered solution is called &quot;Ordered&quot;. And with the swapping, you get &quot;Smart &amp; Polite&quot;.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-04-29T13:23:32.307", "Id": "513472", "Score": "0", "body": "Why do you yield at all? As you described, you unlock all and then block on locking the failed lock, so I see no need. An additional thought, why not start with the locks ordered? That should boost the chance of the first lock blocking if any do so for normal workloads." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-04-29T13:45:45.307", "Id": "513476", "Score": "1", "body": "The paper measures the effect of the yield by testing both with and without it. The algorithm with yield has a slight but consistent performance advantage, at least on the platform, and test cases I tested. It is surmised that the yield dampens a small amount of live-lock that otherwise arises." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-04-29T13:49:46.727", "Id": "513477", "Score": "1", "body": "I have not tested an algorithm that orders _and_ tries-backsoff. Although the paper does compare each algorithm to a theoretical highest performance possible. The Smart & Polite algorithm matches the theoretical minimum until the test case starts requesting more CPU's than the hardware has to offer. The ordered algorithm does not come close to this ideal." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-04-30T12:39:02.093", "Id": "513598", "Score": "0", "body": "I wonder if there would be a significant effect if the locks were passed to your algorithm already pre-ordered, instead of pre-randomised." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-04-30T14:08:09.363", "Id": "513603", "Score": "0", "body": "The test code is in the appendix of the paper. You could try it out. Although for test results that are already at the theoretical best, I would not expect any improvement." } ], "meta_data": { "CommentCount": "5", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-04-27T21:40:03.167", "Id": "260088", "ParentId": "11935", "Score": "5" } } ]
{ "AcceptedAnswerId": "11956", "CommentCount": "1", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-05-21T10:33:39.577", "Id": "11935", "Score": "6", "Tags": [ "c++", "c", "pthreads", "locking" ], "Title": "std::lock implementation in C with pthreads" }
11935
<p>The following counts the number of page loads and then does something if &lt; <code>MIN_PAGE_VIEWS</code>.</p> <p>Can anyone give me any pointers to improve both this function and my JavaScript in general? Both in terms of patterns, design and algorithm.</p> <pre><code>// Call on body onload event. // Checks to see if prompt is to be displayed and if banner is to be displayed. function bodyOnLoad() { var MIN_PAGE_VIEWS = 3; if(readCookie('counter-cookie') == null){ createCookie('counter-cookie', '0', '150'); } // Only start showing random popup after second page visit if (readCookie('counter-cookie') &lt; MIN_PAGE_VIEWS) { var iCount = parseInt(readCookie('counter-cookie')); iCount++; createCookie('counter-cookie',iCount.toString(), '150'); } else{ if (readCookie('ab5cd57e-871a-4b65') != 'yes') { showPanel('popupPanel',80,240,'yes'); } } if(readCookie('banner-cookie') == 'yes'){ showPanel('surveyBanner',100,100, 'no'); displayBanner(); } } // New Cookie and Set expiration date function createCookie(name,value,days) { if (days) { var date = new Date(); date.setTime(date.getTime()+(days*24*60*60*1000)); var expires = "; expires="+date.toGMTString(); } else var expires = ""; document.cookie = name+"="+value+expires+"; path=/"; } // Separates cookies function readCookie(name) { var nameEQ = name + "="; var ca = document.cookie.split(';'); for(var i=0;i &lt; ca.length;i++) { var c = ca[i]; while (c.charAt(0)==' ') c = c.substring(1,c.length); if (c.indexOf(nameEQ) == 0) return c.substring(nameEQ.length,c.length); } return null; } </code></pre>
[]
[ { "body": "<p>If you want to improve your JavaScript, run your code through <a href=\"http://www.jslint.com/\" rel=\"nofollow\">http://www.jslint.com/</a><br>\nWhere it complaints about something, try to understand why - more often than not, it is a valid complaint. :)</p>\n\n<hr>\n\n<ol>\n<li><p>Start the JavaScript with <code>\"use strict\";</code>. (That also means you\nshould wrap the code in a self-executing function.) There is plenty\nof material out there explaining this much better than I would. :)</p></li>\n<li><p>You should store the result of <code>readCookie('counter-cookie')</code> in a\nvariable, instead of calling it repeatedly.</p></li>\n<li><p>In <code>createCookie('counter-cookie',iCount.toString(), '150');</code>, why\nthe <code>.toString()</code>?</p></li>\n<li><p>You should use <code>===</code> and <code>!==</code> instead of <code>==</code> and <code>!=</code>. They are\ndifferent, and the shorter version should be used sparingly.</p></li>\n<li><p>In <code>createCookie</code>, you want <code>if(typeof days === 'number') { ... }</code>,\nand to pass in a number (<code>150</code>) instead of a string (<code>'150'</code>).</p></li>\n<li><p>In <code>createCookie</code>, declare the var <code>expires</code> at the top of the\nmethod. In the first branch of the if, you are using a var in the\nglobal context: Bad Idea<sup>tm</sup>.</p></li>\n<li><p>In <code>createCookie</code>, you seem to be overriding all cookies when\nsetting the date. Is this on purpose? Or does <code>document-cookie =\n'foo';</code> do some black-magic that I am not expecting?</p></li>\n<li><p>In <code>createCookie</code> you use <code>date.toGMTString()</code> - <a href=\"https://developer.mozilla.org/en/JavaScript/Reference/Global_Objects/Date\" rel=\"nofollow\">in MDN it is advised to use .toUTCString instead</a>.</p></li>\n<li><p>In <code>readCookie</code>, that indention is hurtful. :|</p></li>\n<li><p>In <code>readCookie</code>, do you need to <code>while(!false) str.substring()</code>? I\nwould try to get the index, and then to a <strong>single</strong> <code>substring()</code> op.</p></li>\n</ol>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-05-21T14:15:26.173", "Id": "11946", "ParentId": "11939", "Score": "3" } }, { "body": "<ul>\n<li>Always declare variables on the first line of their function. They are automatically <a href=\"http://elegantcode.com/2011/03/24/basic-javascript-part-12-function-hoisting/\" rel=\"nofollow\">hoisted</a> there anyway, so declaring them anywhere else results in code that is written in a different order than it is executed.</li>\n<li>Keep your formatting consistent. <a href=\"http://www.jslint.com/\" rel=\"nofollow\">jslint</a> has a particular style that is considered \"proper\", but obeying their rules exactly is less important than never breaking your own rules.</li>\n<li>Namespace your code. An easy way to do this is to wrap your code in <code>(function () {/* code here */}());</code>. The reason you want to do this is so you don't accidentally overwrite other scripts' variables, and so they don't overwrite yours.</li>\n<li>Try to keep results around that you might need again. For example, <code>readCookie()</code> currently re-parses <code>document.cookie</code> every time it is called, when it really only needs to parse it once, then keep the result around. Of course, then the array isn't updated by <code>createCookie</code>, but it doesn't look like your code requires that functionality.</li>\n<li>Be aware of the difference between <code>===</code> and <code>==</code> - in several cases above, you used the latter when you wanted the former.</li>\n<li>Storing the string <code>\"yes\"</code> to indicate <code>true</code> overcomplicates things. I would just set the cookie to <code>1</code> (which is automatically converted to <code>\"1\"</code>), then, when testing for it, simply write <code>if (readCookie('banner-cookie')) {</code>.</li>\n<li>Some would disagree with me on this one, but I think regular expressions can make your code more readable. They can certainly make it shorter.</li>\n</ul>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-05-23T00:41:50.013", "Id": "11980", "ParentId": "11939", "Score": "1" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-05-21T13:15:13.260", "Id": "11939", "Score": "3", "Tags": [ "javascript" ], "Title": "Page visit counter" }
11939
<p>I have a query to return the ids of failed logins that are newer than a supplied date, and also newer than the last successful login.</p> <p>Table:</p> <pre><code>####################################################### # user_attributes # ####################################################### # id # u_id # label # attribute_datetime # ####################################################### # 1 # 33 # failed_login # 2012-05-21 09:03:00 # # 2 # 33 # succcessful_login # 2012-05-21 09:04:00 # ####################################################### </code></pre> <p>Query:</p> <pre><code>SELECT count(id) FROM `user_attributes` as ua WHERE u_id = 33 AND label = 'failed_login' AND ua.attribute_datetime &gt; '2012-05-21 03:04:00' AND ua.attribute_datetime &gt; ( SELECT attribute_datetime FROM `user_attributes` WHERE u_id = 33 AND label = 'successful_login' ); </code></pre> <p>Returns:</p> <pre><code>############## # result_set # ############## # id # ############## # # ############## </code></pre> <p>Now if we add another failed login:</p> <pre><code>####################################################### # user_attributes # ####################################################### # id # u_id # label # attribute_datetime # ####################################################### # 3 # 33 # failed_login # 2012-05-21 09:10:00 # ####################################################### </code></pre> <p>And run the query again it should return this:</p> <pre><code>############## # result_set # ############## # id # ############## # 3 # ############## </code></pre> <p>Is there a better way to write this query? I am looking to improve the speed of the query as this is going to run every time a user logs in, and the table is going to be large if not huge.</p>
[ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-05-22T03:13:22.460", "Id": "19199", "Score": "0", "body": "Looks pretty good to me. Have you run Explain against it to ensure you are using indexes?" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-05-22T11:19:12.377", "Id": "19204", "Score": "0", "body": "Where do you get the *supplied date* from?" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-05-22T12:37:00.310", "Id": "19209", "Score": "0", "body": "@dreza - I have never used explain I will have to look into it." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-05-22T12:39:06.187", "Id": "19210", "Score": "0", "body": "@palacsint - The supplied date is given via PHP when the query is rendered." } ]
[ { "body": "<p>The code looks good to me as well except if you are looking for the ids of the failed logins you would not want to count the ids (SELECT count(id)) but instead just select the id (SELECT id).</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-05-24T11:16:05.320", "Id": "19271", "Score": "0", "body": "I am not concerned with returning the ids but the number of ids" } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-05-23T06:20:43.533", "Id": "11985", "ParentId": "11940", "Score": "1" } } ]
{ "AcceptedAnswerId": "11985", "CommentCount": "4", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-05-21T13:49:26.953", "Id": "11940", "Score": "1", "Tags": [ "performance", "sql", "mysql" ], "Title": "Return the ids of failed logins" }
11940
<p>The main class (<code>SMSHelper</code>) is responsible of query a REST web service which in turn returns an XML string. This helper is going to return a new <code>SMSCreditInfo</code> instance (merely a data <strong>container</strong>), with the help of a parser (<code>SMSCreditParser</code>):</p> <pre><code>class SMSHelper { protected static $base = 'https://gateway.skebby.it/api/send/smseasy/advanced/rest.php'; /** * @return SMSCreditInfo */ public function getCreditInfo() { // Setting POST data $data = array(); $data['method'] = 'get_credit'; $data['username'] = $this-&gt;username; $data['password'] = $this-&gt;password; // Inizialize SMSCreditInfo container, assuming a failure $creditInfo = new SMSCreditInfo(); $creditInfo-&gt;setIsSuccess(false)-&gt;setCreditLeft(null); // Actually send the request $response = $this-&gt;browser-&gt;post(self::$base, array(), http_build_query($data)); // If it's a failure return SMSCreditInfo if(200 != $reponse-&gt;getStatusCode()) return $creditInfo(); // Ask the parser to parse the XML response return SMSCreditParser::parse($reponse-&gt;getContent()); } } </code></pre> <p>Class <code>SMSCreditParser</code> is actually responsible of parsing the XML string:</p> <pre><code>class SkebbyCreditParser { /** * @return SMSCreditInfo */ public static function parse($xmlString) { $info = new SMSCreditInfo(); // Failure in parsing XML string if(false === ($xml = @simplexml_load_string($xmlString))) return $info-&gt;setIsSuccess(false)-&gt;setCreditLeft(null); // Get credit node value ... } } </code></pre> <p>Does this code follow loose coupling pattern or should be refactored/re-designed?</p> <p>I don't like how these classes are organized and I think they're not following the loose coupling pattern at all. The main reason is because both <code>getCreditInfo()</code> and <code>parse()</code> return the container object, and are not DRY due to the way the container is initialized in case of failure.</p>
[]
[ { "body": "<p>I hope you're still watching this. Answers here at codereview tend to take a while. I've been on vacation, else I would have answered sooner. Hope this answer satisfies :)</p>\n\n<p>\"i think it's not following the loose coupling pattern at all.\" - You'd be correct.</p>\n\n<p>\"not DRY too\" - Also correct.</p>\n\n<p>It would help if you were to use a design pattern that used loose coupling. What you currently have does not appear to use a pattern at all. The best one for this, I think, is the MVC pattern and is what I'll use in my answer. I'd also like to point out that you are not breaking up your methods as much as you probably should. Methods should do one thing and do it well. I went ahead and broke them up in my answer.</p>\n\n<p><strong>SMSHelper</strong></p>\n\n<p>First, I broke up your methods into smaller, more focused, pieces. Methods and functions help clean up your code and are not just for reusability. Breaking up your methods in this manner will make debugging, reading, and future expansion much easier.</p>\n\n<p>Second, I removed any instance of any other class as this violates loose coupling principle. You'll notice I left a note in the code about how <code>$this-&gt;browser</code> possibly violates this principle as well. To correct this, I would change the new <code>_getResponse()</code> method to public and call it in the new <code>SMSController</code> class (below) and have it return an array to pass to the <code>$browser-&gt;post()</code> method which I would also instantiate in the <code>SMSController</code> class. However I left it how it is because you asked specifically about the other two classes and didn't give me enough to be sure how to implement it in the controller.</p>\n\n<p>Third, I made the <code>getCreditInfo()</code> method return FALSE on \"failure\" so it can be handled in the controller. This helps you to comply with the DRY principle as before you were not reusing the code.</p>\n\n<pre><code>class SMSHelper {\n private function _getData() {\n return array(\n 'method' =&gt; 'get_credit',\n 'username' =&gt; $this-&gt;username,\n 'password' =&gt; $this-&gt;password,\n );\n }\n\n private function _getResponse() {\n return $this-&gt;browser-&gt;post(//not sure what browser is, but it probably violates loose coupling as well\n self::$base,\n array(),\n http_build_query($this-&gt;_getData())\n );\n }\n\n public function getCreditInfo() {\n $response = $this-&gt;_getResponse();\n\n if($response != 200) { return FALSE; }\n return $response-&gt;getContent();\n }\n}\n</code></pre>\n\n<p><strong>SMSCreditParser</strong></p>\n\n<p>Again, I removed any instance of other classes, for the same reasons.</p>\n\n<p>Also, I changed the way you parsed the XML. First off, it was very cluttered. You shouldn't define variables in statements. There are some exceptions that are accepted, but this isn't one. Second, the statement you had was unnecessary. Load the string, if it has any errors it will return FALSE, so you can just use the XML variable as your statement.</p>\n\n<p>I also returned FALSE here on \"failure\" so it can be handled in the controller.</p>\n\n<pre><code>class SMSCreditParser {\n public static function parse($xmlString) {\n $xml = simplexml_load_string($xmlString);\n\n if($xml) {\n //etc...\n return $creditNodeValue;\n }\n return FALSE;\n }\n}\n</code></pre>\n\n<p><strong>Controller</strong></p>\n\n<p>Here's the controller class that brings them all together. You start off by calling the <code>getCreditNode()</code> in your constructor before loading the view. This method loads the <code>SMSHelper::getCreditInfo()</code> method. I don't do anything if it returns FALSE because it is unnecessary. Trying to load FALSE into simplexml <em>should</em> just return FALSE. Something tells me it might through an error, so I say <em>should</em>. Sense there is no reason to check its value I immediately pass it to the <code>SMSCreditParser::parse()</code> method. If <code>parse()</code> returns FALSE, then the new <code>_failure()</code> method will be called to set the <code>SMSCreditInfo</code> class and return it.</p>\n\n<pre><code>class SMSController {\n public function __construct() {\n //all your includes for each class, or your autoloader\n $creditNode = $this-&gt;getCreditNode();\n $this-&gt;render($view);\n }\n\n private function _failure() {\n $SMSCreditInfo = new SMSCreditInfo();\n $SMSCreditInfo-&gt;setIsSuccess(false)-&gt;setCreditLeft(null);\n\n return $SMSCreditInfo();\n }\n\n public function getCreditNode() {\n $SMSHelper = new SMSHelper();\n\n $creditInfo = $SMSHelper-&gt;getCreditInfo();\n $parsed = SMSCreditParser::parse($creditInfo);\n\n if($parsed) { return $parsed; }\n return $this-&gt;_failure();\n }\n}\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-05-29T17:06:57.907", "Id": "19422", "Score": "0", "body": "Of course i'm following it. I'll take the time to read but i'd like to thank you first." } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-05-29T16:45:05.267", "Id": "12146", "ParentId": "11943", "Score": "1" } } ]
{ "AcceptedAnswerId": "12146", "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-05-21T13:59:53.203", "Id": "11943", "Score": "1", "Tags": [ "php", "design-patterns", "parsing" ], "Title": "Parsing credit info" }
11943
<p>Well this was a simplest code competition at my work. I tried a couple things, they accepted but none of them is I wanted. Because both are always giving same result.</p> <p>I tried to randomize like this</p> <pre><code>var list = $(".content li").sort(Math.round(Math.random())-0.5); </code></pre> <p>and this</p> <pre><code>var list = $(".content li").get().sort(function(){ return Math.round(Math.random())-0.5 }).slice(0,$(".content li").length) </code></pre> <p>and this</p> <pre><code>$(".content li").each(function(i){ $(this).sort(Math.round(Math.random())-0.5) }); </code></pre> <p>And the work is;</p> <pre><code>$(list).each(function(i){ $(this).delay(i * 300).fadeIn(300); }); </code></pre> <p>So the aim is less line but clever way I think better. Any suggestion?</p>
[]
[ { "body": "<p>Here is a version that is working, but I'm not sure if it is the best way to do it (<strong>this is not the best way, look below</strong>)</p>\n\n<pre><code>var $elements = $('.your-selector');\n\n// print it once to see its content\nconsole.log( $elements.get() );\n\n// get all DOM elements in temporary array\nvar temp = $elements.get();\n\n// randomize that array\ntemp = temp.sort(function() {\n return Math.round( Math.random() ) - 0.5;\n});\n\n// iterate the randomized array\n// while \"$elements\" and \"temp\" have the same length\n// each index of \"$elements\" will be overridden\ntemp.forEach(function( element, index ) {\n // and update the jQuery object\n $elements[ index ] = element;\n});\n\n// print it again to see the difference\n// the order in the original element has been changed\nconsole.log( $elements.get() );\n</code></pre>\n\n<hr />\n\n<p>Here is why your versions are not working</p>\n\n<pre><code>var list = $(\".content li\").sort(Math.round(Math.random())-0.5);\n/*\n$.fn.sort is not an actual function, or it is... This is not documented ??\nWell I don't know what's going on here...\njQuery.fn.sort is not present in the documentation, this it is in the source code\nso can we use it ?!\nif we can... here is a working version\n*/\n// jQuery.fn.sort needs a function as parameter\n$(\".content li\").sort(function() {\n // and this function needs to return a value\n return Math.round(Math.random())-0.5;\n});\n// THIS is a simplified working example :)\n\n\n\nvar list = $(\".content li\").get().sort(function(){\n return Math.round(Math.random())-0.5\n}).slice(0,$(\".content li\").length);\n/*\nFirst, the slice part seems not useful since you're splicing from 0 to the array length\nThen, you use the get method, which return a JavaScript array, and then the sort method\nIt means that, the result of \"sort\" will be the sorted array, and not a jQuery object\n*/\n\n\n\n$(\".content li\").each(function(i){\n $(this).sort(Math.round(Math.random())-0.5)\n});\n/*\nHere, same comment as above: \"sort\" need a function (with a return value) as parameter\nThen, you're using the sort method of a jQuery object containing only one element (this),\n so nothing can be sorted\nFinally, each only iterate the collection and cannot modify elements order,\n or you could do it but it could be harmful\n*/\n</code></pre>\n\n<p>Hope that'll help :)</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-05-22T07:22:45.467", "Id": "19203", "Score": "0", "body": "i see, i was wrong because i tried to write randomize before creating a function. That is clarifies and sort is working on chrome but not working on firefox but that is not the case. Thank you." } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-05-21T20:45:36.027", "Id": "11957", "ParentId": "11948", "Score": "-1" } }, { "body": "<p>This is as concise as I can make it :</p>\n\n<pre><code>var $x = $(\".content li\");//create jQuery object\nArray.prototype.sort.call($x, function(){ return Math.random() &lt; 0.5; });//randomize the jQuery object\n$x.each(function(i, li){ $(\".content\").append(li); });//put li's in the DOM in same order as the randomized jQuery object.\n</code></pre>\n\n<p>See working <a href=\"http://jsfiddle.net/fe7JL/1/\" rel=\"nofollow\">fiddle</a>. Click \"Run\" to re-randomize.</p>\n\n<p>NOTE: I'm not sure my randomization paradigm is a true randomizer. It randomly chooses to swap or not to swap adjacent members. With repeated runs, note how 1 tends to favour the top of the list and 5 tends to favour the bottom. This aspect could be improved.</p>\n\n<p>EDIT: Here's a version with improved shuffle algorithm - wonderfully concise and horribly unreadable :</p>\n\n<pre><code>for (var $x=$(\".content li\"), i=$x.length-1, j, temp; i&gt;=0; i--) { j=Math.floor(Math.random()*(i+1)), temp=$x[i], $x[i]=$x[j], $x[j]=temp; }\n$x.each(function(i, li) { $(\".content\").append(li); });\n</code></pre>\n\n<p>See working <a href=\"http://jsfiddle.net/fe7JL/3/\" rel=\"nofollow\">fiddle</a></p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-05-23T04:40:13.183", "Id": "11984", "ParentId": "11948", "Score": "0" } } ]
{ "AcceptedAnswerId": "11957", "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-05-21T09:34:11.403", "Id": "11948", "Score": "-1", "Tags": [ "javascript", "jquery", "performance", "random" ], "Title": "Randomize a jQuery object list" }
11948
<pre><code>let binsearch ~arr ~cmp x = ( let cmpx = cmp x in (* Assuming arr is ordered according to cmp, then (bs min max) is an *) (* index of a value v in arr such that ((cmp x value) = 0) between *) (* min (inclusive) and max (exclusive). *) let rec bs min max = if min &gt;= max then ( None ) else ( (* mid is always strictly less than max because min &lt; max. *) let mid = (min + max) / 2 in let delta = (cmpx (Array.get arr mid)) in ( if delta = 0 then ( Some mid ) else if delta &lt; 0 then ( (* since mid &lt; max, we make progress *) bs min mid ) else ( bs (mid + 1) max ))) in bs 0 (Array.length arr));; </code></pre> <p>and then it can be used thus</p> <pre><code>let a = [|1; 2; 4; 4; 4; 7; 9; 9; 11; 16|];; let bs = binsearch ~arr:a ~cmp:compare;; let results = (bs 0, bs 1, bs 2, bs 3, bs 4, bs 5, bs 6, bs 7, bs 8, bs 9, bs 10, bs 11, bs 12, bs 13, bs 14, bs 15, bs 16, bs 17);; (results = (None, Some 0, Some 1, None, Some 2, None, None, Some 5, None, Some 7, None, Some 8, None, None, None, None, Some 9, None));; </code></pre>
[]
[ { "body": "<p>Generally speaking, yes. I only have a couple of minor remarks.</p>\n\n<pre><code>let cmpx = cmp x in\n</code></pre>\n\n<p>Using partially-applied functions is actually slightly slower with the native-code compiler. The <code>cmp</code> function (like most functions) isn't going to do anything until it gets all its arguments, so <code>cmpx</code> under the hood is <code>fun y =&gt; cmp x y</code>. It's faster (not by much, but it can matter in an inner loop) if you write <code>let delta = cmpx x (Array.get arr mid)</code> below.</p>\n\n<p>Speaking of which, <code>arr.(mid)</code> is exactly identical to <code>(Array.get arr mid)</code>, but more usual. If you're going for speed, write <code>Array.unsafe_get arr mid</code>, which will save a few cycles, at the expense of putting the onus on you to verify that you are not making an array access out of bounds (here, it's easy to see that you are not).</p>\n\n<p>You have many superfluous parentheses; they are a little surprising to a habitual Ocaml programmer. <code>let … in …</code> has lower precedence than anything else, and <code>if … then … else …</code> has lower precedence than arithmetic and function calls. This is how I'd write your function:</p>\n\n<pre><code>let binsearch ~arr ~cmp x =\n (* Assuming arr is ordered according to cmp, then [bs min max] is an *)\n (* index of a value v in arr such that [(cmp x value) = 0] between *)\n (* min (inclusive) and max (exclusive). *)\n let rec bs min max =\n if min &gt;= max then\n None (* we are down to an empty slice of the array *)\n else\n (* mid is always strictly less than max because min &lt; max. *)\n let mid = (min + max) / 2 in\n let delta = cmp x (Array.unsafe_get arr mid) in\n if delta = 0 then Some mid else\n if delta &lt; 0\n then bs min mid\n else bs (mid + 1) max\n in bs 0 (Array.length arr);;\n</code></pre>\n\n<p>(Details of when to put newlines, especially relative to <code>in</code>, are matters of taste.)</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-05-21T22:52:03.030", "Id": "19196", "Score": "0", "body": "Thanks. I'm a little leery of dropping parentheses since I'm learning the language and haven't wrapped my head around the operator precedence yet. The abbreviated member access is a good point though, and thanks for the performance tips on partial evaluation. Your style of one keyword at the beginning of each line and one at the end makes things flow nicely." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-06-04T20:57:48.590", "Id": "19693", "Score": "0", "body": "the `let cmpx = cmp x in` is a bad idea not only because it is not good for performance but also because you use this function only once and it is never a good idea to declare a function to use it only once." } ], "meta_data": { "CommentCount": "2", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-05-21T21:56:55.260", "Id": "11958", "ParentId": "11952", "Score": "3" } } ]
{ "AcceptedAnswerId": "11958", "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-05-21T18:40:16.750", "Id": "11952", "Score": "3", "Tags": [ "binary-search", "ocaml" ], "Title": "Is this binary search close to idiomatic OCaml?" }
11952
<p>I would like to refactor a large Python method I wrote to have better practices.</p> <p>I wrote a method that parses a design file from the FSL neuroimaging library. Design files are text files with settings for the neuroimaging software. I initially wrote the code to do all the processing in a single loop though the file.</p> <p>I'm looking for all manner of suggestions, but mostly tips of design and best practices. I'd love input on the project as a whole, but I know that might be out of scope for this site.</p> <p>The code structure:</p> <ol> <li>Define variables based on type of design file</li> <li>Parse design file based on type of design file</li> <li>Return the now populated variables setup in 1</li> </ol> <hr> <p>You can also view <a href="https://github.com/mcordell/fsl_tools/blob/d5ea6711f2dc5fcc2ca430deeb838fb398714bfe/fsf_file.py" rel="nofollow noreferrer">the code on GitHub</a> along with the larger project.</p> <pre><code>def parse_design_file(self,fsf_lines, type): """ Parses design file information and return information in parsed variables that can be used by the csv methods """ analysis_name='' output_path='' zvalue='' pvalue='' if type == self.FIRST_TYPE or self.PRE_TYPE: in_file='' if type == self.FIRST_TYPE: ev_convolves=dict() ev_paths=dict() ev_deriv=dict() ev_temp=dict() if type == self.ME_TYPE or type == self.FE_TYPE: feat_paths=dict() count='' if type == self.FIRST_TYPE or type == self.FE_TYPE: ev_names=dict() evg_lines=list() cope_names=dict() cope_def_lines=list() if type == self.PRE_TYPE: tr='' total_volumes='' brain_thresh='' motion_correction='' smoothing='' deleted='' if type == self.FE_TYPE: first_example_dir='' if type == self.ME_TYPE: FE_example_dir='' for line in fsf_lines: #regex matching #all output_match=re.search("set fmri\(outputdir\)",line) feat_file_match=re.search("feat_files\(\d+\)",line) total_vols_match=re.search("fmri\(npts\)", line) z_match=re.search("set fmri\(z_thresh\)",line) p_match=re.search("set fmri\(prob_thresh\)",line) if output_match: output_path=self.get_fsf_value(line,output_match.end()) #TODO hardcoded stripping here, make flexible if type == self.ME_TYPE: run=re.search("ME",line) elif type == self.FIRST_TYPE or type == self.PRE_TYPE: run=re.search("r\d\/",line) elif type == self.FE_TYPE: run=re.search("FE\d*",line) if run: analysis_name=self.get_fsf_value(line,run.end()) if type == self.ME_TYPE: analysis_name=self.strip_cope(analysis_name) if total_vols_match: value=self.get_fsf_value(line,total_vols_match.end()) if type == self.ME_TYPE or type == self.FE_TYPE: count=value if z_match: value=self.get_fsf_value(line,z_match.end()) zvalue=value if p_match: value=self.get_fsf_value(line,p_match.end()) pvalue=value if feat_file_match: if type == self.FIRST_TYPE or type == self.PRE_TYPE: value=self.get_fsf_value(line,feat_file_match.end()) in_file=self.strip_root(value) preproc_match=re.search("preproc.*feat",value) #TODO inconsistent methodology here if preproc_match: self.preproc=value[preproc_match.start():preproc_match.end()] print self.preproc elif type == self.ME_TYPE or type == self.FE_TYPE: value=self.get_fsf_value(line,feat_file_match.end()) index=self.get_fsf_indice(feat_file_match.group()) stripped=self.strip_fanal(line) feat_paths[index]=stripped if (type == self.ME_TYPE and not FE_example_dir) or (type == self.FE_TYPE and not first_example_dir): set_match=re.search("set feat_files\(\d+\) \"",line) no_cope=line[set_match.end():len(line)] no_cope=no_cope.strip('\n') no_cope=no_cope.strip('\"') no_cope=self.strip_cope(no_cope) if type == self.ME_TYPE: FE_example_dir=no_cope else: first_example_dir=no_cope if type == self.PRE_TYPE: tr_match=re.search("fmri\(tr\)", line) mc_match=re.search("set fmri\(mc\)",line) smooth_match=re.search("set fmri\(smooth\)",line) total_vols_match=re.search("fmri\(npts\)", line) removed_volumes=re.search("fmri\(ndelete\)", line) thresh_match=re.search("set fmri\(brain_thresh\)",line) if tr_match: tr=self.get_fsf_value(line,tr_match.end()) if mc_match: value=self.get_fsf_value(line,mc_match.end()) if value == "1": value = "Y" else: value = "N" motion_correction=value if smooth_match: smoothing=self.get_fsf_value(line,smooth_match.end()) if removed_volumes: deleted=self.get_fsf_value(line,removed_volumes.end()) if total_vols_match: total_volumes=self.get_fsf_value(line,total_vols_match.end()) if thresh_match: brain_thresh=self.get_fsf_value(line,thresh_match.end()) if type == self.FIRST_TYPE: ev_conv_match=re.search("fmri\(convolve\d+\)", line) ev_path_match=re.search("fmri\(custom\d+\)", line) ev_deriv_match=re.search("fmri\(deriv_yn\d+\)", line) ev_temps_match=re.search("fmri\(tempfilt_yn\d+\)", line) if ev_conv_match: conv=self.get_fsf_value(line,ev_conv_match.end()) index=self.get_fsf_indice(ev_conv_match.group()) conv_text={ "0" : "none", "1" : "Gaussian", "2" : "Gamma", "3" : "Double-Gamma HRF", "4" : "Gamma basis functions", "5" : "Sine basis functions", "6" : "FIR basis functions", } ev_convolves[index]=conv_text[conv] if ev_deriv_match: value=self.get_fsf_value(line,ev_deriv_match.end()) index=self.get_fsf_indice(ev_deriv_match.group()) if value == "1": value = "Y" else: value = "N" ev_deriv[index]=value if ev_temps_match: value=self.get_fsf_value(line,ev_temps_match.end()) index=self.get_fsf_indice(ev_temps_match.group()) if value == "1": value = "Y" else: value = "N" ev_temp[index]=value if ev_path_match: value=self.get_fsf_value(line,ev_path_match.end()) index=self.get_fsf_indice(ev_path_match.group()) ev_paths[index]=self.strip_root(value) if type == self.FE_TYPE: evg_match=re.search("fmri\(evg\d+\.\d+\)", line) if evg_match: evg_lines.append(line) if type == self.FE_TYPE or type == self.FIRST_TYPE: ev_name_match=re.search("fmri\(evtitle\d+\)", line) cope_name_match=re.search("fmri\(conname_real\.\d+\)", line) cope_def_match=re.search("fmri\(con_real\d+\.\d+\)", line) if cope_name_match: name=self.get_fsf_value(line,cope_name_match.end()) index=self.get_fsf_indice(cope_name_match.group()) cope_names[index]=name if cope_def_match: cope_def_lines.append(line) if ev_name_match: name=self.get_fsf_value(line,ev_name_match.end()) index=self.get_fsf_indice(ev_name_match.group()) ev_names[index]=name if type == self.FIRST_TYPE or type == self.FE_TYPE: design_matrix=[['0' for col in range(len(ev_names)+2)] for row in range(len(cope_names)+1)] if 'ev_temp' in locals(): real_copes=list() index_cope=1 real_copes.append(str(index_cope)) for i in range(1,len(ev_temp)+1): ind=str(i) if ev_temp[ind] == 'Y': index_cope += 2 else: index_cope += 1 real_copes.append(str(index_cope)) real_copes.pop() design_matrix=self.fill_matrix(cope_def_lines,design_matrix,type,1,real_copes) else: design_matrix=self.fill_matrix(cope_def_lines,design_matrix,type,1) for i in range(1,len(cope_names)+1): ind=str(i) design_matrix[i][0]=ind for i in range(1,len(cope_names)+1): ind=str(i) design_matrix[i][1]=cope_names[ind] for i in range(2,len(ev_names)+2): ind=str(i-1) design_matrix[0][i]=ev_names[ind] design_matrix[0][0]='Cope #' design_matrix[0][1]='Cope Name' if type == self.PRE_TYPE: return analysis_name,output_path,tr,total_volumes,deleted,in_file,motion_correction,brain_thresh,smoothing elif type == self.FIRST_TYPE: return analysis_name,output_path,in_file,design_matrix,ev_names,ev_paths,ev_convolves,ev_deriv,ev_temp,cope_names elif type == self.ME_TYPE: return analysis_name,output_path,pvalue,zvalue,feat_paths,count, FE_example_dir elif type == self.FE_TYPE: regressor_matrix=[['0' for col in range(int(count)+1)] for row in range(len(ev_names)+1)] self.fill_matrix(evg_lines,regressor_matrix,5, 0) for i in range(1,len(ev_names)+1): ind=str(i) regressor_matrix[i][0]=ev_names[ind] for i in range(1,int(count)+1): ind=str(i) regressor_matrix[0][i]=ind return analysis_name,output_path,feat_paths,count,design_matrix,regressor_matrix,ev_names,cope_names,first_example_dir </code></pre>
[]
[ { "body": "<p>Your function acts widely different depending on the value of the <code>type</code> parameter. In fact, it basically acts like different functions depending on that parameter. It returns completely different sets of values depending on the value of <code>type</code>. The function would be better off split into several functions, one for each type. Then each function would be simpler, and easier to follow. </p>\n\n<p>I assume that you have done it this way to try and share code between the different filetypes. This is the wrong way to do it. You should share code by calling common functions or using common base classes. You should not share code by having functions exhibit widely different behavior. </p>\n\n<p>For parsing, I'd suggest you actually parse the file, not just run some regular expressions over it. From what I gather your file basically consistents of lines of the form:</p>\n\n<pre><code>set something somevalue\n</code></pre>\n\n<p>I'd write a <code>parse()</code> function that converts the file into a dictionary. So this:</p>\n\n<pre><code># Threshold IC maps\nset fmri(thresh_yn) 1\nset fmri(mmthresh) 0.5\nset fmri(ostats) 0\n</code></pre>\n\n<p>Would become</p>\n\n<pre><code>{'fmri(thesh_yn)' : 1, 'fmri(mmthres)' : 0.5, 'fmri(ostats)' : 0}\n</code></pre>\n\n<p>Then the function for a particular type can just look up entries in the dictionary.</p>\n\n<p>In the end, you return a long tuple. Why? Long tuples are difficult to work with. Perhaps you should really be storing them on an object with many attributes?</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-05-23T06:43:07.030", "Id": "19224", "Score": "0", "body": "This is a dramatic improvement, thank you very much Winston. When you say: \"Perhaps you should really be storing them on an object with many attributes?\" Do you mean create a separate class and populate the attributes?" } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-05-23T03:38:55.493", "Id": "11982", "ParentId": "11961", "Score": "3" } } ]
{ "AcceptedAnswerId": "11982", "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-05-21T23:58:39.273", "Id": "11961", "Score": "4", "Tags": [ "python", "parsing", "configuration" ], "Title": "Parse a text file containing settings for neuroimaging software" }
11961