body
stringlengths
25
86.7k
comments
list
answers
list
meta_data
dict
question_id
stringlengths
1
6
<p>As part of <a href="https://codereview.stackexchange.com/a/40088/35408">this answer</a>, I created a mixin to generate some page-specific CSS for me.</p> <p>I need to style an element based on a class I assign to the <code>html</code>-element. I do this for four different classes on the root-element, which gives me four similar CSS rules.</p> <p>I'm looking for suggestions for the mixin itself. This is not limited to its function, also naming and the general <em>idea</em> may have so room for improvements.</p> <p><strong>Usage:</strong></p> <ul> <li>Pass the <code>$element</code> you want to style...</li> <li>...and the <code>$property</code> (needs to hold a color value) you want to style i with</li> <li>optionally, pass <code>true</code> as a third argument, if the light color variation should be used</li> </ul> <pre><code>@include themify(".page-title", background-color, true); </code></pre> <p><strong>Example Output:</strong></p> <pre><code>.page--blog .page-title { /* $blog-color-light */ background-color: #6fbf00; } .page--portfolio .page-title { /* $portfolio-color-light */ background-color: #ffaa10; } .page--profil .page-title { /* $profil-color-light */ background-color: #6d91da; } .page--impressum .page-title { /* $impressum-color-light */ background-color: #e04345; } </code></pre> <p><strong>Mixin:</strong></p> <pre><code>@mixin themify($element, $property, $light-colors: false) { $pages: null; @if $light-colors == true { $pages: blog $blog-color-light, portfolio $portfolio-color-light, profil $profil-color-light, impressum $impressum-color-light; } @else { $pages: blog $blog-color, portfolio $portfolio-color, profil $profil-color, impressum $impressum-color; } @each $page in $pages { .page--#{nth($page, 1)} #{$element} { #{$property}: nth($page, 2); } } } </code></pre>
[ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-02-03T16:33:51.743", "Id": "68733", "Score": "0", "body": "Questions like this (ie. how do I make my mixin generate the desired output) are generally better suited for SO." } ]
[ { "body": "<p>This uses mappings, which are part of Sass 3.3. You can do the same thing without mappings, it's just not as pretty. In addition to allowing multiple selectors, it allows for more options than just light/dark colors (eg. background images, etc):</p>\n\n<pre><code>$themes:\n ( blog:\n ( default: red\n , light: lighten(red, 20%)\n )\n , portfolio:\n ( default: orange\n , light: lighten(orange, 20%)\n )\n , profile:\n ( default: green\n , light: lighten(green, 20%)\n )\n , impressum:\n ( default: blue\n , light: lighten(blue, 20%)\n )\n );\n\n@mixin themify($property, $color: default) {\n @each $theme, $colors in $themes {\n .page--#{$theme} &amp; {\n #{$property}: map-get($colors, $color);\n }\n }\n}\n\n.foo, .bar {\n @include themify(background-color);\n @include themify(color, light);\n}\n</code></pre>\n\n<p>Output:</p>\n\n<pre><code>/* line 27, ../sass/test.scss */\n.page--blog .foo, .page--blog .bar {\n background-color: red;\n}\n/* line 27, ../sass/test.scss */\n.page--portfolio .foo, .page--portfolio .bar {\n background-color: orange;\n}\n/* line 27, ../sass/test.scss */\n.page--profile .foo, .page--profile .bar {\n background-color: green;\n}\n/* line 27, ../sass/test.scss */\n.page--impressum .foo, .page--impressum .bar {\n background-color: blue;\n}\n/* line 27, ../sass/test.scss */\n.page--blog .foo, .page--blog .bar {\n color: #ff6666;\n}\n/* line 27, ../sass/test.scss */\n.page--portfolio .foo, .page--portfolio .bar {\n color: #ffc966;\n}\n/* line 27, ../sass/test.scss */\n.page--profile .foo, .page--profile .bar {\n color: #00e600;\n}\n/* line 27, ../sass/test.scss */\n.page--impressum .foo, .page--impressum .bar {\n color: #6666ff;\n}\n</code></pre>\n\n<p>However, as you can tell from the output, it generates fairly inefficient CSS if you're using more than one property per selector. You can deal with this by manipulating global variables (again, 3.3 syntax):</p>\n\n<pre><code>$colors: null; // private, don't touch\n\n$themes:\n ( blog:\n ( base: red\n , light: lighten(red, 20%)\n )\n , portfolio:\n ( base: orange\n , light: lighten(orange, 20%)\n )\n , profile:\n ( base: green\n , light: lighten(green, 20%)\n )\n , impressum:\n ( base: blue\n , light: lighten(blue, 20%)\n )\n );\n\n@mixin themify {\n @each $theme, $c in $themes {\n .page--#{$theme} {\n $colors: $c !global;\n\n @content;\n }\n }\n}\n\n@function theme($color: base) {\n @return map-get($colors, $color);\n}\n\n@include themify {\n .foo, .bar {\n background-color: theme(base);\n color: theme(light);\n }\n}\n</code></pre>\n\n<p>Output:</p>\n\n<pre><code>/* line 42, ../sass/test.scss */\n.page--blog .foo, .page--blog .bar {\n background-color: red;\n color: #ff6666;\n}\n\n/* line 42, ../sass/test.scss */\n.page--portfolio .foo, .page--portfolio .bar {\n background-color: orange;\n color: #ffc966;\n}\n\n/* line 42, ../sass/test.scss */\n.page--profile .foo, .page--profile .bar {\n background-color: green;\n color: #00e600;\n}\n\n/* line 42, ../sass/test.scss */\n.page--impressum .foo, .page--impressum .bar {\n background-color: blue;\n color: #6666ff;\n}\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-02-04T17:53:53.440", "Id": "69992", "Score": "0", "body": "Hey. Thank you for these huge improvements. This really works out. I have a few questions. Using you second mixin, I need to specify which `$color` I want, even if it's the default one. Therefor, I can ommit `: base` in the function, right? Also, is there a reason why you choosed `default` for the first mixin and `base` for the second one? Just to distinct?" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-02-04T18:02:03.663", "Id": "69994", "Score": "0", "body": "I rewrote the second example later, 'default' didn't seem like a very good name so I changed it. It can be omitted when using the function (ie. `theme(base)` should return the same thing as `theme()`), I just thought it looked nicer that way." } ], "meta_data": { "CommentCount": "2", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-02-03T16:32:53.130", "Id": "40753", "ParentId": "40574", "Score": "6" } } ]
{ "AcceptedAnswerId": "40753", "CommentCount": "1", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-01-31T20:01:42.993", "Id": "40574", "Score": "8", "Tags": [ "optimization", "css", "sass", "scss" ], "Title": "Improve mixin that outputs page-specific CSS" }
40574
<p>Upon suggestion in the original question within Stack Overflow, I'm bringing <a href="https://stackoverflow.com/questions/21489330/complex-data-structure-organization-in-javascript?noredirect=1#comment32438189_21489330">this question</a> here.</p> <p><strong>Question Explained:</strong></p> <p>In a website that I built, I used complex multidimensional arrays to organize a multitude of information tables linked to events. I want to know if what I did was a viable efficient solution for the specific situation, or if something else would have made more sense, like using database tables or take an object oriented approach. </p> <p><strong>This is what I did:</strong></p> <p>I built a set of dropdown menus with javascript, The first list (category) determined what items where shown on the second list (service). If the user hovered over a category, the correlating services were displayed on the second list. If the user selected a service, a list of items in that service where shown in another part of the page(itemlist). Each item on the itemlist had unique values, prices, and 2 possible types, either check boxes or numerical entries. </p> <p>Hopefully that will make the following array examples make sense. All you need to know further about these arrays is that they correlate to achieve the above result.</p> <p><em>the below array is in image form for your convenience. Stack Overflow refused to keep my formatting, making it unreadable.</em> </p> <p><img src="https://i.stack.imgur.com/7L1Kv.png" alt="enter image description here"></p> <p><em>There are over 20 copies of this (above) array item with different services.</em></p> <p><img src="https://i.stack.imgur.com/bVp2k.png" alt="enter image description here"></p> <blockquote> <p>ServiceArray[0][0]:<br> [0]is the id to be assigned to the element.<br> ['1]is text name to be outputted.<br> ['2]is a variable name to be assigned.<br> ['3]is a key value to be appended to each item so I can call on a correlating value in the first array set.<br> ['4]is an example to be listed </p> </blockquote> <p>the downsides to this approach are obvious. The complex array structures become difficult to manage. When working with the variables, I had to continuously recount each variable to find the array keys. In the end though, i was able to use this approach very dynamically for the drop-downs and service lists. Here are a few examples of the code used to dynamically generate the content with these arrays. </p> <pre><code>$(".dropdown-service &gt; p").click(function () { var thisKey = $(this).data("key"); $("#ServiceOutput").text($(this).text()); $(".layer4").append('&lt;div class="ChoiceWrap"&gt;'); for (var i = 0; i &lt; ServiceArray[Category][thisKey][4][1][5].length; i++) { var listId = ServiceArray[Category][thisKey][6][1][i][7]; var listTitle = ServiceArray[Category][thisKey][8][1][i][0]; var List = ""; for (var x = 0; x &lt; ServiceArray[Category][thisKey][9][1][i][10].length; x++) { var Time = ServiceArray[Category][thisKey][11][1][i][12][x][13]; var Content = ServiceArray[Category][thisKey][14][1][i][15][x][0]; var Hours = ServiceArray[Category][thisKey][16][1][i][17][x][18]; List += '&lt;div class="li"&gt;&lt;div class="selection"&gt;&lt;/div&gt;&lt;p data-time="' + Time + '"&gt;' + Content + '&lt;span class="orange"&gt; ('+ Hours +'Hrs)&lt;/span&gt;&lt;/p&gt;&lt;/div&gt;'; } $(".layer4").append('&lt;div id="' + listId + '" class="listContainer"&gt;&lt;h2&gt;' + listTitle + '&lt;/h2&gt;&lt;div class="ListWrapper"&gt;' + List + '&lt;/div&gt;&lt;/div&gt;'); } $(".layer4").append('&lt;/div&gt;'); }); </code></pre> <p><strong>So the ultimate question:</strong> </p> <p>Is this method the best for the specific situation, or could I have done something more efficient to save time an effort while achieving the same result?</p>
[]
[ { "body": "<p>While there's nothing completely wrong with what you did, if I were the programmer coming in behind you - I would certainly curse your name. Writing \"good\" code (to me of course) requires more than meeting the objectives. Readability and maintainability are just as important.</p>\n\n<p>My concern with your design didn't set in until I saw the sample code to build the menu. Seeing all those brackets and indexes just about melted my brain. I think if you would use object literals rather than straight arrays then my problems go away as it should then be much more readable and straight forward.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-01-31T22:03:44.237", "Id": "68407", "Score": "0", "body": "This is a good answer." } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-01-31T21:46:08.320", "Id": "40579", "ParentId": "40576", "Score": "5" } }, { "body": "<p>Okay, I think that I have everything that I need from the comments in the original thread. Long story, short, this type of data really needs to be stored in objects.</p>\n\n<p>While not enforced by JS, arrays are really best used for groups of different values for a single type of data (e.g., and array of days of the week, months of the year, etc.). Objects, on the other hand, are a group of different peices of data that all represent aspects about a single \"thing\" (e.g., a \"person\" object could contain name, gender, age, height, weight, etc.)</p>\n\n<p>So, given what I can see of your data, what you need are an array of objects (in both cases). <code>PageSplashLists</code> is an array of <code>Category</code> objects, that each also contain an array of options for that <code>Category</code>. <code>ServiceArray</code> appearance to be an array of arrays of <code>Service</code> objects. I'm still not 100% sure of what the relationship is between <code>PageSplashLists</code> and <code>ServiceArray</code>, but let's start with what we have and I can update based on clarifications after the first attempt.</p>\n\n<p>So, for <code>PageSplashLists</code> I would suggest something like this:</p>\n\n<pre><code>PageSplashLists = [\n {categoryGroup: \"Framework\",\n inputType: \"checkbox\",\n categories: [\n {description: \"I have a non-generated website and need it upgraded.\",\n hours: 1},\n {description: \"I have a generated website and need it upgraded.\",\n hours: 2},\n {description: \"I need a new website created for this.\",\n hours: 3}\n ]\n },\n {categoryGroup: \"Design\",\n inputType: \"checkbox\",\n categories: [\n {description: \"I have images or examples of what I want this to look like.\",\n hours: 6},\n {description: \"I can tell you basically what I want this to look like.\",\n hours: 8},\n {description: \"I want you to be creative and design it. Make it amazing.\",\n hours: 10}\n ]\n },\n {categoryGroup: \"Graphic\",\n inputType: \"numeric\",\n categories: [\n {description: \"I need some custom graphics made.\",\n hours: 6},\n {description: \"I need graphic mouseover buttons.\",\n hours: 3},\n {description: \"I need [count] stock photos purchased.\",\n hours: 1}\n ]\n },\n . . . .\n</code></pre>\n\n<p>This way, you would reference each category group by it's array index, but, once \"inside\" you would reference the properties by their name . . . the same would apply to the <code>categories</code> arrays in each object. So, some examples of the references in the first category group would include:</p>\n\n<pre><code>PageSplashLists[0].categoryGroup (equals \"Framework\")\nPageSplashLists[0].inputType (equals \"checkbox\")\nPageSplashLists[0].categories[0].description (equals \"I have a non-generated website and need it upgraded.\")\nPageSplashLists[0].categories[0].hours (equals 1)\n</code></pre>\n\n<p><code>ServiceArray</code> would do something similar to fit its structure:</p>\n\n<pre><code>ServiceArray = [\n [{serviceName: \"Splash Page\",\n serviceKey: SplashPage, // I'm a little unclear as to how you are using these\n sampleURL: \"http://www.hollowaydesignfirm.com\"},\n {serviceName: \"Gaming Website\",\n serviceKey: GamingWebsite,\n sampleURL: \"http://www.faeria.net\"},\n {serviceName: \"Basic Website\",\n serviceKey: BasicWebsite,\n sampleURL: \"http://www.innovationsquareboston.com\"},\n . . . .\n ],\n [\n {serviceName: \"Basic Application\",\n serviceKey: BasicApplication,\n sampleURL: \"http://www.google.com\"},\n {serviceName: \"Market Application\",\n serviceKey: MarketApplication,\n sampleURL: \"http://www.google.com\"},\n {serviceName: \"Advanced Application\",\n serviceKey: AdvancedApplication,\n sampleURL: \"http://www.google.com\"}\n ],\n [\n {serviceName: \"Simple Web Tool\",\n serviceKey: BasicApplication,\n sampleURL: \"http://www.google.com\"},\n {serviceName: \"Advanced Web System\",\n serviceKey: AdvancedWebSystem,\n sampleURL: \"http://www.google.com\"},\n {serviceName: \"Industrial Application\",\n serviceKey: IndustrialApplication,\n sampleURL: \"http://www.google.com\"}\n ],\n . . . .\n</code></pre>\n\n<p>You'll notice that I removed the <code>[0]is the id to be assigned to the element.</code> and the <code>[3]is a key value to be appended to each item so I can call on a correlating value in the first array set</code> . . . the first one can be derived from the <code>serviceName</code> property, by using <code>.replace()</code> to get rid of any spaces in the value. For the second one, since the values are sequential and zero-based, can be derived from the index of the array (they are a direct match). Some examples of the references in the first service group would include:</p>\n\n<pre><code>ServiceArray[0][0].serviceName (equals \"Splash Page\")\nServiceArray[0][1].serviceKey (equals SplashPage)\nServiceArray[0][2].sampleURL (equals \"http://www.hollowaydesignfirm.com\")\n</code></pre>\n\n<p>I still feel like I'm missing more of a relationship between the two groups that might impact how they are each structured, but I don't see any information that would let me make those connections with any sense of surety.</p>\n\n<p>Let me know if you have any questions.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-01-31T22:08:41.093", "Id": "68408", "Score": "0", "body": "This is a good answer too. So, what the outcome here appears to be is that the arrays work, but using objects is a more efficient route for working in team based environments and updating data later on." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-01-31T22:14:29.830", "Id": "68409", "Score": "0", "body": "That and it's a better \"data representation\" of what you are storing, as referenced in my description of the best practices for using arrays and objects, at the beginning." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-01-31T23:04:58.637", "Id": "68415", "Score": "0", "body": "objects are just array with s" } ], "meta_data": { "CommentCount": "3", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-01-31T21:53:17.120", "Id": "40581", "ParentId": "40576", "Score": "2" } }, { "body": "<p>I would go with @mklinker. Multi-dimentional arrays are not very readable. I admit they get the job done, but its messy. And the JavaScript, that's just too crazy. A developer will have to go through the array and map the indexes to figure out what they are looking for. Definitely not fun, hard to modify, etc.</p>\n\n<p>I would rather create objects. With objects, you can serialize object to jSON and make your javascript more cleaner and readable. Your server-side code would also be clean. In addition, you wouldn't have a hard time extending the object should you choose to extend/modify your dropdown. You can then support different types of dropdown menus, for different purposes.</p>\n\n<p>Creating a good design might take longer, but it is totally worth it in the long run. Other developers appreciate it too.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-01-31T21:54:14.477", "Id": "40582", "ParentId": "40576", "Score": "1" } } ]
{ "AcceptedAnswerId": "40581", "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-01-31T21:14:18.407", "Id": "40576", "Score": "1", "Tags": [ "javascript", "jquery", "array" ], "Title": "Complex data structure organization in javascript?" }
40576
<p>I'm looking for feedback on my library for extracting words from a text: <a href="https://npmjs.org/package/uwords" rel="nofollow">https://npmjs.org/package/uwords</a></p> <p>The extracted word is defined as sequence of Unicode characters from Lu, Ll, Lt, Lm, Lo groups. So the code of the main part is (<a href="https://github.com/AlexAtNet/uwords/blob/master/index.js#L9" rel="nofollow">https://github.com/AlexAtNet/uwords/blob/master/index.js#L9</a>):</p> <pre><code>module.exports = function (text) { var words, word, index, limit, code; words = [ ]; word = null; for (index = 0, limit = text.length; index &lt; limit; index += 1) { code = text.charCodeAt(index); if (-1 === _.indexOf(letters, code, true)) { if (null !== word) { words.push(word.join('')); word = null; } } else { if (null === word) { word = [ ]; } word.push(String.fromCharCode(code)); } } if (null !== word) { words.push(word.join('')); } return words; }; </code></pre> <p>and the array <code>letters</code> was created as follows (<a href="https://github.com/AlexAtNet/uwords/blob/master/gruntfile.js#L59" rel="nofollow">https://github.com/AlexAtNet/uwords/blob/master/gruntfile.js#L59</a>):</p> <pre><code> grunt.registerTask('create-letters-json', 'letters.json', function () { var letters, compacted; letters = [ require('unicode/category/Lu'), require('unicode/category/Ll'), require('unicode/category/Lt'), require('unicode/category/Lm'), require('unicode/category/Lo') ].reduce(function (list, item) { list.push.apply(list, Object.keys(item).map(function (value) { return parseInt(value, 10); })); return list; }, [ ]).sort(function (a, b) { return a - b; }); compacted = (function (list) { var result, item, idx, value; result = [ ]; item = { begin : list[0], end : list[0] }; result.push(item); for (idx = 1; idx &lt; list.length; idx += 1) { value = list[idx]; if (item.end + 1 === value) { item.end = value; } else { item = { begin : list[idx], end : list[idx] }; result.push(item); } } for (idx = 0; idx &lt; result.length; idx += 1) { item = result[idx]; if (item.begin === item.end) { result[idx] = item.begin; } else { result[idx] = [ item.begin, item.end ]; } } return result; }(letters)); require('fs').writeFileSync(__dirname + '/letters.json', JSON.stringify(compacted, null, 2)); }); </code></pre> <p>It is quite naive approach but I think that it will work in most of the cases. What do you think?</p>
[ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-02-01T00:47:33.750", "Id": "68424", "Score": "0", "body": "I have not used node js. However, I wonder if you could simply use string replace?" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-02-01T01:58:28.003", "Id": "68427", "Score": "0", "body": "Sorry, did not get it - what do you mean by \"use string replace\"?" } ]
[ { "body": "<p>I have not used node js. However, I wonder if you could simply use string replace? For example, </p>\n\n<pre><code>v = 'I was walking down the park on day. I was running down the block'\nj = message.replace(/was/g, '')\n</code></pre>\n\n<p>The output would be the following. </p>\n\n<pre><code>'I walking down the park one day. I here'\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-02-01T00:44:06.937", "Id": "68422", "Score": "1", "body": "Hi James, please post comments *as comments*. I flagged this post as \"not an answer\"." } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-02-01T00:41:26.170", "Id": "40589", "ParentId": "40578", "Score": "0" } }, { "body": "<p>The top part looks clean, personally I would</p>\n\n<ul>\n<li>Not compare with <code>null</code> all the time, just check <code>word.length</code> and have <code>word</code> be an array at all times.</li>\n<li>Not initialize <code>word</code> and <code>words</code> separately</li>\n<li>Not use <code>String.fromCharCode(code)</code>, I would use <code>text[index]</code> instead</li>\n<li>I would use the <code>~</code> operator instead of comparing to <code>-1</code></li>\n<li>I would first deal with finding a match , and then with not finding a match ( switch the <code>if</code> blocks in other words ), my mind had to do a double take when I was reading your code</li>\n<li>if would add a space to the end of <code>text</code>, so that I would not need the last if statement</li>\n</ul>\n\n<p>All that would give me something like:</p>\n\n<pre><code>module.exports = function (text){\n text += \" \"; \n\n var words = [], \n word = [], \n limit = text.length, code, index;\n\n for (index = 0; index &lt; limit; index += 1) {\n code = text.charCodeAt(index);\n if (~_.indexOf(letters, code, true)) {\n word.push( text[index] )\n } else {\n if (word.length) {\n words.push(word.join(''));\n word = [];\n }\n }\n }\n return words;\n};\n</code></pre>\n\n<p>Finally, I think collecting char-codes in the 2nd script, then taking chars, converting those to char-codes and then use the chars again might not be the best approach.</p>\n\n<p>Personally, I would <code>letters</code> be an object where each letter ( not the char-code ) would be a property of the object set to true. No more char-code conversions, and most likely it would beat the sorted lookup table. ( To be tested.. )</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-02-01T23:41:12.077", "Id": "68520", "Score": "0", "body": "I've tried to use properties instead of the binary search, and it is much faster - but it is not consistent. For some reason `console.log(String.fromCharCode(195101) === String.fromCharCode(64029))` and as the result the `letters.length - Object.keys(obj).length = 1583` `obj = letters.reduce(function (tmp, item) { tmp[String.fromCharCode(item)] = item; return tmp; }, { }))`" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-02-02T00:12:02.373", "Id": "68528", "Score": "0", "body": "Happy that it is faster, disconcerting that you found that behaviour, I am fairly certain that you will win a ton of rep if you ask about this on stackoverflow ;)" } ], "meta_data": { "CommentCount": "2", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-02-01T16:55:47.117", "Id": "40623", "ParentId": "40578", "Score": "2" } } ]
{ "AcceptedAnswerId": "40623", "CommentCount": "2", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-01-31T21:24:28.413", "Id": "40578", "Score": "0", "Tags": [ "javascript", "parsing", "node.js", "unicode" ], "Title": "node.js library for extracting words from a text" }
40578
<pre><code> function reg(email, pass){ $.ajax({ url: "uman.php", type: "post", data:{email: email, password: pass}, success: function(reply){ if (reply == "success"){ $("#signinup").hide(); $("#donesucc").css("display","block"); console.log(reply); } if (reply == "duplicate"){ $("#signinup").hide(); $("#donedupe").css("display","block"); } } }) } </code></pre> <p>Anything I should change? The PHP just echos the status of the query and Javascript takes that value and outputs the results through HTML.</p>
[]
[ { "body": "<p>What do you think about this?</p>\n\n<pre><code>var Request = {\n version: 1.0, //not needed but i like versioning things\n xproxy: function(type, url, data, callback, timeout, headers, contentType) \n {\n if (!timeout || timeout &lt;= 0) { timeout = 15000; }\n $.ajax(\n {\n url: url,\n type: type,\n data: data,\n timeout: timeout,\n contentType: contentType,\n success:function(data) \n {\n if (callback != undefined) { callback(data); }\n },\n error:function(data) \n {\n if (callback != undefined) { callback(data); }\n }, \n beforeSend: function(xhr)\n {\n //headers is a list with two items\n if(headers)\n {\n xhr.setRequestHeader('secret-key', headers[0]);\n xhr.setRequestHeader('api-key', headers[1]);\n }\n }\n });\n }\n};\n\n&lt;script type=\"text/javascript\"&gt;\nvar contentType = \"applicaiton/json\";\nvar url = \"http://api.lastfm.com/get/data/\";\nvar timeout = 1000*5; //five seconds\nvar requestType = \"POST\"; //GET, POST, DELETE, PUT\n\nvar header = [];\nheader.push(\"unique-guid\");\nheader.push(\"23903820983\");\n\nvar data = \"{\\\"username\\\":\\\"james\\\"}\"; //you should really deserialize this w/ a function\nfunction callback(data)\n{\n //do logic here\n}\nRequest.xproxy(requestType, url, data, callback, timeout, header, contentType);\n&lt;/script&gt;\n</code></pre>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-02-01T00:29:33.647", "Id": "40588", "ParentId": "40583", "Score": "2" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-01-31T22:00:09.070", "Id": "40583", "Score": "2", "Tags": [ "javascript", "jquery", "ajax", "authentication" ], "Title": "JQuery/AJAX registration" }
40583
<p>My teacher assigned us to do the recursive version of mergesort, yet I heard that the non-recursive version (bottom up) is a bit tougher, so I decided to this one as well. My main concerns are: </p> <ol> <li>Considering the way I coded it, does it still have the same efficiency?</li> <li>Did I do this in an acceptable way? If not, why?</li> </ol> <p>Main:</p> <pre><code> Random rand = new Random(); ArrayList&lt;Integer&gt; array = new ArrayList&lt;Integer&gt;(); for (int i = 0; i &lt; 100; i++){ array.add(rand.nextInt(20)); } System.out.println("Original:"); for (int num: array){ System.out.print(" " + num); } Algorithm algo = new Algorithm(array); algo.print(); </code></pre> <p>Code:</p> <pre><code>ArrayList&lt;Integer&gt; ar = new ArrayList&lt;Integer&gt;(); int loBound = 0, hiBound = 1; public Algorithm(ArrayList&lt;Integer&gt; initAr){ ar = initAr; partition(); } public void partition(){ if (ar.size() &gt; 1){ int partitionSize = 1; int arraySize = ar.size(); if (ar.size() % 2 != 0) // if the size is odd make it even so loop doesn't terminate early without sorting all values arraySize++; while (arraySize / 2 &gt;= partitionSize){ while (true){ ArrayList&lt;Integer&gt; left = new ArrayList&lt;Integer&gt;(); ArrayList&lt;Integer&gt; right = new ArrayList&lt;Integer&gt;(); // Variables which will be sent to 'update' method as parameters. Tells method which indexes to update (in-between low and high) int loInd = loBound, hiInd; for (int i = loBound; i &lt; hiBound; i++){ left.add(ar.get(i)); } calcBounds(partitionSize); for (int j = loBound; j &lt; hiBound; j++){ right.add(ar.get(j)); } hiInd = hiBound; if (right.size() != partitionSize){ update(left, right, loInd, hiInd); break; } update(left, right, loInd, hiInd); calcBounds(partitionSize); } partitionSize*=2; loBound = 0; hiBound = partitionSize; } } } // calculates the indexes from which I will extract from the original array private void calcBounds(int partitionSize){ if (ar.size() - hiBound &gt; partitionSize){ loBound = hiBound; hiBound = loBound + partitionSize; }else { loBound = hiBound; hiBound = ar.size(); } } // updates original ArrayList after sorting 'left' and 'right' private void update(ArrayList&lt;Integer&gt; left, ArrayList&lt;Integer&gt; right, int loInd, int hiInd){ // sort ArrayList&lt;Integer&gt; result = new ArrayList&lt;Integer&gt;(); int lIndex = 0, rIndex = 0, resIndex = 0; while (lIndex &lt; left.size() || rIndex &lt; right.size()){ if (lIndex &lt; left.size() &amp;&amp; rIndex &lt; right.size()){ if (left.get(lIndex) &lt;= right.get(rIndex)){ result.add(resIndex, left.get(lIndex)); resIndex++; lIndex++; }else { result.add(resIndex, right.get(rIndex)); resIndex++; rIndex++; } }else if (lIndex &lt; left.size()){ result.add(resIndex, left.get(lIndex)); resIndex++; lIndex++; }else if (rIndex &lt; right.size()){ result.add(resIndex, right.get(rIndex)); resIndex++; rIndex++; } } // update original ArrayList using result ArrayList int count = 0; for (int i = loInd; i &lt; hiInd; i ++){ ar.set(i, result.get(count)); count++; } } void print(){ System.out.println(); System.out.println("Sorted:"); for (int num: ar){ System.out.print(" " + num); } } </code></pre>
[]
[ { "body": "<p>I have not looked into it too deeply to be able to fully answer your first question. Althought for you to get a picture of efficiency I would suggest to take the normal recursive merge sort and time it using <code>System.nanoTime()</code> and compare it with this version on the same array to be sorted. That could give you a picture about time complexity and regarding memory you would have to use a profiler. Simply jconsole can be enough in this case to see the memory consumption - careful with the GC kicking in when you don't want it.</p>\n\n<p><strong>Second question:</strong>\nI am not saying that it would be a bad looking code but I have difficulties to understand it. I would suggest few improvements that can help the readability. For example the first one in the method partition - instead of having the whole code block in if (ar.size() > 1) I would suggest having if (ar.size() &lt;= 1) then do return. This gets rid of one level of curly braces for the rest of the code block.</p>\n\n<p>Another suggestion would be to use instance variable as least as possible, in this case loBound = 0, hiBound = 1 and ar. There is a \"Brook's law for methods\" that says that method should be passed necessary variables as parameters if possible, if not then accessing instance variables and so on. Besides it is some statement it is also improves readability if the method changes only parameters it got passed and not instance variables. You can better track what is being changed and returned in and from the method.</p>\n\n<p>From where I am sitting the main downside of this code would be to come to it half year later and figure out what it does and if it does it right. I would say even the author of the code would have to take some time to figure it out.</p>\n\n<p>I am sorry I might not help you with your first question. Hope the comments on the second one regarding the code style could be of use for you. </p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-02-01T23:08:02.990", "Id": "68517", "Score": "0", "body": "Thanks. And, yes, I was also having doubts about setting loBound & hiBound as instance variables." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-02-02T11:00:13.263", "Id": "68558", "Score": "0", "body": "Your welcome. Glad it was helpful." } ], "meta_data": { "CommentCount": "2", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-02-01T22:26:25.207", "Id": "40639", "ParentId": "40585", "Score": "4" } }, { "body": "<p>First off, the practical performance difference between the iterative and recursive versions is likely to be modest in terms of time, but the former will save you O(n log n) procedure calls.</p>\n\n<p>Secondly, for performance, you shouldn't be creating new array-lists on every iteration. You only need one extra array for working space. Personally, I find an array based implementation easier to understand.</p>\n\n<p>Here's my effort in C#:</p>\n\n<pre><code>void Main()\n{\n var xs = new int[] { 1, 3, 5, 1, 2, 4 };\n MergeSort(xs);\n Console.WriteLine(xs);\n}\n\n// In-place merge-sort.\nstatic void MergeSort(int[] xs)\n{\n var n = xs.Length;\n var src = xs;\n var tgt = new int[n];\n for (var span = 1; span &lt; n; span += span) {\n for (var a = 0; a &lt; n; a += span + span) {\n var b = Math.Min(n, a + span);\n var c = Math.Min(n, b + span);\n Merge(src, tgt, a, b, c);\n }\n var tmp = src;\n src = tgt;\n tgt = tmp;\n }\n if (xs != src) for (var i = 0; i &lt; n; i++) xs[i] = src[i];\n}\n\n// Merge the ordered subarrays src[a..b) and src[b..c) into tgt[a..c).\n// src and tgt must be distinct arrays.\nstatic void Merge(int[] src, int[] tgt, int a, int b, int c)\n{\n var aTop = b;\n var bTop = c;\n var i = a;\n while (a &lt; aTop || b &lt; bTop) {\n tgt[i++] = (a == aTop) ? src[b++] : (b == bTop) ? src[a++] : (src[a] &lt;= src[b]) ? src[a++] : src[b++];\n }\n}\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-02-03T05:24:50.487", "Id": "68670", "Score": "2", "body": "500! Congratulations!" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-02-04T15:54:24.173", "Id": "69969", "Score": "0", "body": "Good point about not having to create ArrayLists every time I didn't think about that." } ], "meta_data": { "CommentCount": "2", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-02-03T05:15:48.597", "Id": "40718", "ParentId": "40585", "Score": "3" } } ]
{ "AcceptedAnswerId": "40639", "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-01-31T22:41:49.153", "Id": "40585", "Score": "7", "Tags": [ "java", "optimization", "algorithm", "recursion", "mergesort" ], "Title": "Is this non-recursive mergesort efficient and a good way to simulate the recursive version?" }
40585
<p>I have built this conceptual design of a localization menu on this <a href="http://codepen.io/JGallardo/pen/jyqzo" rel="nofollow noreferrer">CodePen</a></p> <p><img src="https://i.stack.imgur.com/a7ruz.png" alt="Concept 2"></p> <p>I am wondering if I should have structured my <code>&lt;div&gt;</code>s better or if this should be wrapped in a <code>&lt;ul&gt;</code> instead since <code>&lt;div class="locale"&gt;</code> could be reduced in the CSS with <code>.international li</code>. </p> <p><strong>HTML</strong></p> <pre><code>&lt;div class="international"&gt; &lt;div class="locale"&gt; &lt;a href="#"&gt; &lt;!-- link pending --&gt; North America &lt;div class="americas"&gt;&lt;/div&gt; &lt;/a&gt; &lt;/div&gt; &lt;div class="locale"&gt; &lt;a href="#"&gt; &lt;!-- link pending --&gt; Europe &lt;div class="europe"&gt;&lt;/div&gt; &lt;/a&gt; &lt;/div&gt; &lt;div class="locale"&gt; &lt;a href="#"&gt; &lt;!-- link pending --&gt; Korea &lt;div class="korea"&gt;&lt;/div&gt; &lt;/a&gt; &lt;/div&gt; &lt;div class="intlButton"&gt; &lt;a href="#"&gt; &lt;!-- link pending --&gt; &lt;i class="fa fa-globe"&gt;&lt;/i&gt; &lt;/a&gt; &lt;/div&gt; &lt;!-- Planned functionality for production is not shown in this project --&gt; &lt;/div&gt; &lt;!--/ .international --&gt; </code></pre> <p><strong>CSS</strong></p> <pre><code>.international { background-color: rgb(36, 30, 30); color: #fff; letter-spacing: 1px; padding: 12px 0; width: 100%; } .locale { display: inline-block; margin-left: 6px; vertical-align: middle; } .locale a { color: #fff; text-decoration: none; } .americas, .europe, .korea { background-image: url('https://s3-us-west-2.amazonaws.com/s.cdpn.io/101702/flags-small.png'); background-repeat: no-repeat; margin-top: 3px; } .americas { background-position: 0px 0px; height: 11px; width: 48px; } .europe { background-position: -48px 0px; height: 11px; width: 48px; } .korea { background-position: -96px 0px; height: 11px; width: 16px; } .intlButton { float: right; font-size: 24px; margin-right: 6px; } .intlButton a { color: #444; } .intlButton i { background-color: rgba(225, 225, 225, .7); border-radius: 3px; padding: 4px; } </code></pre>
[]
[ { "body": "<p>This should be an <code>ul</code>. Even without CSS you will have a navigational structure. How about giving your nav a better suited name like <code>.nav-localization</code>?</p>\n\n<p>Also I guess the <code>div</code>'s inside your links will act like as sub navigations? These would be <code>ul</code>'s as well then.</p>\n\n<p>I've added comments to get rid of the whitespace between the list-items, since you're using <code>display: inline-block;</code>. This looks quite <em>dirty</em>, but it's the best solution for the whitespace issue and inline-block.</p>\n\n<p>Here is the markup, I'd go for:</p>\n\n<pre><code>&lt;ul class=\"nav-localization\"&gt;\n &lt;li class=\"locale\"&gt;\n &lt;a href=\"#\"&gt;\n North America\n &lt;/a&gt;\n &lt;ul class=\"sub-nav americas\"&gt;&lt;/ul&gt;\n &lt;/li&gt;&lt;!--\n --&gt;&lt;li class=\"locale\"&gt;\n &lt;a href=\"#\"&gt;\n Europe\n &lt;/a&gt;\n &lt;ul class=\"sub-nav europe\"&gt;&lt;/ul&gt;\n &lt;/li&gt;&lt;!--\n --&gt;&lt;li class=\"locale\"&gt;\n &lt;a href=\"#\"&gt;\n Korea\n &lt;/a&gt;\n &lt;ul class=\"sub-nav korea\"&gt;&lt;/ul&gt;\n &lt;/li&gt;&lt;!--\n --&gt;&lt;li class=\"intlButton\"&gt;\n &lt;a href=\"#\"&gt;\n &lt;i class=\"fa fa-globe\"&gt;&lt;/i&gt;\n &lt;/a&gt;\n &lt;/li&gt;\n&lt;/ul&gt;\n</code></pre>\n\n<p><strong>How you would select:</strong></p>\n\n<pre><code>.nav-localization {}\n\n.nav-localization &gt; li {}\n\n.nav-localization &gt; li &gt; a {}\n\n.nav-localization .sub-nav {}\n</code></pre>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-02-01T08:20:56.513", "Id": "40602", "ParentId": "40586", "Score": "3" } } ]
{ "AcceptedAnswerId": "40602", "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-01-31T23:26:14.637", "Id": "40586", "Score": "5", "Tags": [ "html", "css" ], "Title": "Is this HTML structure and CSS DRY enough in this country selection menu?" }
40586
<p>A discussion arose not long ago <a href="http://chat.stackexchange.com/transcript/message/13486960#13486960">on the 2nd Monitor</a> about how much reputation has been lost due to the reputation caps. There are a number of queries on the SEDE which try to address this:</p> <ul> <li><a href="http://data.stackexchange.com/codereview/query/76335/a-users-total-rep-on-meta-if-there-was-no-reputation-cap" rel="nofollow noreferrer">A Users total Rep ON META if there was no reputation cap</a></li> <li><a href="http://data.stackexchange.com/codereview/query/84763/percent-lost-to-reputation-cap-among-top-1000-users" rel="nofollow noreferrer">Percent lost to reputation cap among top 1000 users</a></li> <li><a href="http://data.stackexchange.com/codereview/query/89793/top-rated-users-if-there-was-no-reputation-cap" rel="nofollow noreferrer">Top-rated users if there was no reputation cap</a></li> </ul> <p>All of these queries (there are others as well) appear to suffer from the same two flaws... ( ... <a href="http://data.stackexchange.com/codereview/query/164174/repreplay-repmax-by-user" rel="nofollow noreferrer">until now with the query in this question</a> .... )</p> <ul> <li>the user's actual reputation is affected by things that are complicated, like posts being deleted, migrated on to, and off from the site, the starting rep bonus, and other things.</li> <li>that you cannot calculate a person's lost reputation without knowing the order in which the votes happened.</li> </ul> <p>To understand why the post migration and deletion is important, you have to understand that reputation caps happens on a daily cycle. The number of days that people max their rep is much lower (for non-Skeets) than the number of times things are deleted, etc. There are things that happen on days other than rep-max days, that affect your reputation, and mean that voting records for those things are not available on the Data Explorer. Your user record records your total reputation, but there is no way to sum up all the reputation events and re-create that. Thus, any attempts to figure out how much rep is lost will come up short, or long, and this leads to funny things like negative-lost-reputation.</p> <p>To understand why the order is significant, consider the following poor user 'Bob':</p> <ol> <li>Lucky day, and ends up at exactly 200 rep from a good answer.</li> <li>Someone upvotes again, and he loses 10 rep to the cap.</li> <li>Someone downvotes and he loses 2 (198)</li> <li>Someone downvotes again, he loses another 2</li> <li>Now his rep is 196 and the day ends ... sorry, no mortarboard for you, and you lost 10 rep</li> </ol> <p>If the order was different, then it could be lucky 'Bill' instead:</p> <ol> <li>Lucky day, and ends up at exactly 200 rep from a good answer.</li> <li>Someone downvotes and he loses 2 (198)</li> <li>Someone downvotes again, he loses another 2 (196)</li> <li>Someone upvotes again, and he scores 4, and loses 6 rep to the cap.</li> <li>Now his rep is 200 and the day ends ... Celebrate! Mortarboard for you!</li> </ol> <p>These calculations are more common than others, but, if you were to think of the implications of vote orders when the user offers a bounty... it's big.</p> <p>The most accurate way to calculate the daily rep requires recreating the order of reputation events. There are still some problems though:</p> <ul> <li>there is no way to find out when people downvote answers, which is a -1 rep hit.</li> <li>there is no way to find out if a user hit rep-max, lost some rep, and then an answer which he got reputation for was later deleted, and the reputation lost.</li> <li>if the user rep-maxes on their very first day, their joining bonus makes the process impossible.</li> </ul> <p>So, inspired by the complexities of actually calculating the cap, I <a href="http://data.stackexchange.com/codereview/query/164174/repreplay-repmax-by-user" rel="nofollow noreferrer">put together this query</a> which rebuilds the progression of reputation events for either a specific user, or for each user that has previously won the <a href="https://codereview.stackexchange.com/help/badges/25/mortarboard">Mortarboard</a> badge.</p> <h2>For Review:</h2> <p>How can this code be improved:</p> <ul> <li>cursors are notoriously inefficient, but is there a better way?</li> <li>are there missing edge cases?</li> </ul> <p>Any suggestions for improvement are welcome.... (and feel free to fork the query and take it for a spin!)</p> <pre><code>declare @userid as int = ##UserId:int?-1## declare @userrep as int declare @epoch as date = '1 jan 2099' declare @pdate as date declare @rdate as date declare @rtime as datetime declare @raction as varchar(10) declare @rrep as int declare @rcnt as int declare @rtmp as int declare @message as varchar(250) declare @rollingrep as int declare @rollingbonus as int declare @rollingcap as int ; create table #REPDAY ( UserId int not null, Reputation int not null, RepDate DATE not null, CapLimited int not null, UnCapped int not null, Discarded int not null) ; -- loop through all users who have earned mortarboard -- which is an appoximate list of people who have lost rep. -- or, if a userid is specified, use that user. declare TOPUSERS cursor for select Users.Id as UserId, Users.Reputation as Reputation from Users, Badges where @userid &lt; 0 and badges.Name = 'Mortarboard' and Badges.UserId = Users.id UNION ALL select Id, Reputation from Users where Id = @userid open TOPUSERS fetch next from TOPUSERS into @userid, @userrep while @@FETCH_STATUS = 0 begin -- for each user, reset the accumulators select @pdate = @epoch -- something different select @rcnt = 0 select @rollingrep = 0 select @rollingbonus = 0 select @rollingcap = 0 declare USERVOTES cursor for -- NOTE: convert to DATE truncates the Time-part!!! select convert(DATE, tstamp) as tdate, tstamp, action, rep from ( --Approved suggested edits. select se.ApprovalDate as tstamp, 'edit' as action, 2 as rep from SuggestedEdits se where se.OwnerUserId = @userid and se.ApprovalDate is not null UNION ALL -- Up and Down votes on Q's and A's select v.CreationDate as tstamp, 'invote' as action, case when v.VoteTypeId = 1 then 15 when v.VoteTypeId = 2 then p.PostTypeId * 5 -- cheeky 5 or 10 for question/answer when v.VoteTypeId = 3 then -2 when v.VoteTypeId = 8 then v.BountyAmount else 0 end as rep from Posts p, Votes v where v.PostId = p.Id and p.OwnerUserId = @userid and p.PostTypeId in (1,2) and v.VoteTypeId in (1,2,3,8) UNION ALL -- Bounties that were offered.... select v.CreationDate as tstamp, 'bounty' as action, -1 * v.BountyAmount as rep from Votes v where v.VoteTypeId = 9 and v.UserId = @userid ) as tdata order by tstamp open USERVOTES fetch next from USERVOTES into @rdate, @rtime, @raction, @rrep while @@FETCH_STATUS = 0 begin if @pdate &lt;&gt; @rdate and @rcnt &gt; 0 begin -- break point, new day, save old day's data insert into #repday values (@userid, @userrep, @pdate, @rollingrep, @rollingbonus, @rollingcap) -- reset our accumulators select @rollingrep = 0, @rollingcap = 0, @rollingbonus = 0, @pdate = @rdate end select @rcnt = @rcnt + 1 if @rrep &gt; 10 or @raction = 'bounty' -- things that score &gt; 10 (accept) are not capped - assume bonus never &lt;= 10 select @rollingbonus = @rollingbonus + @rrep else -- things that score 10 or less are subject to cap select @rollingrep = @rollingrep + @rrep if @rollingrep &gt; 200 begin -- last action passed the cap... but how much past? select @rtmp = @rollingrep - 200 -- set the value back to 200, and add the difference to the lost rep select @rollingrep = 200, @rollingcap = @rollingcap + @rtmp select @message = 'Vote Maxed ' + Convert(Varchar(20), @rdate) + ' ' + @raction + ' rep ' + Convert(varchar(3), @rrep) + ' ' + Convert(varchar(3), @rtmp) + ' rep wasted' print @message end fetch next from USERVOTES into @rdate, @rtime, @raction, @rrep end close USERVOTES deallocate USERVOTES -- save away the last day's values that were not break-processed insert into #repday values (@userid, @userrep, @rdate, @rollingrep, @rollingbonus, @rollingcap) select @message = 'Replayed user ' + Convert(varchar(10), @userid) + ' with rep ' + Convert(varchar(10), @userrep) + ' and repcnt ' + Convert(varchar(10), @rcnt) print @message fetch next from TOPUSERS into @userid, @userrep END close TOPUSERS deallocate TOPUSERS ; with UserLost as ( select UserId as LostId, sum(Discarded) as LostAmt from #REPDAY group by UserId ) select UserId as [User Link], Reputation as [Current Rep], Convert(Varchar(12), RepDate, 107) as [Date], CapLimited as [Actual Regular], UnCapped as [Accepts Bonuses], CapLimited + UnCapped as [Day Rep], Discarded as [Lost Rep], LostAmt as [Total Lost], Convert(Decimal(8,2), 100.0 * (convert(real,LostAmt) / convert(real,Reputation + LostAmt)) ) as [Lost%] from #REPDAY, UserLost where LostId = UserId and ( CapLimited + UnCapped &gt;= 200 -- days which count for Mortarboard or Discarded &gt; 0) -- days with lost rep order by Reputation DESC, RepDate ASC </code></pre>
[]
[ { "body": "<p>Going through this code again, it appears there are a few things that could be improved.</p>\n\n<h2>Use #Temp Table for User Selection</h2>\n\n<p>Instead of doing a cheap-shot UNION select to get the set of users to process, the right way would be to create a temp table, and then conditionally populate it:</p>\n\n<pre><code>create table #TopUsers (\n UserId int not null,\n Reputation int not null)\n\nif @userid &lt; 0\nbegin\n\n insert into #TopUsers\n select Users.Id as UserId, Users.Reputation as Reputation\n from Users, Badges\n where badges.Name = 'Mortarboard'\n and Badges.UserId = Users.id\n\nend else begin\n\n insert into #TopUsers\n select Id, Reputation\n from Users\n where Id = @userid\n\nend\n\ndeclare TOPUSERS cursor for\n select *\n from #TopUsers\n</code></pre>\n\n<p>This approach is more verbose, but the intent of the code is clearer and it makes it more maintainable.</p>\n\n<h2>Explicit vs. Implicit JOIN</h2>\n\n<p>Explicit joins have been available in SQL since the SQL-92 standard. The code in this question uses the coding standards from the older SQL-89 standard.</p>\n\n<p>There is nothing technically wrong with the implicit join syntax used in the code, but it is old-fashioned, and using explicit join syntax allows the join conditions in larger queries to be more obvious... changes would be, for example:</p>\n\n<blockquote>\n<pre><code>select Users.Id as UserId, Users.Reputation as Reputation\nfrom Users, Badges\nwhere @userid &lt; 0\n and badges.Name = 'Mortarboard'\n and Badges.UserId = Users.id\n</code></pre>\n</blockquote>\n\n<p>would become:</p>\n\n<pre><code>select Users.Id as UserId, Users.Reputation as Reputation\nfrom Users\ninner join Badges\n on Badges.UserId = Users.id\nwhere @userid &lt; 0\n and badges.Name = 'Mortarboard'\n</code></pre>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-02-03T22:57:13.713", "Id": "40794", "ParentId": "40595", "Score": "10" } } ]
{ "AcceptedAnswerId": "40794", "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-02-01T03:09:36.300", "Id": "40595", "Score": "22", "Tags": [ "sql", "sql-server", "t-sql", "stackexchange", "cursor" ], "Title": "Calculating Lost Reputation" }
40595
<p>I am a self taught coder taking a Programming Fundamentals class to work towards a degree. It's based on Python, which I'm not as familiar with as other languages. I added error handling like I would in javascript or php to be an overachiever. Professor gave online feedback (online course) not to use try-except, that it is ahead of where we are in the semester, that even when we do get there, she doesn't want it in our code, and that this code is "not well formed" because I used try-except. She gave no feedback as to what she meant and I don't think that sounds right but don't now enough to stand my ground. Googling "well formed python" just give me a bunch of xml.</p> <pre><code># main function def main(): # @input dist : distance traveled in miles # @input guse : gas used traveling dist # @output mpg : dist/guse # set dist from input "Enter miles traveled: " dist = input('Enter distance traveled(in miles): ') # make sure dist is a number, and if not print error and restart try: dist = float(dist) except ValueError: print('Distance traveled must be a number! You did not travel "' + \ dist + '" miles!') main() else: # if dist is 0.0, print error and restart try: x = 1 / dist except ZeroDivisionError: print('Miles traveled cannot be 0!') main() else: # set guse from input "Enter gas used in gallons: " gcon = input('Enter gas consumed traveling(in gallons): ') # make sure guse is a number, and if not print error and restart try: gcon = float(gcon) except ValueError: print('Gas consumed must be a number. You did not use "' + \ gcon + '"" gallons of gas!') main() else: # set mpg to dist divided by guse # if guse is 0.0, print error and restart try: mpg = dist / gcon except ZeroDivisionError: print('Gas consumed can not be 0!') main() else: # return(print) mpg print('Average miles per gallon(mpg):', format(mpg, '5.2f')) # print request for enter keypress to end input('press enter to continue') # Call main function main() </code></pre>
[ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-02-01T03:44:40.743", "Id": "68443", "Score": "4", "body": "[What makes a good question?](http://meta.codereview.stackexchange.com/questions/75/what-makes-a-good-question) suggests you start with a description of the problem which the code is trying to solve: for example, \"This is a school assignment to convert Centigrade to Fahrenheit\"; then the code; then the aspects of the code you feel unsure of: for example, whatever the professor said about it." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-02-01T04:06:30.043", "Id": "68445", "Score": "4", "body": "+1 for Much improved question... question for you though.... why is there some gas mileage pseudocode (off topic for Code Review) as well as real code for temperature conversion?" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-02-01T04:10:08.820", "Id": "68447", "Score": "3", "body": "For the pseudocode, there is no right answer... it's pseudocode.... but, **I** would put all the comment-marks '#' in the first column.... which would make it more readable." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-02-01T05:54:33.193", "Id": "68454", "Score": "0", "body": "[Wikipedia shows some examples of pseudocode](http://en.wikipedia.org/wiki/Pseudocode#Syntax). 'IF' is at the beginning of the line. After each 'IF' is a description of the test. On the next line and indented is the action taken if the test is true: for example, `IF foo is not a number[newline][indent]PRINT error[newline][indent]RETURN[newline][no-indent]`. The first word of each line is similar to [a BASIC keyword](http://en.wikipedia.org/wiki/BASIC#Typical_BASIC_keywords), for example IF, SET, PRINT, RETURN, FOR." } ]
[ { "body": "<p>I don't think <code>try</code> <code>except</code> <code>else</code> is a standard python construction - does it even execute? In that sense this does not look 'well formed'. Does this execute? It does not work when copy pasted but I think that's just formatting issues.</p>\n\n<p>It's hard to write this without some try's, since the standard string > float conversion method is </p>\n\n<pre><code> dist = input(\"enter distance\")\n dist_num = float(dist)\n</code></pre>\n\n<p>which will except if dist is not a number; most python coders just try/catch around it. Without try's you'd have to provide a way of checking for floats that doesn't require a try/catch; maybe it's the point of the assignment? Apart from input validation, it's just doing a division otherwise.</p>\n\n<p>To get a float from a string without a try, you could do:</p>\n\n<pre><code>def is_number(input_string):\n for char in input_string: \n if char not in '0123456789.': return False\n return True\n</code></pre>\n\n<p>before the string is converted to a float (this will also filter out negative numbers for free as written)</p>\n\n<p>In terms of style and construction, the conditions for the mileage and consumption are the same: positive numbers > 0. The only differences are the prompts and error messages. So it makes sense to write one function and pass the prompts in to it twice:</p>\n\n<pre><code>def get_input(prompt, error_msg ):\n value = input(prompt)\n if not is_number(value):\n print error_msg\n return get_input(prompt, error_msg)\n\n num = float(value)\n if num &lt;= 0:\n print error_msg\n return get_input(prompt, error_msg)\n\n return num\n</code></pre>\n\n<p>This will just keep asking until the user gives a positive number. \nThe rest is easy:</p>\n\n<pre><code> miles = get_input(\"Enter distance traveled(in miles):\", \"Distance traveled must be a number larger than 0\")\n gas = get_input(\"Enter gasoline consumed (in gallons):\", \"Gasoline consumed must be a number larger than 0\")\n\n mpg = miles/gas\n</code></pre>\n\n<p>This could actually be improved further by replacing 'is_number' with a function that did the float conversion and converted all non-numeric values to -1; then you could just have a single test in the get_input function. I did it 'the long way' so the logic is clearer.</p>\n\n<p>The last thing to look at is the layout, it would typically look like</p>\n\n<pre><code>def is_number():\n ..... etc\n\ndef get_input():\n ..... etc\n\ndef main():\n miles = get_input(\"Enter distance traveled(in miles):\", \"Distance traveled must be a number larger than 0\")\n gas = get_input(\"Enter gasoline consumed (in gallons):\", \"Gasoline consumed must be a number larger than 0\")\n ....... etc\n</code></pre>\n\n<p>That would make it easier to reuse the pieces. The standard pythonic way to call a main function is </p>\n\n<pre><code>if __name__ == 'main':\n main()\n</code></pre>\n\n<p>This makes sure the code only fires when the file is executed as a script, not when it's is imported as a module.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-02-01T08:18:54.553", "Id": "68458", "Score": "2", "body": "[`try-except-else`](http://docs.python.org/3/tutorial/errors.html#tut-handling) is a perfectly legal Python construct, and it's being used correctly here." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-02-01T17:03:50.463", "Id": "68490", "Score": "0", "body": "+1 for trying to answer the specific question, about how to try to code this without using try/except." } ], "meta_data": { "CommentCount": "2", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-02-01T07:29:22.513", "Id": "40600", "ParentId": "40596", "Score": "0" } }, { "body": "<p>I have three main remarks:</p>\n\n<ul>\n<li><p><strong>Recursion is not really an appropriate retry mechanism.</strong></p>\n\n<p>Try this: hold down <kbd>Enter</kbd> for a dozen responses, then hit <kbd>Control</kbd><kbd>C</kbd>. As you see, the stack trace is quite deep. It would be better for the call stack to be the same regardless of how the user arrived at a certain point in the code, because invariants make software easier to test and debug. You're using recursion as a GOTO, except it's worse because it leaves a trace. Instead, the validation should be done in a loop, which you break out of when valid input is obtained.</p></li>\n<li><p><strong>The code structure is a bit repetitive.</strong></p>\n\n<p>The routines to input the distance and gas consumption are actually quite similar, and could be written using shared code.</p></li>\n<li><p><strong>Trial division is a poor way to test for a zero value.</strong></p>\n\n<p>You test whether <code>dist</code> is zero with</p>\n\n<pre><code># if dist is 0.0, print error and restart\ntry:\n x = 1 / dist\nexcept ZeroDivisionError:\n print('Miles traveled cannot be 0!')\n main()\n</code></pre>\n\n<p>There are more straightforward ways to test for a zero value! You end up discarding <code>x</code>, so the trial division isn't even useful work.</p>\n\n<p>On further thought, your validation is not quite right. If you're going to validate your input, you might as well prohibit negative numbers. It <em>is</em> possible for the distance to be zero, when the car has been idling. (The zero-distance case would only be problematic when displaying efficiency in \"metric\" units of L / 100km.)</p></li>\n</ul>\n\n<p>In conclusion, your use of exceptions for validation is partly inappropriate (catching <code>ZeroDivisionError</code> to test for zero, especially for <code>dist</code>, from a logical viewpoint as well as a code expression viewpoint) and partly appropriate (catching <code>ValueError</code> to test for strings that cannot be interpreted as numbers). I don't see any alternative to catching <code>ValueError</code>, except perhaps checking the input string against a regular expression <code>\\d+(?:\\.(?:\\d*))?</code>, and I would consider <code>ValueError</code> to be the superior approach. I think it would be fair to challenge your professor to propose a better alternative — in my opinion, the ball is in her court.</p>\n\n<p>A minor note: your comments are inconsistent with your code. Your code has a variable named <code>gcon</code>; the comments mention <code>guse</code>.</p>\n\n<p>Suggested solution:</p>\n\n<pre><code>def ask(prompt, typeconv, typeconv_err, validation=None, validation_err=None):\n \"\"\"\n Displays the prompt and asks for user input. The result is passed through\n the typeconv function, then possibly a validation function as well. If \n either the type conversion fails (with a ValueError) or the validation \n fails (by being false value), then the respective error message is \n displayed, and the prompt is displayed anew.\n \"\"\"\n while True:\n val = input(prompt)\n try:\n val = typeconf(val)\n except ValueError:\n print(typeconv_err % (val))\n else:\n if validation is not None and not validation(val):\n print(validation_err % (val))\n else:\n return val\n\ndef main():\n dist = ask('Enter distance traveled(in miles): ',\n float,\n 'Distance traveled must be a number! You did not travel \"%s\" miles!',\n lambda dist: dist &gt;= 0.0,\n 'Miles traveled cannot be negative!')\n\n gcon = ask('Enter gas consumed traveling(in gallons): ',\n float,\n 'Gas consumed must be a number. You did not use \"%s\" gallons of gas!',\n lambda gcon: gcon &gt; 0.0,\n 'Gas consumed cannot be 0 or negative!')\n\n # print mpg\n mpg = dist / gcon\n print('Average miles per gallon(mpg):', format(mpg, '5.2f'))\n\n # print request for enter keypress to end\n input('press enter to continue')\n\n# Call main function\nmain()\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-02-01T14:47:30.907", "Id": "68476", "Score": "1", "body": "Can you try to address the teacher's comment in the OP, i.e. compare this solution with another which doesn't use try/except?" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-02-01T17:34:17.213", "Id": "68491", "Score": "0", "body": "@ChrisW Done, in [Rev 4](http://codereview.stackexchange.com/revisions/40601/4)." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-02-01T19:14:10.540", "Id": "68501", "Score": "1", "body": "Thank you. Given that avoiding an exception is more complicated than exception-handling (i.e. it requires parsing/pre-validating the input string) perhaps, who knows, the teacher expected a simplistic program which doesn't validate its input. http://www.python.org/doc//current/tutorial/errors.html#handling-exceptions shows using an exception to parse an int. http://stackoverflow.com/q/2262333/49942 suggests that exception handling is the idiomatic way." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-02-03T01:29:26.507", "Id": "68655", "Score": "1", "body": "Thank you all for helping me out. It basically solved all of my problems with this situation. I was sure that it wasn't the \"best\" way (I know little about python, and didn't have much time), but sub-optimal !== \"not well formed\". She gave no other feedback except she said that when we do cover this in the textbook she still doesn't want use using it in our code. It makes me wonder if it makes it harder for her to navigate and if so, why is she teaching the class?" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-02-03T11:43:09.783", "Id": "68697", "Score": "0", "body": "@user2921414 Some things do make your code harder to read. One thing is 'deeply nested if': see how your indentation keeps increasing and increasing off to the right, and see also [this blog entry](http://blog.kowalczyk.info/article/1ik/Deeply-nested-if-statements.html). If your 'get input' were a subroutine e.g. as shown in 200_success's `ask` function then `main` is straight-forward and hardly indents at all. Try to [create subroutines](http://www.refactoring.com/catalog/extractMethod.html) especially when the functionality is in more than one place e.g. two places where you 'ask' for input." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-02-03T11:53:16.500", "Id": "68700", "Score": "0", "body": "@user2921414 Having a recursive call to `main` (i.e. main calling itself) seems obvious to you but wrong to us. A function which calls itself as its own subroutine is called [recursion](https://www.google.com/search?q=programming+recursion). It's a powerful/advanced tool but IMO you're misusing it here. Your code would do better to use a loop: something like `def main(): while true: if try_run() break;` where try_run gets the input and does the calculation, returns false as soon as it fails (e.g. if an input is bad), and returns true on success. Or see the while loop in 200_success' answer." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-02-03T12:07:52.810", "Id": "68703", "Score": "0", "body": "\"seems wrong to us\" Not exactly \"wrong\" because it does work, at least. But inappropriate; not idiomatic; non-obvious (making a programmer who reads it think \"What?! Why?\"; like using a wrench instead of a hammer, to hammer-in a nail." } ], "meta_data": { "CommentCount": "7", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-02-01T08:14:50.427", "Id": "40601", "ParentId": "40596", "Score": "8" } }, { "body": "<blockquote>\n <p>I added error handling like I would in javascript or php <strong>to be an overachiever</strong>. Professor gave online feedback (online course) <strong>not to use try-except</strong>, that it is ahead of where we are in the semester, that even when we do get there, <strong>she doesn't want it in our code</strong>, and that this code is \"not well formed\" because I used try-except. She gave no feedback as to what she meant and I don't think that sounds right but don't now enough to stand my ground. Googling \"well formed python\" just give me a bunch of xml.</p>\n</blockquote>\n\n<p>That confuses me too; because <a href=\"https://www.google.com/search?q=well+formed\" rel=\"nofollow noreferrer\">well-formed</a> usually means \"syntactically correct\".</p>\n\n<p>Because you said \"no exceptions\" (and previously mentioned 'pseudocode'), perhaps what you are supposed to be learning at the moment is \"<a href=\"http://en.wikipedia.org/wiki/Structured_programming\" rel=\"nofollow noreferrer\">structured programming</a>\".</p>\n\n<p>If so, IMO that would mean you should be practising the basics of control flow: \"if\" statements, 'loops' (like \"for\" and \"while\"), calling subroutines (\"functions\"), returning from subroutines, etc.</p>\n\n<p>It can be argued (<a href=\"http://en.wikipedia.org/wiki/Structured_programming#Exception_handling\" rel=\"nofollow noreferrer\">for example, it says so here</a>) that \"exceptions\" and \"structured programming\" don't go well together.</p>\n\n<p>For example, here is some 'structured' code (pseudocode):</p>\n\n<pre><code>OPEN inputfile\nWHILE not end of input file\n READ next line of text from inputfile\n CALL subroutine to handle the line of text\nCLOSE inputfile\n</code></pre>\n\n<p>That looks good. But, what happens if the 'CALL subroutine' throws an exception? Execution would fly out of the loop: and then the inputfile is never closed!</p>\n\n<p>If the software can throw exceptions, there's a way to handle them <a href=\"https://stackoverflow.com/a/3770375/49942\">as described here for example</a>. However, perhaps that's more advanced than the teacher wants to be explaining and expecting of every student at the moment.</p>\n\n<p>(My first two Math lectures at university were on the subject of \"one plus one\", \"subtraction\", and what happens when you multiply by zero).</p>\n\n<p><a href=\"http://en.wikipedia.org/wiki/Python_(programming_language)\" rel=\"nofollow noreferrer\">Wikipedia claims that Python</a> supports structured programming:</p>\n\n<blockquote>\n <p>Python is a <em>multi-paradigm</em> programming language: object-oriented programming and <strong>structured programming</strong> are fully supported, and there are a number of language features which support functional programming and aspect-oriented programming (including by metaprogramming[26] and by magic methods).</p>\n</blockquote>\n\n<p>Googling for <code>structured programming</code> and <code>python</code> I found this web page: <a href=\"http://docs.huihoo.com/nltk/0.9.5/en/ch05.html\" rel=\"nofollow noreferrer\">Structured Programming in Python</a>.\nPerhaps these (this subset of Python) are the kinds of things you will be learning in this course, and/or the style of Python programming which the teacher imagines you should use.</p>\n\n<p>Although the page is quite long, note that the keyword \"try\" appears only once (quoted as follows) on this whole page; and note well the \"TODO\" comment: which shows that the author/teacher hasn't included how to use \"try\", nor what \"try\" means, in this syllabus.</p>\n\n<blockquote>\n <p>[TODO: explain ValueError exception]</p>\n\n<pre><code>def concordance(word, context):\n \"Generate a concordance for the word with the specified context window\"\n for sent in nltk.corpus.brown.sents(categories='a'):\n try:\n pos = sent.index(word)\n left = ' '.join(sent[:pos])\n right = ' '.join(sent[pos+1:])\n print '%*s %s %-*s' %\\\n (context, left[-context:], word, context, right[:context])\n except ValueError:\n pass\n</code></pre>\n</blockquote>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-02-01T22:13:24.653", "Id": "40638", "ParentId": "40596", "Score": "3" } } ]
{ "AcceptedAnswerId": "40638", "CommentCount": "4", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-02-01T03:29:10.897", "Id": "40596", "Score": "7", "Tags": [ "python", "exception-handling", "python-3.x", "converting", "validation" ], "Title": "Simple MPG calculator in Python" }
40596
<p>I need to validate the form inside a table and change the class of a <code>td</code>-element when the value is not set. I don't have a button inside a form and I can't use the jQuery <code>validate</code> script.</p> <p>I have written this code but is there a way to do this in a simpler way?</p> <p>I have written many pages with code like this.</p> <pre><code>&lt;script&gt; function richiesti() { var dati=0; var cognome=document.clienti.cognome.value; if ( cognome != '' ){ dati++; } else { document.clienti.cognome.focus(); } var nome=document.clienti.nome.value; if ( nome != '' ){ dati++; } else { document.clienti.nome.focus(); } var codfisc=document.clienti.codfisc.value; if ( codfisc != '' ){ dati++; } else { document.clienti.codfisc.focus(); } if ( dati == 3 ){ // Se i tre valori richiesti sono inseriti controllo il codice fiscale // Definisco un pattern per il confronto var pattern = /^[a-zA-Z]{6}[0-9]{2}[a-zA-Z][0-9]{2}[a-zA-Z][0-9]{3}[a-zA-Z]$/; // creo una variabile per richiamare con facilità il nostro campo di input var CodiceFiscale = document.getElementById("codfisc"); // utilizzo il metodo search per verificare che il valore inserito nel campo // di input rispetti la stringa di verifica (pattern) if (CodiceFiscale.value.search(pattern) == -1) { // In caso di errore stampo un avviso e pulisco il campo... alert("Il valore inserito non è un codice fiscale!"); CodiceFiscale.value = ""; CodiceFiscale.focus(); } else { document.clienti.submit() ; } } else { alert('Cognome, Nome e Codice fiscale sono campi obbligatori.'); if ( cognome == '' &amp;&amp; nome == '' &amp;&amp; codfisc == '' ){ // Cambio la classe del td al valore mancante document.getElementById('tdcognome').className="tdorange c_white b"; // Imposto la classe degli altri td nel caso sia stata cambiata document.getElementById('tdcodfisc').className="tdocra c_white b"; document.getElementById('tdnome').className="tdocra c_white b"; document.getElementById('cognome').value="richiesto"; document.clienti.cognome.focus(); } if ( cognome == '' &amp;&amp; nome != '' &amp;&amp; codfisc != '' ){ document.getElementById('tdcognome').className="tdorange c_white b"; document.getElementById('tdcodfisc').className="tdocra c_white b"; document.getElementById('tdnome').className="tdocra c_white b"; document.getElementById('cognome').value="richiesto"; document.clienti.cognome.focus(); } if ( cognome == '' &amp;&amp; nome == '' &amp;&amp; codfisc != '' ){ document.getElementById('tdcognome').className="tdorange c_white b"; document.getElementById('tdcodfisc').className="tdocra c_white b"; document.getElementById('tdnome').className="tdocra c_white b"; document.getElementById('cognome').value="richiesto"; document.clienti.cognome.focus(); } if ( cognome == '' &amp;&amp; nome != '' &amp;&amp; codfisc == '' ){ document.getElementById('tdcognome').className="tdorange c_white b"; document.getElementById('tdcodfisc').className="tdocra c_white b"; document.getElementById('tdnome').className="tdocra c_white b"; document.getElementById('cognome').value="richiesto"; document.clienti.cognome.focus(); } if ( cognome != '' &amp;&amp; nome == '' &amp;&amp; codfisc != '' ){ document.getElementById('tdcognome').className="tdocra c_white b"; document.getElementById('tdcodfisc').className="tdocra c_white b"; document.getElementById('tdnome').className="tdorange c_white b"; document.getElementById('nome').value="richiesto"; document.clienti.nome.focus(); } if ( cognome != '' &amp;&amp; nome == '' &amp;&amp; codfisc == '' ){ document.getElementById('tdcognome').className="tdocra c_white b"; document.getElementById('tdcodfisc').className="tdocra c_white b"; document.getElementById('tdnome').className="tdorange c_white b"; document.getElementById('nome').value="richiesto"; document.clienti.nome.focus(); } if ( cognome != '' &amp;&amp; nome != '' &amp;&amp; codfisc == '' ){ document.getElementById('tdcognome').className="tdocra c_white b"; document.getElementById('tdnome').className="tdocra c_white b"; document.getElementById('tdcodfisc').className="tdorange c_white b"; document.getElementById('codfisc').value="richiesto"; document.clienti.codfisc.focus(); } } } &lt;/script&gt; &lt;HTML&gt; &lt;form name="clienti" id="clienti" method="POST" action="&lt;?php echo $editFormAction; ?&gt;"&gt; &lt;table class="half" &gt; &lt;tr&gt; &lt;td id="tdcognome" class="tdocra c_white b"&gt;Cognome :&lt;/td&gt; &lt;td&gt;&lt;input name="cognome" id="cognome" type="text" class=" text-sx" value="" required&gt;&lt;/td&gt; &lt;td id="tdnome" class="tdocra c_white b"&gt;Nome :&lt;/td&gt; &lt;td&gt;&lt;input name="nome" id="nome" type="text" class="text-sx" value="" required&gt;&lt;/td&gt; &lt;td id="tdcodfisc" class="tdocra c_white b"&gt;Codice Fiscale :&lt;/td&gt; &lt;td&gt;&lt;input name="codfisc" id="codfisc" type="text" class="text-sx" value="" required&gt;&lt;/td&gt; &lt;/tr&gt; &lt;tr&gt; &lt;td colspan="6"&gt;&lt;a class="btn-orange" onClick="richiesti();" href="#"&gt;memorizza dati&lt;/a&gt;&lt;/td&gt; &lt;/tr&gt; &lt;/table&gt; &lt;/form&gt; &lt;/HTML&gt; </code></pre> <p>After the suggestions i make many modify at original code.</p> <p><strong>REVIEW CODE :</strong></p> <pre><code>&lt;script&gt; function richiesti() { //open function richiesti var dati=0; var cognome=document.clienti.cognome; var nome=document.clienti.nome; var codfisc=document.clienti.codfisc; [cognome, nome, codfisc].forEach(function (field) { // open function field if (field.value != ''){ // open if value dati++; } // close if value else { // open else value field.focus(); } // close else value }); // close function field if ( dati == 3 ){ // open if dati var pattern = /^[a-zA-Z]{6}[0-9]{2}[a-zA-Z][0-9]{2}[a-zA-Z][0-9]{3}[a-zA-Z]$/; var codiceFiscale = document.getElementById("codfisc"); if (codiceFiscale.value.search(pattern) == -1) { // open if codiceFiscale alert("Il valore inserito non è un codice fiscale!"); codiceFiscale.value = ""; codiceFiscale.focus(); } // close if codiceFiscale else { // open else codiceFiscale document.clienti.submit() ; } // close else codiceFiscale } // close if dati else { // open else dati alert('Cognome, Nome e Codice fiscale sono campi obbligatori.'); if (cognome.value == '') { // open if cognome document.getElementById('tdcognome').className = "tdorange c_white b"; document.getElementById('tdcodfisc').className = "tdocra c_white b"; document.getElementById('tdnome' ).className = "tdocra c_white b"; document.getElementById('cognome').value = "richiesto"; cognome.focus(); } // close if cognome else { // open else cognome document.getElementById('tdcognome').className="tdocra c_white b"; if (nome.value == '') { // open if nome document.getElementById('tdcodfisc').className = "tdocra c_white b"; document.getElementById('tdnome' ).className = "tdorange c_white b"; document.getElementById('nome').value = "richiesto"; nome.focus(); } // close if nome else { // open else nome if (codfisc.value == '' ) { // open if codfisc document.getElementById('tdnome' ).className = "tdocra c_white b"; document.getElementById('tdcodfisc').className = "tdorange c_white b"; document.getElementById('codfisc').value = "richiesto"; codfisc.focus(); } // close if codfisc } // close else nome } // close else cognome } // close else dati } // close function richiesti &lt;/script&gt; </code></pre>
[]
[ { "body": "<p>Here are some minor refactoring tips. You should put this function into a class/object, if you are repeating your code. And then import the file onto each html page that requires this validation. </p>\n\n<p>You shouldn't check if the variable is empty this way</p>\n\n<pre><code>if ( cognome != '')\n{\n //code goes here\n}\n</code></pre>\n\n<p>The better way is the following: </p>\n\n<pre><code>// this way checks to see if the variable is null and/or empty\nif (congnome)\n{\n//code goes here\n}\n</code></pre>\n\n<p>You could also move the following into its own function <code>document.getElementById('tdnome').className=\"tdocra c_white b\";</code></p>\n\n<p>For example:</p>\n\n<pre><code>function changeClassName(elementId, newClassValue)\n{\n if (elementId)\n {\n document.getElementById(elementId).class = newValue;\n }\n}\n</code></pre>\n\n<p>Then you can just call it. </p>\n\n<pre><code>changeClassName('tdnome', '\"tdocra c_white b');\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-02-01T12:56:19.173", "Id": "68471", "Score": "0", "body": "The validation happen here : <a class=\"btn-orange\" onClick=\"richiesti();\" href=\"#\">memorizza dati</a>" } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-02-01T12:30:04.587", "Id": "40611", "ParentId": "40606", "Score": "3" } }, { "body": "<p>Let's talk about this part:</p>\n\n<pre><code>var cognome=document.clienti.cognome.value;\nif ( cognome != '' ){ dati++; } else { document.clienti.cognome.focus(); }\n</code></pre>\n\n<p>First of all, the indentation is awful. We can either do without braces</p>\n\n<pre><code>if (cognome != '') dati++;\nelse document.clienti.cognome.focus();\n</code></pre>\n\n<p>or preferably, put that conditional onto multiple lines.</p>\n\n<pre><code>if (cognome != ''){\n dati++;\n} else {\n document.clienti.cognome.focus();\n}\n</code></pre>\n\n<p>Now, you use both <code>document.clienti.cognome.value</code> and <code>document.clienti.cognome.focus</code>. It would be better to assign <code>document.clienti.cognome</code> to some variable, then:</p>\n\n<pre><code>var cognome = document.clienti.cognome;\nif (cognome.value != ''){\n dati++;\n} else {\n cognome.focus();\n}\n</code></pre>\n\n<p>This allows us to remove repetition by looping over some values:</p>\n\n<pre><code>var cognome = document.clienti.cognome; \nvar nome = document.clienti.nome;\nvar codfisc = document.clienti.codfisc;\n\n[cognome, nome, codfisc].forEach(function (field) {\n if (field.value != ''){\n dati++;\n } else {\n field.focus();\n }\n});\n</code></pre>\n\n<p>Later, you test for various combinations of fields being populated and assign classes depending on these combinations. The problem is that the classes do not always depend on all fields, so we could simplify that massive sequence of <code>if</code>s:</p>\n\n<pre><code>if (cognome.value == '') {\n document.getElementById('tdcognome').className = \"tdorange c_white b\";\n document.getElementById('tdcodfisc').className = \"tdocra c_white b\"; \n document.getElementById('tdnome' ).className = \"tdocra c_white b\";\n document.getElementById('cognome').value = \"richiesto\";\n cognome.focus();\n}\nelse {\n document.getElementById('tdcognome').className=\"tdocra c_white b\";\n if (nome.value == '') {\n document.getElementById('tdcodfisc').className = \"tdocra c_white b\";\n document.getElementById('tdnome' ).className = \"tdorange c_white b\";\n document.getElementById('nome').value = \"richiesto\";\n nome.focus();\n }\n else {\n if (codfisc.value == '' ) {\n document.getElementById('tdnome' ).className = \"tdocra c_white b\";\n document.getElementById('tdcodfisc').className = \"tdorange c_white b\";\n document.getElementById('codfisc').value = \"richiesto\";\n codfisc.focus();\n }\n }\n}\n</code></pre>\n\n<p>Oh look, the body is always the same if <code>cognome == ''</code>! Because we now cleaned up the conditions, we can also see that some cases have been missed: what happens if <code>cognome != '' &amp;&amp; nome != '' &amp;&amp; codfisc != ''</code>? In cases like this it would be helpful to write a comment explaining that no classes will be changed.</p>\n\n<hr>\n\n<p>There are a few more comments to be made on your style:</p>\n\n<ul>\n<li><p>Avoid non-English comments and variable names. I had difficulty understanding your code because I do not speak Italian. English is spoken by virtually all programmers, so it's a better choice for maintainable code.</p></li>\n<li><p>It seems your indentation has been messed up by copying the code here. However, there are one very bad thing:</p>\n\n<pre><code>if (cond) {\n statement;\n last_statement }\n</code></pre>\n\n<p>Place the closing curly brace on a line of it's own, this makes it easier to see.</p></li>\n<li><p>You have one variable that's uppercase: <code>CodiceFiscale</code>. Stick to a consistent naming scheme, preferably <code>camelCase</code>.</p></li>\n<li><p>Your code could become much shorter by using jQuery. It's a de-facto standard, and helps abstracting over many compatibility issues.</p></li>\n<li><p>Using <code>==</code> instead of <code>===</code> is usually frowned upon, as <code>==</code> tries to coerce the values to some mathching type. Depending on what you're trying to do, this is actually preferable, but most of the time it's a code smell. The <code>===</code> operator first asserts that both values are of the same type.</p></li>\n</ul>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-02-01T17:30:18.753", "Id": "40626", "ParentId": "40606", "Score": "4" } } ]
{ "AcceptedAnswerId": "40626", "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-02-01T10:19:26.043", "Id": "40606", "Score": "4", "Tags": [ "javascript", "php", "html5" ], "Title": "Validating a form without using a button and changing td class" }
40606
<p>I have a huge list of regexes (>1,000 but &lt;1,000,000) that I want to test against (many) single strings.</p> <p>It is unlikely and unintended that more than one such expression would match a single string. I could just maintain a big list of each compiled, individual regex and iterate over that for every input string. However I have it in my head that I should be handing the problem over to the regex compiler to simplify the common substrings since it can (at least theoretically) produce a very neat single DFA.</p> <pre><code>import re import uuid class multiregex(object): def __init__(self,rules): merge = [] self._messages = {} for regex,text in rules: name = "g"+str(uuid.uuid4()).replace('-','') merge += ["(?P&lt;%s&gt;%s)" % (name,regex)] self._messages[name] = text self._re=re.compile('|'.join(merge)) def __call__(self,s): result = self._re.search(s) if result: groups = result.groupdict() return ((self._messages[x], groups[x]) for x in groups.keys() if groups[x]).next() rules = [("foobar", "Hit a foobar"), ("f.*b.*r", "fbr"), ("foob.z", "Frobination"), ("baz", "Hit a baz"), ("b(ingo)?", "b with optional ingo")] m=multiregex(rules) tests=["foobar", "foobaz", "foobazr", "b", "bingo"] for text,hit in (m(x) for x in tests): print "Message: '%s' (because of '%s')" % (text,hit) </code></pre> <p>The code above works, but am I have a few outstanding issues with it:</p> <ol> <li>Is it needlessly over complicating the whole thing? Or is it pushing the problem off to code that's heavily researched and optimised.</li> <li>Is there a neater way of finding just the named capture group that matched than what I've done with <code>groupdict()</code>?</li> <li><p>Are there any more gotchas than the obvious one of two 'rules' each containing the same group name? e.g.:</p> <pre><code>rules = [("(?P&lt;hello&gt;foobar)", "Hit a foobar"), ("(?P&lt;hello&gt;foob.z)", "Frobination")] </code></pre></li> </ol> <p>(The issue of a single syntax error in a single 'rule' killing the whole thing is easy enough to workaround by validating the inputs at rule creation time)</p>
[ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-02-01T11:43:16.010", "Id": "68466", "Score": "0", "body": "If you have > 1000 regular expressions to test, **are you really sure that you want to use regular expressions?** It sounds to me like you are building a parser of some kind, in which case regex is not the way to go I believe." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-02-01T12:02:01.180", "Id": "68468", "Score": "0", "body": "@SimonAndréForsberg regex is definitely right here - they're essentially heuristics contributed by (many) domain experts and the input strings are too unstructured to do anything smarter with a proper lexer/parser." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-02-01T16:29:58.463", "Id": "68484", "Score": "1", "body": "What is the purpose of the regexes? In your code above it prints that a match happened because of a specific rule... Is this needed, or is just 'It Matches!!!' OK (i.e. do you need to know which rule matched)?" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-02-01T16:30:59.467", "Id": "68485", "Score": "0", "body": "@rolfl the knowledge of which one matched is important - the messages need to get relayed back to users, which is why I return a tuple of the message and the text that matched." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-02-01T16:34:02.790", "Id": "68486", "Score": "0", "body": "In which case, combining the regexes in to a larger DFA will likely lose you that possibility.... right?" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-02-01T16:35:20.910", "Id": "68488", "Score": "0", "body": "@rolfl the example code does exactly that but retains them through the named groups" } ]
[ { "body": "<ol>\n<li>I think it's a neat idea, because you're indeed using well-tested code, which reduces the chance of errors.</li>\n<li>Looking at the <code>re</code> API, you do need to retrieve all possibles matches using <code>groupdict()</code>.</li>\n<li>Even that one is not a gotcha since you're naming your groups yourself. Right? I can't think of anything else.</li>\n</ol>\n\n<p>Other comments:</p>\n\n<ul>\n<li>You have a small bug in your last loop where <code>text</code> and <code>hit</code> need to be exchanged.</li>\n<li>There's no easy to way to be sure that the DFA version will be faster than the normal version. Since you're not producing a factorized DFA but a sum of DFAs, naive code could be as slow as testing each regex one by one. Of course it's possible that it's much faster, but measure it if this is what you want to achieve!</li>\n<li>You don't need uuids, a simple counter would be enough. Eg <code>?P&lt;g1&gt;</code> instead of <code>?P&lt;fd897214dd9d4dd28f591a412ef5d3ea&gt;</code>.</li>\n</ul>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-02-12T16:37:02.777", "Id": "71304", "Score": "0", "body": "I did the UUID thing just in case someone else had put a group name inside their regex." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-02-12T16:49:49.003", "Id": "71305", "Score": "0", "body": "Oh, right, it makes sense." } ], "meta_data": { "CommentCount": "2", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-02-12T10:28:10.720", "Id": "41465", "ParentId": "40607", "Score": "5" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "6", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-02-01T11:27:59.993", "Id": "40607", "Score": "6", "Tags": [ "python", "strings", "regex" ], "Title": "Trying multiple regexes against a single string" }
40607
<p>I've recently started to delve into the world of windows phone 8 dev, and as a learning experience I've decided to make a stopwatch application. Now, given I've been a web guy most of my career, I've never come across UI thread locking issues, so the solution I've come up with to ensure my stopwatch class is updating the UI thread 'correctly' is (in my opinion at least) in need of a review.</p> <p>So my overall questions with the below code are;</p> <ol> <li><p>Am I doing it "right"? I realise that can be kind of broad; I just want to make sure I'm not committing any cardinal sins of UI development.</p></li> <li><p>Are there simpler approaches to what I've done?</p></li> <li><p>Are there any improvements to the code that someone would suggest? I'm not sure using thread.sleep is a good idea, but when I take it out, it ends up locking the UI thread again. Hence why I'm asking for input.</p></li> </ol> <p>My StopWatch Class:</p> <pre><code>public class StopwatchClass : IDisposable { DispatcherTimer _timer; public int Interval { get; set; } public int Seconds { get; set; } public int Minutes { get; set; } public int Hours { get; set; } public bool IsRunning { get { return _timer.IsEnabled; } } public TimeSpan Elapsed { get; set; } public List&lt;TimeSpan&gt; Splits { get; set; } public StopwatchClass(int interval) { this.Splits = new List&lt;TimeSpan&gt;(); _timer = new DispatcherTimer(); _timer.Interval = new TimeSpan(0, 0, interval); _timer.Tick += timer_Tick; } void timer_Tick(object sender, EventArgs e) { this.Seconds += 1; if (this.Seconds == 60) { this.Minutes += 1; this.Seconds = 0; } if (this.Minutes == 60) { this.Hours += 1; this.Minutes = 0; } } public void Start() { _timer.Start(); } public void Stop() { _timer.Stop(); } public void Reset() { _timer = new DispatcherTimer(); this.Seconds = 0; this.Minutes = 0; this.Hours = 0; this.Splits.Clear(); } public void Split() { var timeSpan = new TimeSpan(this.Hours, this.Minutes, this.Seconds); this.Splits.Add(timeSpan); } public void Dispose() { _timer.Tick -= timer_Tick; } } </code></pre> <p>And the WP8 button code (secondsValue is a text block on the wp8 page).</p> <pre><code>private async void startStopwatch_Click(object sender, RoutedEventArgs e) { watch.Start(); await Task.Factory.StartNew(() =&gt; { while (watch.IsRunning) { Thread.Sleep(1000); Dispatcher.BeginInvoke(() =&gt; secondsValue.Text = watch.Seconds.ToString()); } }); } </code></pre>
[]
[ { "body": "<p><strong>Minor</strong></p>\n\n<ol>\n<li><p>You should get rid of the <code>Class</code> suffix. There is no value in attaching the type as a suffix to the name. </p></li>\n<li><p>You don't need to write <code>this</code> everywhere to access members.</p></li>\n<li><p>You have an <code>Elapsed</code> property which is not used.</p></li>\n</ol>\n\n<p><strong>Bugs/Major</strong></p>\n\n<ol>\n<li><p>Your <code>Reset()</code> method will break the stopwatch because you create a new timer but you do not re-attach the timer tick event handler.</p></li>\n<li><p>You have a <code>Reset()</code> method which sets up the timer but you also do this in the constructor which is some code duplication and in fact has introduced a bug (see previous point). DRY - Don't Repeat Yourself. Make use of a common method which can get called in both places.</p></li>\n<li><p>Instead of \"polling\" your stopwatch in a continuous loop your <code>StopwatchClass</code> should expose an event like <code>TimeUpdated</code> to which any interested party can hook up to.</p>\n\n<p>In general this can pose problems when interacting with UI because if the callback happens on a different thread then you need to marshal UI access across to the UI thread. However you have used a <code>DispatcherTimer</code> which is evaluated at the top of every dispatcher loop - which means the callbacks are happening on the UI thread and it is safe to access UI elements from within the callback (see <a href=\"http://msdn.microsoft.com/en-us/library/system.windows.threading.dispatchertimer%28v=vs.110%29.aspx\" rel=\"nofollow\">the MSDN example</a>).</p>\n\n<p>So basically you can expose an event which gets fired on the timer callback and whatever code hooks up to it can update the UI. </p></li>\n<li><p>In general MVVM has established itself as a very useful pattern. Which means that rather than updating UI elements directly you would update an observable view model to which the UI is bound. This decouples the UI better from the data and decoupling is always good.</p></li>\n<li><p>The timer is guaranteed to not fire before the interval has elapsed - but there is no guarantee about how long after the interval has elapsed it will fire. This means your stopwatch will start falling behind the real time as you assume each tick is 1 second while in fact it might be 1.01 sec or so. This means after 100 seconds you could be easily 1 sec off or more. A thread time slice in windows is typically around 10ms so I'd suspect the timer to be around that accuracy. Although on Windows Phone you might get better performance (couldn't find any documentation in that regards).</p>\n\n<p>The way to overcome this is to take a timestamp at <code>Start</code> and compute the difference to the current time on each tick. While this will probably also give you an approx. 10ms accuracy it will be constant while your solution will accumulate an error on each tick.</p>\n\n<p>This will also alleviate the need to compute the seconds, minutes and hours since passing as you can get that from the <code>Timespan</code>.</p></li>\n</ol>\n\n<p>With the changes from above your code could look like this:</p>\n\n<pre><code>public class StopwatchClass : IDisposable\n{\n DispatcherTimer _timer;\n\n public int Interval { get; set; }\n\n public int Seconds { get; set; }\n public int Minutes { get; set; }\n public int Hours { get; set; }\n\n public bool IsRunning { get { return _timer.IsEnabled; } }\n public TimeSpan Elapsed { get; set; }\n public List&lt;TimeSpan&gt; Splits { get; set; }\n\n private DateTime _StartTimestamp = DateTime.MaxValue;\n\n public event EventHandler TimeUpdated;\n private void OnTimeUpdated()\n {\n var handler = TimeUpdated;\n if (handler != null)\n {\n TimeUpdated(this, EventArgs.Empty);\n }\n }\n\n public StopwatchClass(int interval)\n {\n Reset();\n }\n\n void timer_Tick(object sender, EventArgs e)\n {\n var timeSinceStart = DateTime.Now - _StartTimestamp;\n Seconds = (int)timeSinceStart.Seconds;\n Minutes = (int).timeSinceStart.Minutes;\n Hours = (int)timeSinceStart.TotalHours;\n OnTimeUpdated();\n }\n\n public void Start()\n {\n _StartTimestamp = DateTime.Now;\n _timer.Start();\n }\n\n public void Stop()\n {\n _StartTimestamp = DateTime.MaxValue\n _timer.Stop();\n }\n\n public void Reset()\n {\n Seconds = 0;\n Minutes = 0;\n Hours = 0;\n Splits = new List&lt;TimeSpan&gt;();\n _timer = new DispatcherTimer();\n _timer.Interval = new TimeSpan(0, 0, interval);\n _timer.Tick += timer_Tick;\n }\n\n public void Split()\n {\n var timeSpan = new TimeSpan(Hours, Minutes, Seconds);\n Splits.Add(timeSpan);\n }\n\n public void Dispose()\n {\n _timer.Tick -= timer_Tick;\n }\n}\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-02-06T04:39:38.037", "Id": "70316", "Score": "0", "body": "so to clarify re the MVVM approach, the ViewModel would have a property (say, elapsed) that is being updated by the stopwatch class?" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-02-10T23:00:05.863", "Id": "71027", "Score": "0", "body": "@AdamGrande: Yes that's the basic idea." } ], "meta_data": { "CommentCount": "2", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-02-02T00:19:56.753", "Id": "40646", "ParentId": "40609", "Score": "3" } } ]
{ "AcceptedAnswerId": "40646", "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-02-01T12:23:35.377", "Id": "40609", "Score": "5", "Tags": [ "c#", "task-parallel-library", "windows-phone" ], "Title": "Non locking UI code in WP8" }
40609
<p>I am building a Python app in which user can maintain wishlist of the products. I only support few e-commerce sites and do not support country specific sites (e.g I may support amazon.com but not amazon.in). I do not support mobile version of the URL (e.g. <a href="http://m.amazon.com" rel="nofollow">http://m.amazon.com</a>) and also I am not interested in the query string part of the URL (and I don't want it also).</p> <p>Following is the code and also the test cases. Though it seems to be working, I am not happy with the code. It looks hackish to me. I would really appreciate improving <code>get_vendor</code> function. Do you find it readable? </p> <pre><code>from urlparse import urlparse supported_vendors = ['flipkart.com', 'homeshop18.com', 'snapdeal.com', 'myntra.com', 'www.flipkart.com', 'www.homeshop18.com', 'www.snapdeal.com', 'www.myntra.com'] test_urls =['http://www.myntra.com/sports-shoes/puma/puma-men-grey-kuris-ii-ind-running-shoes/107455/buy?searchQuery=sports-shoes&amp;serp=1&amp;uq=false#!', 'www.myntra.com/sports-shoes/puma/puma-men-grey-kuris-ii-ind-running-shoes/107455/buy?searchQuery=sports-shoes&amp;serp=1&amp;uq=false#!', 'https://myntra.com/sports-shoes/puma/puma-men-grey-kuris-ii-ind-running-shoes/107455/buy?searchQuery=sports-shoes&amp;serp=1&amp;uq=false#!', 'http://.myntra.com/sports-shoes/puma/puma-men-grey-kuris-ii-ind-running-shoes/107455/buy?searchQuery=sports-shoes&amp;serp=1&amp;uq=false#!', 'htt://www.myntra.com/sports-shoes/puma/puma-men-grey-kuris-ii-ind-running-shoes/107455/buy?searchQuery=sports-shoes&amp;serp=1&amp;uq=false#!', 'http://blahblah.com/sports-shoes/puma/puma-men-grey-kuris-ii-ind-running-shoes/107455/buy?searchQuery=sports-shoes&amp;serp=1&amp;uq=false#!', 'ftp://myntra.com/sports-shoes/puma/puma-men-grey-kuris-ii-ind-running-shoes/107455/buy?searchQuery=sports-shoes&amp;serp=1&amp;uq=false#!'] test_expected_results = [True, True, True, False, False, False, False] def get_vendor(url): def add_http(url): return 'http://'+url def get_url(parsed_url): return 'http://'+parsed_url.netloc+parsed_url.path if not urlparse(url).scheme: parsed_url = urlparse(add_http(url)) elif urlparse(url).scheme not in ['http', 'https']: return (None, url) else: parsed_url = urlparse(url) if parsed_url.netloc not in supported_vendors: return (None, url) else: return (parsed_url.netloc, get_url(parsed_url)) if __name__ == '__main__': # for i in map(get_vendor, test_urls): # print i assert(map(lambda x: bool(x[0]), map(get_vendor, test_urls)) == test_expected_results) </code></pre> <p>based on what vendor returns I apply different scraping functions. Here is the next code:</p> <pre><code>HS18 = ['homeshop18.com', 'www.homeshop18.com'] SD = ['snapdeal.com', 'www.snapdeal.com'] FS = ['flipkart.com', 'www.flipkart.com'] MYN = ['myntra.com', 'www.myntra.com'] vendor, url = get_vendor(url) if not vendor: exit # or throw error product_doc = search_for_url_in_database(url) if not product_doc: if vendor in FS: product_url, product_name, product_img_url, product_price = get_flipkart_product_meta(url) elif vendor in HS18: product_url, product_name, product_img_url, product_price = get_homeshop18_product_meta(url) elif vendor in SD: product_url, product_name, product_img_url, product_price = get_snapdeal_product_meta(url) else: product_url, product_name, product_img_url, product_price = get_myntra_product_meta(url) ... </code></pre> <p>This last if block I can change it to:</p> <pre><code>if not product_doc: if vendor in FS: get_product_meta = get_flipkart_product_meta elif vendor in HS18: get_product_meta = get_homeshop18_product_meta elif vendor in SD: get_product_meta = get_snapdeal_product_meta else: get_product_meta = get_myntra_product_meta product_url, product_name, product_img_url, product_price = get_product_meta(url) ... </code></pre> <ol> <li><p>What do you say about this second <code>if</code> block where I am assigning function object to a variable and calling it later. Should I be doing like this? What's the suggested way?</p></li> <li><p>The lists defined at top, has redundant data. Is there any way to make it better?</p></li> <li><p>I really would like to keep leading <code>www</code> if the url has (even though avoiding this do not harm). So how do I do this with cleaner way? or you suggest to remove <code>www</code> completely?</p></li> </ol> <p>Generally how do you guys handle situation like this, when you have to call a function based on if-else blocks?</p> <p><strong>EDIT</strong>: Following code was suggested by someone on reddit. Looks clean to me:</p> <pre><code>PRODUCT_METAS = { 'homeshop18.com': get_homeshop18_product_meta, 'snapdeal.com': get_snapdeal_product_meta, 'flipkart.com': get_flipkart_product_meta, ' myntra.com': get_myntra_product_meta, } vendor, url = get_vendor(url) if vendor is None: exit() product_doc = search_for_url_in_database(url) if not product_doc: if vendor.startswith('www.'): vendor = vendor[len('www.'):] try: product_url, product_name, product_img_url, product_price = PRODUCT_METAS[vendor](url) except KeyError: exit </code></pre>
[ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-02-02T09:19:52.577", "Id": "68551", "Score": "0", "body": "You allow https but `get_url` always uses http. Is that right?" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-02-02T09:39:39.007", "Id": "68553", "Score": "0", "body": "yes. you are right. These e-commerce sites do not have problem if the URL is HTTP or HTTPS. Or else in `get_url` I have to check whether `scheme` is `http` or `https`, based on that I have to append HTTP or HTTPS. Just to avoid an `if` block, which I thought unnecessary since these sites do not complain, I thought of going with HTTP. And thank you for going over my code." } ]
[ { "body": "<p>The two helper functions feel redundant to me; <code>'http://'+url</code> is clear enough as is, and there is an <code>urlunparse</code> in <code>urlparse</code> module.</p>\n\n<p>My proposal:</p>\n\n<pre><code>def get_vendor(url):\n parsed_url = urlparse(url)\n if not parsed_url.scheme:\n parsed_url = urlparse('http://'+url)\n\n scheme, netloc, path, params, query, fragment = parsed_url\n\n if scheme in ['http', 'https'] and netloc in supported_vendors:\n return (netloc, urlunparse((scheme, netloc, path, '','','')))\n else:\n return (None, url)\n</code></pre>\n\n<hr>\n\n<p>To deal with an optional <code>www.</code> in front, you could avoid complicating the <code>get_vendor</code> function by adding it programmatically to each known URL. Now, if you needed to add a vendor that's only available with or without <code>www.</code>, you would only have to change this back how it was and add to that list.</p>\n\n<pre><code>supported_vendors = ['flipkart.com', 'homeshop18.com', 'snapdeal.com', \n 'myntra.com']\nsupported_vendors += ['www.' + x for x in supported_vendors]\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-02-02T11:50:58.047", "Id": "68563", "Score": "0", "body": "A really much cleaner code! I did not know about urlunparse that's why I was adding HTTP and another helper function. Now with your code, it actually retains the url scheme. Thank you very much!" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-02-02T14:02:51.700", "Id": "68575", "Score": "0", "body": "Can I do anything about leading `www` ? because of this I have to maintain the list with redundant data (i.e. with and without `www`). I just checked and these e-commerce sites do support without leading `www`. But question should I be removing it? Because once the `get_vendor` function returns `vendor` and `url`, based on that I have to do different actions depending on the `vendor`. I updated the OP, would appreciate if you can have a look again." } ], "meta_data": { "CommentCount": "2", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-02-02T10:17:27.757", "Id": "40660", "ParentId": "40612", "Score": "3" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "2", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-02-01T13:26:07.837", "Id": "40612", "Score": "3", "Tags": [ "python", "url" ], "Title": "Finding e-commerce site of the product URL given and see if it is supported" }
40612
<p>I am a beginner in Java programming. Here is my simple calculator. I hope you could scan through my coding and let me know if there is any error in my coding or how I could simplify the code.</p> <pre><code>import java.util.Scanner; public class Decimal { /** * @param args */ public static void main(String[] args) { double n1, n2; String operation; Scanner scannerObject = new Scanner(System.in); System.out.println("Enter first number"); n1 = scannerObject. nextDouble(); System.out.println("Enter second number"); n2 = scannerObject. nextDouble(); Scanner op = new Scanner(System.in); System.out.println("Enter your operation"); operation = op.next(); switch (operation) { case "+": System.out.println("Your answer is " + (n1 + n2)); break; case "-": System.out.println("Your answer is " + (n1 - n2)); break; case "/": System.out.println("Your answer is " + (n1 / n2)); break; case "*": System.out.println("Your asnwer is " + (n1 * n2)); break; default: System.out.println("Je ne sais pas"); } } } </code></pre>
[]
[ { "body": "<p>Looks good for a beginner. </p>\n\n<p>Couple tweaks if you want to make it look nicer. The name of the class should be somewhat describing the purpose so in your case <code>Calculator</code> would fit better. If you are familiar with <a href=\"https://docs.oracle.com/javase/tutorial/java/javaOO/enum.html\" rel=\"nofollow\"><code>enum</code></a> you could parse your <code>+</code>, <code>-</code>, <code>/</code> into an enum and do <code>switch</code> on that. Then next tweak could be to do the <code>System.printout</code> at the end and in the switch case to do just the operation.</p>\n\n<p>Another suggestion would be to make 4 classes implementing binary operations with just one method taking two arguments and returning the result. Then you can have a map with a key being the operation (in enum or string) and the value would be the appropriate class. Then you end up with more classes but this <code>main</code> method gets shorter. </p>\n\n<p>Generally it is better to split the code in more methods and classes and keep the motto \"one class one responsibility\", or <a href=\"https://en.wikipedia.org/wiki/Single_responsibility_principle\" rel=\"nofollow\">Single Responsibility Principle</a>. So as an example each of your arithmetic classes would be responsible for a single arithmetic operation. If you want to follow that completely, then you would have to create a class that gets the input from the user as well. The Calculator class then would be just like a coordinator saying: give me numbers, give me an operator, perform the operation and print out the result at the end.</p>\n\n<p>Note: If you want some sample code leave me a comment here and I can add some.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-02-01T15:48:27.103", "Id": "40618", "ParentId": "40615", "Score": "14" } }, { "body": "<p>This is a really neat program. For what it does, it does a good job.</p>\n\n<p>Really, there's only one criticism, and a few suggestions. The criticism is designed to get you in to the right habits, it's not a major bug....</p>\n\n<h2>Using try-with-resources</h2>\n\n<p>Java, for years, has had a problem with people being lazy about closing resources.... you open a file, read it's contents, and move on.... leaving an open file handle and other resources until the Garbage Collector cleans up the mess. These 'forgotten' resources can sometimes lead to unexpected bugs and deadlocks.</p>\n\n<p>In Java7, the <a href=\"http://docs.oracle.com/javase/tutorial/essential/exceptions/tryResourceClose.html\">concept 'try-with-resources' was added</a> to ensure that resources are guaranteed to be closed nicely whether the code succeeds or not. It actually allows the programmer to be even lazier than before, and get a an even better result.</p>\n\n<p>In your case, the Scanner instance is a resource that should be closed....</p>\n\n<pre><code>public static void main(String[] args) {\n try (Scanner scannerObject = new Scanner(System.in)) {\n double n1, n2;\n String operation;\n\n .....\n\n }\n}\n</code></pre>\n\n<p>OK, that's the right way to use the Scanner.</p>\n\n<h2>Further Improvements</h2>\n\n<p>As your program expands, you will find that there are a few things that become 'uncomfortable'.... the number of operators will increase, and the complexity of the calculations will increase as well... eventually you will want to enter expressions like <code>100 * ( 17 / 20 )</code> to get the percent score if you got 17 out of 20 in a test.... etc.</p>\n\n<p>What you have at the moment is great for it's purpose, but I encourage you to try to find ways to expand on the idea.</p>\n\n<p>Research you may want to do is in to things like <a href=\"http://en.wikipedia.org/wiki/Reverse_Polish_notation\">'Reverse Polish Notation (RPN)'</a> which is an easier-to-parse format for writing mathematical expressions. Then you can look at things that help you convert Infix to Postfix (RPN) notation...</p>\n\n<p>In order to do these more expansive operations you will need to find ways to turn operators in to classes (<a href=\"http://docs.oracle.com/javase/tutorial/java/javaOO/enum.html\">probably an Enum</a>), and have classes that allow you to encapsulate an expression (<a href=\"http://en.wikipedia.org/wiki/Unary_operation\">unary</a> or <a href=\"http://en.wikipedia.org/wiki/Binary_operation\">binary</a> expressions).</p>\n\n<p>Good job on this, otherwise.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2018-03-16T12:25:16.760", "Id": "362791", "Score": "0", "body": "You should never close a Scanner object opened to System.in. If you do, you will never be able to read from System.in again during that program." } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-02-01T16:00:35.810", "Id": "40620", "ParentId": "40615", "Score": "11" } }, { "body": "<p>Not bad for a beginner.</p>\n\n<p>You shouldn't have to instantiate more than one scanner, as your numbers and the operation are coming from the same input stream. You can even accept your input in a more human-friendly way, as one expression.</p>\n\n<p>There's no need to name your scanner <code>somethingObject</code> — most of your variables will be objects!</p>\n\n<p>You have a typo (<code>\"Your asnwer is \"</code>), which illustrates the problem with repetitive code. I'll leave it as an exercise for you to figure out a way to restructure your program to eliminate the repetitive <code>System.out.println()</code> calls.</p>\n\n<p>I'd rename the class to something more descriptive.</p>\n\n<pre><code>public class Calculator {\n public static void main(String[] args) {\n try (Scanner scanner = new Scanner(System.in)) {\n System.out.println(\"Enter an expression of the form 3 * 5\");\n double n1 = scanner.nextDouble();\n String operation = scanner.next();\n double n2 = scanner.nextDouble();\n\n switch (operation) {\n case \"+\":\n System.out.println(\"Your answer is \" + (n1 + n2));\n break;\n\n case \"-\":\n System.out.println(\"Your answer is \" + (n1 - n2));\n break;\n\n case \"/\":\n System.out.println(\"Your answer is \" + (n1 / n2));\n break;\n\n case \"*\":\n System.out.println(\"Your asnwer is \" + (n1 * n2));\n break;\n\n default:\n System.out.println(\"Je ne sais pas\");\n\n }\n }\n }\n}\n</code></pre>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-02-01T17:43:39.520", "Id": "40627", "ParentId": "40615", "Score": "7" } }, { "body": "<p>Good job. Some points that can be improved:</p>\n\n<ul>\n<li><p>As already mentioned by the others, you could extract the computation logic to separate methods.</p></li>\n<li><p>You repeat <code>System.out.println(\"Your answer is \" + [...]);</code> several times in your code. Code repetition is bad. To fix it (if you want to keep the switch-case block), you could store the result of the computation into an integer variable and print the result after the switch-case block.</p></li>\n<li><p>I personally don't declare the variables at the very beginning of the method. I declare them when I need them for the first time. As a consequence, their scope is reduced.</p></li>\n<li><p>You create a <strong>new</strong> scanner to ask the user for the operation type: <code>Scanner op = new Scanner(System.in);</code> Why? You can continue using <code>scannerObject</code>.</p></li>\n<li><p>I disagree with the advice of rolfl to close the resources <em>in this case.</em> I don't think <code>System.in</code>should be closed. If you used both scanner objects (<code>scannerObject</code> and <code>op</code>) and retrieved a value with <code>op</code> after having closed <code>scannerObject</code> you would end up with an exception!</p></li>\n</ul>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2015-03-12T22:11:43.487", "Id": "83948", "ParentId": "40615", "Score": "2" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-02-01T14:32:37.603", "Id": "40615", "Score": "12", "Tags": [ "java", "beginner", "calculator" ], "Title": "Simple Java calculator" }
40615
<blockquote> <p>Write a pointer version of the function <code>strcat</code> that we showed in Chapter 2: strcat(s, t) copies the string <code>t</code> to the end of <code>s</code>.</p> </blockquote> <p>This is the version of <code>strcat</code> from Chapter 2:</p> <pre><code>void strcat(char s[], char t[]) { int i, j; i = j = 0; while(s[i] != '\0') /* find the end of s */ i++; while((s[i++] = t[j++]) != '\0') /* copy t */ ; } </code></pre> <p>Here is my solution:</p> <pre><code>void custom_strcat(char *s, char *t) { while(*s) /* finding the end of the string */ s++; while((*s++ = *t++)) /* copy t */ ; } </code></pre> <p>There are 2 <code>while</code> loops in my function, first loop will run until <code>*s</code> is equal to <code>'\0'</code>. At each iteration the value of <code>s</code> is incremented - thus, it will point to the next element;</p> <p>The second loop will copy the elements of the string <code>t</code> at the and of <code>s</code>. The incrementation is done in the test part - even though after the loop stops <code>s</code> and <code>t</code> will point to other objects.This technique couldn't be applied in the first loop because when the loop stops <code>s</code> will point to an irrelevant value.</p> <p>The exercise can be found at page 121 in K&amp;R second edition.</p>
[]
[ { "body": "<p>I don't know much, but I would change a few things.</p>\n\n<ul>\n<li><p>Functions usually have the first <code>{</code> in a new line</p></li>\n<li><p>Explicit check against <code>'\\0'</code></p></li>\n<li><p>Make the second parameter <code>const</code> since the function won't change the characters it points to</p></li>\n<li><p>Use names more meaningful</p></li>\n</ul>\n\n<p>This is what it would like:</p>\n\n<pre><code>void custom_strcat(char *dest, const char *source) \n{\n while(*dest != '\\0') /* finding the end of the string */\n dest++;\n\n while((*dest++ = *source++) != '\\0') /* copy source */\n ;\n}\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-02-01T16:22:34.193", "Id": "68483", "Score": "4", "body": "+1 I'm not sure that \"Explicit check against '\\0'\" adds anything? I often see it without, in introductory textbooks." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-02-02T09:45:11.497", "Id": "68554", "Score": "4", "body": "@ChrisW: Yes the extra check against `'\\0'` does add something, even though the compiler would insert it silently for you. It makes it immediately clear to the human reader that a test for a null character is intended here, rather than say for a zero integer or for a null pointer. Sure, you can figure that out too when it is not written, but it still requires some brain power from the reader that could be better spent differently." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-02-05T12:42:23.403", "Id": "70177", "Score": "1", "body": "@ChrisW There are unfortunately plenty of introductory text books about C where the quality varies from mildly incorrect to complete [bullschildt](http://www.catb.org/jargon/html/B/bullschildt.html). Marc's argument is a very sound one." } ], "meta_data": { "CommentCount": "3", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-02-01T15:55:50.280", "Id": "40619", "ParentId": "40616", "Score": "8" } }, { "body": "<p>It looks idiomatic and bug-free.</p>\n\n<blockquote>\n<pre><code>s++;\n</code></pre>\n</blockquote>\n\n<p>Perhaps <code>++s</code> as a habit unless postfix <code>s++</code> is required (as it is during the copy).</p>\n\n<blockquote>\n<pre><code>while((*s++ = *t++))\n</code></pre>\n</blockquote>\n\n<p>Could have just a single pair of parentheses.</p>\n\n<blockquote>\n<pre><code>void custom_strcat(char *s, char *t)\n</code></pre>\n</blockquote>\n\n<p>The signature of strcat is usually <code>char* strcat(char* destination, const char* source)</code>. The <code>const</code> means that the source buffer is not modified. The return code is supposed to be a pointer to the original (unmodified) source value, so to implement this the implementation would need to increment a local variable copy of destination.</p>\n\n<blockquote>\n <p>This technique couldn't be applied in the first loop because when the loop stops s will point to an irrelevant value.</p>\n</blockquote>\n\n<p>You could write that as, <code>if (*s) while (*(++s));</code>.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-02-01T16:34:25.300", "Id": "68487", "Score": "0", "body": "I have tried to write `while((*s++ = *t++))` without parentheses but I get the error: `suggest parentheses around assignment used as truth value`." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-02-01T16:46:11.077", "Id": "68489", "Score": "0", "body": "I see: [Compiler warning - suggest parentheses around assignment used as truth value](http://stackoverflow.com/q/5476759/49942)" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-02-05T07:35:27.940", "Id": "70117", "Score": "0", "body": "\"Perhaps ++s as a habit unless postfix s++ is required (as it is during the copy).\" Why? There is absolutely no reason for that. It will _not_ produce more effective code." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-02-05T15:31:02.087", "Id": "70220", "Score": "0", "body": "@Lundin http://programmers.stackexchange.com/a/60002/19237" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-02-05T17:45:13.937", "Id": "70238", "Score": "1", "body": "@ChrisW As it says in that link, it doesn't matter in 99% of the cases. I'm pretty sure it only matters on ancient compilers for computers made in the mid-80s or so. So there is really no rationale behind recommending prefix; as far as I can tell it is just yet another case of premature optimization." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-02-05T18:01:06.190", "Id": "70241", "Score": "0", "body": "@Lundin It might make some difference with a more complicated iterator type. I didn't say it was wrong, just, \"perhaps prefer the prefix as a habit\". There's less reason to \"prefer\" the postfix version. Perhaps the language would be better called `++C` instead of `C++`." } ], "meta_data": { "CommentCount": "6", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-02-01T16:01:29.980", "Id": "40621", "ParentId": "40616", "Score": "10" } }, { "body": "<p>Your code looks fine for what it's intended to be. My biggest gripe against its implementation is the names <code>s</code> and <code>t</code>, as I keep reading <code>s</code> as <code>source</code>. However in the spirit of full code review, I wanted to mention I would disallow use of <code>custom_strcat</code>. Why? Well, it's never too early to learn a little bit about security; specifically <a href=\"http://en.wikipedia.org/wiki/Buffer_overflow\">buffer overflows</a>.</p>\n\n<p>The original <code>strcat</code> function is very easy to misuse because of one critical assumption that it makes: it assumes the caller has ensured the destination buffer is large enough to accept appending the source buffer's contents. When this assumption is false, many bad things can happen. If something external can control the source string, it may be able to exploit any assumptions that are invalidated by unexpected input. While a caller can check for <code>strcat</code>'s assumption easily enough, other functions' assumptions (such as <code>sprintf</code>'s) are not.</p>\n\n<p>Typically this is countered today by passing a buffer-size parameter for any output buffer, and limiting the additions to the buffer such that they fit (see <a href=\"http://www.openbsd.org/cgi-bin/man.cgi?query=strlcat\"><code>strlcat</code></a>). In production code I would never want to see code that didn't include a way of ensuring buffer safety, and that's why I would disallow use of <code>strcat</code> or <code>custom_strcat</code> as written.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-02-05T09:00:01.327", "Id": "70133", "Score": "2", "body": "`strcat`, `strcpy` and similar functions have never specified or guaranteed any form of internal safety. They are perfectly fine to use, if you actually know what they do. You will indeed have to add buffer size checks outside the functions. So there is no problem with these functions, the core problem you describe is called _incompetent programmer who uses functions in his program without knowing what they actually do_. No safe version of a function can save you from that problem." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-02-05T13:10:31.213", "Id": "70181", "Score": "0", "body": "Good points, @Lundin. It doesn't change my stance for the general case, although I might be convinced in bottleneck code if profiles can justify the need." } ], "meta_data": { "CommentCount": "2", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-02-01T17:07:33.413", "Id": "40624", "ParentId": "40616", "Score": "5" } }, { "body": "<p>Overall, the code is acceptable and a common way to implement such algorithms. Below I have posted some things to consider:</p>\n\n<p><strong>Dangerous programming practice</strong></p>\n\n<ul>\n<li><p>Pointer parameters that you are only going to use for reading, should be made read-only by using the keyword <code>const</code>. Google \"const correctness\". (Source: MISRA-C:2004 16.7)</p></li>\n<li><p>Always use <code>{}</code> braces for each statement, even if it only contains one row. If you don't, you are risking to get a classic code maintenance bug later on. Example:</p>\n\n<pre><code>// original code;\nwhile(something)\n do_stuff();\n\n// the code is modified later on:\nwhile(something)\n do_stuff();\n do_more_stuff();\n</code></pre>\n\n<p>As you can see, this introduced a severe bug, the programmer was tricked by the indention. This bug is incredibly common. (Source: MISRA-C:2004 14.8)</p></li>\n<li><p>Never use assignment inside conditions. In this specific case, it might be acceptable, but in other cases you want the compiler to give a warning if it encounters a <code>=</code> instead a condition, because that will prevent against another classic bug, namely accidental <code>=</code> where <code>==</code> was intended. Therefore it is good practice to avoid assignments inside conditions entirely. (Source: MISRA-C:2004 13.1)</p></li>\n<li><p>As others have pointed out, always do the test against null termination explicitly, by comparing against <code>\\0</code>. <code>while(*s)</code> means: \"either this code is perfectly fine as does what I intended\", or it could mean that \"I have written a bug here, because checking against NULL was my true intention\". The reader can't tell. Show that you have actually done some thinking when you wrote the code, by explicitly add a check <code>== '\\0'</code>. (Source: MISRA-C:2004 13.2)</p></li>\n<li><p>The ++ operators are dangerous to use combined with other operations, because they easily introduce various forms of poorly-defined behavior, such as the classic <code>a[i] = i++</code> bug (undefined behavior) or unspecified behavior reliance issues like <code>func(i) + func(i++)</code> (the code relies on order of evaluation), or subtle operator precedence bugs like <code>*ptr++</code> where <code>(*ptr)++</code> was intended. The ++ and -- are simply plain dangerous to use anywhere except than on a line of its own. (Source: MISRA-C:2004 12.1, 12.2, 12.13)</p></li>\n</ul>\n\n<p><strong>Coding style</strong></p>\n\n<ul>\n<li><p>Use intuitive, descriptive variable names. Don't use one-letter names. Commonly used names for copying functions are \"dest\" (destination) and \"source\". </p>\n\n<p>(Although the C standard itself uses poor variable naming, typically\nnaming them \"s1\" and \"s2\". But don't use as bad coding style as they do in the C\nstandard :) )</p></li>\n</ul>\n\n<p><strong>Improved code with all of the above in mind:</strong></p>\n\n<pre><code>void custom_strcat (char* dest, const char* source) \n{\n while(*dest != '\\0') /* finding the end of the string */\n {\n dest++;\n }\n\n *dest = *source;\n while(*dest != '\\0')\n {\n dest++;\n source++;\n *dest = *source;\n }\n}\n</code></pre>\n\n<hr>\n\n<p>(To avoid subjective debating and to demonstrate that these aren't just the personal, subjective opinions of a random internet person, I have cited a widely-acknowledged C programming authority as source for each statement made.)</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-02-05T12:38:24.060", "Id": "40951", "ParentId": "40616", "Score": "2" } } ]
{ "AcceptedAnswerId": "40621", "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-02-01T15:27:06.133", "Id": "40616", "Score": "10", "Tags": [ "c", "beginner", "strings", "pointers" ], "Title": "Pointer version of strcat" }
40616
<p>As usual I'm wondering if there is a better way to do:</p> <p>(The code extends a angular service)</p> <pre><code>(function(window, angular, undefined) { 'use strict'; angular.module('api.base', ['restangular']) .factory('Base', function(Restangular) { return function(route){ var elements = Restangular.all(route); return { one : function (id) { return Restangular.one(route, id).get(); }, all : function (id) { return elements.getList(); }, store : function(data) { return elements.post(data); }, copy : function(original) { return Restangular.copy(original); } } } }) })(window, angular); (function(window, angular, undefined) { 'use strict'; angular.module('api.post', ['api.base']) .factory('Post', function(Base) { function ngPost() { this.prop = ['publish','draft']; this.myMethod = function(){} }; return angular.extend(Base('post'), new ngPost()); }) })(window, angular); </code></pre>
[ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-02-01T18:34:32.077", "Id": "68494", "Score": "2", "body": "Please try to explain a bit more about what it is that your code is doing." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-02-01T19:08:04.850", "Id": "68500", "Score": "0", "body": "The code extends a angular service" } ]
[ { "body": "<p>At first sight, your code is short and there is nothing wrong with it.</p>\n\n<p>At second sight, there are a few things to improve:</p>\n\n<ul>\n<li>Your semicolons are all over the place; you have both missing and pointless semicolons.</li>\n<li>There is no point in declaring <code>id</code> in <code>all</code> since you clearly will not use it</li>\n<li>ngPost is an old skool constructor, it's name really should start with an uppercase</li>\n</ul>\n\n<p>These things I gleaned from JSHint, you should use it.</p>\n\n<p>Furthermore, I could be wrong, it seems that you are mixing functions which I would put in <code>posts</code> together with functions which I would put in <code>post</code>. I am not sure that is the best approach.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-02-01T20:44:28.023", "Id": "68512", "Score": "0", "body": "Thanks for the review but there is a drawback to extend service/factory in angularjs http://stackoverflow.com/questions/21496331/angularjs-are-service-singleton" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-02-01T20:55:30.443", "Id": "68513", "Score": "0", "body": "That code works but you should pay attention" } ], "meta_data": { "CommentCount": "2", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-02-01T20:27:10.627", "Id": "40634", "ParentId": "40628", "Score": "6" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "2", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-02-01T18:25:20.437", "Id": "40628", "Score": "5", "Tags": [ "javascript", "angular.js" ], "Title": "Angularjs extends service" }
40628
<p>I've just created my first plugin, but I think I've written too much bloated code. Could you point me to the right direction?</p> <pre><code>$.fn.replaceme = function() { function add_essentials(element) { var native_btn = element; native_type = native_btn.attr('type'); native_btn.each(function() { var n_btn = $(this); n_btn.next('label').addClass('label-replacement'); n_btn.wrap('&lt;div class="' + native_type + ' input-container"&gt;&lt;/div&gt;'); n_btn.parent('.input-container').append('&lt;span class="' + native_type + ' input-replacement"&gt;&lt;/div&gt;'); }); } function replace_default_action(element) { var input = element; group = input.attr('name'); $('input[name="' + group + '"]').each(function() { var input_select = $(this); if (input_select.is(':checked')) { input_select.siblings('.input-replacement').addClass('selected'); } else { input_select.siblings('.input-replacement').removeClass('selected'); } }); } function label_action(element) { element.prevAll('.input-container').children('.styled-input').prop('checked', 'checked').trigger('change'); } function live_check() { $('.styled-input:checked').each(function() { $(this).siblings('.input-replacement').addClass('selected'); }); }; return this.each(function() { var $this = $(this); add_essentials($this); live_check(); $('body').on('change', '.styled-input', function() { replace_default_action($this); }); $('body').on('click', '.label-replacement', function() { label_action($this); }); }); } $('.styled-input').replaceme(); </code></pre>
[ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-02-01T19:19:55.520", "Id": "68503", "Score": "0", "body": "`group` and `native_type` are globals to start. Edit, also if you'd construct a demo of what your code does on jsfiddle/bin I'd appreciate it" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-02-01T20:14:40.330", "Id": "68508", "Score": "0", "body": "http://jsfiddle.net/UCdKL/9/\nHere is the fiddle, thanks for your quick response" } ]
[ { "body": "<p>Scanning your code I have a few recommendations to make. If you update your question with a demo I'll make a few more.</p>\n\n<p>As I mentioned in comments you have a few obvious issues with globals</p>\n\n<pre><code>var native_btn = element;\nnative_type = native_btn.attr('type');\n//should be\nvar native_btn = element,\n native_type = native_btn.attr('type');\n</code></pre>\n\n<p>And similarly for <code>group</code>. I don't understand why you're doing this</p>\n\n<pre><code>function replace_default_action(element) {\n var input = element;\n group = input.attr('name');\n</code></pre>\n\n<p>Why not:</p>\n\n<pre><code>function replace_default_action(input) {\n var group = input.attr('name'); //on another note I'd prefer groupName over group\n</code></pre>\n\n<p>Throughout your code you make pretty good use of chaining in places it is clear and concise however there are a few spots I would adapt</p>\n\n<p>Obvious one:</p>\n\n<pre><code>$('body').on('change', '.styled-input', function() {\n replace_default_action($this);\n })\n .on('click', '.label-replacement', function() {\n label_action($this);\n });\n</code></pre>\n\n<p>You can write this code with <a href=\"http://api.jquery.com/toggleclass/\" rel=\"nofollow noreferrer\">toggleClass</a> to remove some lines</p>\n\n<pre><code> var input_select = $(this);\n if (input_select.is(':checked')) {\n input_select.siblings('.input-replacement').addClass('selected');\n } else {\n input_select.siblings('.input-replacement').removeClass('selected');\n }\n\n //With toggle class\n var input_select = $(this);\n input_select.siblings('.input-replacement').toggleClass('selected', input_select.is(':checked'));\n</code></pre>\n\n<p>Also I'm pretty sure you have a logic error here:</p>\n\n<pre><code>.append('&lt;span class=\"' + native_type + ' input-replacement\"&gt;&lt;/div&gt;')\n</code></pre>\n\n<p>Finally in javascript, especially with jQuery code (per <a href=\"http://contribute.jquery.org/style-guide/js/#naming-conventions\" rel=\"nofollow noreferrer\">their style guide</a>), we prefer camelcasing over underscores for names. I'll point you to <a href=\"https://stackoverflow.com/questions/8789656/why-use-camelcase-in-javascript\">this discussion from SO</a>.</p>\n\n<p><strong>Update</strong> Here's how I would probably write your code and <a href=\"http://jsfiddle.net/UCdKL/10/\" rel=\"nofollow noreferrer\">here's your updated fiddle up and running</a>. As you'll notice I removed all your helper functions that were only called once as there was no need for them and I found them confusing to be honest. I added guiding comments to replace them. I corrected the things mentioned in this review, including function names and condensed ways of writing the original. In the future I think you would benefit from trying to write your functions as straightforward and simple as possible (it took me a while to understand your original code cause of all the helper abstractions)!</p>\n\n<pre><code>$.fn.replaceme = function() {\n 'use strict';\n\n return this.each(function() {\n\n var $this = $(this);\n var native_type = $this.attr('type');\n\n //setup button for plugin\n $this.each(function() {\n var $btn = $(this);\n $btn.next('label').addClass('label-replacement');\n $btn.wrap('&lt;div class=\"' + native_type + ' input-container\"&gt;');\n $btn.parent('.input-container').append('&lt;span class=\"' + native_type + ' input-replacement\"&gt;');\n });\n\n //check if is live\n $('.styled-input:checked').each(function() {\n $(this).siblings('.input-replacement').addClass('selected');\n });\n\n //handlers\n $('body').on('change', '.styled-input', function() {//set default action, override if already one exists\n var group = $this.attr('name');\n var $cur = $(this);\n $('input[name=\"' + group + '\"]').each(function() {\n $cur.siblings('.input-replacement').toggleClass('selected', $cur.is(':checked'));\n });\n })\n .on('click', '.label-replacement', function() {\n $this.prevAll('.input-container').children('.styled-input').prop('checked', 'checked').trigger('change');\n });\n });\n};\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-02-01T20:26:01.537", "Id": "68510", "Score": "0", "body": "Thanks for reviewing my code, i've learned a few new tips and tricks. Especially about organizing my code. I've got one question, what is the logic error you're pointing out?" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-02-01T20:42:06.557", "Id": "68511", "Score": "0", "body": "You're opening with a span and closing with a div. Should probably just remove the closing tag `$('<span class=\"' + native_type + ' input-replacement\">')`;" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-02-01T21:43:51.897", "Id": "68515", "Score": "0", "body": "Wow, it's time to take a nap! Haha, i feel so stupid!" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-02-03T04:37:05.017", "Id": "68667", "Score": "0", "body": "@JohnElswisk I editted my answer with a counter proposal" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-02-03T04:39:21.643", "Id": "68668", "Score": "0", "body": "Also looking at it again I'm certain this loop is unnecessary `$('input[name=\"' + group + '\"]').each(function() {`" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-02-04T21:12:34.067", "Id": "70042", "Score": "0", "body": "Thank you very much, i see what i did 'wrong' now. Today i've written another small plugin for testing purpose with all your comments in mind. And i see that i can write some parts in fewer and more clear code." } ], "meta_data": { "CommentCount": "6", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-02-01T19:35:27.013", "Id": "40632", "ParentId": "40631", "Score": "4" } } ]
{ "AcceptedAnswerId": "40632", "CommentCount": "2", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-02-01T19:10:29.363", "Id": "40631", "Score": "4", "Tags": [ "javascript", "jquery", "plugin" ], "Title": "Replace radio/checkbox plugin" }
40631
<p><a href="http://en.wikipedia.org/wiki/Java_Persistence_API" rel="nofollow">Java Persistence</a> consists of an API in the <code>javax.persistence</code> package as well as an SQL-like language named JPQL.</p>
[]
[]
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-02-01T22:48:21.190", "Id": "40641", "Score": "0", "Tags": null, "Title": null }
40641
The Java Persistence API (JPA) is a specification that describes the management of relational data in Java applications.
[]
[]
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-02-01T22:48:21.190", "Id": "40642", "Score": "0", "Tags": null, "Title": null }
40642
<p>I want to know if I'm going about creating and calling two functions from my model to my controller in the simplest and cleanest way. </p> <p>Model:</p> <pre><code>public function getPosts() { $post = $this-&gt;paginate(4); return $post; } public function getMonth($post) { $post-&gt;month = date('M', strtotime($this-&gt;created_at)); $post-&gt;month = strtoupper($post-&gt;month); return $post-&gt;month; } public function getDay($post) { $post-&gt;day = date('d', strtotime($this-&gt;created_at)); return $post-&gt;day; } </code></pre> <p>Controller: </p> <pre><code>public function index() { $post = $this-&gt;post-&gt;getPosts(); $post-&gt;month = $this-&gt;post-&gt;getMonth($post); $post-&gt;day = $this-&gt;post-&gt;getDay($post); return View::make('posts.index', compact('post')); } </code></pre> <p>I am unsure about if my controller is acting in a strict MVC way, being that I thought it's only job is to direct traffic, but it's doing more by calling functions from my model. Is this the best way to go about this?</p>
[ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-04-03T18:43:43.597", "Id": "80638", "Score": "0", "body": "please include your full class so that we can see if you have done other declaration and setting and if you are extending certain classes or not - because if you are not using eloquent you have to let us know and maybe we can critic a bit more." } ]
[ { "body": "<p>PHP is not my area of expertise, so just some generic notes:</p>\n\n<ol>\n<li><p><code>4</code> is a magic number here:</p>\n\n<blockquote>\n<pre><code>$post = $this-&gt;paginate(4);\n</code></pre>\n</blockquote>\n\n<p>Why is it 4? What the purpose if this number? A named constant or local variable would be readable with a descriptive name.</p></li>\n<li><blockquote>\n<pre><code>public function getMonth($post)\n{\n $post-&gt;month = date('M', strtotime($this-&gt;created_at));\n $post-&gt;month = strtoupper($post-&gt;month);\n return $post-&gt;month;\n}\n</code></pre>\n</blockquote>\n\n<p>Using a local variable with a proper name, like <code>lowercase_month</code>, in the first line would be readable and more descriptive.</p></li>\n<li><p>These methods violates <em>Command Query Separation</em> since they return some data and modify the <code>$post</code> too.</p>\n\n<blockquote>\n <p>Functions should either do something or answer something, but not both.</p>\n</blockquote>\n\n<p>Source: <em>Clean Code by Robert C. Martin</em>, <em>Chapter 3: Functions</em>, <em>Command Query Separation</em> p45</p></li>\n<li><blockquote>\n<pre><code>$post-&gt;month = date('M', strtotime($this-&gt;created_at));\n$post-&gt;month = strtoupper($post-&gt;month);\n</code></pre>\n</blockquote>\n\n<p>I'd consider moving these calls to the <code>Post</code> class since it seems <a href=\"http://c2.com/cgi/wiki?DataEnvy\" rel=\"nofollow\">data envy</a>. (Pseudocode.)</p>\n\n<pre><code>class Post {\n ...\n public void setMonth($created_at) {\n $lowercase_month = date('M', strtotime($created_at));\n $post-&gt;month = strtoupper($lowercase_month);\n }\n ...\n}\n</code></pre></li>\n</ol>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-04-03T18:38:22.577", "Id": "80636", "Score": "1", "body": "for a non expert - you are pretty complete in your answers. good job." } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-03-22T12:56:36.817", "Id": "45080", "ParentId": "40651", "Score": "7" } } ]
{ "AcceptedAnswerId": "45080", "CommentCount": "1", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-02-02T02:34:55.917", "Id": "40651", "Score": "7", "Tags": [ "php", "mvc", "laravel" ], "Title": "Laravel model and controller interaction" }
40651
<p>I have written a function that launches the default editor set in <code>git config</code>, right now I have managed to get it working for Sublime, nano and Vim.</p> <pre><code>def launchEditor(editor): """ this function launches the default editor for user to compose message to be sent along with git diff. Args: editor(str): name or path of editor Returns: msg(str): html formatted message """ filePath = os.path.join(os.getcwd(), "compose.txt") wfh = open(filePath, 'w') wfh.close() if os.path.exists(filePath): # using sublime if re.search(r'ubl', editor): diff = subprocess.Popen(['cat',filePath], stdout=subprocess.PIPE) pr = subprocess.Popen( editor, stdout=subprocess.PIPE, stderr=subprocess.PIPE, shell=True, stdin=diff.stdout ) pr.wait() if pr.returncode == 0: msg = pr.stdout.read() else: # using vim or nano pr = subprocess.Popen([editor, filePath], stdin=open('/dev/tty', 'r')) pr.wait() if pr.returncode == 0: with open(filePath, 'r') as fh: msg = fh.readlines() os.remove(filePath) return "".join(msg).replace("\n","&lt;br&gt;") </code></pre> <p>Any suggestion on improvement and adding support to other text editors is welcome!!</p> <p>Revision update:</p> <pre><code> Traceback (most recent call last): File "/Users/san/Development/executables//git-ipush", line 268, in &lt;module&gt; sys.exit(main()) File "/Users/san/Development/executables//git-ipush", line 46, in main preCheck(args) File "/Users/sanjeevkumar/Development/executables//git-ipush", line 156, in preCheck message = launchEditor(editor) File "/Users/san/Development/executables//git-ipush", line 77, in launchEditor if subprocess.call([editor, f.name]) != 0: File "/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/subprocess.py", line 524, in call return Popen(*popenargs, **kwargs).wait() File "/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/subprocess.py", line 711, in __init__ errread, errwrite) File "/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/subprocess.py", line 1308, in _execute_child raise child_exception OSError: [Errno 2] No such file or directory </code></pre>
[ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-02-02T11:52:45.033", "Id": "68564", "Score": "0", "body": "Isn't specifying core editor in git config good enough? Just trying to think a use-case or purpose of this. Thanks." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-02-02T12:10:10.173", "Id": "68569", "Score": "0", "body": "the purpose is different, this function just launches for email message to compose in default editor set in git config!" } ]
[ { "body": "<h3>1. Comments on your code</h3>\n\n<ol>\n<li><p>The function is poorly specified in that it combines two tasks: (i) it gets input from the user via an editor; (ii) it replaces newlines in the input with <code>&lt;br&gt;</code>. But what I just want the input and don't want any HTML conversion (especially not a half-baked conversion like this one)?</p>\n\n<p>It would be better to decompose this function into two pieces. In what follows I'm just going to discuss piece (i), launching the editor and capturing the input.</p></li>\n<li><p>There are missing imports (<code>os</code> and <code>subprocess</code>).</p></li>\n<li><p>The function always uses the file <code>compose.txt</code> in the current directory. This means that if I already had a file with that name, it would be erased and then deleted, which would be really annoying.</p>\n\n<p>It would be better to create a <em>temporary file</em> for this purpose, using Python's <a href=\"http://docs.python.org/3/library/tempfile.html\" rel=\"nofollow\"><code>tempfile.NamedTemporaryFile</code></a>.</p></li>\n<li><p>This code:</p>\n\n<pre><code>diff = subprocess.Popen(['cat',filePath], stdout=subprocess.PIPE)\npr = subprocess.Popen(..., stdin=diff.stdout)\n</code></pre>\n\n<p>is a classic \"<a href=\"http://partmaps.org/era/unix/award.html\" rel=\"nofollow\"><em>useless use of cat</em></a>\". If you read the documentation for <a href=\"http://docs.python.org/3/library/subprocess.html#subprocess.Popen\" rel=\"nofollow\"><code>subprocess.Popen</code></a>, you'll see:</p>\n\n<blockquote>\n <p><em>stdin</em>, <em>stdout</em> and <em>stderr</em> specify the executed program’s standard input, standard output and standard error file handles, respectively. Valid values are <code>PIPE</code>, <code>DEVNULL</code>, an existing file descriptor (a positive integer), an <strong>existing file object</strong>, and <code>None</code>.</p>\n</blockquote>\n\n<p>(my emphasis) so you can write:</p>\n\n<pre><code>pr = subprocess.Popen(..., stdin=open(filePath))\n</code></pre>\n\n<p>and save a process. (But actually this is unnecessary, as explained below.)</p></li>\n<li><p>This code:</p>\n\n<pre><code>if re.search(r'ubl', editor):\n</code></pre>\n\n<p>doesn't seem like a very robust way to ensure that <code>editor</code> is <a href=\"http://www.sublimetext.com\" rel=\"nofollow\">Sublime Text</a>. I mean, for all you know I could have just run:</p>\n\n<pre><code>$ ln /usr/bin/vi ubl\n</code></pre>\n\n<p>It's best to treat all the editors the same. After all, <code>git commit</code> doesn't have any special case for Sublime Text, so neither should you.</p>\n\n<p>In particular, you don't need to go through all that <code>subprocess.Popen</code> shenanigans to open a file in Sublime. I find that</p>\n\n<pre><code>subprocess.call(['subl', filename])\n</code></pre>\n\n<p>works fine.</p></li>\n<li><p>If all you are going to do with a subprocess is wait for it to exit:</p>\n\n<pre><code>pr = subprocess.Popen([editor, filePath], stdin=open('/dev/tty', 'r'))\npr.wait()\nif pr.returncode == 0:\n</code></pre>\n\n<p>then use <a href=\"http://docs.python.org/3/library/subprocess.html#subprocess.call\" rel=\"nofollow\"><code>subprocess.call</code></a> instead of <code>subprocess.Popen</code>:</p>\n\n<pre><code>if subprocess.call([editor, filePath]) == 0:\n</code></pre></li>\n<li><p>Specifying <code>stdin=open('/dev/tty', 'r')</code> is unnecessary. Let the editor decide how it wants to get input from the user.</p></li>\n<li><p>If the editor returned with a non-zero code, your function doesn't report an error, it just continues running (but with nothing assigned to <code>msg</code>) until it reaches <code>\"\".join(msg)</code> which fails with a mysterious <code>TypeError</code>. Better to raise an exception if the editor returned an error code.</p>\n\n<p>(I submitted a bug report for the mysterious <code>TypeError</code>: see <a href=\"http://bugs.python.org/issue20507\" rel=\"nofollow\">Python issue 20507</a>.)</p></li>\n<li><p>Your function splits the input into lines by calling <code>msg = fh.readlines()</code>, and then it joins these lines back together again with <code>\"\".join(msg)</code>. This is pointless: if you just want the contents of the file as a string, write <code>msg = fh.read()</code> instead.</p></li>\n</ol>\n\n<h3>2. Revised code</h3>\n\n<pre><code>import subprocess\nimport tempfile\n\ndef input_via_editor(editor):\n \"\"\"Launch editor on an empty temporary file, wait for it to exit, and\n if it exited successfully, return the contents of the file.\n\n \"\"\"\n with tempfile.NamedTemporaryFile() as f:\n f.close()\n try:\n subprocess.check_call([editor, f.name])\n except subprocess.CalledProcessError as e:\n raise IOError(\"{} exited with code {}.\".format(editor, e.returncode))\n with open(f.name) as g:\n return g.read()\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-02-04T17:04:39.307", "Id": "69980", "Score": "0", "body": "hello @Gareth Rees: this raises error, please see above I have edited and pasted the error." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-02-04T17:10:14.727", "Id": "69981", "Score": "0", "body": "Did you read the error message? It says \"No such file or directory\", so it looks as if the value of `editor` is wrong." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-02-04T17:19:37.157", "Id": "69985", "Score": "0", "body": "no, it is not which is why i printed the path of the editor and use `os.path.existis` that evaluates to `True`." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-02-04T17:29:57.097", "Id": "69988", "Score": "0", "body": "tried with your code again: and this time i got this error ` File \"/Users/sanjeevkumar/Development/executables//git-ipush\", line 79, in launchEditor\n with open(f.name) as g:\nIOError: [Errno 2] No such file or directory: '/var/folders/43/m1qv9zf53q19sqh6h9kg9pz80000gn/T/tmp2R8gs4'`" } ], "meta_data": { "CommentCount": "4", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-02-03T19:59:13.297", "Id": "40772", "ParentId": "40652", "Score": "3" } } ]
{ "AcceptedAnswerId": "40772", "CommentCount": "2", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-02-02T03:14:52.897", "Id": "40652", "Score": "6", "Tags": [ "python", "performance", "git" ], "Title": "Function launching default editor" }
40652
<p>After initially <a href="https://codereview.stackexchange.com/questions/40468/monopoly-creating-a-monopoly-board">struggling with the board size</a>, I have now decided the dimension. Please review my code. In the code I am generating HTML code using PHP and MySql. I have not added the database, please let me know how to add it in my question.</p> <p>The key functionality is <code>drawBoard()</code> it has 3 parameters, </p> <ul> <li><code>1</code> is to determine whether I will increment or decrease, </li> <li><code>2</code> determines where to start from</li> <li><code>3</code> determines where to end at</li> </ul> <p>Please let me know if further clarification is required. I have also omitted the generated HTML instead here is <a href="http://snag.gy/tMmkq.jpg" rel="nofollow noreferrer">a picture</a> of what the output looks like. Let me know if generated HTML is needed?</p> <p>I am looking for ways to improve the code and would like to know whether a more quicker loading time can be achieved. Any general suggestions are also welcome. </p> <p><strong>Index.php</strong></p> <pre><code>&lt;?php include 'header.php'; include 'functions.php'; ?&gt; &lt;div class="board"&gt; &lt;div class="row" id="top-row"&gt; &lt;?php drawBoard(1, 0, 11); ?&gt; &lt;/div&gt; &lt;div class="row" id="center-row"&gt; &lt;div class="left-column"&gt; &lt;?php drawBoard(-1, 39, 30); ?&gt; &lt;/div&gt; &lt;div class="center-colum"&gt; &lt;/div&gt; &lt;div class="right-column"&gt; &lt;?php drawBoard(1, 11, 20); ?&gt; &lt;/div&gt; &lt;/div&gt; &lt;div class="row" id="bottom-row"&gt; &lt;?php drawBoard(-1, 30, 19); ?&gt; &lt;/div&gt; &lt;/div&gt; &lt;/body&gt; &lt;/html&gt; </code></pre> <p><strong>functions.php</strong></p> <pre><code>&lt;?php function drawBoard($diff = "", $start = "", $stop =""){ include 'dbconnect.php'; for ($i = $start; $i != $stop; $i += $diff){ $criteria = "pos" . $i; $result = mysqli_query($con,"SELECT * FROM positions WHERE position = '$criteria'") or die("Could not select examples"); while($row = mysqli_fetch_array($result)){ $posid = $row[0]; $title = $row[1]; $set = $row[2]; $withIcon = $row[3]; if ($withIcon == 0) { ?&gt; &lt;div class="position"&gt; &lt;div class="title"&gt; &lt;span class="&lt;?php echo $set ?&gt;"&gt; &lt;?php echo $title ?&gt;&lt;/span&gt; &lt;/div&gt; &lt;div class="runway" id="&lt;?php echo "runway" .$posid ?&gt;"&gt; &lt;span class="piece-1" id="&lt;?php echo "piece1" .$posid ?&gt;"&gt;&lt;/span&gt; &lt;span class="piece-2" id="&lt;?php echo "piece2" .$posid ?&gt;"&gt;&lt;/span&gt; &lt;/div&gt; &lt;div class="price"&gt; &lt;span class="price" id="&lt;?php echo "price" .$posid ?&gt;"&gt;&lt;/span&gt; &lt;/div&gt; &lt;/div&gt; &lt;?php } else { ?&gt; &lt;div class="position"&gt; &lt;div class="runway" id="&lt;?php echo "runway" .$posid ?&gt;"&gt; &lt;span class="piece-1" id="&lt;?php echo "piece1" .$posid ?&gt;"&gt;&lt;/span&gt; &lt;span class="piece-2" id="&lt;?php echo "piece2" .$posid ?&gt;"&gt;&lt;/span&gt; &lt;/div&gt; &lt;div class="positionbody"&gt; &lt;span class="&lt;?php echo $set ?&gt;"&gt;&lt;/span&gt; &lt;/div&gt; &lt;/div&gt; &lt;?php }; } } } ?&gt; </code></pre> <p><strong>CSS</strong> </p> <pre><code>span{ display: block; font: bold 10px "Arial", "Helvetica", sans-serif; color: #000; text-align: center; } /*********************** Board Structure ************************/ .board { background: #EBEBE0; width: 845px; } .row{ background: #fff; float: left; width: 100%; } .left-column{ width: 75px; float: left; } .center-column{ float: left; width: 20px; } .right-column{ float: right; width: 75px; } /************************ Board Positions ************************/ .position { border: 1px solid #CFCFCF; float: left; height: 48px; margin: 0 2px 2px 0; width: 73px; } div .position:last-child { margin-right: 0; } /************************ Positions Title ************************/ .title span{ line-height: 14px; } .brown, .blue, .pink, .orange, .red, .yellow, .green, .navy{ height: 14px; color: white; width: 100%; } .brown{ background: #AA6220; } .blue{ background: #7AC0F6; } .pink{ background: #FF356E; } .orange{ background: #FF7A00; } .red{ background: #C40101; } .yellow{ background: #FFFF00; color: black; } .green{ background: #0B860B; } .navy{ background: #001791; } /************************ Positions Runway ************************/ .runway{ height: 12px; margin: 2px 0 2px 0; position: relative; z-index: 2; } .piece-1{ background-image:url('../img/piece2.png'); float: left; height:12px; margin-left: 2px; width: 12px; } /*********************** Positions Body ************************/ .positionbody{ height:32px; margin-top: -8px; position: relative; z-index: 1; } .go, .chest, .airport, .taxes, .chance, .jailhouse{ background-repeat: no-repeat; width: 32px; height: 32px; margin: 0 auto 0 auto; } .go{ background-image:url('../img/go.png'); } .chest{ background-image:url('../img/chest.png'); } .taxes{ background-image:url('../img/taxes.png'); } .airport{ background-image:url('../img/plane.ico'); z-index: -1; } .airport-title{ height: 12px; position: relative; top:-8px; } .chance{ background-image:url('../img/chance.png'); } .jailhouse{ background-image:url('../img/jail.png'); } /*********************** Positions Price ************************/ .price{ height: 14px; margin-top: 5px; } </code></pre> <p><strong>Post Edit</strong></p> <pre><code>for ($i = $start; $i != $stop; $i += $diff){ </code></pre> <p>This for loop gets its variables from the function parameters. I want to reduce my parameters to just 2 instead of 3. Parameter <code>$diff</code> tells the <code>for loop</code> to either <code>i++</code> or <code>i--</code>. The only other way I can think of achieving this with just 2 parameters is using an if statement like <code>if $start &gt; $stop then $i--</code> but that would mean additional lines of code.</p>
[]
[ { "body": "<p>DISCLAIMER: I don't know PHP. Also I haven't tested this.</p>\n\n<p>Running on the assumption that position is a number or number-like value I figure you could do something like:</p>\n\n<pre><code>function drawBoard($order = \"DESC\", $start = \"\", $stop =\"\"){\n\n include 'dbconnect.php';\n\n\n $result = mysqli_query($con,\"SELECT * FROM positions WHERE REPLACE(position, 'pos', '') BETWEEN '$start' AND '$stop' ORDER BY position $order\")\n or die(\"Could not select examples\");\n\n\n while($row = mysqli_fetch_array($result)){\n</code></pre>\n\n<p>This is one call to SQL. Replace <code>$diff</code> with order *(holding either <code>ASC</code> or <code>DESC</code>). no <code>for</code> loop.</p>\n\n<p><strong>BUT</strong> the values in <code>position</code> would work better without the prefix \"pos\" and as a numeric value.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-02-05T07:01:09.713", "Id": "40928", "ParentId": "40654", "Score": "3" } }, { "body": "<p>When mixing if statements and HTML I and others often use the <a href=\"http://www.php.net/manual/en/control-structures.alternative-syntax.php\" rel=\"nofollow\">alternative syntax</a>, which makes it easier to spot what's being closed even though the brackets might have a great deal of distance between them:</p>\n\n<pre><code>if( condition ): ?&gt;\n HTML\n&lt;?php endif;\n</code></pre>\n\n<p>I like the idea of using semantic variables instead of <code>$row[index]</code> but I think there are more elegant ways of making the assignments. For example by using <code>mysqli_fetch_assoc</code> you might get a semantic associative array that you could use and skip the extra assignments, or you could use</p>\n\n<pre><code>list($posid, $title, ...,...) = $row;\n</code></pre>\n\n<p>To fix the problem that you mention in your edit you could do for example:</p>\n\n<pre><code>for ($i = min($start,$stop); $i != max($start, $stop); $i += 1){\n</code></pre>\n\n<p>If it doesn't matter in which order you loop through the elements. In this case I guess it does, so you would have to get the sign of the difference ($stop-$start):</p>\n\n<pre><code>$diff = ($stop &gt; $start) ? 1 : -1; \n</code></pre>\n\n<p>Finally I think that the default values of <code>drawBoard</code> should be numeric.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-02-05T08:00:59.780", "Id": "40933", "ParentId": "40654", "Score": "4" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-02-02T04:19:26.680", "Id": "40654", "Score": "7", "Tags": [ "php", "html", "css" ], "Title": "Monopoly: Board creation" }
40654
<p>These two functions search for directories with a certain prefix that contain no files of a given type.</p> <ol> <li>Does the code adhere to Ruby standards and conventions?</li> <li>Am I doing something the hard way or the "non-Ruby" way?</li> <li>Should I use more/fewer/different comments?</li> </ol> <p></p> <pre><code>def find_empties(directory, dirprefix, fsuffix) empty_dirs = Array.new Dir.chdir directory do Dir["#{dirprefix}**/"].each do |subdir| Dir.chdir subdir do empty_dirs.push subdir if Dir["**.#{fsuffix}"].empty? end end end return empty_dirs end def find_empties_sorted(directory, dirprefix, fsuffix) empties = find_empties(directory, dirprefix, fsuffix) nums = Hash.new non_numeric = Array.new empties.each do |x| # if starts with digits, trim leading zeroes and extract; else, nothing num = x.sub(/^#{Regexp.escape dirprefix}0*(\d+).*/, '\1') is_num = num !~ /\D/ if is_num n = Integer num nums[n] = Array.new unless nums[n] nums[n].push x else non_numeric.push x end end result = Array.new nums.sort.each do |k, v| v.each do |x| result.push x end end result.concat non_numeric.sort result end </code></pre> <p>The code works as intended, but here's a test case:</p> <pre class="lang-bash prettyprint-override"><code>$ ls emptyfinder.rb emptyrunner.rb $ cat emptyrunner.rb require_relative 'emptyfinder.rb' puts find_empties_sorted(Dir.pwd, 'e', 'txt') $ mkdir testcase $ cd testcase $ mkdir e1 e2 e003 e004 e4 e5 e9 e10 e11 empty emptier emptynot $ touch emptynot/file.txt $ touch empty/not_a_txt.csv $ ruby ../emptyrunner.rb e1/ e2/ e003/ e004/ e4/ e5/ e9/ e10/ e11/ emptier/ empty/ $ </code></pre>
[ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-02-02T09:27:07.677", "Id": "68552", "Score": "1", "body": "Can you share a test case please? For example: an example directory structure and some files and what this script should find and ignore. This can be refactored and the test case will help me keep the same behaviour. Thanks." } ]
[ { "body": "<p>Looks alright.</p>\n\n<p>Your style is more spread out than is usually the case in ruby (though that's not necessarily a bad thing.) For example</p>\n\n<pre><code>is_num = num !~ /\\D/\nif is_num\n ...\n</code></pre>\n\n<p>could as well be one line sans assignments, without loosing clarity. <code>if num !~ /\\D/ # is a number</code></p>\n\n<p>Instead of declaring <code>nums</code> to be a Hash, then having an if statement to check if a pair needs initialised with an array, you can just declare the hash with a block that it then uses to default all values to new arrays like so <code>nums = Hash.new { |h,k| h[k] = [] }</code>.</p>\n\n<p>Instead of iterating through the array v of sorted nums and pushing each item to result, you can just do <code>result.concat v</code>. Sometimes for simple logic, denser one liners are arguably easier to read in ruby: e.g. <code>nums.sort.each { |k, v| result.concat v }</code></p>\n\n<p>Be aware that you can initialise arrays and hashes as literals, e.g. <code>a = []</code> and this is sometimes prefered.</p>\n\n<p>Your level of commenting seems appropriate to me, i.e. explaining <em>what</em> the code is meant to do (or <em>why</em> but not <em>how</em>) when it's not obvious from the code itself.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-02-02T22:54:29.843", "Id": "68645", "Score": "1", "body": "Also, you don't need explicit returns." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-02-02T23:51:37.443", "Id": "68652", "Score": "0", "body": "Thanks for your help. That `Hash` block initialization trick is very nice. Is there any reason `[]` and `{}` are sometimes preferred over `Array.new` and `Hash.new` besides brevity? Also, the line `result.concat non_numeric.sort` returns `result`, but I put `result` afterwards for clarity as well. Should I keep this or leave it out?" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-02-03T07:27:34.060", "Id": "68681", "Score": "0", "body": "I don't believe there is any programatic difference between literals and constructor calls for creating plain empty arrays or hashes in Ruby. The constructors offer some powerful features (such as taking blocks), however ruby style usually emphasises the simple clarity of literals, as it provides literal syntaxes for just about everything. Since every function has a return value, it is good practice for every function to return something meaningful, even if it isn't something important. Therefore the reader should understand that, `result` is returned implicitly." } ], "meta_data": { "CommentCount": "3", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-02-02T22:30:04.777", "Id": "40697", "ParentId": "40655", "Score": "8" } }, { "body": "<p>You could simplify your code quite a bit. Here's one way: </p>\n\n<pre><code>def find_empties_sorted(directory, dirprefix, fsuffix)\n Dir[\"#{directory}/#{dirprefix}**/\"].each_with_object([]) { |e,arr|\n arr &lt;&lt; e[/[^\\/]+(?=\\/$)/] if Dir[\"#{e}**.#{fsuffix}\"].empty? }\n .each_with_object ({}) do |x,h|\n n = x[/\\d+$/]\n ni = n ? n.to_i : n\n (h[ni] ||= []) &lt;&lt; (n ? x[0,x.size-n.size] + ni.to_s : x)\n end.sort { |(k1,_), (k2,_)| k1.nil? ? (k2.nil? ? 0 : 1) : (k2.nil? ? -1 : k1&lt;=&gt;k2) }\n .transpose\n .last\n .flatten\nend\n</code></pre>\n\n<p>For the data you used, this would return:</p>\n\n<pre><code> #=&gt; [\"e1\", \"e2\", \"e3\", \"e4\", \"e4\", \"e5\",\n # \"e9\", \"e10\", \"e11\", \"emptier\", \"empty\"]\n</code></pre>\n\n<p>If you want <code>/</code> at the end of each subdir, change <code>.flatten</code> to</p>\n\n<pre><code>.flatten.map { |s| s &lt;&lt; '/' }\n #=&gt; [\"e1/\", \"e2/\", \"e3/\", \"e4/\", \"e4/\", \"e5/\",\n # \"e9/\", \"e10/\", \"e11/\", \"emptier/\", \"empty/\"]\n</code></pre>\n\n<p>I've used <a href=\"http://ruby-doc.org/core-2.1.0/Enumerable.html#method-i-each_with_object\" rel=\"nofollow\">Enumerable#each_with_object</a> (v1.9+) twice, as\n it provides a convenient way to build an object such as an array or hash (which is returned).\nIn the first case the object is an initially-empty array (with block variable <code>arr</code>); in the second it is an initially-empty hash (with block variable <code>h</code>).</p>\n\n<p>I will use your data--with two changes--to explain what's going on here. I've added an empty directory <code>e</code> and a file <code>f.txt</code> to the directory to <code>testdir</code>.</p>\n\n<pre><code>directory = 'testcase'\ndirprefix = 'e'\nfsuffix = 'txt' \n\na = Dir[\"#{directory}/#{dirprefix}**/\"].each_with_object([]) { |e,arr|\n arr &lt;&lt; e[/[^\\/]+(?=\\/$)/] if Dir[\"#{e}**.#{fsuffix}\"].empty? }\n #=&gt; [ \"e\", \"e003\", \"e004\", \"e1\", \"e10\", \"e11\",\n # \"e2\", \"e4\", \"e5\", \"e9\", \"emptier\", \"empty\"]\n</code></pre>\n\n<p>A word about the regex <code>/[^\\/]+(?=\\/$)/</code> (which I've used to avoid the need to <code>chdir</code>). <code>[^\\/]+</code> looks for a string that contains one or more characters other than <code>/</code>. <code>(?=\\/$)</code> is called a <a href=\"http://www.regular-expressions.info/lookaround.html\" rel=\"nofollow\">positive lookahead</a>. It is not part of the match (which is why it is sometimes referred to as having \"zero width\"), but it requires that the match be followed by <code>/$</code>, where <code>$</code> signifies the end-of-line. This strips off <code>directory</code> from the beginning of <code>e</code>. To make it easier to remove leading zeros on trailing numbers, I've not included <code>/</code> at the end of each subdir. (It can be added at the end if desired.)</p>\n\n<p>Next we execute</p>\n\n<pre><code>b = a.each_with_object ({}) do |x,h|\n n = x[/\\d+$/]\n ni = n ? n.to_i : n\n (h[ni] ||= []) &lt;&lt; (n ? x[0,x.size-n.size] + ni.to_s : x)\n end\n</code></pre>\n\n<p>Initially the hash <code>h</code> is empty. <code>x</code> is first assigned the value \"e\" (from the array <code>a</code>). We compute </p>\n\n<pre><code>n = x[/\\d+$/] #=&gt; nil (because no trailing number)\nni = n ? n.to_i : n #=&gt; nil\n(h[ni] ||= []) &lt;&lt; (n ? x[0,x.size-n.size] + ni.to_s : x) # h =&gt; { nil=&gt;[\"e\"] }\n</code></pre>\n\n<p><code>h[ni] ||= []</code> is shorthand for <code>h[ni] = h[ni] || []</code>, so if <code>h[ni]</code> is undefined (<code>nil</code>), as it is here, <code>||</code> causes <code>h[ni] =&gt; []</code>; if <code>h[i]</code> is already defined as an array (so is neither <code>nil</code> nor <code>false</code>),<code>[]</code> is not considered. Alternatively (as @Nat mentioned), we could substitute <code>(Hash.new { |h,k| h[k] = [] })</code> for <code>({})</code> following <code>each_with_object</code>.</p>\n\n<p>Next, <code>x</code> is assigned the value <code>\"e003\"</code>. We compute</p>\n\n<pre><code>n = x[/\\d+$/] #=&gt; \"003\"\nni = n ? n.to_i : n #=&gt; 3\n(h[ni] ||= []) &lt;&lt; (n ? x[0,x.size-n.size] + ni.to_s : x)\n # h =&gt; { nil=&gt;[\"e\"], 3=&gt;[\"e3\"] } \n</code></pre>\n\n<p>Continuing through the elements of a, we obtain:</p>\n\n<pre><code>b = {nil=&gt;[\"e\", \"emptier\", \"empty\"], 3=&gt;[\"e3\"], 4=&gt;[\"e4\", \"e4\"], 1=&gt;[\"e1\"],\n 10=&gt;[\"e10\"], 11=&gt;[\"e11\"], 2=&gt;[\"e2\"], 5=&gt;[\"e5\"], 9=&gt;[\"e9\"]} \n</code></pre>\n\n<p>We now sort the keys. <code>b.sort</code> would raise the exception <code>ArgumentError: comparison of Array with Array failed</code> because <code>Fixnum objects</code> cannot be compared with <code>nil</code>. We therefore need to define the \"spaceship\" method, <code>&lt;=&gt;</code> that\n<code>sort</code> is to use. Since we want the key <code>nil</code> to be last, we do it this way:</p>\n\n<pre><code>c = b.sort { |(k1,_), (k2,_)| k1.nil? ? (k2.nil? ? 0 : 1) : (k2.nil? ? -1 : k1&lt;=&gt;k2) }\n #=&gt; [[1, [\"e1\"]], [2, [\"e2\"]], [3, [\"e3\"]], [4, [\"e4\", \"e4\"]], [5, [\"e5\"]],\n # [9, [\"e9\"]], [10, [\"e10\"]], [11, [\"e11\"]], [nil, [\"e\", \"emptier\", \"empty\"]]]\n</code></pre>\n\n<p>Note that <code>sort</code> returns an array. We could have written:</p>\n\n<pre><code>c = b.sort { |(k1,v1), (k2,v2)|... \n</code></pre>\n\n<p>where <code>k1 =&gt; v1</code> is one member of the hash and <code>k1 =&gt; v1</code> is another, but since we are sorting on the keys, and do not use the values <code>v1</code> and <code>v2</code>, we can replace the latter with underscores.</p>\n\n<p>We could have done this differently, using <code>sort</code> without a block, had we used <code>n</code> instead of <code>nil</code> for the key for directories without trailing numbers, and chosen <code>n</code> so that it was larger than any of the other keys. This is one way to do that:</p>\n\n<pre><code>empties = find_empties_sorted(directory, dirprefix, fsuffix)\n Dir[\"#{directory}/#{dirprefix}**/\"].each_with_object([]) { |e,arr|\n arr &lt;&lt; e[/[^\\/]+(?=\\/$)/] if Dir[\"#{e}**.#{fsuffix}\"].empty? }\nn = ('1' + '0'*empties.map(&amp;:size).max).to_i #=&gt; 10000000\n</code></pre>\n\n<p>We are almost finished. Next we transpose to obtain an array with only two elements:</p>\n\n<pre><code>d = c.transpose\n #=&gt; [[1, 2, 3, 4, 5, 9, 10, 11, nil],\n # [[\"e1\"], [\"e2\"], [\"e3\"], [\"e4\", \"e4\"], [\"e5\"],\n # [\"e9\"], [\"e10\"], [\"e11\"], [\"e\", \"emptier\", \"empty\"]]]\n</code></pre>\n\n<p>As we only want the second element:</p>\n\n<pre><code>e = d.last\n #=&gt; [[\"e1\"], [\"e2\"], [\"e3\"], [\"e4\", \"e4\"], [\"e5\"],\n # [\"e9\"], [\"e10\"], [\"e11\"], [\"e\", \"emptier\", \"empty\"]]\n</code></pre>\n\n<p>And lastly, we must flatten:</p>\n\n<pre><code>e.flatten\n #=&gt; [\"e1\", \"e2\", \"e3\", \"e4\", \"e4\", \"e5\",\n # \"e9\", \"e10\", \"e11\", \"e\", \"emptier\", \"empty\"]\n</code></pre>\n\n<p>This array is returned by the method.</p>\n\n<p>If you would prefer less chaining, go ahead and add temporary variables and/or additional methods. The more you work with Ruby, however, the more chaining becomes the natural thing to do. It's no more difficult to debug, as you can do what I did in explaining what I've done.</p>\n\n<p>In deciding the proper balance between conciseness and the use of temporary variables and separate methods, I'm always thinking about how the code reads. Aside from performance, my main objectives are to make my code read well and read fast. I want an experienced Rubyist to be able to read and comprehend it in minimum time. Personally, I much prefer reading tightly-chained code to code that is all spread out, uses lots of very short methods, lots of temporary variables with highly-descriptive (and accordingly, long) names, and so on.</p>\n\n<p>It would take very little time (well under 30 seconds) for any experienced Rubyist to scan my code and have a general idea of what I was doing: creating an array of directories, converting that to a hash, sorting the hash on its keys, transposing the resulting array, extracting its last element and flattening. Yes, they would have to look more closely at certain parts, such as the regexes, sort criteria, and so on, and for that I would help by adding a few comments. Comprehension of some parts of the code, including <code>.transpose</code>, <code>.last</code> and <code>.flatten</code> would be virtually automatic, so it makes perfect sense to express those three operations as compactly as possible: here, three words separated by dots.</p>\n\n<p>What I've just said is the opinion of one Ruby hobbiest. I invite others--particularly those who write Ruby code for a living--to weigh-in on these issues by adding comments.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-02-09T05:25:51.993", "Id": "70814", "Score": "0", "body": "Thanks very much for your help and in-depth explanation. This is the kind of answer I was looking for. That said, I have a few questions. Looking at your code immediately brought to mind the [Zen of Python](http://stackoverflow.com/q/4568704/732016)'s \"complex is better\" than complicated - does that apply here? I've read that [Ruby is supposed to read like English](http://mislav.uniqpath.com/poignant-guide/book/chapter-3.html), or is that just for simpler programs? Finally, is it generally better practice to separate methods (`find_empties` and `find_empties_sorted`) or have just one?" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-02-09T06:33:48.547", "Id": "70817", "Score": "0", "body": "W, I've tried to address the questions in your comment by adding some discussion at the end of my answer. Feel free to ask more follow-ups." } ], "meta_data": { "CommentCount": "2", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-02-09T00:29:28.413", "Id": "41261", "ParentId": "40655", "Score": "7" } }, { "body": "<p>Although @CarySwoveland gave a very extensive answer, with quite a few good tips, I agree with @WChargin's remark on the code not being very readable, as it is riddled with <code>e</code>s,<code>n</code>s,<code>x</code>s and <code>h</code>s, which make it not very readable.</p>\n\n<p>Also using the more obscure <code>transpose.last</code> is a nice trick, but, using <code>map(&amp;:last)</code> will give the same result, and look more familiar to more ruby developers.</p>\n\n<p>The pattern:</p>\n\n<pre><code>.each_with_object([]) { |e,arr|\n arr &lt;&lt; e[/[^\\/]+(?=\\/$)/] if Dir[\"#{e}**.#{fsuffix}\"].empty? }\n</code></pre>\n\n<p>could be more readable when written with a combination of <code>select</code> and <code>map</code>:</p>\n\n<pre><code>.select { |e| Dir[\"#{e}**.#{fsuffix}\"].empty? }.map { |e| e[/[^\\/]+(?=\\/$)/] }\n</code></pre>\n\n<p><code>e[/[^\\/]+(?=\\/$)/]</code> - could be replaced by <code>File.basename(e)</code>, which is, again, more readable, and less error-prone to future maintainers of your code.</p>\n\n<p>The pattern:</p>\n\n<pre><code>.each_with_object ({}) do |x,h|\n n = x[/\\d+$/]\n ni = n ? n.to_i : n\n (h[ni] ||= []) &lt;&lt; x\n end\n</code></pre>\n\n<p>can be better represented using <code>group_by</code>:</p>\n\n<pre><code>.group_by do |x|\n n = x[/\\d+$/]\n n ? n.to_i : n\nend\n</code></pre>\n\n<p>Here is my version of the code:</p>\n\n<pre><code>def find_empties_sorted(directory, dirprefix, fsuffix)\n Dir[\"#{directory}/#{dirprefix}**/\"]\n .select { |dirName| Dir[\"#{dirName}**.#{fsuffix}\"].empty? }\n .group_by { |dirName| (suffix = dirName[/\\d+\\/?$/]).nil? ? Float::INFINITY : suffix.to_i }\n .sort.map(&amp;:last).flatten\nend\n</code></pre>\n\n<p>The first line selects all subdirectories matching the pattern. The second line selects only the ones which are empty. The third groups by the numeric suffix (non-numeric suffixes will be grouped under <code>Float::INFINITY</code>, so they will be last). The last line sorts by the numeric suffix of the directories, and returns the directory names.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2015-01-10T15:17:59.463", "Id": "139709", "Score": "0", "body": "I don't recall seeing your answer until now. I agree with everything you said (except possibly the use of one-letter names for some block variables). Excellent analysis!" } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-03-01T09:27:45.737", "Id": "43126", "ParentId": "40655", "Score": "2" } } ]
{ "AcceptedAnswerId": "41261", "CommentCount": "1", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-02-02T04:46:17.810", "Id": "40655", "Score": "9", "Tags": [ "ruby", "beginner", "file-system" ], "Title": "Search for directories with a certain prefix that contain no files of a given type" }
40655
<p>Would love some feedback on this. I'm coming from a Java background and kinda feel like I've just done exactly what I would do in Java. Is there a better way?</p> <pre><code>for (i &lt;- 1 to 100) { if ( i % 3 == 0 &amp;&amp; i% 5 == 0) println(i +" = FizzBuzz") else if (i % 3 == 0) println(i +" = Fizz") else if (i % 5 == 0) println(i +" = Buzz") } </code></pre>
[]
[ { "body": "<ul>\n<li><p>Instead of using both 3 and 5:</p>\n\n<pre><code>if (i % 3 == 0 &amp;&amp; i % 5 == 0)\n</code></pre>\n\n<p>you can just use 15:</p>\n\n<pre><code>if (i % 15 == 0)\n</code></pre></li>\n<li><p>You're also supposed to print the number <em>by itself</em> if neither case applies:</p>\n\n<pre><code>else\n println(i)\n</code></pre>\n\n<p>For your existing cases, however, you're only supposed to print the <em>message</em>.</p></li>\n</ul>\n\n<p>Final solution:</p>\n\n<pre><code>for (i &lt;- 1 to 100) {\n if (i % 15 == 0) \n println(\"FizzBuzz\")\n else if (i % 3 == 0) \n println(\"Fizz\")\n else if (i % 5 == 0) \n println(\"Buzz\")\n else\n println(i)\n}\n</code></pre>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-02-02T05:36:47.050", "Id": "40657", "ParentId": "40656", "Score": "14" } }, { "body": "<p>FizzBuzz is kind of a difficult example because its simplicity means it looks more or less the same in every language. That said, we can go out of our way to emphasize the functional aspect of Scala.</p>\n\n<p>First, we can wrap the core logic of FizzBuzz up in its own function:</p>\n\n<pre><code>def fizzBuzz(x:Int) = {\n if (x % 15 == 0)\n \"FizzBuzz\"\n else if (x % 3 == 0)\n \"Fizz\"\n else if (x % 5 == 0)\n \"Buzz\"\n else\n x\n}\n</code></pre>\n\n<p>Now, we can compose this with printing and map it over the domain we're interested in:</p>\n\n<pre><code>(1 until 100).map(fizzBuzz _ andThen println)\n</code></pre>\n\n<p>Notice that, where in Java we would probably repeat the <code>println</code> in every case, in Scala, with first-class functions, we can easily separate it out as its own step in the process.</p>\n\n<p>The advantage of this becomes clearer when we think about recombining elements. If we wanted to, we could, for example, join everything in a string without rewriting the essential FizzBuzzzing logic:</p>\n\n<pre><code>println((1 until 100).map(fizzBuzz).mkString(\", \"))\n</code></pre>\n\n<p>So, hopefully you can see that Scala's \"better way\" is first-class functions. With them, we more easily compose the pieces of our system.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-02-02T09:59:02.737", "Id": "68556", "Score": "1", "body": "As a disclaimer, I'm not a Scala guy, so that code can probably be cleaned up a little. Still, the fundamental takeaway is the same." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-02-02T11:19:25.067", "Id": "68559", "Score": "0", "body": "Hey, that's cool - I like it. This is the kind of response I was looking for. It's really a bit of a shift in thinking, I think that a simple example like FizzBuzz makes it really clear." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-02-02T18:20:16.527", "Id": "68606", "Score": "1", "body": "@cookiemonster you might want to also glance at [Higher-order FizzBuzz in Clojure](http://codereview.stackexchange.com/questions/13634/higher-order-fizzbuzz-in-clojure). I think that calculating pi (#18 on [20 controversial programming opinions](http://programmers.blogoverflow.com/2012/08/20-controversial-programming-opinions/)) because it isn't quite as simple (not *hard*, but not quite as simple) and really does require some different thinking in the functional world." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-10-27T02:39:37.863", "Id": "124128", "Score": "0", "body": "While x % 15 == 0 and x%3==0 && x%5==0 give the same result, they are NOT conceptually the same." } ], "meta_data": { "CommentCount": "4", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-02-02T09:58:10.833", "Id": "40659", "ParentId": "40656", "Score": "31" } }, { "body": "<p>Or if you prefer match/case to if/else:</p>\n\n<pre><code>(1 until 100).map(i =&gt; (i % 3, i % 5) match {\n case (0, 0) =&gt; \"FizzBuzz\"\n case (0, _) =&gt; \"Fizz\"\n case (_, 0) =&gt; \"Buzz\"\n case _ =&gt; i\n}).foreach(println)\n</code></pre>\n\n<p>Update:</p>\n\n<p>So what we are doing here is taking list of numbers and mapping them first to tuples where on the left side is that number module 3 and on the right side modulo 5. Then we are matching those tuples to cases where both are zero, left is zero, right is zero or neither is zero. </p>\n\n<p>Also the actual logic is in the map-block and side-effect of printing is in the foreach-block.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-02-02T16:24:19.670", "Id": "68596", "Score": "4", "body": "This is by far the most scala-y solution proposed yet, IMO. map() is preferred over standard for loops, and the match here is much more elegant than the chained if/else." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2016-09-23T12:00:48.473", "Id": "266595", "Score": "0", "body": "Some comments:\n #1 using 1 until 100 means range 1-99 \n #2 we don't need map as we are not going to re-use the collection of fizz, buzz, fizzbuzz strings. straightaway foreach would have worked too." } ], "meta_data": { "CommentCount": "2", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-02-02T14:56:17.307", "Id": "40672", "ParentId": "40656", "Score": "47" } }, { "body": "<p>I tried to come up with a different looking solution. I am not claiming it is better, but I thought I should put it here since this approach might be more appropriate for some applications which are somewhat related to FizzBuzz.</p>\n\n<p>Basically I treat the fizz and buzz problems separately and merge them. I also use a lot of Scala features such as Stream, Option, currying and case matching.</p>\n\n<pre><code> def transformPeriodic(period: Int, word: String)(counter: Int) =\n if (counter % period == 0) Some(word) else None\n\n val fizzTransform = transformPeriodic(3, \"Fizz\") _\n val buzzTransform = transformPeriodic(5, \"Buzz\") _\n\n def mergeFizzBuzz(fizzOpt: Option[String], buzzOpt: Option[String]): Option[String] = {\n (fizzOpt, buzzOpt) match {\n case (None, None) =&gt; None\n case _ =&gt; Some(fizzOpt.getOrElse(\"\") + buzzOpt.getOrElse(\"\"))\n }\n }\n\n val streamInt = Stream.from(1)\n val tripletStream = streamInt.map(i =&gt; (i, fizzTransform(i), buzzTransform(i)))\n val doubletStream = tripletStream.map { case (i, fizzOpt, buzzOpt) =&gt; (i, mergeFizzBuzz(fizzOpt, buzzOpt)) }\n val fizzBuzzStream = doubletStream.map { case (i, fizzBuzzOpt) =&gt; fizzBuzzOpt.getOrElse(i) }\n\n fizzBuzzStream take 15 foreach println\n</code></pre>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-03-26T20:08:29.130", "Id": "45439", "ParentId": "40656", "Score": "5" } }, { "body": "<p>A bit old but here's my two cents: you could use PartialFunction.</p>\n\n<p>Basically you define the functions you want to use and compose them in the proper order:</p>\n\n<pre><code>def f(divisor: Int, result: Int =&gt; String): PartialFunction[Int, String] = {\n case i if (i % divisor == 0) =&gt; result(i)\n}\nval f3 = f(3, _ =&gt; \"Fizz\")\nval f5 = f(5, _ =&gt; \"Buzz\")\nval f15 = f(15, x =&gt; f3(x) + f5(x)) // DRY\nval id = f(1, _.toString)\n\nval fizzBuzz = f15 orElse f3 orElse f5 orElse id\n(1 to 100).map(fizzBuzz andThen println)\n</code></pre>\n\n<p><code>f15</code> must be called first otherwise <code>f3</code> or <code>f5</code> will stop the composition.\nIn the same way <code>id</code> is the last fallback (any number is modulo 1) and print the input (that's why I defined <code>result</code> as a function, and not just a string).</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-10-22T04:09:48.830", "Id": "67509", "ParentId": "40656", "Score": "7" } }, { "body": "<p>We'd usually make the solution more functional. That is, move the \"fizzbuzz\" logic into something that returns a string, and use that:</p>\n\n<pre><code>def fizzbuzz(i: Int) = \n if (i % 3 == 0 &amp;&amp; i % 5 == 0) \"FizzBuzz\"\n else if (i % 3 == 0) \"Fizz\"\n else if (i % 5 == 0) \"Buzz\"\n else s\"$i\"\n\nfor (i &lt;- 1 to 100) println(fizzbuzz(i))\n</code></pre>\n\n<p>It's a small thing, but it goes to the core of the philosophical difference.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2016-08-15T21:07:55.907", "Id": "138793", "ParentId": "40656", "Score": "1" } }, { "body": "<p>This takes advantage of scala's functional types:</p>\n\n<pre><code>val wordMap = Seq(3 -&gt; \"Fizz\", 5 -&gt; \"Buzz\")\n(1 to 100).map(i =&gt; {\n Some(\n wordMap.collect({ case (num, str) if i % num == 0 =&gt; str}).mkString\n ).filterNot(_.isEmpty).getOrElse(i.toString)\n}).foreach(println)\n</code></pre>\n\n<p>It's also easily extensible if additional number to word mappings are included (e.g. also print <code>\"Bazz\"</code> for all numbers divisible by 7, and \"Ten\" for all numbers divisible by 10), just change the <code>wordMap</code>:</p>\n\n<pre><code>val wordMap = Seq(3 -&gt; \"Fizz\", 5 -&gt; \"Buzz\", 7 -&gt; \"Bazz\", 10 -&gt; \"Ten\")\n(1 to 100).map(i =&gt; {\n Some(\n wordMap.collect({ case (num, str) if i % num == 0 =&gt; str}).mkString\n ).filterNot(_.isEmpty).getOrElse(i.toString)\n}).foreach(println)\n</code></pre>\n\n<p>Some related literature: <a href=\"http://dave.fayr.am/posts/2012-10-4-finding-fizzbuzz.html\" rel=\"nofollow noreferrer\">Overthinking FizzBuzz with Monads</a></p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2017-09-14T02:04:45.813", "Id": "175622", "ParentId": "40656", "Score": "2" } } ]
{ "AcceptedAnswerId": "40659", "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-02-02T05:00:57.227", "Id": "40656", "Score": "26", "Tags": [ "scala", "fizzbuzz" ], "Title": "First Scala FizzBuzz implementation" }
40656
<p>I am scraping an online shop page, trying to get the price mentioned in that page. In the following block the price is mentioned:</p> <pre><code>&lt;span id="hs18Price" itemprop="price" title="New Baby Care Pack"&gt; &lt;span class='WebRupee'&gt;&amp;#x20B9;&lt;/span&gt;&amp;nbsp;999&lt;/span&gt; </code></pre> <p>I am using <a href="http://www.crummy.com/software/BeautifulSoup/" rel="noreferrer">Beautiful Soup</a> to get this tag and using a regular expression to get the price:</p> <pre><code># -*- coding: utf8 -*- import re import requests from bs4 import BeautifulSoup hs18_test_urls = ['http://www.homeshop18.com/diary-wimpy-kid-hard-luck/author:jeff-kinney/isbn:9780141350677/books/juvenile-fiction/product:30926027/cid:10065/?it_category=HP&amp;it_action=BO-R01001&amp;it_label=HP-R01001-140121094603-30926027-PR-BO-RM-OT-RT01_BooksFlat40PercentOff-RL02-160120&amp;it_value=0', 'http://www.homeshop18.com/apple-ipad-air-wi-fi-16gb-space-grey/computers-tablets/tablets/product:31228967/cid:16327/', 'http://www.homeshop18.com/reebok-men-black-yellow-sandals-j97184/footwear/men/product:30795219/cid:15067/', 'http://www.homeshop18.com/american-swan-women-shirt-pink/clothing/women/product:31225645/cid:15021/', 'http://www.homeshop18.com/diva-fashion-art-silk-saree-parrot-green/clothing/women/product:31514557/cid:15011/?it_category=hs18bot&amp;it_action=recentlySoldProducts&amp;it_label=31225645&amp;it_value=1'] hs18_expected_test_results = [u'210', u'35900', u'1499', u'479', u'1199'] def get_homeshop18_product_meta(url): reg = ur'^ ₹? (\d+)' response = requests.get(url) if response.status_code == requests.codes.ok: soup = BeautifulSoup(response.text) product_name = soup.find('meta', {'property' : 'og:title'})['content'] product_url = soup.find('meta', {'property' : 'og:url'})['content'] product_img_url = soup.find('meta', {'property': 'og:image'})['content'] product_price_tag_element = soup.find('span', {'id': 'hs18Price', 'itemprop': 'price'}) product_price_match = re.match(reg, product_price_tag_element.text) if product_price_match: product_price = product_price_match.group(1) else: product_price = None return (product_url, product_name, product_img_url, product_price) return None if __name__ == '__main__': assert(map(lambda x: x[3], map(get_homeshop18_product_meta, hs18_test_urls)) == hs18_expected_test_results) </code></pre> <h3>Questions:</h3> <ol> <li>With beautiful soup I can get contents within that span tag. Is there any way to just get the content of the outer span and ignoring whatever is within the inner span tag? i.e. it should give me only <code>&amp;nbsp; 210</code>.</li> <li>If the above is not possible, then is there any further improvements you suggest with regards to <code>re</code> or the code in general?</li> <li><p>I am using a unicode character(<code>\U20B9</code>) in my script. Should I be doing that? I couldn't get <code>re</code> to match even after sending <code>re.UNICODE</code> flag.</p> <pre><code>reg = r'^ \U20B9? (\d+)' </code></pre> <p></p> <pre><code>product_price_match = re.match(reg, product_price_tag_element.text, re.UNICODE) </code></pre></li> <li><p>For the reason mentioned in #3, I am using <code>-*- coding: utf8 -*-</code> at the start. Is that okay? Is this the pythonic way? or any suggested way?</p></li> </ol>
[ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-02-03T03:31:32.267", "Id": "68661", "Score": "0", "body": "I think you need `\\u20B9` instead of `\\U20B9` (lowercase for 4 instead of 8 nybbles). If that still doesn't work, I'd consider either dropping the raw string prefix, or splitting the string to avoid the literal `₹`." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-02-03T16:26:26.333", "Id": "68732", "Score": "0", "body": "^yes! it matches to `u'\\u20B9'`" } ]
[ { "body": "<p>As it happens, there are positive answers to each of your questions:</p>\n\n<ol>\n<li><p>with Beautiful Soup you can remove the WebRupee <code>span</code> with <a href=\"http://www.crummy.com/software/BeautifulSoup/bs4/doc/#replace-with\" rel=\"noreferrer\">replace_with()</a> entirely....</p>\n\n<pre><code>webrupee_element = soup.find('span', {'class': 'WebRupee'})\nwebrupee_element.replace_with('')\n</code></pre>\n\n<p>... then, when you get the text value of the <code>product_price_tag_element.text</code> it will not have the symbol.</p>\n\n<p><strong>EDIT:</strong> Of course, it would be faster/better to do:</p>\n\n<pre><code>for wr in product_price_tag_element.find('span'):\n wr.replace_with('')\n</code></pre></li>\n<li><p>Your regex is not matching the value properly because the <code>&amp;nbsp;</code> character may not be mapping directly to the regular <code>' '</code> character in your regex. You should use the 'whitespace' escape-sequence <code>\\s</code> in your regex instead of <code>' '</code>, like <code>reg = ur'^\\s*₹?\\s*(\\d+)\\s*'</code></p></li>\n<li><p>Unicode string literals in python should be escaped with either the <code>\\u</code> or <code>\\U</code> escape, but <a href=\"http://docs.python.org/2/howto/unicode.html#unicode-literals-in-python-source-code\" rel=\"noreferrer\">they are different</a>:</p>\n\n<blockquote>\n <p>Specific code points can be written using the \\u escape sequence, which is followed by four hex digits giving the code point. The \\U escape sequence is similar, but expects 8 hex digits, not 4.</p>\n</blockquote>\n\n<p>in your case you should use lower-case <code>\\u</code></p></li>\n<li><p>You can remove the utf-8/unicode declaration if you encode the values in the more-pythonic way of unicode escapes.</p></li>\n</ol>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-02-03T17:07:20.597", "Id": "68742", "Score": "0", "body": "any reason using `for` loop? Since there is only one span tag, why not this, or just to be safe?:\n\n`product_price_tag_element.find('span').replace_with('')`\n\n`price = product_price_tag_element.text.strip()`" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-02-03T17:08:15.777", "Id": "68743", "Score": "0", "body": "it is just a way to make testing for the actual span a bit easier/safer. If there is no child WebRupee span the loop is still safe. Actually, I would even go so far as to recommend `product_price_tag_element.children`" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-02-03T17:19:02.080", "Id": "68751", "Score": "0", "body": "makes sense. however `product_price_tag_element.children` also contains the text along with span as child. So I cannot actually do `replace_with('')` that would be replacing my text also." } ], "meta_data": { "CommentCount": "3", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-02-03T12:54:09.473", "Id": "40733", "ParentId": "40658", "Score": "10" } } ]
{ "AcceptedAnswerId": "40733", "CommentCount": "2", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-02-02T07:53:23.233", "Id": "40658", "Score": "15", "Tags": [ "python", "regex", "unicode", "web-scraping", "beautifulsoup" ], "Title": "Getting data correctly from <span> tag with beautifulsoup and regex" }
40658
<pre><code>function RegisterN() { if($_SERVER['REQUEST_METHOD'] == 'POST'){ if (isset($_POST["password"],$_POST["password1"]) &amp;&amp; $_POST["password"]!=$_POST["password1"]) { # Check if password and password1 are same echo "Your password confirmation is not equal to your password or it missing."; } else if(!$_POST["email"]){ # Check if email is present echo "Please enter your email."; } else if (!$_POST["password"]){ # Check if password is present again echo "Please enter your password"; } else if (!$_POST["password1"]){ # Check if password1 is present again echo "Please enter your second password"; } else { if (strlen ($_POST["password"])&gt;25 || strlen ($_POST["password"])&lt;6) # check password length max 25, min 6 { echo "Password must be between 6 and 25 characters"; } else { $dbh = new Database(); # Open database $dbh-&gt;setAttribute(PDO::ATTR_EMULATE_PREPARES, false); # Small SQL injection security $stmt = $dbh-&gt;prepare('SELECT email FROM members WHERE email=?'); # Check if email exists $stmt-&gt;bindParam(1, $_POST['email'], PDO::PARAM_INT); $stmt-&gt;execute(); $rows = $stmt-&gt;fetchAll(PDO::FETCH_ASSOC); if( ! $rows) { # No email found - moving on - If all set - let's register :) $email = $_POST['email']; $password = $_POST['password']; $hash_cost_log2 = 8; $hash_portable = FALSE; require("includes/PasswordHash.php"); # Hash password lib $hasher = new PasswordHash($hash_cost_log2, $hash_portable); # Hashing the password $hash = $hasher-&gt;HashPassword($password); if (strlen($hash) &lt; 20) fail('Failed to hash new password'); unset($hasher); $STH =$dbh-&gt;prepare("INSERT INTO members (email,password) VALUES (:email, :password)"); # Registering new user $STH-&gt;bindParam(':email', $email); $STH-&gt;bindParam(':password', $hash); $STH-&gt;execute(); echo "Account created successfully."; header('Refresh: 2; url=index.php'); # Redirect to index.php in 2 seconds } else { # email found - closing database - register fail $dbh=null; echo('Email already exists.'); } $dbh=null; # Closing database after register } } } else { echo"Invalid Token."; # If user access the page without POST } } </code></pre> <p>I want to know if I can make it more secure. Before I made the script, I checked other scripts to see how they work, and what security measures they use.</p> <p>What the script does: </p> <ul> <li><p>Check if request comes from POST </p></li> <li><p>Check if all fields ware filled ( It's being checked by JS as well, but that can be "cracked" )</p></li> <li><p>Check if email already exists</p></li> <li><p>Hash password</p></li> <li><p>Finally register</p></li> </ul> <p>In addition, I saw that other scripts are far smaller than mine. Does that happen because they use frameworks?</p> <p><strong>Update</strong> : OOP implemented ( <a href="http://pastebin.com/0DKVxrDK" rel="nofollow">http://pastebin.com/0DKVxrDK</a> ) for check email and register </p>
[ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-02-02T11:30:47.267", "Id": "68560", "Score": "0", "body": "What is the `PasswordHash` class you're using? It seems you're not salting the hash thus making it irresponsibly weak, but I can't know for sure without having more information." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-02-02T11:33:22.850", "Id": "68561", "Score": "0", "body": "I'm using PasswordHash from Openwall , http://www.openwall.com/phpass/ ( I followed http://www.openwall.com/articles/PHP-Users-Passwords )" } ]
[ { "body": "<p>Here are my recommendation,</p>\n\n<ul>\n<li>you could make sure users password have a minimum length. 8 alphanumeric characters is ideal If a users password is 1 char, it can easily be broken no matter how good the salt is</li>\n<li><p>move you database connection and setup into a different class: In the database class, create two separate functions. </p>\n\n<ul>\n<li>Does Email Exist and Return boolean </li>\n<li>Create users returning a new user object</li>\n</ul></li>\n</ul>\n\n<p>Database Connection Class uses the singleton design pattern. We only need 1 connection object to exist when our application is running. The singleton pattern is a design pattern that restricts the instantiation of a class to one object. </p>\n\n<pre><code>class Database\n{\n private static $dbh = null;\n //TODO you should move this inside config file\n private $host = 'mysql:host=localhost;dbname=test';\n private $pwd = '';\n private $user = '';\n\n\n public function __construct()\n {\n try\n {\n Database::$dbh = new PDO($this-&gt;host, $this-&gt;user, $this-&gt;pwd);\n Database::$dbh-&gt;setAttribute( PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION );\n }\n catch (PDOException $e)\n {\n echo \"Connection Error: \" . $e-&gt;getMessage();\n }\n }\n\n public static function getInstance()\n {\n if (Database::$dbh === null) {\n new Database();\n }\n return Database::$dbh;\n }\n}\n\n//all of our sql code should be in a centralized location for easy updating\nclass SQLPreparedQuery {\n public static $EMAIL_EXIST = \"SELECT email FROM user WHERE email=? LIMIT 1\";\n public static $USER_ADD = \"INSET INTO user (username, email, first, last) VALUES(?,?,?,?)\";\n}\n</code></pre>\n\n<hr>\n\n<pre><code>require_once './Database.php';\nrequire_once './SQLPreparedQuery.php';\nclass UserModel {\n public function doesEmailExist($email) {\n $doesEmailExist = false;\n try {\n $dbh = Database::getInstance();\n\n $stmt = $dbh-&gt;prepare(SQLPreparedQuery::$EMAIL_EXIST);\n $stmt-&gt;bindParam(1, $email, PDO::PARAM_INT);\n $stmt-&gt;execute();\n $result = $stmt-&gt;fetchAll(PDO::FETCH_ASSOC);\n $doesEmailExist = (empty($result) ? false : true);\n }\n catch (PDOException $ex) { \n echo \"An Error occured!\" . $ex;\n }\n return $doesEmailExist;\n }\n\n//USAGE\n//This will return true if it exist and false if it doesn't\n\n$userModel = new UserModel();\n$status = $userModel-&gt;doesEmailExist('james@example.com');\n</code></pre>\n\n<hr>\n\n<pre><code>CREATE TABLE `user` (\n `iduser` int(11) NOT NULL AUTO_INCREMENT,\n `first` varchar(45) DEFAULT NULL,\n `last` varchar(45) DEFAULT NULL,\n `email` varchar(45) NOT NULL,\n PRIMARY KEY (`iduser`),\n UNIQUE KEY `email_UNIQUE` (`email`)\n) ENGINE=InnoDB AUTO_INCREMENT=2 DEFAULT CHARSET=latin1$$\n\nINSERT INTO `test`.`user` (`first`, `last`, `email`) VALUES ('james', 'brown', 'james@example.com');\n</code></pre>\n\n<p>You should always add UNIQUE constraints to usernames and email address to ensure uniqueness in your database. </p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-02-02T13:03:28.427", "Id": "68571", "Score": "0", "body": "Password check was added and tested. Thank you. About the other 3 recommendations I'm a little lost.. but I'll try to apply them asap." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-02-02T13:21:22.983", "Id": "68572", "Score": "1", "body": "If you make your code modular (each function does one thing only/ DRY - Don't repeat your self), you can reuse that function later on. For example, your current implementation you check if the email exist and insert your new user inside the same RegisterN function. Why not break that code block up into two different function so you can later reuse. It makes it easier to make changes and update your code in the future." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-02-03T15:17:54.633", "Id": "68716", "Score": "0", "body": "Oke, since yesterday I was looking for a solution regarding to DRY, however I can't find the right path. I tried this but didn't work ( Don't blame me, still try to learn this new stuff ) http://pastebin.com/XRf5pV99" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-02-03T16:10:55.257", "Id": "68730", "Score": "1", "body": "@rgerculy OOP can be difficult. I will post an example once i get off." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-02-03T19:58:47.603", "Id": "68774", "Score": "0", "body": "I made some research and found this : http://stackoverflow.com/questions/3200155/php-class-database-interaction-using-pdo . Is that what I should use ? If so for me would be : http://pastebin.com/y892My4A .... ?" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-02-04T13:04:22.447", "Id": "69930", "Score": "0", "body": "One question , this safe to use on live project ? : catch (PDOException $ex) { \n echo \"An Error occured!\" . $ex;\n }" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-02-04T13:07:58.637", "Id": "69931", "Score": "0", "body": "@rgerculy no it is not good echo the error onto the page. You should create a logger class and log PDOException to file. That way if you are running into any issue you can view the log to troubleshoot." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-02-04T13:32:31.690", "Id": "69935", "Score": "0", "body": "Ok, will use file_put_contents log errors into text file. That should be enough." } ], "meta_data": { "CommentCount": "8", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-02-02T12:53:30.713", "Id": "40665", "ParentId": "40661", "Score": "6" } }, { "body": "<blockquote>\n <ul>\n <li>Hash password</li>\n </ul>\n</blockquote>\n\n<p>I would recommend reading my \"Protip\" about secure passwords: <a href=\"https://coderwall.com/p/nnyida\" rel=\"nofollow\">https://coderwall.com/p/nnyida</a> - I don't know the class you are using, but mine is just few lines of self-explaining code, so you know what you use.</p>\n\n<blockquote>\n <p>In addition, I saw that other scripts are far smaller than my. That happens because they use frameworks?</p>\n</blockquote>\n\n<p>Frameworks simply make your code easier to write, read and use. They will give your code some structure, and share some best-practices, so you are not reinventing wheel.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-02-04T12:44:46.990", "Id": "69929", "Score": "0", "body": "Your function you link to uses the function `crypt()` which uses an internal \"DSE based hashing algorithm\" [which should not be considered secure for password hashing](http://security.stackexchange.com/questions/5204/can-des-based-hashed-password-be-recovered-if-salt-is-known). [See this question for a better list of hashing functions which are aprropriate](http://security.stackexchange.com/questions/211/how-to-securely-hash-passwords)." } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-02-02T13:24:45.383", "Id": "40668", "ParentId": "40661", "Score": "3" } } ]
{ "AcceptedAnswerId": "40665", "CommentCount": "2", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-02-02T11:16:13.933", "Id": "40661", "Score": "6", "Tags": [ "php", "mysql", "security", "pdo" ], "Title": "Register script security and optimization" }
40661
<blockquote> <p>Write a function <code>strend(s, t)</code> which returns <code>1</code> if the string <code>t</code> occurs at the end of <code>s</code>, and <code>0</code> otherwise.</p> </blockquote> <p>Here is my solution:</p> <pre><code>unsigned int strend(char *source, char *pattern) { char *saver = pattern; while(*source) source++; while(*saver) saver++; while(saver &gt;= pattern) if(*saver-- != *source--) return 0; return 1; } </code></pre> <p>There are 2 <code>while</code> loops that will run until <code>source</code> and <code>saver</code> will point to the end of the string that they are representing. You will notice the presence of the variable <code>saver</code>, at the end of the second while loop this variable will have the value <code>pattern + X</code>, where <code>X</code> represent the number of charachters in the string <code>pattern</code>.</p> <p>By using the variable <code>saver</code> I know when to stop the third loop. When <code>saver</code> is less than <code>pattern</code> that means that every charachter in the string <code>pattern</code> was compared with the coresponding one in <code>source</code>. At each iteration of the loop I check if the current charachter that <code>saver</code> points to is equal to the coresponding charachter in <code>source</code>. </p> <p>Here is my second version:</p> <pre><code>unsigned int strend(char *source, char *pattern) { char *saver = pattern + strlen(pattern); source += strlen(source); while(saver &gt;= pattern) if(*source-- != *saver--) return 0; return 1; } </code></pre> <p>There is a dependency between my second implementation of <code>strend</code> and <code>strlen</code>. I, also, have some problems with the naming of the variable <code>saver</code>. What would be a more suggestive name for its purpose?</p> <p>The exercise can be found at page 121 in K&amp;R second edition.</p>
[ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-02-02T14:25:15.397", "Id": "68578", "Score": "2", "body": "The \"dependency\" on `strlen` in your second example is generally a good thing. Its reuse of existing functionality lets you focus on new problems, rather than ones that are already solved. (But it's good to know how to roll your own, too!)" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-02-02T17:48:04.260", "Id": "68603", "Score": "0", "body": "I propose changing `char*` to `const char*`" } ]
[ { "body": "<p>I guess you have the naming problem because the code use the variable for multiple purposes. First, it points to the end of the <code>pattern</code>, then it's used for the pointer of the current character under test. (See below.)</p>\n\n<p>In the first snippet there two identical while loops:</p>\n\n<pre><code>while(*source)\n source++;\n\nwhile(*saver)\n saver++;\n</code></pre>\n\n<p>It's a nice catch that you changed them to <code>strlen()</code>. If you don't want <code>#include &lt;string.h&gt;</code> you still could extract it to a function to remove some code duplication:</p>\n\n<pre><code>char *getLastChar(char *input) {\n while(*input)\n input++;\n return input;\n}\n</code></pre>\n\n<p>Here is a refactored version of the first snippet:</p>\n\n<pre><code>#define DIFFERENT 0\n#define EQUAL 1\n\nunsigned int strend1(char *source, char *pattern) {\n char *patternEnd = getLastChar(pattern);\n char *sourceEnd = getLastChar(source);\n\n char *currentPatternChar = patternEnd;\n char *currentSourceChar = sourceEnd;\n while (currentSourceChar &gt;= source &amp;&amp; currentPatternChar &gt;= pattern) {\n if (*currentSourceChar != *currentPatternChar) {\n return DIFFERENT;\n }\n\n currentPatternChar--;\n currentSourceChar--;\n }\n return EQUAL;\n}\n</code></pre>\n\n<p>Some things to note:</p>\n\n<ol>\n<li><p>I've added another check to the <code>while</code> loop: <code>currentSourceChar &gt;= source</code>. It handles those cases (fixes a bug) when the pattern is longer that the <code>source</code> string.</p></li>\n<li><p>I've used two constants for the return values instead of magic numbers. It helps readers and maintainers because it shows the intent of <code>0</code> and <code>1</code>.</p></li>\n<li><p>The <code>patternEnd</code> and <code>currentPatternChar</code> variables are basically the same (as well as their source pair) but I think it improves readability a little bit. First, you have a pointer to the last char (<code>patternEnd</code>), then another variables is used for iteration (<code>currentPatternChar</code>). (A good compiler will optimize it for you.)</p></li>\n</ol>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-02-02T14:04:33.523", "Id": "40670", "ParentId": "40664", "Score": "8" } }, { "body": "<p>I see no point in avoiding the use of Standard Library functions. Learning to\nuse them is part of becoming a proficient C programmer. Hence using <code>strlen</code>\nis good and reinventing <code>strcmp</code> or <code>memcmp</code>, as you have done, is bad. Making the return\nvalue unsigned is just extra typing/noise and achieves nothing. Here is a\nsimplified version:</p>\n\n<pre><code>int strend1(const char *str, const char *pattern)\n{\n size_t plen = strlen(pattern);\n size_t slen = strlen(str);\n return (plen &lt;= slen) \n &amp;&amp; !memcmp(pattern, str + slen - plen, plen) ? 1 : 0;\n}\n</code></pre>\n\n<p>Note that the parameters are <code>const</code>.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-02-03T11:51:39.873", "Id": "68699", "Score": "0", "body": "I'm practicing my terminology. Can strend be considered a wrapper for memcmp?" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-02-03T16:45:50.887", "Id": "68739", "Score": "1", "body": "A wrapper would modify the interface in some way, maybe providing a default parameter (eg the length for `memcmp`) or making the function work with different types. As such I'd expect the wrapper to be able 'naturally' (ie without it being contrived) to take a name derived from the wrapped function. I don't think that is really true of `strend` and `memcmp` - you might rename it `memcmp_end` but that does not really reflect what it does because no 'end' is defined, except in terms of string parameters, which `memcmp` does not take. So no, I don't consider it a wrapper." } ], "meta_data": { "CommentCount": "2", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-02-02T16:55:36.443", "Id": "40681", "ParentId": "40664", "Score": "10" } } ]
{ "AcceptedAnswerId": "40670", "CommentCount": "2", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-02-02T12:33:03.853", "Id": "40664", "Score": "10", "Tags": [ "c", "beginner", "strings", "pointers" ], "Title": "strend, function that checks the occurence of a pattern at the end of a string" }
40664
<blockquote> <p><strong><em>PYTHON 2.7-</em></strong></p> </blockquote> <p>I want to make my code OOP. I also want feedback from you on correctness, tidiness, design patterns and so on.</p> <p><a href="https://www.dropbox.com/sh/7s57lruhc9ykoz6/QqE1HxXJ08" rel="nofollow">Here's the download link</a>. It's not permanent but it's the best I have time for.</p> <p>I get this syntax error now, tried multiple things without progress.</p> <hr> <p>The code:</p> <pre><code>filesDict = {'', "backgroundMusicMenu": pygame.mixer.Sound('music/Who Likes To Party.ogg'), "foxSound": pygame.mixer.Sound('sounds/foxSound.wav'), "rabbitSound": pygame.mixer.Sound('sounds/rabbitSound.wav'), "buttonStartImage": pygame.image.load('textures/buttonStart.png'), "playerImage": pygame.image.load('textures/Fox.png'), "playerImageTwo": pygame.image.load('textures/Fox2.png'), "rabbitImage": pygame.image.load('textures/topic_rabbit.png'), "rabbitImageTwo": pygame.image.load('textures/topic_rabbit2.png'), "buttonEasyImage": pygame.image.load('textures/buttonEasy.png'), "buttonNormalImage": pygame.image.load('textures/buttonNormal.png'), "buttonHardImage": pygame.image.load('textures/buttonHard.png'), "background_image": pygame.image.load('textures/bg.jpg').convert()} </code></pre> <hr> <p>The error:</p> <pre><code> File "C:\Users\USER\My Programs\Python\Slutarbete2.2\mainPEP8d.py", line 10 7 "backgroundMusicMenu": pygame.mixer.sound( ^ SyntaxError: invalid syntax </code></pre> <hr> <pre><code># -*- coding: utf-8 -*- #Börjar med att importera alla moduler för att få spelkoden att funka här. #Importerar först alla tillgängliga moduler till pygame paketet. #Sedan så sätter jag en begränsad uppsättning av konstanter och funktioner #i global namespace av scriptet. Efter det importerar jag timern som är #essentiell i spel osv. import pygame import sys import random import math import os from pygame.locals import * from threading import Timer #Börjar sätta upp spel funktionerna och klockan. pygame.init() pygame.mixer.init() mainClock = pygame.time.Clock() def movementVariables(): global moveUp global moveDown global moveLeft global moveRight global levelOne for event in pygame.event.get(): if event.type == QUIT: pygame.quit() sys.exit() #Tangentbords variabler if event.type == KEYDOWN: #testkey if event.key == K_SPACE: levelOne = False if event.key == K_LEFT: moveRight = False moveLeft = True if event.key == K_RIGHT: moveRight = True moveLeft = False if event.key == K_UP: moveDown = False moveUp = True if event.key == K_DOWN: moveDown = True moveUp = False if event.type == KEYUP: if event.key == K_ESCAPE: pygame.quit() sys.exit() if event.key == K_LEFT: moveLeft = False if event.key == K_RIGHT: moveRight = False if event.key == K_UP: moveUp = False if event.key == K_DOWN: moveDown = False def movementMechanism(): if moveDown and player.bottom &lt; WINDOW_HEIGHT: player.top += MOVE_SPEED if moveUp and player.top &gt; 0: player.top -= MOVE_SPEED if moveLeft and player.left &gt; 0: player.left -= MOVE_SPEED if moveRight and player.right &lt; WINDOW_WIDTH: player.right += MOVE_SPEED windowSurface.blit(playerImage, player) #Ger resolutionen till spelfönstret samt ger namnet för spelet och fönstret. WINDOW_WIDTH = 640 WINDOW_HEIGHT = 400 windowSurface = pygame.display.set_mode((WINDOW_WIDTH, WINDOW_HEIGHT), 0) icon = pygame.image.load('textures/systemicon.png') pygame.display.set_icon(icon) pygame.display.set_caption('Catch the rabbits!') #Ger alla färger dess rgb koder, och vilken font och vinn texten. BLACK = (0, 0, 0) BLUE = (0, 0, 255) WHITE = (255, 255, 255) textFont = pygame.font.SysFont("impact", 60) textEnd = textFont.render("YOU WON!", True, (193, 0, 0)) #Spelarens och fiendernas data structurer. #Fiendernas storlek. #Laddar alla bitmap (.png) och ljud (.wav) filer till spelaren och fienderna #samt bakgrundsbilderna rabbitCounter = 0 NEW_RABBIT = 40 RABBIT_SIZE = 64 #"Who Likes To Party" Kevin MacLeod (incompetech.com) #"No Frills Salsa" Kevin MacLeod (incompetech.com) #Licensed under Creative Commons: By Attribution 3.0 #http://creativecommons.org/licenses/by/3.0/ filesDict = {'', "backgroundMusicMenu": pygame.mixer.Sound('music/Who Likes To Party.ogg'), "foxSound": pygame.mixer.Sound('sounds/foxSound.wav'), "rabbitSound": pygame.mixer.Sound('sounds/rabbitSound.wav'), "buttonStartImage": pygame.image.load('textures/buttonStart.png'), "playerImage": pygame.image.load('textures/Fox.png'), "playerImageTwo": pygame.image.load('textures/Fox2.png'), "rabbitImage": pygame.image.load('textures/topic_rabbit.png'), "rabbitImageTwo": pygame.image.load('textures/topic_rabbit2.png'), "buttonEasyImage": pygame.image.load('textures/buttonEasy.png'), "buttonNormalImage": pygame.image.load('textures/buttonNormal.png'), "buttonHardImage": pygame.image.load('textures/buttonHard.png'), "background_image": pygame.image.load('textures/bg.jpg').convert()} pygame.mixer.music.load('music/No Frills Salsa.ogg') player = pygame.Rect(420, 100, 40, 40) buttonStart = pygame.Rect(220, 150, 200, 90) buttonEasy = pygame.Rect(10, 150, 200, 90) buttonNormal = pygame.Rect(220, 150, 200, 90) buttonHard = pygame.Rect(430, 150, 200, 90) rabbits = [] for i in range(20): rabbits.append(pygame.Rect(random.randint(0, WINDOW_WIDTH - RABBIT_SIZE), random.randint (0, WINDOW_HEIGHT - RABBIT_SIZE), RABBIT_SIZE, RABBIT_SIZE)) #Rörlighetsvariablerna moveLeft = False moveRight = False moveUp = False moveDown = False #Rörlighetshastigheten MOVE_SPEED = 0 #Start Meny menuMusic = False endit = False while not endit: filesDict["backgroundMusicMenu"].play(-1) windowSurface.fill(WHITE) for event in pygame.event.get(): if (event.type == pygame.MOUSEBUTTONDOWN and event.button == 1): mouse_coordinates = pygame.mouse.get_pos() if buttonStart.collidepoint(mouse_coordinates): end_it = True windowSurface.blit(filesDict["buttonStartImage"], buttonStart) pygame.display.flip() #Svårighetsgrader enditlevel = False while not enditlevels: windowSurface.fill(WHITE) for event in pygame.event.get(): if (event.type == pygame.MOUSEBUTTONDOWN and event.button == 1): mouse_coordinates = pygame.mouse.get_pos() if buttonEasy.collidepoint(mouse_coordinates): MOVE_SPEED = 9 NEW_RABBIT = 40 end_it_levels = True if (event.type == pygame.MOUSEBUTTONDOWN and event.button == 1): mouse_coordinates = pygame.mouse.get_pos() if buttonNormal.collidepoint(mouse_coordinates): MOVE_SPEED = 7 NEW_RABBIT = 30 end_it_levels = True if (event.type == pygame.MOUSEBUTTONDOWN and event.button == 1): mouse_coordinates = pygame.mouse.get_pos() if buttonHard.collidepoint(mouse_coordinates): MOVE_SPEED = 5 NEW_RABBIT = 20 end_it_levels = True windowSurface.blit(get_image('textures/buttonEasy.png'), buttonEasy) windowSurface.blit(get_image('textures/buttonNormal.png'), buttonNormal) windowSurface.blit(get_image('textures/buttonHard.png'), buttonHard) pygame.display.flip() #Spel loopen backgroundMusicMenu.stop() levelOne = True if levelOne is True: rabbitSound.play() foxSound.play() pygame.mixer.music.play() #Checkar ifall quit movementVariables() #Gör en loop som gör att det spawnar mera och mera kaniner rabbitCounter += 1 if rabbitCounter &gt;= NEW_RABBIT: rabbitCounter = 0 rabbits.append(pygame.Rect(random.randint(0, WINDOW_WIDTH - RABBIT_SIZE), random.randint (0, WINDOW_HEIGHT - RABBIT_SIZE), RABBIT_SIZE, RABBIT_SIZE)) #Snöbakgrunden sätts på bakgrunden när man väljt svårighetsgrad windowSurface.blit(get_image('textures/bg.jpg'), [0, 0]) #Rörlighets mekanism så att spelaren inte går utanför skärmen samt inte går #för fort. movementMechanism() #Kaninernas texture blits for rabbit in rabbits: windowSurface.blit(get_image('rabbitImage.png'), rabbit) #Random movement för kaninerna stepMovementNegativeRabbit = random.randrange(0, -3, -2) stepMovementPositiveRabbit = random.randrange(0, 3, 2) rabbitMovement = ['', ((stepMovementNegativeRabbit), 0), ((stepMovementPositiveRabbit), 0), (0, (stepMovementNegativeRabbit)), (0, (stepMovementPositiveRabbit))] for rabbit in rabbits: rabbit.move_ip(*random.choice(rabbitMovement)) #Checkning ifall spelaren rört en kanin for rabbit in rabbits[:]: if player.colliderect(rabbit): windowSurface.blit(get_image('textures/topic_rabbit2.png'), rabbit) windowSurface.blit(get_image('textures/Fox.png'), player) def explosionRabbit(): for rabbit in rabbits: if player.colliderect(rabbit) and (moveLeft is False and moveRight is False and moveUp is False and moveDown is False): rabbits.remove(rabbit) if player.colliderect(rabbit) and (moveLeft is False and moveRight is False and moveUp is False and moveDown is False): #timer inställningar tRabbit = Timer(0.1, explosionRabbit) tRabbit.start() if len(rabbits) == 0: rabbitCounter = 0 windowSurface.blit(get_image(textLevelOne.png), (100, 104)) levelOne = False windowSurface.fill((0, 0, 0)) #Ritar fönstret pygame.display.update() mainClock.tick(60) </code></pre>
[ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-02-02T13:41:13.357", "Id": "68573", "Score": "0", "body": "Hello and Welcome! Please add a short description to your question about what kind of game this is, it will be much easier to understand your code and will make it easier to give a better review that way. / Hej och välkommen, lägg gärna till en beskrivning om vad din kod gör. Det blir lättare att förstå din kod och ge en bra review då. (Lucky for you I'm Swedish!)" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-02-02T13:42:18.973", "Id": "68574", "Score": "0", "body": "Information to provide can be: Is it a platform game? Is it a strategy game? What does the bunny have to do with anything?" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-02-02T14:03:21.633", "Id": "68576", "Score": "1", "body": "It's a simple game with the player being a blitted fox 40x40 pixels which when hovering over the rabbits that are also 40x40 blits dissappear and respawn over a period of some amount of time and when all the rabbits have been \"eaten\" it will stop the game essentially. The rabbits also spawn randomly on screen each time. First the start game screen comes up, then the difficulty screen and then the actual game where the things i said previous to this sentance exist. (And yes I'm swedish too!, but sticking to English.)" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-02-02T14:14:51.273", "Id": "68577", "Score": "0", "body": "Guess you can say it's a 2d game?" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-02-02T16:40:11.687", "Id": "68598", "Score": "1", "body": "Could you make the assets available for download, so that we can try playing the game?" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-02-02T19:49:20.787", "Id": "68615", "Score": "0", "body": "@GarethRees Added the download link for the assets" } ]
[ { "body": "<p><em>I haven't played your game and I haven't understood much of the code but here are a few comments.</em></p>\n<p>A few things are not quite pythonic. You can make your code go through some automatic checks with <a href=\"http://pep8online.com/\" rel=\"nofollow noreferrer\">pep8online</a> (<a href=\"http://www.python.org/dev/peps/pep-0008/\" rel=\"nofollow noreferrer\">PEP8</a> is the Style Guide for Python Code) and pylint. Among the things that could be applied to your code :</p>\n<blockquote>\n<p>Don't compare boolean values to True or False using ==</p>\n<p>For sequences, (strings, lists, tuples), use the fact that empty sequences are false.</p>\n</blockquote>\n<hr />\n<p>I have troubles understanding the point of <code>startSoundLevelOne</code> in :</p>\n<pre><code>startSoundLevelOne = True\nwhile levelOne == True:\n while startSoundLevelOne == True:\n rabbitSound.play()\n foxSound.play()\n pygame.mixer.music.play()\n startSoundLevelOne = False\n</code></pre>\n<p>Same thing applies to <code>menuMusic</code>.</p>\n<hr />\n<p>You should try to avoid <a href=\"http://en.wikipedia.org/wiki/Magic_number_%28programming%29\" rel=\"nofollow noreferrer\">magic numbers</a>.</p>\n<hr />\n<p>Your code does not take into account that when something is moving <code>up</code>, it is not also moving <code>down</code> (and the same thing for left/right). It might make things easier for you to track if instead of <code>move&lt;Right/Left/Up/Down&gt;</code>, you had a variable for vertical move <code>moveVert</code> taking values <code>-1</code>, <code>0</code> and <code>1</code> (or anything else you fancy) for up/none/down and the same kind of thing for horizontal move. This could also be a single variable altogether.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-02-03T17:31:22.607", "Id": "68754", "Score": "0", "body": "Well I reformatted all the coding to PEP-8 styling. Removed all the useless `styleSoundLevelOne` and `menuMusic`. Haven't tried to make the magic numbers less used in the coding because I'm not really sure how to do that. Gonna try to change the movement variables." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-02-03T17:35:28.640", "Id": "68755", "Score": "0", "body": "Can you recommend some good programming text editors? I'm using IDLE for using the Python Shell and Notepad++ for editing the code. Maybe some editor with built-in debugging perhaps?" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-02-04T08:38:10.433", "Id": "69903", "Score": "0", "body": "Nothing special to recommend. Notepad++ is good enough as far as I can tell." } ], "meta_data": { "CommentCount": "3", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-02-03T10:41:33.437", "Id": "40728", "ParentId": "40666", "Score": "2" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "6", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-02-02T13:11:04.497", "Id": "40666", "Score": "3", "Tags": [ "python", "object-oriented", "python-2.x", "pygame" ], "Title": "Making this Pygame code object-oriented" }
40666
<p>Can anyone please review the following <code>.htaccess</code> file and let me if it is correctly put together?</p> <p>What I think it does:</p> <ul> <li>So it direct to a custom 404 page</li> <li>Remove the extensions from the end of the urls (example <code>.php</code>)</li> <li>Remove <code>/index</code></li> <li>I don't really understand what the final rule does, can anyone please explain it if could?</li> </ul> <pre><code>DirectoryIndex index.html index.php ErrorDocument 404 /404 RewriteEngine On RewriteBase / # Remove enter code here.php; use THE_REQUEST to prevent infinite loops # By puting the L-flag here, the request gets redirected immediately RewriteCond %{THE_REQUEST} ^GET\ (.*)\.php\ HTTP RewriteRule (.*)\.php$ $1 [R=301,L] # Remove /index # By puting the L-flag here, the request gets redirected immediately # The trailing slash is removed in a next request, so be efficient and dont put it on there at all RewriteRule (.*)/index$ $1 [R=301,L] # Remove slash if not directory # By puting the L-flag here, the request gets redirected immediately RewriteCond %{REQUEST_FILENAME} !-d RewriteCond %{REQUEST_URI} /$ RewriteRule (.*)/ $1 [R=301,L] # Add .php to access file, but don't redirect # On some hosts RewriteCond %{REQUEST_FILENAME}.php -f will be true, even if # no such file exists. Be safe and add an extra condition # There is no point in escaping a dot in a string RewriteCond %{REQUEST_FILENAME}.php -f RewriteCond %{REQUEST_URI} !(/|\.php)$ RewriteRule (.*) $1.php [L] </code></pre>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-07-22T05:02:51.150", "Id": "435754", "Score": "0", "body": "in order for your custom error page to be directed properly you need to put a URL after it and remove the duplicate 404 ie ErrorDocument 404 `https://www.youdomain.something/errorpage.php`" } ]
[ { "body": "<p>This is basically a canonicalizing URL prettifier that redirects clients to a shorter URL.</p>\n\n<p>The <code>RewriteCond</code> operating on <code>%{THE_REQUEST}</code> is weird, since it works directly at the HTTP protocol level. I understand that you want to avoid redirecting POSTs, since a redirect would convert POSTs into GETs, and such breakage would be an unacceptable consequence for having nicer-looking URLs. However, it would be better to test <code>%{REQUEST_METHOD}</code> instead.</p>\n\n<p>In the worst case, you could end up redirecting the client three times:</p>\n\n<ol>\n<li><code>GET /path/to/directory/index.php/</code>:</li>\n<li><code>GET /path/to/something/index.php</code></li>\n<li><code>GET /path/to/something/index</code></li>\n<li><code>GET /path/to/something</code></li>\n</ol>\n\n<p>By combining the first two rules, you could eliminate the third request.</p>\n\n<pre><code># Strip off /index.php or /index or .php\nRewriteCond %{REQUEST_METHOD} =GET\nRewriteRule (.*)(/index\\.php|/index|\\.php)$ $1 [R=301,L]\n</code></pre>\n\n<p>In the trailing slash cleanup, you have a superfluous <code>RewriteCond</code>:</p>\n\n<pre><code># Remove slash if not directory \nRewriteCond %{REQUEST_FILENAME} !-d \nRewriteRule (.*)/$ $1 [R=301,L]\n</code></pre>\n\n<p>I would tweak your last rule a bit. Do the string analysis check before the filesystem check. Use <code>$0</code> instead of <code>%{REQUEST_URI}</code> and <code>$1</code>.</p>\n\n<pre><code>RewriteCond $0 !(/|\\.php)$\nRewriteCond %{REQUEST_FILENAME}.php -f \nRewriteRule .* $0.php\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-02-02T23:07:45.853", "Id": "68646", "Score": "0", "body": "Can you please show me how it would look like all put together? I have tried to put them together but I am confused - I really don't know what I am doing" } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-02-02T17:26:33.420", "Id": "40684", "ParentId": "40669", "Score": "6" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "1", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-02-02T13:33:45.637", "Id": "40669", "Score": "4", "Tags": [ ".htaccess" ], "Title": "Review URL-prettifying .htaccess file" }
40669
<p><a href="http://projecteuler.net/problem=7" rel="nofollow">Project Euler problem 7</a> says:</p> <blockquote> <p>By listing the first six prime numbers: 2, 3, 5, 7, 11, and 13, we can see that the 6th prime is 13. What is the 10001st prime number?</p> </blockquote> <p>I believe that my code is working, but very very slowly. I guess the increment divisor can be changed, but I'm not sure how.</p> <pre><code>using System; using System.Collections.Generic; using System.Diagnostics; using System.Linq; using System.Text; using System.Threading.Tasks; namespace p7 { // By listing the first six prime numbers: 2, 3, 5, 7, 11, and 13, we can see that the 6th prime is 13. // What is the 10001st prime number? class Program { // - SET 'divisor' TO 13 // - WHILE( divisor &lt;= ceil[ sqrt(number) ] ) // - IF number%divisor == 0 &amp;&amp; number != divisor THEN // - Not prime / divisible by 'divisor' // - ELSE IF ceil[ sqrt(number) ] == divisor THEN // - PRIME!!! // - ELSE increment divisor by 2 static void Main(string[] args) { Stopwatch sw = Stopwatch.StartNew(); int count = 6; // we already know 6 primes: 2,3,5,7,11,13 long x = 14; // so can look for a prime after number 13 while (count &lt; 10001) { if (IsPrime(x, 13)) { count++; x++; } } Console.WriteLine(x); Console.WriteLine("Time used (float): {0} ms", sw.Elapsed.TotalMilliseconds); Console.WriteLine("Time used (rounded): {0} ms", sw.ElapsedMilliseconds); Console.ReadKey(); } static bool IsPrime(Int64 p, Int64 divisor) { Int64 sqrt = (Int64)Math.Ceiling(Math.Sqrt(p)); while (divisor &lt;= sqrt) { if (p % divisor == 0) return false; else if (sqrt == divisor) return true; divisor += 2; } return true; } } } </code></pre>
[]
[ { "body": "<p>Your prime testing code is wrong. For example, it would consider <code>14</code> to be a prime! You cannot take a shortcut by only testing divisors > 13. Instead:</p>\n\n<pre><code>static bool IsPrime(Int64 p)\n{\n if (p % 2 == 0) return false;\n Int64 max = (Int64) Math.Ceiling(Math.Sqrt(p));\n for (Int64 divisor = 3; divisor &lt; max; divisor += 2)\n {\n if (p % divisor == 0) return false;\n }\n return true;\n}\n</code></pre>\n\n<p>Points to note:</p>\n\n<ul>\n<li>I use a <code>for</code> loop instead of <code>while</code>, as this better expresses what I'm doing.</li>\n<li>I only go up to <code>divisor &lt; ceiling(sqrt(p))</code>, which saves one iteration. Not significant, but it's less redundant this way.</li>\n<li>While I do test for <code>p % 2 == 0</code>, this branch will never be taken because we will later modify our prime number search loop to only search odd numbers. I leave that test here for correctness.</li>\n<li>Note also that smaller numbers are more likely to be divisors than larger numbers. It's therefore advantageous to test them early.</li>\n</ul>\n\n<p>Your prime search loop looks at <em>each number</em> in from 13 onward. However with the exception of <code>2</code>, only odd numbers can be primes. We can therefore halve the search time by incrementing in steps of two.</p>\n\n<pre><code>int count = 6;\nint targetCount = 10001;\nlong x;\nfor (x = 13 + 2; count &lt; targetCount; x += 2)\n{\n if (IsPrime(x)) count++;\n}\n</code></pre>\n\n<p>But wait! If we are finding all prime numbers from 13 onward we can use those to speed up our prime test by only testing appropriate prime factors! We can do this by creating a table of primes:</p>\n\n<pre><code>long[] primes = new long[targetCount];\nprimes[0] = 2;\nprimes[1] = 3;\nprimes[2] = 5;\nprimes[3] = 7;\nprimes[4] = 11;\nprimes[5] = 13;\n\nint counter = 6;\nfor (long x = primes[counter - 1] + 2; counter &lt; targetCount; x += 2)\n{\n if (IsPrime(x, primes)) primes[counter++] = x;\n}\n// the result is in primes[targetCount - 1]\n</code></pre>\n\n<p>where <code>IsPrime</code> has been changed to</p>\n\n<pre><code>static bool IsPrime(Int64 p, long[] primes)\n{\n Int64 max = (Int64) Math.Ceiling(Math.Sqrt(p));\n foreach (long divisor in primes)\n {\n if (divisor &gt; max) break;\n if (p % divisor == 0) return false;\n }\n return true;\n}\n</code></pre>\n\n<p>And hey presto, is this fast! I get <code>104743</code> as an answer in a matter of milliseconds.</p>\n\n<p>How did I make this code so fast?</p>\n\n<ol>\n<li>Write correct code without taking bad shortcuts.</li>\n<li>Think about what I need and what I have anyway.</li>\n<li>Then, figure out an elegant way to connect those two states. Here, my experience with <em>dynamic programming</em> reminded me to build a table of primes.</li>\n</ol>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-02-02T15:35:36.483", "Id": "68580", "Score": "0", "body": "104033 is prime, but approximately number 9300." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-02-02T15:36:36.497", "Id": "68581", "Score": "0", "body": "@ChrisW Yes, It should output `104743`. I think some prime test may be terminating too early." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-02-02T15:36:46.660", "Id": "68582", "Score": "1", "body": "(divisor >= max) looks wrong: use (divisor > max)" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-02-02T15:47:35.643", "Id": "68584", "Score": "0", "body": "You're fortunate that there are more primes that squares, so that `if (divisor > max) break;` will probably trigger: otherwise your foreach loop would waste time iterating through an array of mostly zero values. I would usually use a growable `List<long>` instead of a fixed-length `long[]` array." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-02-02T15:57:53.840", "Id": "68587", "Score": "1", "body": "@ChrisW I mostly disagree with using a `List`: an array should have less overhead, and we precisely know the final size needed. You are right that the `divisor > max` test is dubious but it is safe as long as the first four primes are already stored inside the array." } ], "meta_data": { "CommentCount": "5", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-02-02T15:30:33.327", "Id": "40675", "ParentId": "40673", "Score": "11" } }, { "body": "<p>For such a small prime, you can use a simple sieve of Eratosthenes, which runs in a negligible amount of time for your purposes. The <a href=\"http://en.wikipedia.org/wiki/Sieve_of_Eratosthenes\">Wikipedia page</a> has a pseudocode implementation. I recommend reading the algorithm description, but not the code, and attempt to correctly implement it for yourself, which shouldn't be too hard.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-02-02T20:51:04.847", "Id": "68620", "Score": "0", "body": "A problem with implementing Eratosthenes' sieve is knowing how big to make it, in order to contain the 10001th prime." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-02-02T23:15:26.713", "Id": "68647", "Score": "4", "body": "@ChrisW: Unless you happen to know that the nth prime number is [always](http://en.wikipedia.org/wiki/Prime_number_theorem#Approximations_for_the_nth_prime_number) smaller than n(ln n + ln ln n) (which in this case tells you it's at most 114319 — not too much wasted effort given the above answer!)" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-12-17T06:03:04.173", "Id": "134289", "Score": "0", "body": "This is exactly how i solved this one too" } ], "meta_data": { "CommentCount": "3", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-02-02T17:12:48.370", "Id": "40682", "ParentId": "40673", "Score": "11" } } ]
{ "AcceptedAnswerId": "40675", "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-02-02T14:59:00.957", "Id": "40673", "Score": "6", "Tags": [ "c#", "algorithm", "programming-challenge", "primes" ], "Title": "What is the 10001st prime number?" }
40673
<p>Is there a better way I can code this? It's old code and I'm not sure makes sense today. JSLint gives me a lot of errors too. I don't have experience with JavaScript and I would like to optimize this snippet. </p> <p>Any suggestion? Maybe I can achieve better code with JQuery? </p> <pre><code>&lt;script type="text/javascript"&gt; // &lt;![CDATA[ var jump_page = '{LA_JUMP_PAGE}:', var on_page = '{ON_PAGE}'; var per_page = '{PER_PAGE}'; var base_url = '{A_BASE_URL}'; var style_cookie = 'phpBBstyle'; var style_cookie_settings = '{A_COOKIE_SETTINGS}'; var onload_functions = new Array(); var onunload_functions = new Array(); /** * Find a member */ function find_username(url) { popup(url, 760, 570, '_usersearch'); return false; } /** * New function for handling multiple calls to window.onload and window.unload by pentapenguin */ window.onload = function() { for (var i = 0; i &lt; onload_functions.length; i++) { eval(onload_functions[i]); } }; window.onunload = function() { for (var i = 0; i &lt; onunload_functions.length; i++) { eval(onunload_functions[i]); } }; // ]]&gt; &lt;/script&gt; </code></pre> <p>This is how an handler is called for example:</p> <pre><code>&lt;script type="text/javascript"&gt; // &lt;![CDATA[ /** * Change language */ function change_language(lang_iso) { document.forms['register'].change_lang.value = lang_iso; document.forms['register'].submit.click(); } &lt;!-- IF CAPTCHA_TEMPLATE and S_CONFIRM_REFRESH --&gt; onload_functions.push('apply_onkeypress_event()'); &lt;!-- ENDIF --&gt; // ]]&gt; &lt;/script&gt; </code></pre>
[ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-02-02T16:09:44.347", "Id": "68592", "Score": "1", "body": "@syb0rg A JSLint \"error\" does not necessarily mean that the code is broken." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-02-02T16:25:47.027", "Id": "68597", "Score": "0", "body": "@200_success It failed initially at 2%, so I assumed it was broken code. Close vote retracted." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-02-03T10:16:28.897", "Id": "68687", "Score": "0", "body": "jslint probably doesn't like the comma at the end of the first line, should be a semicolon, or you should setup all the vars with a single var statement and commas in between declarations." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-02-03T10:17:50.997", "Id": "68689", "Score": "0", "body": "Also, Egyptian brackets are considered better practice in javascript." } ]
[ { "body": "<p>The <a href=\"http://www.w3.org/TR/DOM-Level-2-Events/events.html#Events-eventgroupings-htmlevents\" rel=\"nofollow noreferrer\">modern way</a> to attach <code>onLoad</code> and <code>onUnload</code> handlers is to use <code>window.addEventListener('load', onloadFunction)</code> and <code>window.addEventListener('unload', onunloadFunction)</code>. Unlike <code>window.onload</code>, you can attach multiple handlers, saving you the work of writing your own support for multiple handlers.</p>\n\n<p>Unfortunately, Internet Explorer only added support for <code>addEventListener()</code> in IE 9. Therefore, you'll probably need a <a href=\"https://stackoverflow.com/a/6927800/1157100\">shim</a>. That would be a common shim that supports a standard interface, rather than your own hack, so I would still consider it an improvement.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-02-02T17:12:39.383", "Id": "68601", "Score": "0", "body": "Thanks 200_success, How can I merge my code above with your solution? I dont want to use shim for now." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-02-03T02:25:12.830", "Id": "68656", "Score": "1", "body": "@user2513846 that depends on why you don't want to use a shim?" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-02-04T14:31:55.603", "Id": "69945", "Score": "0", "body": "I just dont want to add extra scripts I gues and keep it as simple as possible." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-02-04T15:22:34.293", "Id": "69960", "Score": "0", "body": "The shim that I linked to is just one function, and it replaces two of your functions. If anything, it makes your code simpler!" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-02-05T15:24:06.767", "Id": "70212", "Score": "0", "body": "well sounds good then lol . sorry I just dont have enough knoledge in JS. What code should I use to replace my code above?" } ], "meta_data": { "CommentCount": "5", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-02-02T16:19:32.623", "Id": "40679", "ParentId": "40674", "Score": "8" } }, { "body": "<p>JSLint is probably complaining about your use of <code>eval()</code>, and I would be wary too. <a href=\"https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/eval#Don.27t_use_eval.21\" rel=\"nofollow\">Don't use <code>eval</code> needlessly.</a> You didn't show your onload/onunload handlers, but you should write them as functions rather than strings to be evaluated.</p>\n\n<p>Bad:</p>\n\n<pre><code>window.onload = function() {\n for (var i = 0; i &lt; onload_functions.length; i++) {\n eval(onload_functions[i]);\n }\n};\n\nonload_functions.push('apply_onkeypress_event()');\n</code></pre>\n\n<p>Better:</p>\n\n<pre><code>window.onload = function() {\n for (var i = 0; i &lt; onload_functions.length; i++) {\n onload_functions[i]();\n }\n};\n\nonload_functions.push(apply_onkeypress_event);\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-02-02T19:17:11.300", "Id": "68610", "Score": "0", "body": "this would be an example of the handler:\n <script type=\"text/javascript\">\n // <![CDATA[\n /**\n * Change language\n */\n function change_language(lang_iso)\n {\n document.forms['register'].change_lang.value = lang_iso;\n document.forms['register'].submit.click();\n }\n\n <!-- IF CAPTCHA_TEMPLATE and S_CONFIRM_REFRESH -->\n onload_functions.push('apply_onkeypress_event()');\n <!-- ENDIF -->\n\n // ]]>\n </script>" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-02-02T19:18:42.683", "Id": "68611", "Score": "0", "body": "sorry not sure why it's not coded" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-02-03T07:09:10.407", "Id": "68679", "Score": "0", "body": "Because it is in a comment, edit the question instead!" } ], "meta_data": { "CommentCount": "3", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-02-02T16:33:39.480", "Id": "40680", "ParentId": "40674", "Score": "6" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "4", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-02-02T15:13:52.493", "Id": "40674", "Score": "7", "Tags": [ "javascript", "optimization" ], "Title": "Var scope on the same line" }
40674
<p>As a first step to attempting the <a href="https://codereview.meta.stackexchange.com/questions/1471/weekend-challenge-reboot">Weekend Challenger Reboot</a>, I decided to first implement a regular 'tic-tac-toe' game and then expand it later to be 'ultimate tic-tac-toe'.</p> <p>Below is the code for the tic-tac-toe board. It's fully functional and unit tested, but I'm not too happy about the <code>getWinner()</code> method. This method's purpose is to check to see if there is any winner in the game, and to return the identity of said winner if they exist.</p> <p>The reasons I don't like it are:</p> <ol> <li>The method is very long, which immediately sets off warning flags in my mind.</li> <li>It makes use of a 'flag' type variable that tracks if we've found a winner yet. I don't like flag variables because they're really something that I got in the habit of doing back when I did procedural programming, and therefore probably shouldn't exist in an object-oriented design.</li> <li>There's an awful lot of <code>continue</code> and <code>break</code> statements which seem to indicate poorly-designed loops.</li> <li>I'm pretty sure that if there is no winner, this method is O<sub>(n<sup>2</sup>)</sub>.</li> </ol> <p>This is the code for the <code>getWinner()</code> method:</p> <pre><code>public class Board { private final Player[][] fields; ... public Player getWinner() { Player winner = null; boolean isWon = false; // check columns (same x) for (int x = 0; x &lt; fields.length; x++) { Player value = fields[x][0]; if (value == null) { continue; } for (int y = 1; y &lt; fields[x].length; y++) { Player current = fields[x][y]; if (current == null || !current.equals(value)) { break; } if (y == fields[x].length -1) { isWon = true; winner = value; } } if(isWon) { break; } } if (! isWon) { // check rows (same y) for (int y = 0; y &lt; fields[0].length; y++) { Player value = fields[0][y]; if (value == null) { continue; } for (int x = 1; x &lt; fields.length; x++) { Player current = fields[x][y]; if (current == null || !current.equals(value)) { break; } if (x == fields.length -1) { isWon = true; winner = value; } } if(isWon) { break; } } } if (! isWon) { // check diagonal (bottom left to top right Player value = fields[0][0]; if (value != null) { for (int i = 1; i &lt; fields.length; i++) { if (fields[i][i] != value) { break; } if (i == fields.length -1) { isWon = true; winner = value; } } } } if (! isWon) { // check anti-diagonal (top left to bottom right) int length = fields.length; Player value = fields[0][length-1]; if (value != null) { for (int i = 1; i &lt; length; i++) { if (fields[i][length-i-1] != value) { break; } if (i == length -1) { isWon = true; winner = value; } } } } return winner; } ... } </code></pre> <p>The rest of the code is mostly irrelevant. Something important to be aware of is that the board will always be a perfect square -- eg. 3x3 or 4x4 or 5x5. The <code>Player</code> is a simple enum:</p> <pre><code>public enum Player { X("X"), O("O"); private String str; private Player(String str) { this.str = str; } @Override public String toString() { return str; } } </code></pre>
[ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-02-02T16:09:31.987", "Id": "68591", "Score": "1", "body": "Nice that you support multiple sizes, I'm loving it!" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-02-02T18:55:45.270", "Id": "68608", "Score": "0", "body": "I don't think that you need to worry about the complexity of your algorithms if they are just going to run on small cases. There isn't much difference between `O(n)` and `O(n^2)` when `n <= 10`." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-02-02T19:44:20.347", "Id": "68613", "Score": "1", "body": "@sweeneyrod -- While the Board constraints have a minimum size of 3, there's no maximum. So in theory we could have a massize 100x100 board. (Not sure how fun the game would be, but there ya go.)" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-02-02T20:41:28.287", "Id": "68619", "Score": "0", "body": "That's what I meant - you are unlikely to be playing on a large board." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-02-02T20:55:24.803", "Id": "68623", "Score": "2", "body": "@RoddyoftheFrozenPeas It becomes horrifyingly more difficult to win on a 100x100 board, I can tell you that!" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-02-02T21:21:28.160", "Id": "68627", "Score": "2", "body": "@RoddyoftheFrozenPeas a 100,100,? game is in the same category as a 3,3,3 - both of which are known as [m,n,k-games](http://en.wikipedia.org/wiki/M,n,k-game)." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-05-06T22:43:28.947", "Id": "86248", "Score": "1", "body": "@MichaelT I have to thank you for that comment, that's what made me make my [flexible Tic-Tac-Toe implementation](http://codereview.stackexchange.com/questions/45086/recursive-and-flexible-approach-to-tic-tac-toe)" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-05-26T16:02:54.933", "Id": "427311", "Score": "0", "body": "@SimonForsberg: *more* difficult to win? 3x3 Tic Tac Toe is a draw with best play from both sides, so it's already impossible with a simple brute-force AI opponent (that recurses down all possible moves to find forced wins and avoid forced losses). I wrote a tic-tac-toe game that worked that way for a first-year undergrad assignment. (One of the few program I remember writing for undergrad; I don't think best-play was a requirement for the assignment, though.) Anyway, brute force best play is not computationally feasible for bigger boards." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-05-26T17:53:18.927", "Id": "427325", "Score": "1", "body": "@PeterCordes Yes, I am aware that 3x3 Tic Tac Toe is quite trivial to solve with a brute force approach. Tic Tac Toe is a so-called m,n,k-game, and all m,n,k games are either a win or a draw for the first player if both players play optimally. However, if you would try to get 100 pieces in a row on a 100x100 board your opponent has much more time to realize what you are doing and block you, which is why I said my previous comment. It would be interesting to analyze if it's easier or harder to win when just playing randomly on boards of different sizes." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-05-26T18:12:55.603", "Id": "427329", "Score": "0", "body": "@SimonForsberg: yeah, or another interesting question would be how easy it is to force a win with best play (or some heuristics like trying to build lines) from one side vs. looking only 1 to 4 moves ahead (and choosing randomly from moves that don't lead to losses) for the other side. With a larger board you could imagine building up multiple threats more subtly. OTOH it's probably really easy to play for a draw by getting at least 1 mark onto every row + column. (e.g. play along diagonals other than the central diagonal.) Squares scale with n^2 but wins scale with n." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-05-26T18:52:20.250", "Id": "427339", "Score": "0", "body": "@PeterCordes My point exactly with my first comment, that is why it becomes harder to win on bigger boards." } ]
[ { "body": "<p>It's <strong>method extraction</strong> time!</p>\n\n<p>But before that, I have to comment on your <code>Player</code> enum:</p>\n\n<ul>\n<li><code>str</code> is a bad name, <code>name</code> would be better.</li>\n<li>Speaking of name, all enums have a <code>name()</code> method by default. You don't need your <code>str</code> variable, <code>return name();</code> instead.</li>\n<li>Speaking of <code>return name();</code>, that's exactly what the default implementation of <code>toString()</code> already does for enums. Absolutely no need to override it.</li>\n</ul>\n\n<p>And therefore, we've reduced your <code>Player</code> enum to:</p>\n\n<pre><code>public enum Player {\n X, O;\n}\n</code></pre>\n\n<p>Ain't it lovely with enums? :)</p>\n\n<p>Now, back to your <code>getWinner()</code> method:</p>\n\n<p>You have a whole bunch of duplicated code there indeed. It would be handy if you could get a <code>Collection</code> of some kind (or an array), add some elements to it and check: Is there a winner given by these <code>Player</code> values?</p>\n\n<p>This is just one version of doing it, it's not the optimal one but it should get you started. This code will add a bunch of <code>Player</code> objects to a list and then we check if those objects match to find if there's a winner.</p>\n\n<pre><code>List&lt;Player&gt; players = new ArrayList&lt;&gt;();\nfor (int x = 0; x &lt; fields.length; x++) {\n for (int y = 0; y &lt; fields[x].length; y++) {\n players.add(fields[x][y]);\n }\n Player winner = findWinner(players);\n if (winner != null) \n return winner;\n}\n\nPlayer findWinner(List&lt;Player&gt; players) {\n Player win = players.get(0);\n for (Player pl : players) {\n // it's fine that we loop through index 0 again,\n // even though we've already processed it. \n // It's a fast operation and it won't change the result\n if (pl != win)\n return null;\n }\n return pl;\n}\n</code></pre>\n\n<p>Please note that there are even more improvements possible for the <code>getWinner</code> method, I don't want to reveal <strong>all</strong> my secrets for now though ;) And also, this is just one way of doing it, which will reduce your code duplication a bit at least. There are other possible approaches here as well.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-02-02T16:00:35.747", "Id": "40678", "ParentId": "40676", "Score": "14" } }, { "body": "<p>Hints on how to reduce your cyclomatic complexity:</p>\n\n<ol>\n<li><code>if (isWon) { break; }</code> at the end of the outer loop is the same as <code>&amp;&amp; !isWon</code> inside the guard of the loop.</li>\n<li><code>if (value == null) { continue; }</code> before the inner loop is the same as <code>&amp;&amp; (value != null)</code> in the guard of the loop.</li>\n</ol>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-02-03T02:27:40.067", "Id": "68657", "Score": "1", "body": "Your first suggestion does not actually reduce the complexity... it just moves it from two `if` statements with a complexity of 1 each, to a single `if` statement with a complexity of 2 (because there are two ways pass through the condition with short-circuit logic). Your second statement has the same flaw" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-02-03T02:36:10.020", "Id": "68659", "Score": "0", "body": "It at least makes it easier to read :) But from my non-expert reading of [wikipedia](http://en.wikipedia.org/wiki/Cyclomatic_complexity), the complexity seems to be reduced; using the (value == null) example, in the original code there are four paths (neither block is entered, (value == null) block is entered, loop is entered, or both are entered), but with my suggestion, there are only two paths (the loop is entered, or the loop is not entered). But even if the cyclomatic complexity is not reduced, I think the readability is enhanced." } ], "meta_data": { "CommentCount": "2", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-02-02T21:00:13.267", "Id": "40691", "ParentId": "40676", "Score": "4" } }, { "body": "<p>Consider using better data structures (objects). Your constructor will be more complex, but all the complexity will be there, not in the algorithm. </p>\n\n<p>Here's a beginning of a design. Lots of details to work out, maybe not worth the effort if you're almost done and just cleaning things up.</p>\n\n<p>Build a Set whose elements are Sets whose contents are the elements of the winning rows, columns and long diagonals (only 2n+2 of these for an nxn board). </p>\n\n<p>To test for a win, iterate on that Set and see whether any of its elements (potential wins) has just one element (different from EMPTY). (You'll want to allow three values in cells: X, O and EMPTY).</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-02-02T21:27:39.903", "Id": "40692", "ParentId": "40676", "Score": "7" } }, { "body": "<p>This is a classic case of where early-return makes sense....</p>\n\n<p>There are some schools of thought that suggest early return is a bad thing, but consider changing all your <code>if (isWon) {break;}</code> statements to be <code>return winner;</code>.</p>\n\n<p>We can then get rid of the <code>isWon</code> and the <code>winner</code> variables entirely, as well as the then the unnecessary checks to gate each logic loop. Your method would look like:</p>\n\n<pre><code>public Player getWinner() {\n\n // check columns (same x)\n for (int x = 0; x &lt; fields.length; x++) {\n Player value = fields[x][0];\n\n if (value == null) {\n continue;\n }\n for (int y = 1; y &lt; fields[x].length; y++) {\n Player current = fields[x][y];\n if (current == null || !current.equals(value)) {\n break;\n }\n if (y == fields[x].length -1) {\n // Early Return.... We have a WINNER!\n return value;\n }\n }\n }\n // there was no winner in this check\n // no need for isWon check or variable... we can't get here unless there is\n // no winner yet....\n for (int y = 0; y &lt; fields[0].length; y++) {\n Player value = fields[0][y];\n if (value == null) {\n continue;\n }\n for (int x = 1; x &lt; fields.length; x++) {\n Player current = fields[x][y];\n if (current == null || !current.equals(value)) {\n break;\n }\n if (x == fields.length -1) {\n // We have a winner!\n return value;\n }\n }\n }\n\n }\n // and so on....\n ....\n\n // there is no winner.\n return null;\n}\n</code></pre>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-02-03T02:02:01.463", "Id": "40710", "ParentId": "40676", "Score": "7" } }, { "body": "<p>I would make a function that takes the play field and a 'kernel' to run over each cell.</p>\n\n<p>Here's some code for you:</p>\n\n<pre><code>void Main()\n{\n int[][] verticalWin = { new int[] {0,1}, new int[] {0,2} };\n int[][] horizontalWin = { new int[] {1,0}, new int[] {2,0} };\n\n int[][] playfield = { new int[] { 20,10,10 },\n new int[] { 20,10,20 },\n new int[] { 10,10,10}};\n\n var winner = GetWinner(playfield, verticalWin);\n Console.WriteLine(winner);\n\n winner = GetWinner(playfield, horizontalWin);\n Console.WriteLine(winner);\n}\n\n// Define other methods and classes here\n\nint GetWinner(int[][] playfield, int[][] kernel){\n for (int x=0; x&lt;playfield[0].Length; x++){\n for (int y=0; y&lt;playfield[0].Length; y++){\n var player = playfield[x][y];\n int k=0;\n while (k&lt;kernel[0].Length \n &amp;&amp; playfield.Length &gt; (kernel[k][0] + x)\n &amp;&amp; playfield.Length &gt; (kernel[k][1] + y)\n &amp;&amp; player == playfield[x+kernel[k][0]][y +kernel[k][1]]\n ) {\n k++;\n }\n if (k==kernel.Length){\n return player;\n }\n }\n }\n return 0;\n}\n</code></pre>\n\n<p>Obviously I've made some simplifications, but it should just be a matter of changing the type of the player variable, and create your kernels for win conditions. The length of the kernel (index 0,0 aka current cell is implied) will determine how many in a row is needed.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-02-03T14:11:23.103", "Id": "68714", "Score": "0", "body": "if you need optimization because of a large playfield, you can simply check early that the current x,y index is within the bounds of the most extreme attempted index of the kernel (if you follow my outlined convention, the most extreme case will always be the last coordinate of the kernel).\nLet me know if you like to give this a go and I can help to identify what needs to change. Good luck on your project!" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-02-04T18:56:10.173", "Id": "70005", "Score": "0", "body": "This code doesn't look very readable to me. It is quite hard to follow how it works. Your while condition is very big and your `k` and `kernel` variables could also be named better..." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-02-04T21:06:10.633", "Id": "70038", "Score": "1", "body": "What readable code *is* is highly subjective - that said I agree that it should be commented. The while check can be extracted to a method if wanted. Readable code is good, though working code also have some value. Don't forget that I also offered to help with the final implementation, as opposed to withholding some magic sauce. ;)" } ], "meta_data": { "CommentCount": "3", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-02-03T14:06:38.223", "Id": "40740", "ParentId": "40676", "Score": "3" } }, { "body": "<p>Well, if the players are considered to be 0 and 1, and the game matrix to be frame, then given a player and a matrix, I can easily get a winner without having to check all possibilities!</p>\n\n<pre><code>int winner(int player, int pos) {\n int v = 0, h = 0, s0 = 0, s1 = 0;\n int col = pos % 3;\n int row = pos / 3;\n for (int i = 0; i &lt; 3; i++) {\n if (frame[i][col] == player) {\n v++;// vertical\n }\n if (frame[row][i] == player) {\n h++;// horizontal\n }\n }\n if (pos % 4 == 0) {\n for (int i = 0; i &lt; 3; i++) {\n if (frame[i][i] == player) {\n s0++;// backward slash like slant\n }\n }\n }\n if ((pos + 2) % 4 == 0) {\n for (int i = 0; i &lt; 3; i++) {\n if (frame[2 - i][i] == player) {\n s1++;// forward slant\n }\n }\n }\n\n if (v == 3 || h == 3 || s0 == 3 || s1 == 3) {\n return player;\n }\n return -1;\n}\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-07-31T15:44:11.557", "Id": "105346", "Score": "0", "body": "What is `pos`? Also, it looks like this method only works for a 3x3 tic-tac-toe implementation -- could it be expanded for boards of arbitrary size?" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-07-31T15:45:03.043", "Id": "105347", "Score": "0", "body": "Welcome to Code Review! Could you be a bit more descriptive in your answer ? It's not the best way to dump code in an answer for reviewing code. You could explain how you achieve this algorithm." } ], "meta_data": { "CommentCount": "2", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-07-31T15:31:15.127", "Id": "58662", "ParentId": "40676", "Score": "1" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "11", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-02-02T15:36:02.860", "Id": "40676", "Score": "17", "Tags": [ "java", "algorithm", "game", "community-challenge" ], "Title": "Tic-tac-toe 'get winner' algorithm" }
40676
<p>This finds its origin in the following reflection. In their book from 1995, the so-called gang of four (GoF) described the state pattern. What they were actually telling us in their description, is that any object oriented language that implements dynamic polymorphism has an embedded finite state machine (FSM) engine. C++ is such a language, and the example code in the book is written in that language. Why then, do we have to use large frameworks, libraries and tools in order to implement state machines in C++?</p> <p>I asked myself that question recently for a C++ project where I have the freedom to choose my tools. Since I have long been a supporter of the KISS-principle (keep it simple stupid), my first intention was to just apply the pattern as described in the book.</p> <p>Basically, the state pattern tells us that the FSM should have a pointer member to a virtual state class, always pointing to a specialization of that class, that represents the current concrete state. It then delegates the events it receives to the state pointer, like this (quoting the book):</p> <pre><code>TCPConnection::ActiveOpen () { _state-&gt;ActiveOpen(this); } </code></pre> <p>where TCPConnection is the FSM and ActiveOpen() is an event.</p> <p>However, the event handlers look like this:</p> <pre><code>void TCPClosed::ActiveOpen (TCPConnection* t) { // send SYN, receive SYN, ACK, etc. ChangeState(t, TCPEstablished::Instance()); } </code></pre> <p>where TCPClosed and TCPEstablished are concrete states.</p> <p>Not so neat. I started to wonder if templates couldn't help me to parametrize the target state in <code>ChangeState()</code>. If the state had both a reference to the FSM and the ability to transform itself as a result of a transition, surely I would get a much simpler and cleaner syntax.</p> <h2>Example FSM</h2> <p>Let's assume that I have the following silly state machine to implement (made with ArgoUML, if anybody is curious).</p> <p><img src="https://i.stack.imgur.com/Wij86.png" alt="silly state machine"></p> <p><a href="https://i.stack.imgur.com/Wij86.png" rel="nofollow noreferrer">Silly state machine</a></p> <p>It is silly, but it contains the features that, in my experience, are necessary in a state machine implementation:</p> <ol> <li>Entry, exit and transition actions.</li> <li>Guards (conditional transitions).</li> <li>Event parameters (a free event signature would be nice).</li> <li>Composite states (states that contain sub-states).</li> <li>Orthogonal states (also called and-states, which are semantically equivalent to separate simultaneous FSMs, but it is sometimes necessary to run them in the same class). E.g. LevelState and DirectionState are orthogonal states in the example.</li> <li>Access to FSM members (variables or functions).</li> </ol> <p>The UML has a lot more than that, but I am not convinced that the rest is strictly necessary in the FSM implementation. After all, we have the rest of the programming language for that...</p> <h2>What I want is all you get</h2> <p>The kind of event handler I want is this:</p> <pre><code>void Machine::Red::paint(Machine::Color color) { if (color == BLUE) change&lt;Blue&gt;(); } </code></pre> <p>where Machine is my FSM, Red the state, paint() the event, color an event parameter and Blue the target state for the transition. But you knew all that, it's in the diagram.</p> <p>As the code below testifies (public domain, use it as you wish, but don't blame me - compiles with g++ 4.6, C++11 switched on), I have managed to implement the state machine depicted above, in such a simple syntax, with the help of a 40-line state template that I have called <code>GenericState</code> (genericstate.h, the rest is the state machine code):</p> <ol> <li>Entry and exit actions can be defined at any state level. Transition actions are programmed as regular instructions in the event handlers before the actual state transitions. There is, however, a difference with the UML in the order of execution: transition actions, exit actions (old state), entry actions (new state). The UML has exit, transition actions, entry. But mine is the same order as Miro Samek's model (<a href="http://www.state-machine.com/" rel="nofollow noreferrer">http://www.state-machine.com/</a>) - i.e. it is not uncommon and there is nothing wrong with it as long as it is consistent.</li> <li>Guards are regular "if" or "switch" statements in event handlers.</li> <li>Event parameters are regular event handler arguments. The event handler signature is free (and clutter-free).</li> <li>Composite states are implemented by applying the same model recursively. In the sate machine above, the state "Left" contains a <code>ColorState</code> virtual state that can be "Red" or "Blue". However, when going from "Left" to "Right", the exit action from the current color will not be executed (contrary to the UML semantics, but not a practical problem I believe).</li> <li>Orthogonal states are managed by letting the FSM have several virtual state members instead of just one (<code>LevelState</code> and <code>DirectionState</code> in <code>Machine</code> in the example).</li> <li>Access to the FSM members is given to all states through the FSM reference "m" (e.g. <code>m.changedColor()</code>).</li> </ol> <h2>Questions:</h2> <ul> <li>Any known similar implementation?</li> <li>Any obvious bug or hazard?</li> <li>Any obvious potential for improvement (performance, type safety in template use, etc.)?</li> <li>It looks like I have unintentionally applied the so-called "curiously recurring template pattern". Do you recognize any other pattern in my implementation? Any other pattern related comment?</li> <li>My implementation has a low RAM footprint (only one state instantiated at a time per FSM instance and orthogonal region) but a certain runtime cost: every state transition will incur the creation of a state instance and the destruction of another one on the heap. Comments about that?</li> <li>A reader of an earlier version commented off-line that my states were not flyweight as described by GoF. This basically means that my state instances cannot be shared between several state machine instances. I agree. I would not get such a simple syntax otherwise. I think the trade off was worth it. Comments?</li> </ul> <p><strong>genericstate.h</strong></p> <pre><code>#ifndef GENERICSTATE_H #define GENERICSTATE_H #include &lt;memory&gt; template &lt;class State&gt; using StateRef = std::unique_ptr&lt;State&gt;; template &lt;typename StateMachine, class State&gt; class GenericState { public: explicit GenericState(StateMachine &amp;m, StateRef&lt;State&gt; &amp;state) : m(m), state(state) {} template &lt;class ConcreteState&gt; static void init(StateMachine &amp;m, StateRef&lt;State&gt; &amp;state) { state = StateRef&lt;State&gt;(new ConcreteState(m, state)); state-&gt;entry(); } protected: template &lt;class ConcreteState&gt; void change() { exit(); init&lt;ConcreteState&gt;(m, state); } void reenter() { exit(); entry(); } private: virtual void entry() {} virtual void exit() {} protected: StateMachine &amp;m; private: StateRef&lt;State&gt; &amp;state; }; #endif // GENERICSTATE_H </code></pre> <p><strong>machine.h</strong></p> <pre><code>#ifndef MACHINE_H #define MACHINE_H #include &lt;string&gt; #include &lt;iostream&gt; #include "genericstate.h" class Machine { public: Machine() {} ~Machine() {} void start(); public: enum Color { BLUE, RED }; public: void liftUp() { levelState-&gt;liftUp(); } void bringDown() { levelState-&gt;bringDown(); } void paint(Color color) { directionState-&gt;paint(color); } void turnRight() { directionState-&gt;turnRight(); } void turnLeft() { directionState-&gt;turnLeft(); } private: static void print(const std::string &amp;str) { std::cout &lt;&lt; str &lt;&lt; std::endl; } static void unhandledEvent() { print("unhandled event"); } void changedColor() { print("changed color"); } private: struct LevelState : public GenericState&lt;Machine, LevelState&gt; { using GenericState::GenericState; virtual void liftUp() { unhandledEvent(); } virtual void bringDown() { unhandledEvent(); } }; StateRef&lt;LevelState&gt; levelState; struct High : public LevelState { using LevelState::LevelState; void entry() { print("entering High"); } void liftUp() { print("already High"); } void bringDown() { change&lt;Low&gt;(); } void exit() { print("leaving High"); } }; struct Low : public LevelState { using LevelState::LevelState; void entry() { print("entering Low"); } void liftUp() { change&lt;High&gt;(); } void bringDown() { print("already Low"); } void exit() { print("leaving Low"); } }; private: struct ColorState : public GenericState&lt;Machine, ColorState&gt; { using GenericState::GenericState; virtual void paint(Color color) { (void)color; unhandledEvent(); } }; struct Red : public ColorState { using ColorState::ColorState; void entry() { m.changedColor(); } void paint(Color color); }; struct Blue : public ColorState { using ColorState::ColorState; void entry() { m.changedColor(); } void paint(Color color); }; private: struct DirectionState : public GenericState&lt;Machine, DirectionState&gt; { using GenericState::GenericState; virtual void paint(Color color) { (void)color; unhandledEvent(); } virtual void turnRight() { unhandledEvent(); } virtual void turnLeft() { unhandledEvent(); } }; StateRef&lt;DirectionState&gt; directionState; struct Left : public DirectionState { using DirectionState::DirectionState; void entry() { ColorState::init&lt;Red&gt;(m, colorState); } void paint(Color color) { colorState-&gt;paint(color); } void turnRight() { change&lt;Right&gt;(); } private: StateRef&lt;ColorState&gt; colorState; }; struct Right : public DirectionState { using DirectionState::DirectionState; void turnLeft() { change&lt;Left&gt;(); } }; }; #endif // MACHINE_H </code></pre> <p><strong>machine.cpp</strong></p> <pre><code>#include "machine.h" void Machine::start() { LevelState::init&lt;High&gt;(*this, levelState); DirectionState::init&lt;Left&gt;(*this, directionState); } void Machine::Red::paint(Machine::Color color) { if (color == BLUE) change&lt;Blue&gt;(); else ColorState::paint(color); } void Machine::Blue::paint(Machine::Color color) { if (color == RED) change&lt;Red&gt;(); else ColorState::paint(color); } </code></pre> <p><strong>main.cpp</strong></p> <pre><code>#include "machine.h" int main() { Machine m; m.start(); m.bringDown(); m.bringDown(); m.liftUp(); m.liftUp(); m.turnRight(); m.paint(Machine::BLUE); m.turnLeft(); m.paint(Machine::RED); m.paint(Machine::BLUE); return 0; } </code></pre> <h2>Output</h2> <blockquote> <pre class="lang-none prettyprint-override"><code>entering High changed color leaving High entering Low already Low leaving Low entering High already High unhandled event changed color unhandled event changed color </code></pre> </blockquote>
[ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-02-04T16:05:17.010", "Id": "69973", "Score": "0", "body": "Here is a TM in C++: http://stackoverflow.com/a/275295/14065" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-02-04T19:32:54.420", "Id": "70012", "Score": "0", "body": "@LokiAstari: I certainly have much more to learn about C++ templates and the whole discussion seems really interesting. Perfect bedtime reading, although it may keep me awake far too late :-)" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2015-08-21T16:14:32.513", "Id": "185791", "Score": "0", "body": "Have a look at \"Machine Objects\" here: http://ehiti.de/machine_objects It's a template library based on the approach you have outlined: state pattern and C++ template programming." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2015-10-17T09:09:50.380", "Id": "198004", "Score": "0", "body": "As an exercise, this [state machine](https://github.com/stateforge/StateBuilder/tree/master/StateBuilderCpp/examples/stdcpp/Silly) has been added as an example to my state machine tools." } ]
[ { "body": "<p>I don't have much to say.</p>\n<p>Your implementation is similar to the GoF's (<a href=\"https://web.archive.org/web/20151002171119/http://codewrangler.home.comcast.net/%7Ecodewrangler/tech_info/patterns_code.html#State\" rel=\"nofollow noreferrer\">posted here</a>) except that your machine instance is passed by reference to the states' constructors, instead of being passed-in to the states' state-transition methods.</p>\n<ul>\n<li>Advantage: cleaner syntax of the state-transition method</li>\n<li>Disadvantage: state instances can't be flyweights</li>\n</ul>\n<p>I wonder whether the following would allow a similarly-clean syntax but allow states to be flyweights:</p>\n<pre><code>class LevelState {\npublic:\n virtual LevelState* liftUp() = 0;\n virtual LevelState* bringDown() = 0;\n};\n\nclass HighLevelState : public LevelState {\npublic:\n LevelState* liftUp() { print(&quot;already High&quot;); return this; }\n LevelState* bringDown() { print(&quot;leaving High&quot;); return LowLevelState::enter(); }\n static LevelState* enter() { print(&quot;entering High&quot;); return &amp;singleton; }\nprivate:\n static HighLevelState singleton;\n};\n\nclass Machine\n{\npublic:\n Machine() { levelState = LowLevelState::enter(); }\n ~Machine() {}\n void liftUp() { levelState = levelState-&gt;liftUp(); }\n void bringDown() { levelState = levelState-&gt;bringDown(); }\n\nprivate:\n LevelState* levelState;\n};\n</code></pre>\n<p>This has some of the same advantages as your scheme (clean state methods) but also allows singleton/flyweight states.</p>\n<p>Heap operations can be relatively expensive; and I imagine that some state machines (<a href=\"http://www.goldparser.org/doc/templates/tag-dfa-table.htm\" rel=\"nofollow noreferrer\">for example, the tokenizer of a parser</a>) might want to be as fast as possible.</p>\n<p>IMO a benefit of your scheme is when the state instances should carry state-specific data. For example, perhaps the TCPEstablished state has <a href=\"http://en.wikipedia.org/wiki/Transmission_Control_Protocol#TCP_segment_structure\" rel=\"nofollow noreferrer\">associated data</a> which needs to be stored somewhere. If the state is a flyweight then that data must be stored in the machine; but maybe the machine has many states, each with state-specific data, and it's not appropriate for the machine to contain data for the states which it's not in at the moment: in that case you may want state-specific data for the machine in the state instance =&gt; state is not a flyweight.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-02-11T11:40:43.703", "Id": "71088", "Score": "0", "body": "However, it looks to me that what makes my solution non-flyweight is the reference to the FSM and state reference in the state. Making singletons of concrete states won't help that. In fact, it will in practice make my FSM a singleton, which does not fulfill my need." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-02-11T11:46:07.697", "Id": "71090", "Score": "0", "body": "Yes, your solution is incompatible with flyweight states, unless you machine is also a singleton. BTW I noticed that (in your example use case) you hardly use the `m` member of your `GenericState`. GenericState is mostly only using `StateRef<State> &state` i.e. states contain a reference to the `unique_ptr` in which they're contained, so that they can change themselves." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-02-11T11:52:30.810", "Id": "71092", "Score": "0", "body": "True about m. It's not supposed to be used in GenericState. It's supposed to be used in concrete states (and is in my example). That why it's protected and not private." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-02-11T14:10:13.287", "Id": "71099", "Score": "0", "body": "I have added a section in the text of my question about flyweight and runtime cost." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-02-11T14:22:40.123", "Id": "71100", "Score": "0", "body": "@nilo The main time at which you're referring to `m` in a leaf state seems to be in the `void entry() { ColorState::init<Red>(m, colorState); }` method. Could you eliminate that by having a single 'composite' `DirectionAndColorState` whose leaf states are `Right`, `LeftBlue`, and `LeftRed`, perhaps with `Left` as an abstract superclass of `LeftBlue`, and `LeftRed`?" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-02-11T14:38:28.333", "Id": "71101", "Score": "0", "body": "What I was referring to was Red::entry() { m.changedColor(); }. The point is that the states shall be able to access the state machine members in a seamless manner. Like t->ProcessOctet(o) in the GoF's example. Even if I use it lightly in my example, it plays a central role in the way I want to apply the pattern." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-02-11T14:52:19.747", "Id": "71106", "Score": "0", "body": "When it comes to flattening the composite states, I do not want to do that in the general case. Sometimes, the best way to describe a state machine is by using composite states. In that case, I want to be able to express them in a natural way in my code." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-02-11T14:57:54.213", "Id": "71107", "Score": "0", "body": "I have also thought about the alternative design where the composite state is a parent class of its sub-states. But that would force the children to forward the events they don't care about to their parent, which is the opposite of the semantics I am using at the top level. Not very consistent, in other words. This is why I have chosen this solution instead." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-02-11T15:08:59.783", "Id": "71108", "Score": "1", "body": "@nilo I don't think leaf states need to 'forward events they don't care about' to their superclass. If they don't care about an event then they simply don't override the corresponding virtual function, so that virtual function is only defined/handled in the superclass." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-02-11T15:22:18.817", "Id": "71110", "Score": "0", "body": "Correct about not overriding parent state behavior. I knew I had a good argument against that design, but I picked the wrong argument :-) My argument I think was the ability to define orthogonal states lower down in the hierarchy. Left should be able to have simultaneously a TasteState region (Sweet, Sour, etc.) and a ColorState region (Red and Blue). I think applying the model recursively is the best way to achieve that." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-02-11T16:19:48.993", "Id": "71122", "Score": "0", "body": "I have removed the section about flyweight and runtime cost in the main question, since I now realize that there is a trivial solution to runtime cost, if I am ready to have one state instance per concrete state in the state machine. I will post it as an answer to my question later on." } ], "meta_data": { "CommentCount": "11", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2014-02-11T00:12:37.200", "Id": "41369", "ParentId": "40686", "Score": "9" } } ]
{ "AcceptedAnswerId": "41369", "CommentCount": "4", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-02-02T19:10:45.347", "Id": "40686", "Score": "15", "Tags": [ "c++", "c++11", "state", "state-machine" ], "Title": "State pattern + C++ template" }
40686
<p>I am very new to PHP and I kind of sort of want to create the pages like I would in ASP.NET; it's just the way I am wired. I have been inserting the header/menu using a PHP Include and here is what the code looks like for just the first page.</p> <p>Am I doing this properly, or is there a better way?</p> <p><strong>index.php</strong></p> <pre><code>&lt;!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"&gt; &lt;html xmlns="http://www.w3.org/1999/xhtml"&gt; &lt;head&gt; &lt;meta http-equiv="Content-Type" content="text/html; charset=utf-8" /&gt; &lt;title&gt;New Jerusalem&lt;/title&gt; &lt;link rel="stylesheet" type="text/css" href="Main.css"/&gt; &lt;/head&gt; &lt;body&gt; &lt;div id="wrapper"&gt; &lt;div id="header"&gt; &lt;?php include ('Menu.php') ?&gt; &lt;/div&gt; &lt;div id="content"&gt; &lt;h1 class="PageTitle" &gt;Sturgis Hellfighters&lt;/h1&gt; &lt;div class="indexright" width="50%"&gt; &lt;h3 class="smallheader"&gt;Scripture Corner&lt;/h3&gt; &lt;p&gt;&lt;img src="images/Romans5-8.jpg" width="475" alt="Romans 5:8" /&gt;&lt;/p&gt; &lt;p&gt;&lt;/p&gt; &lt;/div&gt; &lt;div class="indexleft" width="50%"&gt; &lt;p&gt;&lt;img src="images/BridalFallsSpearfishCanyon.jpg" width="475" height="720" alt="Bridal Falls Spearfish Canyon" /&gt; &lt;/p&gt; &lt;/div&gt; &lt;/div&gt; &lt;/div&gt; &lt;/body&gt; &lt;/html&gt; </code></pre> <hr> <p><strong>Menu.php</strong></p> <pre><code>&lt;img src="images/SiteHeader.jpg" width="1000" height="150" alt="HellFighters New Jerusalem" id="siteheader"/&gt; &lt;ul id="HomeMenu"&gt; &lt;li class="TopLevel"&gt;&lt;a href="index.php"&gt;Home&lt;/a&gt;&lt;/li&gt; &lt;li class="TopLevel"&gt;&lt;a href="#"&gt;News&lt;/a&gt; &lt;ul&gt; &lt;li class="SecondLevel"&gt;&lt;a href="#"&gt;Sturgis Current Events&lt;/a&gt;&lt;/li&gt; &lt;li class="SecondLevel"&gt;&lt;a href="#"&gt;Rapid City Events&lt;/a&gt;&lt;/li&gt; &lt;li class="SecondLevel"&gt;&lt;a href="#"&gt;Pierre Events&lt;/a&gt;&lt;/li&gt; &lt;li class="SecondLevel"&gt;&lt;a href="#"&gt;Other Events&lt;/a&gt;&lt;/li&gt; &lt;/ul&gt; &lt;/li&gt; &lt;li class="TopLevel"&gt;&lt;a href="#"&gt;Photos&lt;/a&gt; &lt;ul&gt; &lt;li class="SecondLevel"&gt;&lt;a href="christmasatpineridge.php"&gt;Christmas On Pine Ridge&lt;/a&gt;&lt;/li&gt; &lt;li class="SecondLevel"&gt;&lt;a href="XmasMission.php"&gt;Christmas At the Mission&lt;/a&gt;&lt;/li&gt; &lt;li class="SecondLevel"&gt;&lt;a href="OpenHouse.php"&gt;Open House&lt;/a&gt;&lt;/li&gt; &lt;li class="SecondLevel"&gt;&lt;a href="Nationals.php"&gt;Nationals&lt;/a&gt; &lt;/ul&gt; &lt;/li&gt; &lt;li class="TopLevel"&gt;&lt;a href="#"&gt;Events&lt;/a&gt; &lt;ul&gt; &lt;!-- --&gt; &lt;li class="SecondLevel"&gt;&lt;a href="#"&gt;A Pine Ridge Christmas&lt;/a&gt; &lt;li class="SecondLevel"&gt;&lt;a href="#"&gt;A Sturgis HellFighter Christmas&lt;/a&gt; &lt;li class="SecondLevel"&gt;&lt;a href="#"&gt;Sturgis Motorcycle Rally&lt;/a&gt;&lt;/li&gt; &lt;li class="SecondLevel"&gt;&lt;a href="#"&gt;Random City Swap Meet&lt;/a&gt;&lt;/li&gt; &lt;li class="SecondLevel"&gt;&lt;a href="#"&gt;Cool Event&lt;/a&gt;&lt;/li&gt; &lt;/ul&gt; &lt;/li&gt; &lt;li class="TopLevel"&gt;&lt;a href="#"&gt;Contact Info&lt;/a&gt; &lt;ul&gt; &lt;li class="SecondLevel"&gt;&lt;a href="#"&gt;President&lt;/a&gt;&lt;/li&gt; &lt;li class="SecondLevel"&gt;&lt;a href="#"&gt;Vice-President&lt;/a&gt;&lt;/li&gt; &lt;li class="SecondLevel"&gt;&lt;a href="#"&gt;Preacher Man&lt;/a&gt;&lt;/li&gt; &lt;/ul&gt; &lt;/li&gt; &lt;/ul&gt; </code></pre> <hr> <p>I would like to use HTML5 if possible, so if your review brings up HTML5 that is cool with me too.</p> <hr> <p>If you would like to see the front page, <a href="http://sturgishellfighters.hartwebpages.com">click here</a>.</p> <p><strong>This page will be changing as I am currently working on it.</strong></p>
[ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-02-02T20:51:33.903", "Id": "68621", "Score": "0", "body": "I was surprised to see that you had a working example, `<?php include ('Menu.php') ?>` I would think would generate a fatal error with the semicolon." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-02-02T20:54:22.780", "Id": "68622", "Score": "0", "body": "@Pickett what do you mean? because I didn't put a semicolon at the end? I was following some examples. they could have been old examples..." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-02-02T20:57:06.327", "Id": "68624", "Score": "2", "body": "Sorry, my bad. Your syntax [is OK](http://www.php.net/manual/en/language.basic-syntax.instruction-separation.php), however I would still end each statement with a semicolon." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-02-02T20:57:56.700", "Id": "68625", "Score": "0", "body": "@Pickett I agree, I like Semicolons." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-02-03T13:10:46.130", "Id": "68712", "Score": "1", "body": "Pedantic note/tip: if `menu.php` doesn't contain any PHP, then change its extension to what it really is: `html`. The php extension means your sever is passing the file to the PHP parser first, which doesn't do anything but take up more resources & slowing you down. the PHP extension is only required for files that contain code" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-02-03T13:37:04.720", "Id": "68713", "Score": "0", "body": "Thank you. I thought if it was going to be called by a php file it had to be a php file." } ]
[ { "body": "<p>Going to some HTML5 stuff straight away.</p>\n\n<ol>\n<li><p>Replace your doctype with the HTML5 doctype. This is necessary for the next few steps</p>\n\n<pre><code>&lt;!DOCTYPE html&gt;\n</code></pre></li>\n<li><p>Use the shorter charset meta tag and the meta viewport tag inside your head area. The viewport meta tag is necessary for mobile devices and ensures a good default viewport.</p>\n\n<pre><code>&lt;meta charset=\"utf-8\"&gt;\n&lt;meta name=\"viewport\" content=\"width=device-width, initial-scale=1.0\"&gt;\n</code></pre>\n\n<p><em>Side note</em>: <em>You may omit the <code>type</code>-attribute for style, script and link tag (not for RSS) and the closing <code>/</code> for self-closing tags. <strong>This is not a recommendation</strong>, but it's possible.</em></p></li>\n<li><p>Use ID's only when you definitely can say \"There will be only one element of this per page, ever\". A <em>wrapper</em> is not unique to a page. It should be a class.</p>\n\n<p>Generally speaking, ID's don't provide you with a true benefit and kinda makes your life harder. I don't use ID's as styling hooks anymore and I'm really happy with it.</p></li>\n<li><p>You're navigation is included with PHP and is named <code>menu.php</code>, but it actually contains a header image as well. A better name would be <code>header.php</code>, wouldn't it?</p>\n\n<p>That being said, you may consider moving everything above your header and the header itself to a <code>header.php</code>. Even your head area and the html tag. This is only usable, if you your header is the same on all of your pages.</p></li>\n<li><p>I'm using dash-delmited class names in my HTML. No CamelCase names. This is my preference and if you want to use CamelCase, this is fine. However I would avoid using no delimiting and lowercase names like <code>indexright</code> or <code>smallheader</code>.</p></li>\n</ol>\n\n<p>That's it for now. I'll going to edit some more stuff later. Stay tuned.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-02-02T20:43:38.907", "Id": "40690", "ParentId": "40688", "Score": "11" } }, { "body": "<p>In addition to kleinfreund suggestions :</p>\n\n<ol>\n<li><p>For a link to the homepage, i'd rather do</p>\n\n<pre><code>&lt;a href=\"/\"&gt;Home&lt;/a&gt;\n</code></pre>\n\n<p>instead of</p>\n\n<pre><code>&lt;a href=\"index.php\"&gt;Home&lt;/a&gt;\n</code></pre>\n\n<p>as <a href=\"http://sturgishellfighters.hartwebpages.com/\">http://sturgishellfighters.hartwebpages.com/</a> is a cleaner URL than <a href=\"http://sturgishellfighters.hartwebpages.com/index.php\">http://sturgishellfighters.hartwebpages.com/index.php</a></p></li>\n<li><p>If you care about W3C validation, you should remove the <code>width</code> attribute of the <code>div</code>s and use CSS achieve the same effect.</p></li>\n<li><p>For stronger semantic, you can use HTML5 sectioning elements instead of <code>div</code>s.</p>\n\n<p>Like <code>&lt;header&gt;</code> instead of <code>&lt;div id=\"header\"&gt;</code>,</p>\n\n<p><code>&lt;main id=\"content\"&gt;</code> instead of <code>&lt;div id=\"content\"&gt;</code>,</p>\n\n<p>and wrap your main navigation <code>&lt;ul id=\"HomeMenu\"&gt;</code> with <code>&lt;nav&gt;</code></p></li>\n<li><p>For more accessibility, you can add ARIA landmark roles to the tags mentioned above :</p>\n\n<pre><code>&lt;header role=\"banner\"&gt;\n&lt;nav role=\"navigation\"&gt;\n&lt;main id=\"content\" role=\"main\"&gt;\n</code></pre></li>\n</ol>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-02-09T01:34:02.660", "Id": "70805", "Score": "0", "body": "the width in the tags is a good one, I normally don't do that, I don't know why I did that this time. as for the URL I am not too familiar with redirects on the server, but that is something that I would like to set up too, I think that is what makes this happen where the URL doesn't change when you change the pages." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-02-09T21:20:47.823", "Id": "70876", "Score": "0", "body": "of course I really don't like creating a class for one specific item though either, it makes more work for myself, so it it is one thing on one page then I would probably set the width in the HTML, because it isn't really styling it's structure." } ], "meta_data": { "CommentCount": "2", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-02-09T01:28:33.980", "Id": "41263", "ParentId": "40688", "Score": "6" } } ]
{ "AcceptedAnswerId": "40690", "CommentCount": "6", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-02-02T20:27:56.387", "Id": "40688", "Score": "11", "Tags": [ "php", "html", "beginner", "html5" ], "Title": "Review structure of PHP/HTML" }
40688
<p>The following code loads a YouTube video inside an iframe, where the tricky part is to sync the <code>onYouTubeIframeAPIReady</code> and <code>on('shown.bs.modal')</code> functions. The code works well in Firefox and decently in Chrome, but in Safari it is quite buggy. Any hints towards improvement would be appreciated.</p> <pre><code>jQuery( document ).ready(function() { var tag = document.createElement('script'); tag.src = "https://www.youtube.com/iframe_api"; var firstScriptTag = document.getElementsByTagName('script')[0]; firstScriptTag.parentNode.insertBefore(tag, firstScriptTag); jQuery("#video_modal").on('shown.bs.modal', function() { if(typeof player.playVideo == 'function') { player.playVideo(); } else { var fn = function(){ player.playVideo(); }; setTimeout(fn, 200); } }); jQuery("#video_modal").on('hidden.bs.modal', function() { player.stopVideo(); }); }); var player; function onYouTubeIframeAPIReady() { player = new YT.Player('player', { videoId: 'zg8KE6bEP50', origin: 'http://rollnstroll.se', width: '640', height: '390' }); } </code></pre>
[]
[ { "body": "<p>Don't remove the indentation inside of code blocks so that the code is on the same line as the signature. It makes the code harder to read as it's hard to piece together which <code>}</code> goes to which signature.</p>\n\n<p>For example, this:</p>\n\n<pre><code>function onYouTubeIframeAPIReady() {\nplayer = new YT.Player('player', {\n videoId: 'zg8KE6bEP50',\n origin: 'http://rollnstroll.se',\n width: '640',\n height: '390'\n});\n}\n</code></pre>\n\n<p>Would become this:</p>\n\n<pre><code>function onYouTubeIframeAPIReady() {\n player = new YT.Player('player', {\n videoId: 'zg8KE6bEP50',\n origin: 'http://rollnstroll.se',\n width: '640',\n height: '390'\n });\n}\n</code></pre>\n\n<hr>\n\n<pre><code>var tag = document.createElement('script');\n</code></pre>\n\n<p>The name \"tag\" is extremely general and gives little aid in defining the use of the variable. Since in the next line you give it a script source, I recommend calling it something that defines the script source.</p>\n\n<p>Here is what I came up with</p>\n\n<pre><code>var ytIframeAPI = document.createElement(\"script\");\n</code></pre>\n\n<hr>\n\n<p>Why are you inserting a script into the HTML via JavaScript? Why don't you just put the script tag in your HTML so it is loaded to start?</p>\n\n<p>That way, you don't have to wait for the script to load from the source <em>after</em> the page has loaded; the script will load <em>as</em> the page is loading.</p>\n\n<hr>\n\n<pre><code>var fn = function(){\n player.playVideo();\n};\nsetTimeout(fn, 200);\n</code></pre>\n\n<p>Again, like \"tag\", \"fn\" means nothing to the variable; I know that it is a function. The variable name does not have to tell me.</p>\n\n<p>You have two options here:</p>\n\n<ol>\n<li><p>Give it a better name.</p></li>\n<li><p>Use an anonymous function.</p></li>\n</ol>\n\n<p>Since the only purpose of that function is to use it in <code>setTimeout</code>, you can just use an anonymous function in place of <code>fn</code>.</p>\n\n<p>Here is what I mean:</p>\n\n<pre><code>} else {\n setTimeout(function() {\n player.playVideo();\n }, 200);\n}\n</code></pre>\n\n<p>See? I didn't even have to give the function a name.</p>\n\n<hr>\n\n<p>This might just be a typo, but this confuses me:</p>\n\n<pre><code>if(typeof player.playVideo == 'function') {\n player.playVideo();\n} else {\n var fn = function(){\n player.playVideo();\n };\n setTimeout(fn, 200);\n}\n</code></pre>\n\n<p>If <code>player.playVideo</code> wasn't a function, it's going to go to else. Then, you call <code>player.playVideo</code>. Well, if it wasn't a function, how are you supposed to call it?</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2015-07-03T21:15:14.983", "Id": "95730", "ParentId": "40689", "Score": "3" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-02-02T20:36:06.500", "Id": "40689", "Score": "1", "Tags": [ "javascript", "jquery", "twitter-bootstrap", "youtube" ], "Title": "Loading YouTube videos inside a bootstrap modal" }
40689
<p>I am currently using the Udacity Introduction to Java course. There was a topic on Algorithms and it gave an example Algorithm for comparing and purchasing two different cars in pseudo code. I decided to turn that into some Java code to see just how well I grasped the concept.</p> <p>The algorithm was:</p> <blockquote> <p>For each car, compute. Gas cost = (miles driven / mpg) * price per gallon. Total cost = gas cost + car cost. If car 1 &lt; car 2, buy car 1. Else, buy car 2.</p> </blockquote> <pre><code>//Algorithm for buying a car //by comparing car price, MPG, //local gas price, and the miles //to be drive in total. //idea from udacity Intro //to Java course. import java.util.Scanner; public class buyingCars { public static void main (String[] args) { Scanner input = new Scanner(System.in); System.out.println("Enter the price of car one: "); int carOnePrice = input.nextInt(); System.out.println("Enter the price of car two: "); int carTwoPrice = input.nextInt(); System.out.println("Enter the price of gas in your area: "); double gasPrice = input.nextDouble(); System.out.println ("What is the average mpg of car one? "); int carOneMpg = input.nextInt(); System.out.println ("What is the average mpg of car two? " ); int carTwoMpg = input.nextInt(); System.out.println("Give me an amount of miles total you think you will drive in this car: "); int milesDriven = input.nextInt(); double gasCostCarOne = (milesDriven / carOneMpg) * gasPrice; double totalCostCarOne = gasCostCarOne + carOnePrice; double gasCostCarTwo = (milesDriven / carTwoMpg) * gasPrice; double totalCostCarTwo = gasCostCarTwo + carTwoPrice; if (totalCostCarOne &lt; totalCostCarTwo) { System.out.println("Car One will, in total, cost less than car two. Buy it."); } else { System.out.println("Car two will, in total, cost less than car one. Buy it."); } } } </code></pre> <p>What I am wondering is if my code was clean and my form is good? Are there things I am doing in my code that I should not be, or is everything looking pretty solid?</p> <p>Also, is there a simpler way of doing this? It just seems like an awful lot of code that could potentially be narrowed down. Could each car hold it's values in an array or something like that?</p> <p>If there is a problem with my post, please let me know. I am still getting use to posting here.</p>
[ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-01-12T06:07:04.520", "Id": "68628", "Score": "0", "body": "@PradeepSimha I can't find how to migrate it to codereview.. odd" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-01-12T06:09:30.530", "Id": "68629", "Score": "1", "body": "Regardless of your personal opinion, if you're asking a question here, your code needs to be here." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-01-12T06:15:09.910", "Id": "68630", "Score": "0", "body": "@chrylis Okay, I'll fix that." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-01-12T06:30:17.253", "Id": "68631", "Score": "1", "body": "Well since Java is Object Oriented, you should design your code in a OO way." } ]
[ { "body": "<p>Seeing that you are at the start of your programming career. You are all good to go! Everything is nicely laid out. There are a lot of ways to make this \"better\" to other developers. But for your phase of learning you are right where you need to be! Good work keep coding!</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-01-12T06:37:56.133", "Id": "40694", "ParentId": "40693", "Score": "0" } }, { "body": "<p>The first thing I would try is so factor out the input-prompting routines:</p>\n\n<pre><code> private static Scanner input = new Scanner(System.in);\n\n private static int askInt(String prompt) {\n System.out.println(prompt);\n return input.nextInt();\n }\n\n private static double askDouble(String prompt) {\n System.out.println(prompt);\n return input.nextDouble();\n }\n</code></pre>\n\n<p>In my opinion, there's no particular reason why the car price, fuel efficiency, or distance numbers should be integral. Why not just do all of the work in <code>double</code>s?</p>\n\n<pre><code>public class CarComparison {\n private static Scanner input = new Scanner(System.in);\n\n private static double ask(String prompt) {\n System.out.println(prompt);\n return input.nextDouble();\n }\n\n public static void main(String[] args) {\n double carOnePrice = ask(\"Enter the price of car one: \");\n double carTwoPrice = ask(\"Enter the price of car two: \");\n double gasPrice = ask(\"Enter the price of gas in your area: \");\n double carOneMpg = ask(\"What is the average mpg of car one? \");\n double carTwoMpg = ask(\"What is the average mpg of car two? \");\n double milesDriven = ask(\"Give me an amount of miles total you think you will drive in this car: \");\n\n double gasCostCarOne = (milesDriven / carOneMpg) * gasPrice;\n double totalCostCarOne = gasCostCarOne + carOnePrice;\n\n double gasCostCarTwo = (milesDriven / carTwoMpg) * gasPrice;\n double totalCostCarTwo = gasCostCarTwo + carTwoPrice;\n\n if (totalCostCarOne == totalCostCarTwo) {\n System.out.println(\"The two cars cost the same.\");\n } else if (totalCostCarOne &lt; totalCostCarTwo) {\n System.out.println(\"Car One will, in total, cost less than car two. Buy it.\");\n } else {\n System.out.println(\"Car two will, in total, cost less than car one. Buy it.\");\n }\n }\n}\n</code></pre>\n\n<p>For completeness, I've added handling for the unlikely case of a tie.</p>\n\n<p>A next step might be to define a <code>totalCost()</code> function or to define a <code>Car</code> object, but I think that for this problem, the benefits of further changes would be marginal, and I would just leave it at that.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-02-03T05:02:04.613", "Id": "40716", "ParentId": "40693", "Score": "2" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "4", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-01-12T05:56:10.173", "Id": "40693", "Score": "2", "Tags": [ "java" ], "Title": "Comparing two cars via their lifetime price" }
40693
<p>I'm trying to get the average luma of an area in an YUV image in the Android camera. I have come up with the following code which I think is correct and produces consistent results.</p> <pre><code>private static final int AVERAGE_LUMA_SAMPLE_SIZE = 2; // sample the average luma // yuvImage is the byte data return from a camera's previewFrame public static int getAverageLuma(byte[] yuvImage, int imageWidth, int imageHeight, RectF sampleArea) { int totalLuma = 0; int totalSampled = 0; int top = (int)Math.max(sampleArea.top, 0); int left = (int)Math.max(sampleArea.left, 0); int right = (int)Math.min(sampleArea.right, imageWidth); int bottom = (int)Math.min(sampleArea.bottom, imageHeight); for(int i = top; i &lt; bottom; i += AVERAGE_LUMA_SAMPLE_SIZE) { int rowStartPosition = (i * imageWidth) + left; for (int j = 0; j &lt; right; j += AVERAGE_LUMA_SAMPLE_SIZE) { int bytePostion = rowStartPosition + j; int y = (0xff &amp; ((int) yuvImage[bytePostion])) - 16; totalLuma += Math.max(y, 0); totalSampled++; } } return Math.round((float)totalLuma / totalSampled); } </code></pre>
[]
[ { "body": "<p>One of the reasons that large 2d data sets are often reduced to a single 1D array is so that you can process the data in a single loop and the memory is contiguous. The trick to processing this data efficiently in a single loop is to be able to fiddle the single pointer in a way that makes sense...... and to do that, we need some smart pointer skips...</p>\n\n<p>Consider the following single loop. It starts at the right place, and then skips the areas outside the sample rectangle....</p>\n\n<pre><code>int startpos = top * imageWidth + left;\nint lastpos = bottom * imageWidth + right;\n// skip is the amount of unsampled data from the right-side of the sample\n// rectangle to the left side of the next row.\nint skip = imageWidth - right + left;\n\n// limit is a moving limit that we use to break-process the samples.\n// limit only applies if we actually need to skip data.\nint limit = skip == 0 ? lastpos + 1 : (top * imageWidth) + right;\nfor (int i = startpos; i &lt;= lastpos; i+= AVERAGE_LUMA_SAMPLE_SIZE ) {\n if (i &gt; limit) {\n // take the loop-increment in to consideration.\n i += skip - AVERAGE_LUMA_SAMPLE_SIZE;\n limit += imageWidth;\n } else {\n\n // Do the sampling work here.....\n\n\n }\n}\n</code></pre>\n\n<p>Normally I am against updating a loop-counter index inside the loop, but there are times when it makes sense. This is one of those times.</p>\n\n<p>Note, the skip variable is being calculated naively in this code. It should be smarter about taking the sample-size into consideration, and making sure it hits the beginning of the sample rectangle properly on the next line.... as it stands, if the rectangle is an odd-size, it may cause the start position of the next row to not be on the rectangle boundary. On average, I don't think this will make a difference, but that is your call.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-02-03T04:59:38.190", "Id": "68669", "Score": "0", "body": "this line `int limit = skip == 0 ? lastpos + 1 : right;` should be replaced by `int limit = skip == 0 ? lastpos + 1 :(top * imageWidth) + right;`. Otherwise, perfect." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-02-03T11:17:31.077", "Id": "68692", "Score": "0", "body": "Thanks @IsenGrim - the problem with typing out without testing. Of course you are right." } ], "meta_data": { "CommentCount": "2", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-02-02T23:04:34.177", "Id": "40698", "ParentId": "40696", "Score": "2" } }, { "body": "<p>I think you've gotten the bounds of the sample area wrong. <code>j</code> should range from <code>left</code> to <code>right</code>, and <code>rowStartPosition</code> should not include <code>left</code>.</p>\n\n<p><code>(0xff &amp; ((int)yuvImage[bytePosition]))</code> deserves a comment explaining that you want to interpret the bytes as unsigned numbers.</p>\n\n<p>You might have to worry about overflow if you analyze every 25% of the pixels of a very bright 32-megapixel rectangle. It's not something you would have to worry about with today's cameras, but it might be worthwhile to code defensively for the future.</p>\n\n<p><del>You could subtract 16 from the average rather than from each element.</del> <em>Never mind, that's not the same, due to <code>Math.max(y, 0)</code>.</em></p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-02-03T04:02:47.973", "Id": "68663", "Score": "0", "body": "Hmm, where should I start reading up about coding defensively in this particular situation you just mentioned? (any keyword suggestions I should google?)\n\nEdit: you're talking about overflowing the integer boundaries of `totalLuma`, aren't you?" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-02-03T04:16:14.937", "Id": "68665", "Score": "1", "body": "The easy defense is to test that `totalLuma` stays positive; if it ever goes negative, throw an exception. If you want to _prevent_ overflow, one way is to use a `float` to store `totalLuma`. Alternatively, you could realize that there's a danger of overflow if the `sampleArea` exceeds `AVERAGE_LUMA_SAMPLE_SIZE * AVERAGE_LUMA_SAMPLE_SIZE * Integer.MAX_VALUE / (0xff - 16)` pixels, and calculate the average in smaller batches when that area is exceeded. That's tricker to implement, but it allows you to stick with integer arithmetic." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-02-03T07:57:05.037", "Id": "68683", "Score": "0", "body": "… or you could just use a `long` for `totalLuma`." } ], "meta_data": { "CommentCount": "3", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-02-03T01:04:05.433", "Id": "40706", "ParentId": "40696", "Score": "2" } } ]
{ "AcceptedAnswerId": "40698", "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-02-02T21:59:10.980", "Id": "40696", "Score": "4", "Tags": [ "java", "android", "image" ], "Title": "Calculating luma of a rect in an image of .yuv format" }
40696
<p>I'm starting to implement basic sorting algorithms. Criticisms on the implementation is welcome. </p> <pre><code>#import pudb; pu.db def bubble_sort(list_): """Implement bubblesort algorithm: iterate L to R in list, switching values if Left &gt; Right. Break when no alterations made to to list. """ not_complete = True while not_complete: not_complete = False for val, item in enumerate(list_): if val == len(list_)-1: val = 0 else: if list_[val] &gt; list_[val+1]: list_[val], list_[val+1] = list_[val+1], list_[val] not_complete = True return list_ if __name__ == '__main__': assert bubble_sort(list(range(9))[::-1]) == list(range(9)) </code></pre>
[]
[ { "body": "<blockquote>\n<pre><code>for val, item in enumerate(list_):\n</code></pre>\n</blockquote>\n\n<p>You don't use <code>item</code>, so don't get it. Instead, use <code>xrange(len(list_))</code></p>\n\n<blockquote>\n<pre><code>if val == len(list_)-1: val = 0\n</code></pre>\n</blockquote>\n\n<p>This rechecks position 0 again. There is no need to do that. Instead, change the loop so it goes one less round. </p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-02-03T00:14:48.263", "Id": "40702", "ParentId": "40699", "Score": "7" } }, { "body": "<ol>\n<li><p>This line seems to be left over from a debugging session:</p>\n\n<pre><code>#import pudb; pu.db\n</code></pre>\n\n<p>But there is no need to edit your code to debug it — and you should strive to avoid doing so, because it's too easy to forget to remove the debugging code. (And <a href=\"https://codereview.stackexchange.com/q/40734/11728\">in your other question</a> you did forget to remove it!)</p>\n\n<p>Instead, learn how to use the tools. You can run the built-in debugger <a href=\"http://docs.python.org/3/library/pdb.html\" rel=\"nofollow noreferrer\"><code>pdb</code></a> from the command line like this:</p>\n\n<pre><code>$ python -mpdb myprogram.py\n</code></pre>\n\n<p>and you can run <code>pudb</code> from the command line <a href=\"https://pypi.python.org/pypi/pudb\" rel=\"nofollow noreferrer\">as described in the documentation</a>.</p></li>\n<li><p>The docstring is written from the wrong point of view:</p>\n\n<pre><code>\"\"\"Implement bubblesort algorithm: iterate L to R in list, switching values\nif Left &gt; Right. Break when no alterations made to to list. \"\"\"\n</code></pre>\n\n<p>Docstrings should be written from the <em>user's</em> point of view: What does this function do? How should I call it? What values does it return? What side effects does it have? For example:</p>\n\n<pre><code>&gt;&gt;&gt; help(abs)\nHelp on built-in function abs in module builtins:\n\nabs(...)\n abs(number) -&gt; number\n\n Return the absolute value of the argument.\n</code></pre>\n\n<p>Your docstring is written from the point of view of the <em>implementer</em>. This kind of material should be in comments.</p></li>\n<li><p>You spelled your variable <code>list_</code> to avoid shadowing the built-in function <code>list</code>. I would prefer to find a better name for the variable rather than arbitrarily respelling it like this. Since your algorithm works on any <a href=\"http://docs.python.org/3/library/stdtypes.html#mutable-sequence-types\" rel=\"nofollow noreferrer\"><em>mutable sequence</em></a> (not just lists), then <code>seq</code> might be a good name.</p></li>\n<li><p>Instead of:</p>\n\n<pre><code>else:\n if condition:\n code\n</code></pre>\n\n<p>write:</p>\n\n<pre><code>elif condition:\n code\n</code></pre></li>\n<li><p>You have a special case:</p>\n\n<pre><code>if val == len(list_)-1: val = 0\n</code></pre>\n\n<p>to ensure that <code>val + 1</code> does not run off the end of the list. But it would be better to stop the iteration before that happens. So instead of:</p>\n\n<pre><code>for val, item in enumerate(list_):\n</code></pre>\n\n<p>write:</p>\n\n<pre><code>for val in range(len(list_) - 1):\n</code></pre></li>\n<li><p><code>val</code> is an index into the list: it's conventional to give such variables names like <code>i</code> and <code>j</code>.</p></li>\n<li><p>Each time around the <code>while not_complete</code> loop, you make a pass over the whole of the sequence. But there is an easy optimization, <a href=\"https://en.wikipedia.org/wiki/Bubble_sort#Optimizing_bubble_sort\" rel=\"nofollow noreferrer\">noted by Wikipedia</a>:</p>\n\n<blockquote>\n <p>The bubble sort algorithm can be easily optimized by observing that the n-th pass finds the n-th largest element and puts it into its final place. So, the inner loop can avoid looking at the last n-1 items when running for the n-th time.</p>\n</blockquote>\n\n<p>So I would write it like this:</p>\n\n<pre><code>def bubble_sort(seq):\n \"\"\"Sort the mutable sequence seq in place and return it.\"\"\"\n for i in reversed(range(len(seq))):\n finished = True\n for j in range(i):\n if seq[j] &gt; seq[j + 1]:\n seq[j], seq[j + 1] = seq[j + 1], seq[j]\n finished = False\n if finished:\n break\n return seq\n</code></pre></li>\n<li><p>You have some test code at the end of the script. It is best to organize test code like this into <em>unit tests</em> using the <a href=\"http://docs.python.org/3/library/unittest.html\" rel=\"nofollow noreferrer\"><code>unittest</code></a> module. For example:</p>\n\n<pre><code>from unittest import TestCase\nfrom random import random\n\nclass BubbleSortTest(TestCase):\n def test_bubble_sort(self):\n seq = [random() for _ in range(4000)]\n sorted_seq = sorted(seq)\n self.assertEqual(bubble_sort(seq), sorted_seq)\n</code></pre>\n\n<p>Note how I've used randomization to get a wider range of test cases. (I've also made the length of the test array large enough to give a noticeable delay and so emphasize how poor an algorithm bubble sort is.)</p></li>\n</ol>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-02-03T13:41:02.517", "Id": "40736", "ParentId": "40699", "Score": "11" } }, { "body": "<pre><code>def swap(mylist,i):\n temp1 = mylist[i] \n temp2 = mylist[i+1]\n mylist[i] = temp2\n mylist[i+1] = temp1\n\ndef one_scan(mylist):\n for i in range (len(mylist)-1): \n if(mylist[i] &gt;= mylist[i+1]):\n swap(mylist,i)\n\ndef sortMyL(L):\n i = 0\n while(i&lt;len(L)):\n one_scan(L)\n i+=1\n print(\"Sorted list\")\n print(L)\n</code></pre>\n\n<p>Let's say x = [3,2,1,6,7]</p>\n\n<p><code>sortMyL(x)</code> will print out [1,2,3,6,7]</p>\n\n<p>Feel free to ask any questions. </p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-04-23T03:14:12.833", "Id": "47945", "ParentId": "40699", "Score": "0" } } ]
{ "AcceptedAnswerId": "40736", "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-02-02T23:06:02.143", "Id": "40699", "Score": "11", "Tags": [ "python", "algorithm", "sorting", "reinventing-the-wheel" ], "Title": "Bubble sort algorithm in Python" }
40699
<p>Reference: <a href="https://stackoverflow.com/questions/21515940/is-this-a-faithful-rendition-of-the-selection-sort-algorithm">Is this a faithful rendition of the selection sort algorithm?</a></p> <p>I'm working through an elementary book on sort and search algorithms, and writing some sample code to test my understanding. Here, I've been fiddling with a Ruby implementation of a selection sort algorithm. My first attempt (see link) seemed to work, but used multiple arrays, and deleted from one and placed into a second. I was advised that an in-place approach would be more normal.</p> <p>This is my first cut at that approach. Sadly, it's exactly sort of thing I wanted to avoid, as it feels nastily procedural, with nested loops. However, I think it's a faithful implementation.</p> <pre><code>class SelectionSorter def sort(list) sorted_boundary = (0..(list.length)-1) sorted_boundary.each do |sorted_index| smallest_index = sorted_index smallest_value = list[smallest_index] comparison = sorted_index + 1 (comparison..(list.length-1)).each do |next_index| if list[next_index] &lt; smallest_value smallest_index = next_index smallest_value = list[smallest_index] end end unless sorted_index == smallest_index list[smallest_index] = list[sorted_index] list[sorted_index] = smallest_value end end list end end </code></pre> <p>Unit test here:</p> <pre><code>require 'minitest/autorun' require_relative 'sort' class SelectionSortTest &lt; MiniTest::Test describe SelectionSorter do it 'sorts a randomly generated list' do list = (1..12).map { rand(100-1) + 1 } sorted_list = list.sort sorter = SelectionSorter.new sorter.sort(list).must_equal sorted_list end end end </code></pre> <p>I'd love to do this in a more recursive fashion, with less stored state, and without nested loops. Any suggestions?</p>
[ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-02-02T23:42:12.040", "Id": "68650", "Score": "0", "body": "Perhaps mention that `selection sort` is just one approach to doing a regular sort. Sample data not reqd. Also, you lost your link when moving the question from SO." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-02-03T05:56:14.247", "Id": "68675", "Score": "0", "body": "Test added - I forgot to include this - it was in the original on SO." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-02-27T20:32:13.157", "Id": "74112", "Score": "0", "body": "f you are satisfied with any of the answers, you should select the one that was most helpful to you." } ]
[ { "body": "<p>Here are a couple of Ruby-like approaches you might consider:</p>\n\n<pre><code>def sort(unsorted)\n sorted = []\n until unsorted.empty? do\n smallest = [unsorted.first, 0]\n (1...unsorted.size).each do |i|\n v = unsorted[i]\n smallest = [v, i] if v &lt; smallest.first\n end \n sorted &lt;&lt; unsorted.delete_at(smallest.last)\n end\n sorted\nend\n\na = [2, 5, 3, 1, 6, 3, 3, 4, 8, 3, 7]\nb = sort(a)\n#=&gt; [1, 2, 3, 3, 3, 3, 4, 5, 6, 7, 8] \n</code></pre>\n\n<p>This is quite straightforward, similar to what you would see when using a procedural language.</p>\n\n<p>Here's a recursive approach:</p>\n\n<pre><code>def sort(unsorted, sorted = [])\n return sorted if unsorted.empty?\n m = unsorted.min\n sorted.concat([m]*(unsorted.count(m)))\n unsorted.delete(m)\n sort(unsorted, sorted)\nend\n\nsort(a)\n#=&gt; [1, 2, 3, 3, 3, 3, 4, 5, 6, 7, 8] \n</code></pre>\n\n<ul>\n<li>First find <code>m</code>, the minimum of the unsorted elements.</li>\n<li>Append <code>unsorted.count(m)</code> <code>m</code>'s to the sorted list. <code>sorted += [m]*(unsorted.count(m))</code> could be used instead of <code>concat</code>, but <code>+=</code> creates a new array, whereas <code>concat</code> does not.</li>\n<li>Delete all values <code>m</code> from the unsorted list.</li>\n</ul>\n\n<p>The latter solution is relatively inefficient, as we make three passes through the unsorted list each time we move one or more values from the unsorted to the sorted list. That's mainly because I wanted to illustrate how the sort could be done without using indices.</p>\n\n<p>This is a sort of \"fake\" recursion, because it doesn't exploit the power of recursion; we could have simply put the code that transfers the <code>mins</code> in a <code>until unsorted.empty? do</code> loop. I don't see how recursion can be used to advantage here. </p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-02-03T05:44:37.467", "Id": "68672", "Score": "0", "body": "Thanks! This bears some similarities to my original idea, although I elected not to use .min. I think yours is rather elegant, but thanks for helping me understand the tension between aesthetic principles and efficiency! I might have a crack at profiling them." } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-02-03T01:11:59.913", "Id": "40707", "ParentId": "40700", "Score": "5" } }, { "body": "<p>If you really want to go down functional path you should learn a Haskell (<a href=\"http://learnyouahaskell.com/chapters\" rel=\"nofollow\">for Great Good</a>) or at least consult <a href=\"http://rosettacode.org/wiki/Sorting_algorithms/Selection_sort#Haskell\" rel=\"nofollow\">Haskell solutions</a>. You can find compact Ruby solution there too. Ruby is not designed for recursive approach, you will suffer from performance issues or blown up stack. Anyway my translation of Haskell approach if you don't know Haskell (ineffective!):</p>\n\n<pre><code>def uninject(b, &amp;block)\n result = []\n while ab = block[b]\n result &lt;&lt; ab.first\n b = ab.last\n end\n result\nend\n\ndef sort(list)\n uninject(list) do |slist|\n unless slist.empty?\n head, *tail = slist\n tail.inject([head, []]) do |(min_v, rest), v| \n v &lt; min_v ? [v, [min_v, *rest]] : [min_v, [v, *rest]]\n end\n end\n end\nend\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-02-03T05:46:49.970", "Id": "68673", "Score": "0", "body": "Yes, I was planning to try a pure functional approach, probably in Haskell. I've dabbled in Haskell, but not so much as to be confident to understand code. But it appeals to me very much." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-02-03T05:47:38.693", "Id": "68674", "Score": "0", "body": "Is it true to say Ruby isn't designed for a recursive approach? Maybe it isn't *optimised* for such an approach, being an explicitly OO language, but it seems often Ruby adopts a recursive approach, or at least an approach that discourages side-effects?" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-02-03T11:49:00.257", "Id": "68698", "Score": "0", "body": "No tail call optimization means not designed for recursive approach in my books (that's why `uninject` in my code is a loop, while in Haskell `unfoldr` is recursive). Besides functional language should use immutable data structures to be efficient, otherwise it's just copying data from one place to another." } ], "meta_data": { "CommentCount": "3", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-02-03T02:09:03.673", "Id": "40711", "ParentId": "40700", "Score": "4" } }, { "body": "<p>To be true to the spirit of the algorithm, you really should not make any array copies. Below is a recursive solution which accomplishes that except in one method, and that one method can easily be rewritten to avoid making any copies altogether. But I was aiming for clarity.</p>\n\n<p>One of the reasons you're having trouble implementing this in a functional style is that the algorithm, at heart, is not functional. In much the same way, <a href=\"https://stackoverflow.com/questions/7717691/why-is-the-minimalist-example-haskell-quicksort-not-a-true-quicksort\">a true quicksort cannot be done in idiomatic haskell</a>.</p>\n\n<p>What I've done below is keep to the spirit of the original algorithm, while taking advantage of some of ruby's syntactic sugar, so that the algorithm is still slightly briefer and more readable than it would be in, say, C. But really, at the end of the day, you are faced with a choice:</p>\n\n<ol>\n<li>Be true to the algorithm but essentially write C code in ruby</li>\n<li>Don't but true to the algorithm, in which case you can do all sorts of things (the other answers show some of them).</li>\n</ol>\n\n<p>But if we're in case 2, you have to start asking why not just use the built in \".sort\" method?</p>\n\n<pre class=\"lang-rb prettyprint-override\"><code>class SelectionSorter\n\n def sort(list, start_index=0)\n return list if start_index == list.size-1\n swap(list, start_index, min_index(list, start_index))\n sort(list, start_index + 1)\n end\n\n def swap(list, start_index, min_index)\n temp = list[start_index]\n list[start_index] = list[min_index]\n list[min_index] = temp\n end\n\n def min_index(list, start_index)\n # this is a \"cheat\" but could be replaced with a standard loop to avoid \n # any array copies\n unsorted = list[start_index..-1]\n start_index + unsorted.find_index(unsorted.min)\n end\n\nend\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-02-03T05:39:53.057", "Id": "68671", "Score": "1", "body": "This is really helpful, thanks. As I move onto some of the other algorithms, I expect I'll encounter approaches that lend themselves to a more functional approach." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-02-03T06:13:24.713", "Id": "68676", "Score": "0", "body": "Many traditional sorting algorithms do in place sorts, which by definition involves lots of mutation, and hence is incompatible with a functional approach. In some cases you can make tweaks and adapt the algos to a functional approach and, depending on your language and compiler, still get good performance. And some algorithms are specially designed for a functional approach, and if you really want to do functional programming it's best to just use those." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-02-03T06:14:52.707", "Id": "68677", "Score": "0", "body": "To add one final comment: If your goal is just to practice your ruby skills and improve your idiomatic ruby, then the answer is simply to choose different problems to practice on: ones that are a natural fit." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-02-03T08:46:37.710", "Id": "68684", "Score": "0", "body": "The goal is to understand the algorithms. Ruby is the language I know best, but my aesthetic sense makes me uncomfortable when I write what to me seems to be ugly Ruby. Part of the learning process is, I suspect, to understand which language most suits the algorithm!" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-02-04T03:36:15.683", "Id": "68873", "Score": "0", "body": "Jonah, I like the way you have broken this into three methods, but I wanted to point out that recursion isn't really buying you anything. You could keep your structure and simplify by replacing `sort()` with: `def sort(list); (list.size-1).times { |start_index| swap(list, start_index, min_index(list, start_index)) }; list; end`.\nend" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-02-04T07:45:58.070", "Id": "69898", "Score": "0", "body": "Cary, this is a good point. The OP did mention recursion though, and I think in this case it's of such a simple kind that it's just as readable. But yeah, I probably like your suggestion a little better." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-02-04T18:46:36.583", "Id": "70003", "Score": "0", "body": "I did the same in my answer, but when it dawned on me that the problem really didn't lend itself to recursion, I thought it would be better to leave that solution up and explain why recursion isn't the cat's meow here." } ], "meta_data": { "CommentCount": "7", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-02-03T05:06:57.427", "Id": "40717", "ParentId": "40700", "Score": "7" } }, { "body": "<p>The implementation you posted in this question is fine, in my opinion. As you suspected, it is a \"natural\" approach for Ruby, and I wouldn't make major changes to it. You could get rid of the <code>unless</code>, since swapping an element with itself is a no-op.</p>\n\n<p>Just for the sake of comparison, I'll offer two other implementations. First, define a helper function:</p>\n\n<pre><code># Returns the index and value of the smallest among\n# array[start], array[start + 1], ..., array.last\n#\n# Implemented recursively, but you could substitute a more natural\n# implementation using array.each_with_index.\ndef smallest(array, start=0)\n if start == array.length - 1\n return start, array[start]\n else\n j, val = smallest(array, start + 1)\n return array[start] &lt; val ? [start, array[start]] : [j, val]\n end\nend\n</code></pre>\n\n<p>Using that helper, you could implement a recursive, functional selection sort:</p>\n\n<pre><code>def functional_selection_sort(array)\n if array.empty?\n []\n else\n _, min = smallest(array)\n min, larger = array.partition { |item| item == min }\n min.concat(functional_selection_sort(larger))\n end\nend\n</code></pre>\n\n<p>If you want to sort the array in place, though, it's hard to avoid using <code>.each</code> in some form or other:</p>\n\n<pre><code>def inplace_selection_sort!(array)\n array.each_with_index do |item, index|\n smallest_i, smallest = smallest(array, index)\n array[index], array[smallest_i] = smallest, item\n end\nend\n</code></pre>\n\n<p>Note the use of <code>!</code> in the name to emphasize that it works in place.</p>\n\n<p>The behaviour:</p>\n\n<blockquote>\n<pre><code>a = [3, 1, 4, 1, 5, 9, 2, 6, 5]\nfunctional_selection_sort(a) #=&gt; [1, 1, 2, 3, 4, 5, 5, 6, 9]\na #=&gt; [3, 1, 4, 1, 5, 9, 2, 6, 5]\ninplace_selection_sort!(a) #=&gt; [1, 1, 2, 3, 4, 5, 5, 6, 9]\na #=&gt; [1, 1, 2, 3, 4, 5, 5, 6, 9]\n</code></pre>\n</blockquote>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-02-03T07:14:43.593", "Id": "40722", "ParentId": "40700", "Score": "1" } }, { "body": "<p>Here's how I'd tackle the in-place version leveraging Ruby's capabilities. It's not recursive, but it's structured fairly functionally.</p>\n\n<pre><code>class Array\n def swap!(i,j)\n self[i], self[j] = self[j], self[i] unless i == j\n end\n\n def min_index_from(i)\n (i...length).each.inject {|min, current| self[current] &lt; self[min] ? current : min}\n end\n\n def selection_sort!\n (0...length-1).each {|i| swap!(i, min_index_from(i)) }\n self\n end\nend\n\nif __FILE__ == $0\n require 'test/unit'\n class SelectionSort_test &lt; Test::Unit::TestCase\n def test_selection_sort\n 10.times do\n a = Array.new(1000).map {rand}\n b = a.sort\n assert_equal a.selection_sort!, b\n end\n end\n end\nend\n</code></pre>\n\n<p>If you try to do this recursively, the recursive subproblem is only one element smaller than the previous level's problem so you can quickly run into stack limits if you try to sort large vectors.</p>\n\n<p>Instead, I tried to slim it down so the iterative aspects felt less \"clunky\", and to make it glaringly obvious that the nature of selection sort is to repeatedly find the minimum element of the remaining data and exchange it with the first element of the remaining data.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-02-03T18:14:41.170", "Id": "68763", "Score": "0", "body": "Hi, and welcome to CodeReview. Nice enough answer but you should consider adding some comment on *why* doing it iteratively is better than the recursive alternative (especially since the OP's intent was to make it 'more recursive'" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-02-03T22:17:09.683", "Id": "68799", "Score": "0", "body": "@rolfl Thanks for the welcome. Hopefully the additional comments clarify the intent." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-02-03T22:26:11.730", "Id": "68809", "Score": "0", "body": "That helps a lot... you already have my +1" } ], "meta_data": { "CommentCount": "3", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-02-03T17:46:44.767", "Id": "40764", "ParentId": "40700", "Score": "4" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "3", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-02-02T23:16:17.257", "Id": "40700", "Score": "11", "Tags": [ "algorithm", "ruby", "recursion", "sorting" ], "Title": "Selection sorter" }
40700
<p>I am new to HTML and CSS. I was wondering if anyone could give me some advice on my use of markup and CSS to achieve this result. I am trying to get a fixed full height sidebar with a list with sprite image for each item.</p> <p><a href="http://jsfiddle.net/spadez/JBuE6/40/" rel="nofollow">This</a> is the code I have which achieves this.</p> <p><strong>HTML</strong></p> <pre><code>&lt;div class="container"&gt; &lt;div class="col_left"&gt; &lt;a href="url"&gt;&lt;img src="logo.png"&gt;&lt;/img&gt;&lt;/a&gt; &lt;ul&gt; &lt;li class="navimg" id="user"&gt;&lt;a href="url"&gt;User&lt;/a&gt;&lt;/li&gt; &lt;li class="navimg" id="vacancy"&gt;&lt;a href="url"&gt;Vacancies&lt;/a&gt;&lt;/li&gt; &lt;li class="navimg" id="company"&gt;&lt;a href="url"&gt;Company&lt;/a&gt;&lt;/li&gt; &lt;/ul&gt; &lt;/div&gt; &lt;div class="col_right"&gt; &lt;ul&gt; &lt;li&gt;&lt;a href="#"&gt;Create New&lt;/a&gt;&lt;/li&gt; &lt;/ul&gt; &lt;h1&gt;Title&lt;/h1&gt; &lt;h2&gt;Create new list&lt;/h2&gt; &lt;form name="input"&gt; &lt;input type="text" name="Title"&gt; &lt;input type="text" name="Location"&gt; &lt;input type="text" name="Description"&gt; &lt;input type="text" name="Closing date"&gt; &lt;input type="submit" value="Add"&gt; &lt;/form&gt; &lt;/div&gt; &lt;/div&gt; </code></pre> <p><strong>CSS</strong></p> <pre><code>* { margin: 0px; padding: 0px; } li { list-style-type: none; } .container { display: block; position:absolute; height:auto; bottom:0; top:0; left:0; right:0; background-color:white; } .column_wrap { position:relative; } .col_left { background-color:#f2f2f2; width:250px; position:absolute; left:0; top:0; bottom:0; height:auto; display: block; } .col_left img { float:right; display: block; line-height:40px; margin-left: auto; margin-right: auto; } .col_left li a { color: gray; display: block; line-height: 26x; } .col_left li a:hover { color: green; } .col_right { margin-left:250px; } .col_right li { float: right; } .col_right a { float: right; background: green; padding: 10px; color: white; font-weight:bold; } .col_right a:hover { background: blue; } input { display: block; border: 2px solid gray; padding: 10px; margin: 10px } input:hover { border: 2px solid blue; } input:focus { border: 2px solid blue; } .navimg { background:url('http://www.otlayi.com/web_images/content/free-doc-type-sprite-icons.jpg'); width: 0px; height: 20px; padding-left: 30px; } #user { background-position: -10px -6px; } #vacancy { background-position: -48px -6px; } #company { background-position: -88px -6px; } </code></pre> <p>However, I think there might be some areas where my code is inefficient, messy or non symantic. Can anyone give me any advice please? I would really appreciate it.</p>
[ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-02-06T17:43:06.127", "Id": "70440", "Score": "0", "body": "What is supposed to happen with the green button at the right? the \"Create New\"? Will that send you to a different page, display a modal, etc?" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-02-06T17:50:08.473", "Id": "70444", "Score": "0", "body": "I don't understand why you are floating your logo to the right. Do you have a mockup of what you are trying to achieve?" } ]
[ { "body": "<p>A few suggestions</p>\n\n<p>You were using this to pass classes to your main logo</p>\n\n<pre><code>.col_left img {\n float:right;\n display: block;\n line-height:40px;\n margin-left: auto;\n margin-right: auto;\n}\n</code></pre>\n\n<p>But that will create problems if you introduce any other images there. So instead try giving that element a class. For example, a class of <code>logo</code> or anything that you want to name it. This way there will not be any unexpected conflicts caused by CSS inheritance</p>\n\n<p><strong>HTML</strong></p>\n\n<pre><code>&lt;a href=\"/\" class=\"logo\"&gt;\n &lt;img src=\"http://placehold.it/100x60\"&gt;\n&lt;/a&gt;\n</code></pre>\n\n<p><strong>CSS</strong></p>\n\n<pre><code>.logo {\n float:right;\n display: block;\n line-height:40px;\n margin-left: auto;\n margin-right: auto;\n} \n</code></pre>\n\n<p>In testing, can use image placeholders. In my example, I used Placehold.it which allows you to just give a desired height</p>\n\n<p>All of your <code>&lt;li&gt;</code>s on the left have the same rules. So you might as well give that <code>&lt;ul&gt;</code> a class and pass rules that way. However some rules may not apply. Also you gave both an id and class to those <code>&lt;li&gt;</code>s. this is what I did </p>\n\n<p><strong>HTML</strong></p>\n\n<pre><code>&lt;ul class=\"options\"&gt;\n &lt;li class=\"user\"&gt;\n &lt;a href=\"#\"&gt;User&lt;/a&gt;\n &lt;/li&gt;\n &lt;li class=\"vacancy\"&gt;\n &lt;a href=\"#\"&gt;Vacancies&lt;/a&gt;\n &lt;/li&gt;\n &lt;li class=\"company\"&gt;\n &lt;a href=\"#\"&gt;Company&lt;/a&gt;\n &lt;/li&gt;\n&lt;/ul&gt;\n</code></pre>\n\n<p><strong>CSS</strong></p>\n\n<pre><code>.user, .vacancy, .company {\n background:url('http://www.otlayi.com/web_images/content/free-doc-type-sprite-icons.jpg');\n width: 0px;\n height: 20px;\n padding-left: 30px;\n}\n\n.user { background-position: -10px -6px; } \n.vacancy { background-position: -48px -6px; }\n.company { background-position: -88px -6px; }\n</code></pre>\n\n<p>I did it that way so that you can choose to add in what you want to accept what CSS rules. </p>\n\n<p>in testing. When you have links, it is common to just use <code>href=\"#\"</code></p>\n\n<p>Full code available at this <a href=\"http://codepen.io/JGallardo/pen/hjeHo\" rel=\"nofollow\">CodePen</a>.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-02-06T18:20:48.823", "Id": "41092", "ParentId": "40701", "Score": "2" } } ]
{ "AcceptedAnswerId": "41092", "CommentCount": "2", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-02-02T23:23:03.957", "Id": "40701", "Score": "3", "Tags": [ "html", "beginner", "css" ], "Title": "HTML and CSS markup to achieve desired result" }
40701
<p>A helper is a method commonly used in object-oriented programming to provide additional functionality to classes that not directly associated with the class. This is known as an Inversion of Responsibility.</p> <p>Helper methods are typically grouped into a single helper class through the delegation pattern.</p>
[]
[]
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-02-03T06:19:27.003", "Id": "40719", "Score": "0", "Tags": null, "Title": null }
40719
Additional functionality not defined in a class that the helper operates on.
[]
[]
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-02-03T06:19:27.003", "Id": "40720", "Score": "0", "Tags": null, "Title": null }
40720
<p>I'm writing an object oriented package, and one problem I am trying to solve is a class that will get all PHP files in a particular directory and instantiate the classes but not abstracts or interface types.</p> <p>From an object oriented perspective, is this class SOLID?</p> <pre><code>&lt;?php namespace Massculator; class Collector { public function collect($path, $gatewayNamespace) { $classes = new \RecursiveDirectoryIterator(dirname(__FILE__) . $path); foreach(new \RecursiveIteratorIterator($classes) as $file) { $class = basename($file); $class = str_replace('.php', '', $class); if(class_exists($gatewayNamespace . $class)) { $constructedClass = $gatewayNamespace . $class; if((new \ReflectionClass($constructedClass))-&gt;isAbstract()) $return[] = new $constructedClass; } } return $return; } } </code></pre> <p>The class has one method and that method has a couple of tasks:</p> <ol> <li>get files</li> <li>parse only PHP files</li> <li>instantiate non abstracts</li> </ol> <p>It seems like this breaks the single responsibility principle, but creating another class simply to do a <code>str_replace</code> seems pointless. What do you think?</p>
[]
[ { "body": "<p><em>README:</em><br>\nFirst off, I'll just focus on making this one class a tad more generic, and expandable <em>and</em> maintainable and... well, generally more OO. Then, though I'm not going to go into too much detail on the matter, I'll just list a few quick tips of how you could go about separating concerns even more and create an entire <code>File</code> namespace.<br>\nCode-review can be harsh, but I do not intend to be hurtful or patronizing. My intentions are simply to convey, to the best of my abilities my views on what might be a preferable approach. I base this on experience, as well as personal preference and. While I try to be as objective as possible, I'm only human, so it stands to reason that the code I suggest might not be to your liking. But the code listed here is untested, written off the top of my head and only serves to illustrate my point.</p>\n\n<p>This class/method definitely could do with a couple of additional methods. For example: I might want to set a path, and then -at various points in time- want to get reflection classes for a given <em>\"gateway namespace\"</em>.<Br>\nYour code, as it now stands would imply calling the <code>collect</code> method with the same <code>$path</code> argument, which will create an all-new <code>RecursiveDirectoryIterator</code> instance, only to get those files I'm after.<br></p>\n\n<p>If, however, your class would look like this:</p>\n\n<pre><code>class Collector\n{\n protected $iterator = null;\n public function __construct($path = null)\n {\n if ($path) $this-&gt;setPath($path);\n }\n public function setPath($path)\n {\n $this-&gt;iterator = new \\RecursiveDirectoryIterator(\n dirname(__FILE__) . $path\n );\n return $this;\n }\n public function collect($namespace, $path = null)\n {\n $return = array();\n if ($path !== null) $this-&gt;setPath($path);\n foreach(new \\RecursiveIteratorIterator($this-&gt;iterator) as $file)\n {\n $class = str_replace('.php','', basename($file));\n }\n }\n}\n</code></pre>\n\n<p>You allow users to set the base-path when creating the instance, and then use that instance to get whatever reflection classes they will be needing at any given moment.<br>\nMoreover, you can expand on this <em>\"theme\"</em> even more, by allowing them to set a property that you can use instead of using <code>dirname(__FILE__)</code>, which -if we're honest- isn't really improving the reusability of your current code.</p>\n\n<p>I also struggle to see the point in a method that only allows reflection on <em>abstract</em> classes only:</p>\n\n<pre><code>if((new \\ReflectionClass($constructedClass))-&gt;isAbstract())\n</code></pre>\n\n<p>Why not create reflection classes for all matched files, and assign them to a property, so you can then use a getter where the user can specify which classes he/she needs?</p>\n\n<pre><code>class Collector\n{\n const COLLECT_ABSTRACT = 0;\n const COLLECT_REGULAR = 1;\n const COLLECT_BOTH = 2;\n //properties:\n $iterator = null;\n $collection = array();\n public function getCollection($gatewayNS, $which = self::COLLECT_ABSTRACT)\n {\n if (!isset($this-&gt;collection[$gatewayNS]))\n $this-&gt;getNS($gatewayNS);\n if (!isset($this-&gt;collection[$gatewayNS][$which]))\n throw new \\InvalidArgumentException('invalid offset (0,1,2 are allowed)');\n return $this-&gt;collection[$gatewayNS][$which];\n }\n\n private function getNS($ns)\n {\n $this-&gt;collection[$ns] = array(\n self::COLLECT_ABSTRACT =&gt; array(),\n self::COLLECT_REGULAR =&gt; array(),\n self::COLLECT_BOTH =&gt; array()\n );\n foreach(new \\RecursiveIteratorIterator($this-&gt;iterator) as $file)\n {\n $class = $ns.str_replace('.php','', basename($file));\n if (class_exists($class))\n {\n $class = new \\ReflectionClass($class);\n $this-&gt;collections[$ns][self::COLLECT_BOTH] = $class;\n if ($class-&gt;isAbstract())\n $this-&gt;collection[$ns][self::COLLECT_ABSTRACT] = $class;\n else\n $this-&gt;collection[$ns][self::COLLECT_REGULAR] = $class;\n }\n }\n return $this-&gt;collections[$ns];\n }\n}\n</code></pre>\n\n<p>That should help you on your way to turn this one-method-function-in-OOP-drag thing into a bona-fide class, that you can use in future projects, as well as your current one.<br>\nThis is, of course, just a start. This class still needs some more work, and actually, could do with some helper classes, too. As I said, I'm not going to deal with this in great detail, but just as a primer/list of suggestions. The first one, though, is not a suggestion, but an appeal:</p>\n\n<p><em><strong>Code should document itself</em></strong><br>\nLooking at your code, I'm not at all aware of all the other classes you're using, lest I browse through the actual code. Namespaced class files <em>should</em> start with a series of <code>use</code> statements, that tell me what other classes they depend upon. That way, I can get a rough Idea of what classes I can expect to see in the return values, and which objects are going to be valid as arguments, too.<br>\nThat, and of course: nobody likes to see all those backslashes throughout the code.</p>\n\n<p><em><strong>Clear Interface is not optional</em></strong><br>\nA clear-cut, consistent interface isn't just a nice-to-have thing. It's vital. If you want to churn out code you can pass on to others, or re-use without having to refactor half of it, you need to stop and think about what data is likely to be passed to your classes<br>\nYou're iterating directories, in search of files. So yes, strings are likely candidates for arguments. As are <code>SplFileInfo</code> instances, don't you think?</p>\n\n<p>Now, to add support for these instances, you have 2 choices: Either check the type of the argument that is passed (<code>$arg instanceof \\SplFileInfo</code>) or <em>create a wrapper</em>.<br>\nIMO, the wrapper is the way to go, as it normalizes your API, allows for type-hints and centralizes all code concerning how you deal with file-paths in a couple of classes. If ever the <code>SplFileInfo</code> class changes, you can update those classes and be done with it all, certain that all other code will work fine.</p>\n\n<p>Read up on what <a href=\"http://www.php.net/manual/en/class.splfileobject.php\" rel=\"nofollow\">the <code>SplFileInfo</code> class</a> can do for you. If you're interested, write a constructor that accepts either an instance of this class or a string, and -if you receive a string- use that to construct an <code>SplFileObject</code> asap.</p>\n\n<p><em><strong>Collector is a container</em></strong><br>\nIf you do set about writing a File-managing lib, this <code>Collector</code> shouldn't contain anything but processed files. It's a data-container, not a data processor.<br>\nYou should consider writing some file-parsers (or <em>\"Adapters\"</em>), that each deal with a specific type of file. They can implement various interfaces, like the <code>ParserInterface</code> for the (and I'm just making these names up as I type) <code>DOMFile</code>, <code>PHPFile</code> and <code>YamlFile</code> classes). This signals users that these classes can process a files content.<br>\nAnother interface could then be <code>CompressorInterface</code>, which might be useful when dealing with gzipped text files.<Br>\nOf course, all these classes can extend from a generic abstract class <code>FileAdapter</code> or something, that specifies generic read-write methods, and perhaps allows the user to change the mode to binary, read-only, or even stream... Just go wild here :)</p>\n\n<p><em><strong>Remember, remember: files are files</em></strong><Br>\nAfter all this talk and suggestions of what you <em>can</em> do, it's important to stress that, while you can do a lot, you can take things to far: these are files, and files mean I/O. If you build an API that lends itself to file usage a bit too well, you could end up with people using files as a replacement for DB storage. Don't.<br>\nIf people might use your API as an alternative to caching, or simple DB's, then you might have over-done it.</p>\n\n<p><em><strong>Copy with pride, but credit</em></strong><Br>\nA lot of open-source projects do offer some classes to read/process files already. There's nothing wrong with looking at those for inspiration. Copy what you need, provided the license permits it. And of course, feel free to contribute, too :)</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-02-03T18:47:35.430", "Id": "68767", "Score": "0", "body": "Thanks for the review and suggestions. I always knew there were a couple of code smells surrounding that class and one like it in my codebase. What I was trying to achieve was an immutable class architecture. A sort of black box, something goes in, something comes out (maybe I'm more suited to functional programming). The reason is sympathy for my client code. One thing I hate to do is have 3 or 4 lines of code mutating a class with setters and then a final getter before doing a task. But your examples were good and this is something I mostly struggle with." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-02-04T07:18:12.760", "Id": "69896", "Score": "0", "body": "@DingoEgret: It's not you, a method/class should be X goes in, Y comes out. Always. That's why I suggested specific classes for each type of output/each action. That's what the SRP is all about. PS: I like functional programming, too, that needn't be a hindrance, though" } ], "meta_data": { "CommentCount": "2", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-02-03T12:37:45.507", "Id": "40732", "ParentId": "40721", "Score": "3" } } ]
{ "AcceptedAnswerId": "40732", "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-02-03T06:36:23.263", "Id": "40721", "Score": "4", "Tags": [ "php", "object-oriented", "file-system" ], "Title": "Collecting files from a particular directory" }
40721
<p>I'm writing a twirling cursor, which is a cursor that twirls in place in the console. In Forth, this takes just 3 lines, whereas in Python3 I have this:</p> <pre><code>from time import sleep # sleep(sec) import sys def flash(c): """Shows character c momentarily.""" # backspace ($8) and sleep(sec) keep it in place and slow enough to see print(c,end=""); sys.stdout.flush(); sleep(0.05); print(chr(0x8),end=""); sys.stdout.flush() return def halftwirl(): """Twirls the cursor in place half-way i.e. | / - \.""" flash(chr(0x7C)); flash(chr(0x2F)); flash(chr(0x2D)); flash(chr(0x5C)); return def twirl(n): """Twirls cursor in place n times.""" for i in range(2*n): halftwirl() return # Programme print(twirl.__doc__) twirl(5) </code></pre> <p>Whilst this works, and is no different from Forth in terms of code structure (see the Forth below), it is still, to my eyes, quite verbose.</p> <p>In Forth, where there is no expense in calling subroutines, one naturally does something like this:</p> <blockquote> <pre><code>\ Building Blocks 0x7C constant .| 0x2F constant ./ 0x2D constant .- 0x5C constant .\ 0x8 constant .del \ backspace delete : flash ( c -- ) emit 50 ms .del emit ; \ show character momentarily : half-twirl ( -- ) .| flash ./ flash .- flash .\ flash ; \ half-twirl cursor in place : twirl ( n -- ) 0 do half-twirl half-twirl loop ; \ twirl cursor in place n times </code></pre> </blockquote> <p><strong>Questions:</strong></p> <ol> <li><p>Is the cost of calling subroutines in Python cheap enough to support refactoring, i.e. pulling out <code>flash()</code> as its own subroutine, <code>halftwirl()</code> as its own, and making <code>twirl()</code> call these within its inner loop? </p></li> <li><p>Is the resulting verbosity as compared to similarly factored Forth code just the cost of doing business when writing in Python compared to Forth, or am I missing some Python idioms?</p></li> </ol>
[ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-02-03T16:45:27.050", "Id": "68738", "Score": "2", "body": "Python functions return `None` by default, so unless you are planning on returning a value, don't include a return statement." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-02-11T20:28:27.460", "Id": "71180", "Score": "0", "body": "Don't put more than one statement on a single line. `print(c,end=\"\"); sys.stdout.flush(); sleep(0.05); print(chr(0x8),end=\"\"); sys.stdout.flush()` is not clear at all." } ]
[ { "body": "<p>Repetitive code should be put in a loop.</p>\n\n<p>Most programmers don't have the ASCII table memorized. Why not use literal characters instead?</p>\n\n<p>Flush can be handled by <code>print()</code> itself. I don't believe you need to flush after backspacing.</p>\n\n<p>The speed of the rotation can be made overridable with a trivial change.</p>\n\n<pre><code>from time import sleep \n\ndef halftwirl(delay=0.05):\n \"\"\"Twirls the cursor in place half-way i.e. | / - \\.\"\"\"\n for glyph in '|/-\\\\':\n print(glyph, end='', flush=True)\n sleep(delay) # sleep(sec) to keep it slow enough to see\n print('\\b', end='') # backspace to keep it in place\n</code></pre>\n\n<p>To answer your questions:</p>\n\n<ol>\n<li>Performance is just not an issue here. The main slowdowns would be the deliberate <code>sleep()</code> call and I/O overhead.</li>\n<li>See the rewrite above.</li>\n</ol>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-02-03T18:47:02.860", "Id": "68766", "Score": "3", "body": "The string constant would look nicer if written `r'|/-\\'`." } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-02-03T10:06:16.157", "Id": "40725", "ParentId": "40724", "Score": "4" } } ]
{ "AcceptedAnswerId": "40725", "CommentCount": "2", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-02-03T09:43:06.240", "Id": "40724", "Score": "3", "Tags": [ "python", "python-3.x", "console" ], "Title": "Twirling cursor" }
40724
<p>I'm learning basic algorithms and implementing them in Python. Critiques needed/welcome.</p> <pre><code>import pudb; pu.db import random def selection_sort(list_): """Implement selection_sort algorithm: iterate L to R in list, grab value if greatest and inserting into correct pos. After each loop, decrement length of iterated list by 1""" val_list, greatest = list(range(len(list_))), 0 for num in range(len(list_)): greatest = val_list[-1] for val in val_list: if list_[greatest] &lt; list_[val]: greatest = val if list_[greatest] &gt; list_[val_list[-1]]: list_.insert(val, list_.pop(greatest)) val_list.remove(val) return list_ if __name__ == '__main__': unsorted = list(range(9)) random.shuffle(unsorted) assert selection_sort(unsorted) == list(range(9)) </code></pre>
[]
[ { "body": "<p>Most of my <a href=\"https://codereview.stackexchange.com/a/40736/11728\">comments on your previous question</a> apply here too, so I'll just summarize them quickly:</p>\n\n<ol>\n<li><p>Debugging code that you forgot to remove.</p></li>\n<li><p>Docstring written from the implementer's point of view.</p></li>\n<li><p>Variable name respelled to avoid shadowing a built-in.</p></li>\n<li><p>Test case not organized into a unit test.</p></li>\n<li><p>Test case not very stringent (just 9 items).</p></li>\n</ol>\n\n<p>In addition:</p>\n\n<ol>\n<li><p>Given an array of length <em>n</em>, your algorithm makes <em>n</em> passes over the array, and in pass <em>i</em> it finds the <i>i</i>th largest item in the array (which at that point in the algorithm is the largest item in the first <em>n</em> − <em>i</em> positions) and swaps it into the position <em>n</em> − <em>i</em> − 1. This ought to be simple, but it's implemented in a very complex way, via the list <code>val_list</code> of indexes.</p>\n\n<p>Here's a much simpler implementation:</p>\n\n<pre><code>def selection_sort(seq):\n \"\"\"Sort the mutable sequence seq in place and return it.\"\"\"\n for i in reversed(range(len(seq))):\n # Find the index of greatest item in seq[:i+1].\n greatest = 0\n for j in range(1, i + 1):\n if seq[j] &gt; seq[greatest]:\n greatest = j\n seq[i], seq[greatest] = seq[greatest], seq[i]\n return seq\n</code></pre>\n\n<p>Note that I've avoided testing <code>seq[greatest] &gt; seq[i]</code> before doing the swap, because I know that the only way this condition can fail is if <code>greatest == i</code>, and then the swap has no effect. So it's simplest to skip the test.</p>\n\n<p>I could simplify this still further using Python's built-in function <a href=\"http://docs.python.org/3/library/functions.html#max\" rel=\"nofollow noreferrer\"><code>max</code></a>:</p>\n\n<pre><code>def selection_sort(seq):\n \"\"\"Sort the mutable sequence seq in place and return it.\"\"\"\n for i in reversed(range(len(seq))):\n greatest = max(range(i + 1), key=seq.__getitem__)\n seq[i], seq[greatest] = seq[greatest], seq[i]\n return seq\n</code></pre>\n\n<p>But this seems like it's avoiding the spirit of the exercise: I mean, if I can use <code>max</code>, then why not <a href=\"http://docs.python.org/3/library/functions.html#sorted\" rel=\"nofollow noreferrer\"><code>sorted</code></a>?</p></li>\n</ol>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-02-03T14:25:55.333", "Id": "40743", "ParentId": "40734", "Score": "11" } } ]
{ "AcceptedAnswerId": "40743", "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-02-03T12:56:13.913", "Id": "40734", "Score": "5", "Tags": [ "python", "algorithm", "sorting" ], "Title": "Selection sort algorithm in Python" }
40734
<p>So I've been kind of irritated with my logging recently as I find myself copying and pasting the same kinds of generic messages around to lots of different methods or retyping them ever so <em>slightly</em> differently (when they ought to be identical).</p> <p>Hence, I created this kind of framework:</p> <pre><code>public class Log { // other logging utility methods truncated public enum Message { //Main PROGRAM_EXIT ("Exiting program, return code = {0}"), THREAD_INTERRUPTED ("Thread interrupted while {0}"), FATAL_TERMINATING_ERROR ("Fatal exception thrown through entire stack: {0}"), SHUTDOWN_HOOK_EXCEPTION ("Exception while attempting to gracefully exit: {0}"), IO_READ_ATTEMPT ("Attempting to read file: {0}"), IO_READ_FAILURE ("Unable to read from file: {0}"), IO_WRITE_ATTEMPT ("Attempting to write to file: {0}"), IO_WRITE_FAILURE ("Unable to write to file: {0}"), IOEXCEPTION ("IOException while {0} to {1} : {2}"), private final String text; private Message(String text) { this.text = text; } @Override public String toString() { return text; } public String format(Object ... args) { String returnValue = toString(); for(int i = 0; i &lt; args.length; i++) { String placeholder = "{" + i + "}"; if(!returnValue.contains(placeholder)) { LOGGER.error("Too many arguments supplied to generateMessage() from " + getCallingMethodName()); LOGGER.error(" -- " + name()); break; } returnValue = returnValue.replace("{" + i + "}", args[i] == null ? "null" : args[i].toString()); } return returnValue; } } } </code></pre> <p>It's then invoked like the following:</p> <pre><code>private static final String FILE_PATH = "resources/something.txt"; //... LOGGER.error(Log.Message.IO_READ_FAILURE.format(FILE_PATH)); </code></pre> <p>... which would log ...</p> <blockquote> <p>Unable to read from file: resources/something.txt</p> </blockquote> <p>It all works fine, but it feels a little too verbose at times for what I'm trying to accomplish, like I've tacked on a bit too many nuts and bolts. Like I've gone deer hunting with a .50 cal or something.</p> <p>Any suggestions to improve this? The same messages <em>are</em> used redundantly in several places, so I am seeing some value out of it, but I'm not sure if there's a good way to make this still more clean or otherwise accomplish what I'm trying to do in a more succinct way.</p> <p>If it's relevant, I'm using <code>log4j</code>.</p>
[]
[ { "body": "<p>Well,</p>\n\n<p>It does what it is supposed to and works fine. \nMy comment is more regarding the logger class than the enum of messages.</p>\n\n<p>You indicated you use this logger throughout your project, well if you change your messages add/remove some you would have to recompile a lot of stuff. </p>\n\n<p>Personally I would have an interface for logger and instead of reading strings read in an exception.</p>\n\n<p>you could then choose to make some of the repetitious exceptions reusable in a similar fashion to above. </p>\n\n<p>This would decouple everything.</p>\n\n<p>The advantage would be that if one message changed only that file would, if you wanted to add an exception...just throw a different exception and finally if you wanted to change your logging means you just have to change your implementation. </p>\n\n<pre><code>interface Logger\n{\n Log(Exception ex);\n}\n\nclass ConsoleLogger implements Logger { ... }\n\npublic class Main\n{\n Logger logger = new ConsoleLogger();\n\n\n public static void main(string[] args)\n {\n try\n {\n ...\n }catch(Exception ex)\n { \n logger.Log(ex);\n }\n\n }\n\n}\n</code></pre>\n\n<p>Of course if your logger is not only logging exceptions but messages also this may require a reworking to support maybe a custom <code>LogMessage</code> interface or something and it could either be a message or a exception...</p>\n\n<p>but that could very well be too verbose. in either case regardless of how you send your messages the point I wanted to highlight was for something as transmutable as a Logger with static types,</p>\n\n<p>a more malleable option will save you headaches in the long run...</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-02-03T14:45:43.677", "Id": "40744", "ParentId": "40738", "Score": "2" } }, { "body": "<p>You don't need to re-implement <a href=\"http://docs.oracle.com/javase/7/docs/api/java/text/MessageFormat.html\" rel=\"nofollow\"><code>MessageFormat</code></a>. It is much more powerful than what your implementation provides.</p>\n\n<hr>\n\n<p>You don't show us the class of <code>LOGGER</code>, but based on the fact that you have a <code>Log</code> class, I suspect you are not using a logging library. I highly recommend you look into using one instead of implementing your on custom implementation. </p>\n\n<p>If you are using a logging library, you are abstracting to much away from the library. All of the frameworks I've used support message formating and detailed exception logging (with stack traces).</p>\n\n<hr>\n\n<p>The problem you are really trying to solve here is to allow yourself to reuse a number of common log message formats. This can be done with a simple set of Strings set to <code>public static final</code>.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-02-03T15:33:17.777", "Id": "68718", "Score": "0", "body": "LOGGER is `org.apache.log4j.Logger`" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-02-03T15:40:29.210", "Id": "68720", "Score": "0", "body": "I actually didn't know `MessageFormat` was a thing in Java. I was emulating a pattern I saw in C#. Haha. Nice." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-02-03T15:44:24.880", "Id": "68723", "Score": "0", "body": "@JeffGohlke: A quick search shows that log4j 1.x does not support message formating. log4j 2.x will be out of beta soon and does support it. Another option is to use [slf4j](http://www.slf4j.org/) for a consistent logging API, that supports message formating, and will let you migrate from log4j 1.x to 2.x, or a different framework, without any changes to your code." } ], "meta_data": { "CommentCount": "3", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-02-03T15:19:54.503", "Id": "40745", "ParentId": "40738", "Score": "3" } }, { "body": "<p>Using the same log message too many times could indicate that the code has some duplication. If that's the case you might want to solve this instead of curing the symptoms. For example, you could write a file reader method/class, modify the project to read files using only this class. (There are existing libraries for that.) Only this class should log messages like <code>IO_READ_ATTEMPT</code> and <code>IO_READ_FAILURE</code> (or throw exceptions with these messages) because every IO read errors happens in it. (It would improve the abstraction level of the application too. For example, you could easily switch to another file storage from file system since every storage logic would be in the same place.)</p>\n\n<hr>\n\n<p>If you don't know SLF4J, check <a href=\"http://slf4j.org/faq.html#logging_performance\" rel=\"nofollow\">its parametrized messages</a>. For example, in SLF4J,</p>\n\n<pre><code>logger.debug(\"The entry is {}.\", entry);\n</code></pre>\n\n<p>calls <code>entry.toString()</code> only, when debug logging is enabled. Otherwise, it does not do any string concatenation/processing.</p>\n\n<hr>\n\n<p>I would consider another approach too: wrap the <code>Logger</code> instance, for example:</p>\n\n<pre><code>public class FileOperationsLogger {\n\n private final Logger logger;\n\n public FileOperationsLogger(Logger logger) {\n this.logger = checkNotNull(logger, \"logger cannot be null\");\n }\n\n // delegate error/warn/info/debug methods to the logger instance\n\n public void logIoReadFailure(final String filename) {\n logger.error(\"Unable to read from file: {}\", filename);\n }\n\n // ... other specific log methods with messages\n}\n</code></pre>\n\n<p>It would provide type safety (<code>filename</code> could be only String).</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-02-03T15:46:35.023", "Id": "40750", "ParentId": "40738", "Score": "2" } } ]
{ "AcceptedAnswerId": "40745", "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-02-03T13:46:40.947", "Id": "40738", "Score": "3", "Tags": [ "java", "strings", "formatting", "logging" ], "Title": "Any recommendations to improve this logging framework? Or is it overkill?" }
40738
<blockquote> <p>Write versions of the library functions <code>strncpy</code>, <code>strncat</code> and <code>strncmp</code>, which operate on the most <code>n</code> characters of their argument strings. For example, <code>strncpy(s, t, n)</code> copies at most <code>n</code> characters of <code>t</code> to <code>s</code>. Full Description in Appendix B.</p> </blockquote> <p>Here is my implementation of <code>strncmp</code>:</p> <pre><code>int custom_strncmp(const char *s, const char *t, size_t n) { while(n--) { if(*s != *t) { return *s - *t; } else { ++s; ++t; } } return 0; } </code></pre> <p>The <code>while</code> loop will run until <code>n</code> reaches the value <code>0</code>, or until the characters that <code>s</code> and <code>t</code> point to are not equal. At each iteration I check if the <code>*s</code> and <code>*t</code> are equal; if they are, I increment <code>s</code> and <code>t</code>. If they are not equal, I return their difference. After the loop stops, the value <code>0</code> is returned.</p> <p>Here is my implementation of <code>strncat</code>:</p> <pre><code>char *custom_strncat(char *s, const char *t, size_t n, size_t bfsize) { size_t slen = strlen(s); char *pend = s + slen; if(slen + n &gt;= bfsize) return NULL; while(n--) *pend++ = *t++; return s; } </code></pre> <p>This version of <code>strncat</code> is a secure one. The first <code>if-statement</code> checks if there is enough space in the <code>s</code> buffer to store the contents of <code>t</code>. The <code>while</code> loop will run until <code>n</code> reaches the value <code>0</code>. At each iteration the value that <code>t</code> points to is copied in to <code>*s</code>. After the loop stops, is returned a pointer to the result.</p> <p>Here is my implementation of <code>strncpy</code>:</p> <pre><code>char *custom_strncpy(char *s, const char *ct, size_t n) { char *saver = s; while(n--) *saver++ = *ct++; *saver = '\0'; return s; } </code></pre> <p>The <code>while</code> loop will run until <code>n</code> reaches the value <code>0</code>, at each iteration the current character that <code>ct</code> points to is copied in <code>*saver</code>. After the loop stops, the <code>'\0'</code> is copied in <code>*saver</code> and a pointer to the result is returned.</p> <p>The exercise can be found at page 121 in K&amp;R second edition.</p>
[]
[ { "body": "<p>I think you've misinterpreted the <a href=\"http://www.cplusplus.com/reference/cstring/strncat/\" rel=\"nofollow noreferrer\">definition of strncat</a>, which says,</p>\n\n<blockquote>\n <p>Appends the first <code>num</code> characters of source to destination, plus a terminating null-character.\n If the length of the C string in source is less than <code>num</code>, only the content up to the terminating null-character is copied.</p>\n</blockquote>\n\n<p><code>n</code> is the maximum number of characters in source you you want to copy, and <code>bfsize</code> doesn't exist in the standard version of <code>strncat</code>.</p>\n\n<pre><code>char destination[256];\nstrpy(destination, \"foo\");\nstrncat(destination, \"bar\", 2);\n// expect destination should now contain \"fooba\" !\n</code></pre>\n\n<p>It's good of you to write a custom version with an extra parameter to make it safe, but that's not what the question asked for.</p>\n\n<p>See also <a href=\"http://www.gsp.com/cgi-bin/man.cgi?topic=Strn\" rel=\"nofollow noreferrer\">Manual Reference Pages - Strn (3)</a> (e.g. <code>Strncat</code> instead of <code>strncat</code>); or, <a href=\"http://msdn.microsoft.com/en-us/library/tbyd7s1y.aspx\" rel=\"nofollow noreferrer\">the Microsoft versions</a> of the 'safe' functions have <code>_l</code> as a suffix.</p>\n\n<p>I'm not sure that returning null and doing no copy is the standard way to avoid buffer overflow.</p>\n\n<hr>\n\n<p>In your <code>custom_strncmp</code> method, I'm not sure what correct behaviour should be if you call</p>\n\n<pre><code>strncmp(\"foo\", \"foo\", 10);\n</code></pre>\n\n<p>Your function might return 0 or non-zero, or crash, depending on what's after the end of the string.</p>\n\n<p>You could perhaps write it more elegantly as a for loop:</p>\n\n<pre><code>for ( ; n--; ++s, ++t) {\n if(*s != *t) {\n return *s - *t;\n }\n}\n</code></pre>\n\n<hr>\n\n<p>In <code>custom_strncat</code> you don't handle the condition where <code>n &gt; strlen(t)</code>.</p>\n\n<hr>\n\n<p>Your parameters could (should) be better named, e.g. <code>source</code> and <code>destination</code>. Parameter names are important (even more important than good names for local variables) because they may be the only documentation about how the function should be called.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2014-02-03T15:32:13.977", "Id": "40747", "ParentId": "40741", "Score": "7" } }, { "body": "<p>Years later, but for completeness ... <code>custom_strncpy</code> above is not compatible with standard <code>strncpy</code>.</p>\n\n<ol>\n<li>It writes <code>n+1</code> characters into destination (only <code>n</code> is correct).</li>\n<li>It reads past <code>\\0</code> of source string.</li>\n<li>It does not <code>\\0</code>-pad destination string if source is smaller.</li>\n<li>it always <code>\\0</code> terminates. (strncpy will not in case strlen(source) >= <code>s</code>).</li>\n</ol>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-09-05T15:02:22.353", "Id": "203186", "ParentId": "40741", "Score": "4" } } ]
{ "AcceptedAnswerId": "40747", "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2014-02-03T14:09:26.330", "Id": "40741", "Score": "8", "Tags": [ "c", "beginner", "strings" ], "Title": "implementations of strncmp, strncat, strncpy" }
40741
<p>I am working on a small custom Markup script in Java that converts a Markdown/Wiki style markup into HTML.</p> <p>The below works, but as I add more Markup I can see it becoming unwieldy and hard to maintain. Is there is a better, more elegant, way to do something similar? </p> <pre><code>private String processString(String t) { t = setBoldItal(t); t = setBold(t); t = setItal(t); t = setUnderline(t); t = setHeadings(t); t = setImages(t); t = setOutLinks(t); t = setLocalLink(t); return t; } </code></pre> <p>And on top of it, passing in the string itself and setting it back to the same string just doesn't feel right. But, I just don't know of any other way to go about this.</p>
[ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-02-03T19:29:44.610", "Id": "68772", "Score": "0", "body": "Could you provide implementation, at least some examples, of the different `set` methods you're calling?" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-02-03T23:46:06.817", "Id": "68818", "Score": "0", "body": "it's not the same String, as Strings are immutable, so you don't have to worry about this part. You could name your return value something else, if that helps." } ]
[ { "body": "<p>This sounds like a case where you should encapsulate the data with a <a href=\"http://en.wikipedia.org/wiki/Decorator_pattern\" rel=\"nofollow\">'Decorator Pattern'</a>.</p>\n\n<p>You should declare a simple interface such as:</p>\n\n<pre><code>public interface StyledString {\n public String toFormatted();\n public StyledString getSource();\n}\n</code></pre>\n\n<p>Then create a concrete class for each style you have:</p>\n\n<pre><code>public class BoldStyle implements StyledString {\n private final StyledString source;\n\n public BoldStyle(StyledString source) {\n this.source = source;\n }\n\n public String toFormatted() {\n return \"&lt;b&gt;\" + source.toFormatted() + \"&lt;/b&gt;\";\n }\n\n public StyledString getSource() {\n return source;\n }\n\n}\n</code></pre>\n\n<p>You should also have a 'NoStyle' class that takes a raw String input, and returns a null getSource();</p>\n\n<p>using this system you can easily add Styles, and you can have styles that join phrases, etc.....</p>\n\n<p>Also, you can add the styles together in a way that makes decomposing the value easier at a later point, and you only need to add/wrap the styles that you want.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-02-03T15:41:19.540", "Id": "40748", "ParentId": "40746", "Score": "3" } }, { "body": "<p>You could create a <code>StringProcessor</code> interface:</p>\n\n<pre><code>public interface StringProcessor {\n\n String process(String input);\n}\n\n\npublic class BoldProcessor implements StringProcessor {\n\n public String process(final String input) {\n ...\n }\n}\n</code></pre>\n\n<p>and create a <code>List</code> from the available implementations:</p>\n\n<pre><code>final List&lt;StringProcessor&gt; processors = new ArrayList&lt;StringProcessor&gt;();\nprocessors.add(new ItalicProcessor());\nprocessors.add(new BoldProcessor());\n...\n</code></pre>\n\n<p>and use it:</p>\n\n<pre><code>String result = input; \nfor (final StringProcessor processor: processors) {\n result = processor.process(result);\n}\nreturn result;\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-02-03T20:27:55.920", "Id": "68783", "Score": "4", "body": "Great solution. I recommend encapsulating all this into a new object that contains a list of processors so that you can instantiate these objects from config files. Once you've done that you will easily be able to change your text attributes without recompiling." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-02-04T07:58:19.863", "Id": "69899", "Score": "4", "body": "Just a note, as this is the decorator pattern. You don't need BoldAndItalicProcessor, you just need BoldProcessor and ItalicProcessor." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-02-04T08:33:13.233", "Id": "69900", "Score": "1", "body": "@SilviuBurcea: Thank you, good point, I've updated the post." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-02-04T20:19:57.137", "Id": "70023", "Score": "0", "body": "@SilviuBurcea Actually, that's a different tag in what I'm doing. It adds in `<span class=\"boldclass italclass\">stuff</span>` when it finds `***stuff***` instead of just one, then the other. Which, I **should** really detect if something is text first then add in the respective css classes to the tag (and I will in the future). But for now, this works and it's an easier implementation." } ], "meta_data": { "CommentCount": "4", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-02-03T15:54:30.820", "Id": "40751", "ParentId": "40746", "Score": "17" } }, { "body": "<p>If you want to process a language, even a simple one like a Wiki Markup, you should eventually write a proper parser, not do step-by-step replacement, nor chain a number of individual processors, no matter how fancy their implementation.</p>\n\n<p>You can go with the fully generic approach, generate an AST from the markup (this would look similar to @rolfl's <code>StyledString</code>), and then use an AST serializer to create the end result (but for efficiency's sake, please append to a <code>StringBuilder</code> instead of repeatedly creating new strings). This allows you to use multiple serializers; e.g. if at one point you want to create PDF instead of HTML, this gives you a huge advantage. Your AST nodes should implement the visitor pattern for this purpose. (The serializer would be the visitor.)</p>\n\n<p>But that would probably be overkill here. A simple parser that outputs the HTML as it parses would be simpler and probably sufficient.</p>\n\n<p>You can use parser generators like ANTLR to generate the parser, or you can hand-write a parser.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-02-03T19:19:24.030", "Id": "68771", "Score": "0", "body": "This is something I will definitely keep in mind. Hopefully I will get a chance to do something like this. But, it's very much overkill at the moment because what I'm working on is still in the initial prototyping phase and I don't want to get too attached to it. Thank you for leading me in the proper direction." } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-02-03T17:50:40.330", "Id": "40765", "ParentId": "40746", "Score": "7" } }, { "body": "<p>I like @palacsint's approach but I just have one thing to add, you can probably do most of the processing with the same class.</p>\n\n<pre><code>public class TagProcessor implements StringProcessor {\n private final String wrapWith;\n public TagProcessor(String wrapWith) {\n this.wrapWith = wrapWith;\n }\n @Override\n public String process(String input) {\n return \"&lt;\" + wrapWith + \"&gt;\" + input + \"&lt;/\" + wrapWith + \"&gt;\";\n }\n}\n\nprocessors.add(new TagProcessor(\"i\"));\nprocessors.add(new TagProcessor(\"b\"));\n</code></pre>\n\n<p>I also believe that you can add generalize a lot of the functionality for other processors into a proper class and use it's constructor to send proper parameters. (Wrapping in <code>&lt;div class=\"someclass\"&gt;...&lt;/div&gt;</code> for example).</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-02-03T19:04:42.960", "Id": "40770", "ParentId": "40746", "Score": "4" } } ]
{ "AcceptedAnswerId": "40751", "CommentCount": "2", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-02-03T15:30:13.990", "Id": "40746", "Score": "12", "Tags": [ "java", "design-patterns", "strings" ], "Title": "Better way to manipulate this string in sequence?" }
40746
<p>I saw this UI for a mobile app, but I reverse engineered it for the web. This is how it looks in my <a href="http://codepen.io/JGallardo/pen/EHDme" rel="nofollow noreferrer">CodePen</a></p> <p><img src="https://i.stack.imgur.com/n2fOa.png" alt="live demo"></p> <p>This would be either a favorites or featured list locations to travel to. I decided to go with a <code>&lt;ul&gt;</code> with class of "locations" </p> <p><strong>HTML</strong></p> <pre><code>&lt;ul class="locations"&gt; &lt;li&gt; &lt;a href="#"&gt; &lt;!-- url would be generated--&gt; &lt;img src="http://shared-assets.s3.amazonaws.com/codepen/img/new-york-320x140.jpg"&gt; &lt;span&gt;New York&lt;/span&gt; &lt;/a&gt; &lt;/li&gt; &lt;li&gt; &lt;a href="#"&gt; &lt;!-- url would be generated--&gt; &lt;img src="http://shared-assets.s3.amazonaws.com/codepen/img/san-francisco-320x140.jpg"&gt; &lt;span&gt;San Francisco&lt;/span&gt; &lt;/a&gt; &lt;/li&gt; &lt;li&gt; &lt;a href="#"&gt; &lt;!-- url would be generated--&gt; &lt;img src="http://shared-assets.s3.amazonaws.com/codepen/img/paris-320x140.jpg"&gt; &lt;span&gt;Paris&lt;/span&gt; &lt;/a&gt; &lt;/li&gt; &lt;li&gt; &lt;a href="#"&gt; &lt;!-- url would be generated--&gt; &lt;img src="http://shared-assets.s3.amazonaws.com/codepen/img/london-320x140.jpg"&gt; &lt;span&gt;London&lt;/span&gt; &lt;/a&gt; &lt;/li&gt; &lt;/ul&gt; </code></pre> <p>In Production, I will be building this with Meteor which uses MustacheJS templates. So this is likely how I will structure the list. </p> <p><strong>MustacheJS template</strong> (proposed)</p> <pre><code>&lt;template name="featuredLocations"&gt; &lt;ul class="locations"&gt; &lt;li&gt; &lt;a href="{{{locationLink}}}"&gt; &lt;img src="{{{locationImage}}}"&gt; &lt;span&gt;{{city}}&lt;/span&gt; &lt;/a&gt; &lt;/li&gt; &lt;/ul&gt; &lt;/template&gt; </code></pre> <p><strong>CSS</strong></p> <pre><code>.locations { list-style-type: none; padding-left: 0; margin: 0; } .locations &gt; li { border-bottom: 1px #dd4977 solid; height: 136px; width: 100%; position: relative; overflow:hidden; } .locations li a { background-color: #777; display: block; height: 100%; postion: relative; text-decoration: none; z-index: 1; } .locations &gt; li &gt; img { width: 100%; height: 135px; position: absolute; top:0; left: 0; right: 0; z-index: 10; } .locations &gt; li &gt; a &gt; span { background-color: #dd4977; color: #fff; font-size: 21px; letter-spacing: 1px; padding: 3px 5px 0 5px; position: absolute; bottom: 0; left: 6px; z-index: 20; } </code></pre> <p><br></p> <hr> <p><em>The actual images in production will be bigger and will scale down according to the device. There will be media queries that are not shown here.</em> </p>
[]
[ { "body": "<p>The use of <code>ul</code> seems appropriate. My concern with using <code>&lt;img&gt;</code>s would be with the image dimensions. From what I can see above, unless you create your images specifically in those dimensions, it will become a pain to ensure they scale correctly.</p>\n\n<p>I've found that if you want to preserve a predetermined width and height for your images without ruining the aspect ratio it's almost always easier to use <code>background-image</code> rather than <code>&lt;img&gt;</code> tags. </p>\n\n<p>Using <code>background-size: cover</code> you can ensure that the image covers the available space, without losing the ratio:</p>\n\n<blockquote>\n <p>The cover value specifies that the background image should be sized so\n that it is as small as possible while ensuring that both dimensions\n are greater than or equal to the corresponding size of the container</p>\n</blockquote>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-02-03T17:26:59.497", "Id": "68752", "Score": "0", "body": "right, well the idea was that images that are selected would be cropped down to a certain dimension to ensure that they look good at various scales." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-02-03T17:29:36.280", "Id": "68753", "Score": "1", "body": "I think that `cover` will serve you better and be much simpler to implement :)" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-02-03T18:57:53.950", "Id": "68768", "Score": "2", "body": "background-size: cover is specially helpful when you want to scale the image, but *don't know* what will be the *dominant* dimension. That is, if you need to scale to fit the width, or the height." } ], "meta_data": { "CommentCount": "3", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-02-03T17:24:35.977", "Id": "40762", "ParentId": "40756", "Score": "7" } }, { "body": "<p>With my customers, I often run into the trouble that background images are not printed by default on most browsers (but it can be enabled in the print options).</p>\n\n<p>This is an other option to let the images scale to the available space:</p>\n\n<pre><code>img{\n max-width:100% !important;\n height: auto;\n display: block;\n}\n</code></pre>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-06-30T06:37:23.520", "Id": "55663", "ParentId": "40756", "Score": "1" } } ]
{ "AcceptedAnswerId": "40762", "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-02-03T16:55:13.190", "Id": "40756", "Score": "5", "Tags": [ "html", "css", "mustache" ], "Title": "Was this use of <img> tags in this HTML over background images better?" }
40756
<p>I have a click event that calls a function which makes some CSS changes (acts on Text in 3 unique text elements). </p> <p>The function (below) works, but is lacking a 'restore default' function (to return the text to its original state), AND is in dire need of refactoring. </p> <p>Q: How can the original state of ALL text elements be restored once user clicks away from this section?</p> <p>Here is the partially working, ugly function: </p> <pre><code>function txtResize() { var clicked = this.id; if (clicked == "Text1") { $("#" + clicked).css("opacity", "1"); $("#Text2, #Text3").css("opacity", "0.2"); } else if (clicked == "Text2") { $("#" + clicked).css("opacity", "1"); $("#Text1, #Text3").css("opacity", "0.2"); } else if (clicked == "Text3") { $("#" + clicked).css("opacity", "1"); $("#Text1, #Text2").css("opacity", "0.2"); } // code above is ok, below does not work else if ( !(clicked == "Text1") &amp;&amp; !(clicked == "Text2") &amp;&amp; !(clicked == "Text3") ) { $("#Text1, #Text2, #Text3").css("opacity", "1"); // return to default state } }; </code></pre> <p>UPDATE: (20 Jan) - Have improved the code, but it still somewhat clunky and involves two distinct functions.</p> <pre><code>function txtResize() { var clicked = this.id; if (clicked === "Text1" || clicked === "Text2" || clicked === "Text3" ) { $("#Text1, #Text2, #Text3").animate({"opacity": "0.2"}, 500) $("#" + clicked).animate({"opacity": "1"}, 200); } }; function txtRestore(){ $("#Text1, #Text2, #Text3").animate({"opacity": "1"}, 1000); }; </code></pre>
[ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-01-16T15:22:22.877", "Id": "68747", "Score": "0", "body": "Perhaps the note on refactoring could be de-emphasized but the main issue is that my text does not return to its original state (two of the paragraphs remain opacity = unreadable. I want the last statement in if/else to restore text back, and figured in doing so many would point out how badly the code needs refactoring so I threw that in as well. Will edit to ensure focus is on restoring the default value of text, not refactoring." } ]
[ { "body": "<p>as a first step I would rewrite the last if statement</p>\n\n<pre><code>else if ((clicked =! \"Text1\") &amp;&amp; (clicked != \"Text2\") &amp;&amp; (clicked != \"Text3\") ) \n {\n $(\"#ActText, #AdaptText, #PlanText\").css(\"opacity\", \"1\"); // return to default state\n } \n</code></pre>\n\n<p>After that you could rewrite it as a switch statement: <a href=\"http://www.w3schools.com/js/js_switch.asp\" rel=\"nofollow\">http://www.w3schools.com/js/js_switch.asp</a> </p>\n\n<p>edit : this would be better...</p>\n\n<pre><code>var textArray = new Array(\"Text1\",\"Text2\",\"Text3\");\nif($.inArray(clicked,textArray){\n $(\"#Text2, #Text3\").css(\"opacity\", \"1\");\n}\nelse {\n $(\"#\" + clicked).css(\"opacity\", \"0.2\");\n}\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-01-16T16:19:24.790", "Id": "68748", "Score": "0", "body": "Your solution itself needs refactoring, I would use an array and `$.inArray()`." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-01-16T16:46:50.973", "Id": "68749", "Score": "0", "body": "Thanks Blacksheep, I didn't even notice that each action in the if statements was the same." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-01-17T01:09:20.367", "Id": "68750", "Score": "0", "body": "The text with opacity = 1 should stand alone, the other two text elements should take opacity 0.2. I think this solution has it backwards, meaning if text2 or text3 is clicked, then what? IOW, shouldn't #text2 and #text3 also be variables?" } ], "meta_data": { "CommentCount": "3", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-01-16T15:14:54.587", "Id": "40760", "ParentId": "40759", "Score": "3" } }, { "body": "<p>Here is an alternative. I do use that technic a lot as it shrinks the amount of code.</p>\n\n<p>The <code>exec</code> function is self invoked and returns a new function (this is <code>closure</code>); so the elements you want to work with are accessible in the inner function.</p>\n\n<pre><code>var exec = (function() {\n var $el = $('#Text1, #Text2, #Text3'); //allows you to use easily .siblings later \n return function(id) { //closure\n $el.filter(function() { return this.id === id; }).css(\"opacity\", \"1\");\n $el.siblings().css(\"opacity\", \"0.2\");\n };\n})(); //self invoked: it returns a new function but has access to $el\n\nvar rollback = function() {\n $(\"#ActText, #AdaptText, #PlanText\").css(\"opacity\", \"1\"); // return to default state\n};\n\n['Text1', 'Text2', 'Text3'].indexOf(this.id) &gt; -1 ? exec(this.id) : rollback(); //indexOf is part oc ECMAscript 5th version. So ensure you can use it or provide an alternative/shim \n</code></pre>\n\n<p>It is not bullet-proof as I didn't test it. But it provides you with a get-go :)</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-01-16T15:35:56.767", "Id": "40761", "ParentId": "40759", "Score": "0" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "1", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-01-16T15:04:16.237", "Id": "40759", "Score": "4", "Tags": [ "javascript", "jquery", "css" ], "Title": "Changing text with a click event: how to restore default state of text in jQuery if/else statement" }
40759
<p>I have started to try and work out the <a href="http://www.topcoder.com/">TopCoder</a> problems. The <a href="http://community.topcoder.com/stat?c=problem_statement&amp;pm=40">"StringDup" problem</a> asks us to:</p> <blockquote> <p>Create a class called StringDup. Given a string made up of ONLY letters and digits, determine which character is repeated the most in the string ('A' is different than 'a'). If there is a tie, the character which appears first in the string (from left to right) should be returned.</p> </blockquote> <p>Is there any way I can make my solution better or more efficient? Is there something that I have missed? I'm new to Java and I thought this would be a good way to learn.</p> <pre><code>public class StringDup { public char getMax(String word) { int characterCount = 0; int maxCharacter = 0; char maxCharacterChar = '.'; char[] cArray = word.toCharArray(); for(int i =0; i &lt; cArray.length; i++) { int characterASCII = (int)cArray[i]; characterCount = 0; //System.out.print("Chracter ASCII: " + characterASCII + "\n"); for(int x = 0; x &lt; cArray.length; x++) { if(characterASCII == (int)cArray[x]) { characterCount ++; //System.out.print("Character Count for " + characterASCII + " " + characterCount + "\n"); if(characterCount &gt; maxCharacter) { maxCharacter = characterCount; maxCharacterChar = cArray[i]; } } } } return maxCharacterChar; } } </code></pre> <p>It is called using the main method.</p> <pre><code>StringDup frequentChar = new StringDup(); System.out.print(frequentChar.getMax("sssdkljgh")); </code></pre>
[]
[ { "body": "<p>Currently it returns <code>.</code> in case of an invalid input (empty string, for example). It's not in the specification, so I think it shouldn't do that. Crash early. It is rather a bug in the client code when it calls the method with invalid input. Clients might produce bigger side-effect on a non-expected <code>.</code> result. I'd throw an <code>IllegalStateException</code> here. See: <em>The Pragmatic Programmer: From Journeyman to Master</em> by <em>Andrew Hunt</em> and <em>David Thomas</em>: <em>Dead Programs Tell No Lies</em>.</p>\n\n<p>If you're allowed to use external libraries you could write it in a higher level of abstraction with Guava's <a href=\"http://docs.guava-libraries.googlecode.com/git/javadoc/com/google/common/collect/LinkedHashMultiset.html\" rel=\"nofollow\"><code>Multiset</code>s</a> and <a href=\"http://docs.guava-libraries.googlecode.com/git/javadoc/com/google/common/collect/Iterables.html\" rel=\"nofollow\"><code>Iterables</code></a>:</p>\n\n<pre><code>import static com.google.common.base.Preconditions.checkArgument;\n\nimport java.util.List;\n\nimport org.apache.commons.lang3.StringUtils;\n\nimport com.google.common.base.CharMatcher;\nimport com.google.common.base.Predicate;\nimport com.google.common.collect.Iterables;\nimport com.google.common.collect.LinkedHashMultiset;\nimport com.google.common.collect.Multiset;\nimport com.google.common.collect.Multisets;\nimport com.google.common.primitives.Chars;\n\npublic class StringDup {\n\n public char getMax(final String word) {\n checkArgument(StringUtils.isNotEmpty(word), \n \"empty input is not allowed\");\n\n final Predicate&lt;Character&gt; allValidPredicate \n = new Predicate&lt;Character&gt;() {\n @Override\n public boolean apply(final Character c) {\n return CharMatcher.JAVA_LETTER_OR_DIGIT.matches(c);\n }\n };\n\n final List&lt;Character&gt; inputCharList \n = Chars.asList(word.toCharArray());\n final Iterable&lt;Character&gt; validInputChars \n = Iterables.filter(inputCharList, allValidPredicate);\n final Multiset&lt;Character&gt; countedChars \n = LinkedHashMultiset.create(validInputChars);\n checkArgument(!countedChars.isEmpty(), \n \"Input does not contain any valid chars: %s\", word);\n final Multiset&lt;Character&gt; highestCountFirst \n = Multisets.copyHighestCountFirst(countedChars);\n return highestCountFirst.iterator().next();\n }\n}\n</code></pre>\n\n<p>Finally, a few unit tests with JUnit to make sure it works as intended:</p>\n\n<pre><code>import static org.junit.Assert.assertEquals;\n\nimport org.junit.Test;\n\npublic class StringDupTest {\n\n @Test(expected = IllegalArgumentException.class)\n public void testNullInput() throws Exception {\n getMax(null);\n }\n\n @Test(expected = IllegalArgumentException.class)\n public void testEmptyStringInput() throws Exception {\n getMax(\"\");\n }\n\n @Test\n public void test() {\n assertEquals('h', getMax(\"asdfffhjhhhhx\"));\n assertEquals('f', getMax(\"asdfffhj#hfhhx\"));\n assertEquals('A', getMax(\"AAaa\"));\n assertEquals('a', getMax(\"AAaaa\"));\n assertEquals('a', getMax(\"a\"));\n assertEquals('a', getMax(\"a2\"));\n assertEquals('2', getMax(\"a22\"));\n }\n\n @Test(expected = IllegalArgumentException.class)\n public void testOnlyInvalidChars() throws Exception {\n getMax(\"#\");\n }\n\n private char getMax(final String input) {\n return new StringDup().getMax(input);\n }\n}\n</code></pre>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-02-03T19:01:53.017", "Id": "40769", "ParentId": "40763", "Score": "3" } }, { "body": "<p>Your algorithm has two loops, and that's really not necessary.</p>\n\n<p>This question is looking for a special 'trick' to be done.... and that trick is to process the data in reverse order....</p>\n\n<p>Consider this loop:</p>\n\n<pre><code>public static char getMax(String word) {\n if (word == null || word.isEmpty()) {\n throw new IllegalArgumentException(\"input word must have non-empty value.\");\n }\n char maxchar = ' ';\n int maxcnt = 0;\n // if you are confident that your input will be only ascii, then this array can be size 128.\n int[] charcnt = new int[Character.MAX_VALUE + 1];\n for (int i = word.length() - 1; i &gt;= 0; i--) {\n char ch = word.charAt(i);\n // increment this character's cnt and compare it to our max.\n if (++charcnt[ch] &gt;= maxcnt) {\n maxcnt = charcnt[ch];\n maxchar = ch;\n }\n }\n return maxchar;\n}\n</code></pre>\n\n<p>note the following things:</p>\n\n<ul>\n<li>validate the input.</li>\n<li>create an array of counters for each character.</li>\n<li>work backwards... if this is the max count (or equal to it) then we have a new winner.</li>\n<li>there is no validation on the input characters .... you should probably limit the chars to the <code>a-zA-Z0-9</code> set that is specified.... the solution above will work for any String.</li>\n</ul>\n\n<p>Some additional notes....</p>\n\n<ul>\n<li>in Java, the standard code style puts the opening <code>{</code> brace on the same line as the block declaration (if condition, method declaration, etc.) Putting the brace on a new line is a <code>C</code> thing to do, and is frowned upon.</li>\n<li><code>x</code> is not a good variable name for anything unless it is a co-ordinate in a multidimensional array (normally linked with <code>(x, y, ...)</code> ). In your use case, you should use the variable <code>j</code> because that is the one that by convention is used inside the <code>i</code> loop.</li>\n</ul>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-02-03T19:21:19.390", "Id": "40771", "ParentId": "40763", "Score": "7" } } ]
{ "AcceptedAnswerId": "40771", "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-02-03T17:43:39.017", "Id": "40763", "Score": "8", "Tags": [ "java", "beginner", "strings", "programming-challenge" ], "Title": "Finding the most common character in a string" }
40763
<p>I have a form, which uses AJAX to send POST data to the following controller method:</p> <pre><code>public function action_sendmail() { $jsonHelper=Loader::helper('json'); $answer = (int) $_POST['security']; if($answer &lt;= 0) $answer = 1; if($answer == 4){ $name = filter_var($_POST['name'], FILTER_SANITIZE_STRING); $email = filter_var($_POST['email'], FILTER_SANITIZE_EMAIL); $message = filter_var($_POST['message'], FILTER_SANITIZE_STRING); $name = strip_tags($name); $email = strip_tags($email); $message = strip_tags($message); $name = str_replace(array("\r", "\n", "%0a", "%0d"), '', stripslashes($name)); $email = str_replace(array("\r", "\n", "%0a", "%0d"), '', stripslashes($email)); $message = str_replace(array("\r", "\n", "%0a", "%0d"), '', stripslashes($message)); if(!filter_var($email, FILTER_VALIDATE_EMAIL)){ echo $jsonHelper-&gt;encode(t("Wrong email address.")); die; } if(preg_match("/^[+]?[0-9]*$/", $_POST['phone'])) { $phone = strip_tags($_POST['phone']); } else { echo $jsonHelper-&gt;encode(t("Wrong phone number format.")); die; } $message = t('Phone number').": ".$phone."\n\n".$message; $mail = Loader::helper('mail'); $mail-&gt;setBody($message); $mail-&gt;from($email, $name); $mail-&gt;to("test@example.com"); $mail-&gt;to($email); $mail-&gt;setSubject(t('Example subject')); $sent = true; $mail-&gt;sendMail(); if($sent) { echo $jsonHelper-&gt;encode("sent"); die; } else { echo $jsonHelper-&gt;encode(t("Could not send mail. Please try again.")); die; } } else{ echo $jsonHelper-&gt;encode(t("Wrong security answer!")); die; } } </code></pre> <p>The script sanitizes different attributes (name, email and the message) and sends an email to a specified address and the one from the HTML form. <strong>My question:</strong> Is the form secure?</p>
[]
[ { "body": "<p>Secure: Not yet, but it's a start. Your validation is too strict in some places, and may result in the wrong email address being used. In particular here:</p>\n\n<pre><code>$email = filter_var($_POST['email'], FILTER_SANITIZE_EMAIL);\n//a bit later on:\n$email = str_replace(array(\"\\r\", \"\\n\", \"%0a\", \"%0d\"), '', stripslashes($email));\n</code></pre>\n\n<p>If the value of <code>$email</code> is one of these examples of <strong><em>valid</em></strong> email addresses:</p>\n\n<pre><code>!#$%&amp;'*+-/=?^_`{}|~@example.org\n\"()&lt;&gt;[]:,;@\\\\\\\"!#$%&amp;'*+-/=?^_`{}| ~.a\"@example.org\n\"very.(),:;&lt;&gt;[]\\\".VERY.\\\"very@\\\\ \\\"very\\\".unusual\"@strange.example.com\n</code></pre>\n\n<p>you're stripping the slashes, which'll yield:</p>\n\n<pre><code>!#$%&amp;'*+-=?^_`{}|~@example.org\n\"()&lt;&gt;[]:,;@\"!#$%&amp;'*+-=?^_`{}| ~.a\"@example.org\n\"very.(),:;&lt;&gt;[]\".VERY.\"very@ \"very\".unusual\"@strange.example.com\n</code></pre>\n\n<p>Effectively <em>changing</em> the actual email address, and this may in turn turn a valid, though outlandish email address into an invalid one.<br>\nBTW: source for these email addresses <a href=\"http://en.wikipedia.org/wiki/Email_address\" rel=\"nofollow noreferrer\">is the email wiki</a></p>\n\n<p>When it comes to email addresses: use <code>filter_validate($emai, FILTER_VALIDATE_EMAIL)</code> and rely on that function's ability to validate the string. Don't do any processing of your own, especially not <em>after</em> having sanitized and validated the email address.<br>\nBottom line, if you want to validate an email address, while allowing users to pass an (accidental) <code>\\r</code> char, use this:</p>\n\n<pre><code>$email = filter_var($_POST['email'], FILTER+_SANITIZE_EMAIL);\nif (!filter_var($email, FILTER_VALIDATE_EMAIL))\n{\n echo $jsonHelper-&gt;encode($email.' is an invalid address'));\n}\n</code></pre>\n\n<p>On the other hand, you're not sanitizing the message and name as well as maybe you should. It's not unlikely your script is vulnerable to <em>mail injection</em>. <a href=\"http://www.codeproject.com/Articles/428076/PHP-Mail-Injection-Protection-and-E-Mail-Validatio\" rel=\"nofollow noreferrer\">A must-read on this subject can be found here</a>.</p>\n\n<p>Since we're all in the business of programming, I hope you'll understand I'm not going to repeat myself here, but I've dealt with mail injection previously on this site: <a href=\"https://codereview.stackexchange.com/questions/36330/critique-sanitized-user-email-php-script/36354#36354\">read my answer to this question</a>, which focusses on injection a bit more.</p>\n\n<p><em>Some other niggles:</em></p>\n\n<ul>\n<li>Please, as ever, try to stick to the coding standards as described by PHP-FIG. Most, if not all, major players subscribe to this standard, so should you. <a href=\"http://www.php-fig.org\" rel=\"nofollow noreferrer\">Check the standard here</a>.<br>\nThings like <code>public function foobar(){</code> are not accepted, the opening brace should go on the next line. It may seem silly to stumble over this, but really: it isn't.</li>\n<li>don't use <code>die</code> in a method, and avoid using <code>echo</code>. I take it you're using a framework of sorts. Check if there's an ajax helper that outputs, or use the view to echo JSON content. And from within an action (controller method), don't call <code>die</code>, but rather <code>return</code>, signaling an uneventfull end of the controllers' job. <code>die</code> breaks the normal way of processing a request, which may cause problems down the road.</li>\n</ul>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-02-04T09:36:57.570", "Id": "69905", "Score": "0", "body": "Thanks for the reply, but I still cannot understand why is my code vulnerable to mail injection? I make sure to remove all newlines." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-02-04T09:45:28.090", "Id": "69906", "Score": "0", "body": "I have followed the dream.in.code method of removing newlines. It is also reviewed on the link you provided as one of the viable options. Why is it vulnerable to mail injection?" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-02-04T10:11:32.237", "Id": "69909", "Score": "1", "body": "@user3001234: Not quite: you're not removing the line-endings, but merely percent-encoding them. Looking at the PEAR `_sanitizeHeaders` method, I'd assume that alone does not suffice, since they remove `%0a`, too. I'm only guessing here, but I take it that, seeing as they remove this, there is a way to exploit encoded line-endings, too. You're also not checking for `<CR>` and the like. Perhaps consider calling `strip_tags` on the message, and send it with explicit _text_ headers" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-02-04T10:15:24.330", "Id": "69911", "Score": "0", "body": "Should I be using the `_sanitizeHeaders` method from the page you provided? It appears to be secure." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-02-04T10:20:53.650", "Id": "69914", "Score": "1", "body": "@user3001234: You can use it for inspiration. Personally, I tend to avoid PEAR packages, because they do tend to raise notices, because of their tendency to try to be as backward-compatible as possible. Running PHP5.5, methods that don't specify their being `public`, `private` or `protected` and methods that are being called both as member functions and statics... that's just messy PHP4-style coding. The main point is: the sanitizing has all been written out, copy with pride (and in accordance with the licence)" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-02-04T10:22:25.830", "Id": "69915", "Score": "0", "body": "Doing `$value = preg_replace('=((<CR>|<LF>|0x0A/%0A|0x0D/%0D|\\\\n|\\\\r)\\S).*=i', null, $value);` for `$name`, `$email` and `$message` should be enough, I suppose. I don't want to use PEAR packages; I'm using Zend mail already." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-02-04T10:24:37.807", "Id": "69916", "Score": "1", "body": "@user3001234: _not_ for `$email`, for the email address `filter_validate($email, FILTER_SANITIZE_EMAIL)` already removes any non-valid address chars. and I believe `\"<CR>MyAddress\"@example.org` is a valid email address, because the `<>` is contained within quotes. Just call the `preg_replace` on the name and message and you should be fine" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-02-04T10:26:15.517", "Id": "69917", "Score": "1", "body": "Okay, thanks for pointing me in the right direction. I used the dream.in.code method because I wasn't aware of `<CR>`. The table in the page you provided pretty much sums it up - the PEAR method is the safest one as far as I can see." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-02-04T10:29:14.653", "Id": "69918", "Score": "0", "body": "Also, any other remarks regarding security? Would you say that my contact form is secure now that I use the PEAR `preg_replace` method for removing newlines?" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-02-04T10:37:16.750", "Id": "69921", "Score": "1", "body": "@user3001234: AFAIKT, yes, I'd say it's pretty secure. You don't seem to be storing the data in a DB anywhere (if you do, use prepared statements, and you're good). So the only things you need to check are: 1) validation and 2) mail injection. You've addressed both sufficiently, I do think" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-02-04T10:39:45.683", "Id": "69922", "Score": "1", "body": "I use the ADO DB layer whenever I have to store/retrieve data from a database, so I suppose I'm fine. Thanks for your help." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-02-04T16:39:06.480", "Id": "69975", "Score": "0", "body": "I've just noticed something strange - when using the PEAR method for sanitizing headers, the `preg_replace` removes all data that comes after the newline. Why is this and how do I solve it? The text message (email body) gets cut off." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-02-04T16:49:29.993", "Id": "69977", "Score": "0", "body": "I ended up using `$value = trim(str_replace(array(\"\\r\", \"\\n\", \"%0a\", \"%0d\", \"<CR>\", \"<LF>\"), '', stripslashes($value)));` for `$message` and `$name`." } ], "meta_data": { "CommentCount": "13", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-02-04T09:30:09.347", "Id": "40834", "ParentId": "40766", "Score": "5" } } ]
{ "AcceptedAnswerId": "40834", "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-02-03T17:57:14.703", "Id": "40766", "Score": "6", "Tags": [ "php", "security", "form", "email" ], "Title": "Security of a \"contact us\" form" }
40766
<p>Here's a PHP wrapper around a public OAuth2 REST API. I would love to hear your thoughts and comments. Testing was a bit frustrating since I tried for my first time. Not sure if I have done the mocking properly.</p> <p>You can see the whole project on <a href="https://github.com/stakisko/feedly-api" rel="nofollow">Github</a></p> <pre><code>class Feedly { private $_apiBaseUrl = "https://cloud.feedly.com", $_authorizePath = "/v3/auth/auth", $_accessTokenPath = "/v3/auth/token", $_storeAccessTokenToSession; /** * @param boolean $sandbox Enable/Disable Sandbox Mode * @param boolean $storeAccessTokenToSession Choose whether to store the Access token * to $_SESSION or not */ public function __construct($sandbox=FALSE, $storeAccessTokenToSession=TRUE) { $this-&gt;_storeAccessTokenToSession = $storeAccessTokenToSession; if($this-&gt;_storeAccessTokenToSession) session_start(); if($sandbox) $this-&gt;_apiBaseUrl = "https://sandbox.feedly.com"; } /** * Return authorization URL * @param string $client_id Client's ID provided by Feedly's Administrators * @param string $redirect_uri Endpoint to reroute with the results * @param string $response_type * @param string $scope * * @return string Authorization URL */ public function getLoginUrl ($client_id, $redirect_uri, $response_type="code", $scope="https://cloud.feedly.com/subscriptions") { return($this-&gt;_apiBaseUrl . $this-&gt;_authorizePath . "?" . http_build_query(array( "client_id"=&gt;$client_id, "redirect_uri"=&gt;$redirect_uri, "response_type"=&gt;$response_type, "scope"=&gt;$scope ) ) ); } /** * Exchange a `code` got from `getLoginUrl` for an `Access Token` * @param string $client_id Client's ID provided by Feedly's Administrators * @param string $client_secret Client's Secret provided by Feedly's Administrators * @param string $auth_code Code obtained from `getLoginUrl` * @param string $redirect_url Endpoint to reroute with the results */ public function GetAccessToken($client_id, $client_secret, $auth_code, $redirect_url) { $r = null; if (($r = @curl_init($this-&gt;_apiBaseUrl . $this-&gt;_accessTokenPath)) == false) { throw new Exception("Cannot initialize cUrl session. Is cUrl enabled for your PHP installation?"); } curl_setopt($r, CURLOPT_RETURNTRANSFER, 1); curl_setopt($r, CURLOPT_ENCODING, 1); curl_setopt($r, CURLOPT_SSL_VERIFYPEER, false); curl_setopt($r, CURLOPT_CAINFO, "C:\wamp\bin\apache\Apache2.2.21\cacert.crt"); // Add client ID and client secret to the headers. curl_setopt($r, CURLOPT_HTTPHEADER, array ( "Authorization: Basic " . base64_encode($client_id . ":" . $client_secret), )); $post_fields = "code=" . urlencode($auth_code) . "&amp;client_id=" . urlencode($client_id) . "&amp;client_secret=" . urlencode($client_secret) . "&amp;redirect_uri=" . urlencode($redirect_url) . "&amp;grant_type=authorization_code"; curl_setopt($r, CURLOPT_POST, true); curl_setopt($r, CURLOPT_POSTFIELDS, $post_fields); $response = curl_exec($r); $http_status = curl_getinfo($r, CURLINFO_HTTP_CODE); $tmpr = json_decode($response, true); curl_close($r); if($http_status!==200) throw new Exception("Response from API: " . $tmpr['errorMessage']); if($this-&gt;_storeAccessTokenToSession){ if(!isset($_SESSION['access_token'])){ $_SESSION['access_token'] = $tmpr['access_token']; session_write_close(); } } return $response; } /** * cUrl Initiliazation * @param string $url URL to query * @param string $token Access Token in case we don't store it to $_SESSION */ private function InitCurl($url, $token=NULL) { $r = null; if (($r = @curl_init($url)) == false) { throw new Exception("Cannot initialize cUrl session. Is cUrl enabled for your PHP installation?"); } curl_setopt($r, CURLOPT_RETURNTRANSFER, 1); curl_setopt($r, CURLOPT_ENCODING, 1); curl_setopt($r, CURLOPT_SSL_VERIFYPEER, false); curl_setopt($r, CURLOPT_CAINFO, "C:\wamp\bin\apache\Apache2.2.21\cacert.crt"); $access_token = is_null($token) ? $this-&gt;_getAccessTokenFromSession() : $token; curl_setopt($r, CURLOPT_HTTPHEADER, array ( "Authorization: OAuth " . $access_token )); return($r); } /** * Query a URL with GET using cUrl after initialization * @param string $url URL to query * @param string $get_params Parameters to pass to URL as GET params * @param string $token Access Token in case we don't store it to $_SESSION */ public function ExecGetRequest($url, $get_params=NULL, $token=NULL) { $url = $this-&gt;_apiBaseUrl . $url; if(is_array($get_params)) $r = $this-&gt;InitCurl($url .'?', http_build_query($url, $get_params), $token); else $r = $this-&gt;InitCurl($url, $token); $response = curl_exec($r); if ($response == false) { die("curl_exec() failed. Error: " . curl_error($r)); } $http_status = curl_getinfo($r, CURLINFO_HTTP_CODE); $tmpr = json_decode($response, true); curl_close($r); if($http_status!==200) throw new Exception("Something went wrong: " . $tmpr['errorMessage']); else return $response; } /** * Make a POST request * @param string $url URL to query * @param string $get_params Parameters to pass to URL as GET params * @param string $post_params Parameters to pass to URL as POST params * @param string $token Access Token in case we don't store it to $_SESSION */ public function ExecPostRequest($url, $get_params=NULL, $post_params=NULL, $token=NULL) { $url = $this-&gt;_apiBaseUrl . $url; if(is_array($get_params)) $r = $this-&gt;InitCurl($url .'?', http_build_query($url, $get_params), $token); else $r = $this-&gt;InitCurl($url, $token); $post_fields = http_build_query($post_params); curl_setopt($r, CURLOPT_POST, true); curl_setopt($r, CURLOPT_POSTFIELDS, $post_fields); $response = curl_exec($r); if ($response == false) { die("curl_exec() failed. Error: " . curl_error($r)); } $http_status = curl_getinfo($r, CURLINFO_HTTP_CODE); $tmpr = json_decode($response, true); curl_close($r); if($http_status!==200) throw new Exception("Something went wrong: " . $tmpr['errorMessage']); else return $response; } /** * @see http://developer.feedly.com/v3/profile/#get-the-profile-of-the-user * @param string $token Access Token in case we don't store it to $_SESSION * @return json Response from the server */ public function getProfile($token=NULL) { return $this-&gt;ExecGetRequest('/v3/profile', NULL, $token); } /** * @see http://developer.feedly.com/v3/profile/#update-the-profile-of-the-user * @param string $email * @param string $givenName * @param string $familyName * @param string $picture * @param boolean $gender * @param string $locale * @param string $reader google reader id * @param string $twitter twitter handle. example: edwk * @param string $facebook facebook id * @param string $token Access Token in case we don't store it to $_SESSION * @return json Response from the server */ public function setProfile($token=NULL, $email=NULL, $givenName=NULL, $familyName=NULL, $picture=NULL, $gender=NULL, $locale=NULL, $reader=NULL, $twitter=NULL, $facebook=NULL) { return $this-&gt;ExecPostRequest('/v3/profile', NULL, array( 'email'=&gt;$email, 'givenName'=&gt;$givenName, 'familyName'=&gt;$familyName, 'picture'=&gt;$picture, 'gender'=&gt;$gender, 'locale'=&gt;$locale, 'reader'=&gt;$reader, 'twitter'=&gt;$twitter, 'facebook'=&gt;$facebook ), $token); } /** * @see http://developer.feedly.com/v3/preferences/#get-the-preferences-of-the-user * @param string $token Access Token in case we don't store it to $_SESSION * @return json Response from the server */ public function getPreferences($token=NULL) { return $this-&gt;ExecGetRequest('/v3/preferences', NULL, $token); } /* More code happens here, check the full version *https://github.com/stakisko/feedly-api/blob/master/feedly.php */ /** * @return string Access Token from $_SESSION */ protected function _getAccessTokenFromSession(){ if(isset($_SESSION['access_token'])){ return $_SESSION['access_token']; }else { throw new Exception("No access token", 1); } } } &lt;?php include_once './feedly.php'; include_once './vendor/autoload.php'; class FeedlyAPITest extends PHPUnit_Framework_TestCase { private $instance; function __construct(){ ini_set("session.use_cookies", 0); $this-&gt;instance = new Feedly(true, false); } /** * Test valid returned URL for authorization */ public function testGetLoginURL() { $this-&gt;assertNotEmpty($this-&gt;instance-&gt;getLoginUrl("sandbox", "http://localhost")); } /** * Testing GetAccessToken on failure * will throw exception */ public function testGetAccessTokenThrowsExceptionOnFailure() { try { $this-&gt;instance-&gt;GetAccessToken(); } catch (Exception $expected) { return; } $this-&gt;fail(); } /** * Testing GetAccessToken */ public function testGetAccessToken() { $json = ' { "access_token": 1385150462, "stuff": { "this": 2, "that": 4, "other": 1 } } '; $feedly = $this-&gt;getMock('Feedly', array('GetAccessToken'), array(true, false)); $feedly-&gt;expects($this-&gt;any()) -&gt;method('GetAccessToken') -&gt;will($this-&gt;returnValue($json)); $this-&gt;assertEquals($json, $feedly-&gt;GetAccessToken("sandbox", "FUFNPXDNP2J0BF7RCEUZ", "", "http://localhost")); } /** * Testing a GET Request to API without providing an Access Token * will throw exception */ public function testExecGetRequestWithoutAccessTokenThrowsException(){ try { $this-&gt;instance-&gt;ExecGetRequest('/v3/profile'); } catch (Exception $expected) { return; } $this-&gt;fail(); } /** * Testing a GET Request to API */ public function testExecGetRequest(){ $json = ' { "access_token": 1385150462, "stuff": { "this": 2, "that": 4, "other": 1 } } '; $feedly = $this-&gt;getMock('Feedly', array('ExecGetRequest'), array(true, false)); $feedly-&gt;expects($this-&gt;any()) -&gt;method('ExecGetRequest') -&gt;will($this-&gt;returnValue($json)); $this-&gt;assertEquals($json, $feedly-&gt;ExecGetRequest("/dum/url")); } /** * Testing a POST Request to API */ public function testExecPostRequest(){ $json = ' { "access_token": 1385150462, "stuff": { "this": 2, "that": 4, "other": 1 } } '; $feedly = $this-&gt;getMock('Feedly', array('ExecPostRequest'), array(true, false)); $feedly-&gt;expects($this-&gt;any()) -&gt;method('ExecPostRequest') -&gt;will($this-&gt;returnValue($json)); $this-&gt;assertEquals($json, $feedly-&gt;ExecPostRequest('/dummy/url', NULL, array( 'email'=&gt;'odysseus@ithaka.gr', 'givenName'=&gt;'' ))); } } </code></pre>
[ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-02-04T07:38:27.987", "Id": "69897", "Score": "2", "body": "_Please_, __Please__ subscribe to the, as of yet, unofficial coding standards [as described here](http://www.php-fig.org/). The more people adopt these, the better. Symfony, Zend, Doctrine, PEAR,... all subscribe to these conventions" } ]
[ { "body": "<p>Two minor notes:</p>\n\n<ol>\n<li><p>The following is not too easy to read:</p>\n\n<pre><code>curl_setopt($r, CURLOPT_ENCODING, 1);\n</code></pre>\n\n<p>Readers have to be really familar with curl parameters or have to check the documentation. It <a href=\"http://hu1.php.net/curl_setopt\" rel=\"nofollow\">says the following</a>:</p>\n\n<blockquote>\n <p>The contents of the \"Accept-Encoding: \" header. This enables decoding\n of the response. Supported encodings are \"identity\", \"deflate\", and \"gzip\". \n If an empty string, \"\", is set, a header containing all supported encoding \n types is sent.</p>\n</blockquote>\n\n<p>But it's <code>1</code>, which isn't a string. <code>1 == \"\"</code>? I suggest the following:</p>\n\n<pre><code>curl_setopt($r, CURLOPT_ENCODING, ALL_SUPPORTED_ENCODING_TYPES);\n</code></pre>\n\n<p>where <code>ALL_SUPPORTED_ENCODING_TYPES</code> is a constant with an empty string value. (I suppose <code>1 == \"\"</code>.)</p></li>\n<li><p>Comments like this is unnecessary:</p>\n\n<pre><code>/**\n * Testing GetAccessToken\n */\npublic function testGetAccessToken()\n</code></pre>\n\n<p>The function name says the same, so I'd remove the comment. In the following case I'd rename the function to <code>testValidReturnedUrlForAuthorization()</code> and remove the comment:</p>\n\n<pre><code> /**\n * Test valid returned URL for authorization\n */\npublic function testGetLoginURL()\n</code></pre>\n\n<p>(<em>Clean Code</em> by <em>Robert C. Martin</em>: <em>Chapter 4: Comments, Noise Comments</em>)</p></li>\n</ol>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-02-03T21:00:08.337", "Id": "68793", "Score": "1", "body": "You have absolutely right. I ve missed that! Fixed. Thank you." } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-02-03T20:15:50.103", "Id": "40778", "ParentId": "40767", "Score": "4" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "1", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-02-03T18:21:11.457", "Id": "40767", "Score": "5", "Tags": [ "php", "unit-testing", "api", "wrapper", "mocks" ], "Title": "PHP wrapper around an API - best practices" }
40767
<p>After profiling my current script I've found that nearly 100% of the run time (and I'm not surprised) comes from the following function:</p> <pre><code>def rem_asc_by_pos(xmlFile, fileOut,removeIndices): fileIn = xmlFile.replace('.xml', '.asc') with open(fileIn, 'r') as fin: with open(fileOut, 'w') as fout: #remove indices from each line and write to new file if len(removeIndices) &gt; 0: for line in fin: lineList = list(line) checkLine = '' newLine = [] for ind,char in enumerate(lineList): if ind not in removeIndices: newLine.append(char) lineOut = ''.join(newLine) fout.write(lineOut) </code></pre> <p>The files themselves can have anywhere from a 15 thousand lines to 2.5 million at the most, each line is usually from 300-600 characters.</p> <p>I was thinking that the write operation may be causing an increase in run-time so I could write multiple lines at a time but wouldn't know a good way to determine when it should write the lines (so as to not run out of memory).</p> <p>Is there anything obvious that I might be able to change to decrease the overall run-time? To go through all the files currently it takes about 20 hours and any decrease from that is appreciated!</p> <p>edit: Adding an example of input and expected output!</p> <p>Input: I have a bunch of data files that look similar to this:</p> <pre><code>511111 12 1.000000 1.000000 1.000000 .750000 511112 12 1.000000 .666667 .500000 .555556 </code></pre> <p>The removeIndicies list contains the indicies to remove from each line, for this example we want to remove the first three and indicies 19-28.</p> <p>Expected output:</p> <pre><code>111 12 1.000000 1.000000 .750000 112 12 1.000000 .500000 .555556 </code></pre>
[ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-02-03T20:20:02.167", "Id": "68782", "Score": "1", "body": "Can you explain what this function is supposed to do? Can you give examples of the input and output?" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-02-03T20:36:47.177", "Id": "68784", "Score": "0", "body": "I've added an example of the input file lines and the expected output." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-02-03T20:38:24.357", "Id": "68785", "Score": "0", "body": "What was wrong with `cut`? I mean, couldn't you just run `cut -c 4-18,29- FILE`?" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-02-03T20:45:14.623", "Id": "68786", "Score": "0", "body": "Sorry for the confusion, the XML file has the indices of the variablesToRemove. I'll reduce the code example so that it is more relevant. I can't find any reference to 'cut' in the pydocs." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-02-03T20:46:35.993", "Id": "68787", "Score": "0", "body": "[`cut`](http://pubs.opengroup.org/onlinepubs/9699919799/utilities/cut.html) is a standard Unix utility for carrying out this kind of task. It will be much faster than doing it in Python. (You might still want to use Python to build the `cut` command line.)" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-02-03T20:50:01.413", "Id": "68788", "Score": "0", "body": "Thanks for this suggestion, I'm limited to Windows as my current platform but I'll see if I can find a solution along these lines." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-02-03T22:04:04.867", "Id": "68798", "Score": "0", "body": "Are the files all self-consisten, or do they have header data? If they are homogenous you could split them into a comfortable size for read-all-write-all processing (appending as necessary) to cut down on the IO thrashing" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-02-04T19:37:42.373", "Id": "70013", "Score": "1", "body": "I think the answers to the question [_Efficient way of parsing fixed width files in Python_](http://stackoverflow.com/a/4915359/355230) might be helpful. Specifically, **Update 2** in my own answer which supports negative widths to represent ignored \"padding\" fields." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-02-04T20:06:12.870", "Id": "70018", "Score": "0", "body": "I agree with you, that is very helpful! Thank you!" } ]
[ { "body": "<h3>1. Test case</h3>\n\n<p>You can't fix what you don't measure. So let's make a test case containing a million lines similar to the example input in your question:</p>\n\n<pre><code>&gt;&gt;&gt; with open('in.txt', 'w') as f:\n... for _ in range(10**6):\n... _ = f.write('511111 12 1.000000 1.000000 1.000000 .750000\\n')\n</code></pre>\n\n<p>How long does your code take?</p>\n\n<pre><code>&gt;&gt;&gt; from timeit import timeit\n&gt;&gt;&gt; indices = list(range(3)) + list(range(18, 29))\n&gt;&gt;&gt; timeit(lambda:rem_asc_by_pos('in.txt', 'out.txt', indices), number=1)\n32.99110442500023\n</code></pre>\n\n<h3>2. Rewrite</h3>\n\n<p>Here's a quick rewrite to simplify your code:</p>\n\n<ol>\n<li>Follow the Python style guide (<a href=\"http://www.python.org/dev/peps/pep-0008/\">PEP8</a>).</li>\n<li>Write a docstring explaining what the code does.</li>\n<li>Pick a better name for the function.</li>\n<li>Combine the two <code>with</code> clauses into one to keep the indentation sensible.</li>\n<li>No need to pass mode <code>'r'</code> to <code>open</code>: that's the default.</li>\n</ol>\n\n<p>And some changes to speed it up:</p>\n\n<ol>\n<li>Turn the list of removed indices into a <code>set</code>, so that we can look up indices in constant time.</li>\n<li>There's no need to split <code>line</code> into a list: you can iterate over a string just as easily.</li>\n<li>Drop the <code>checkLine</code> and <code>newList</code> and <code>lineOut</code> intermediate variables.</li>\n<li>Cache <code>fout.write</code> in a local variable to avoid having to look it up for every line.</li>\n</ol>\n\n<pre class=\"lang-py prettyprint-override\"><code>def remove_indices(file_in, file_out, indices):\n \"\"\"Copy file_in to file_out, removing the given indices.\"\"\"\n index_set = set(indices)\n with open(file_in) as fin, open(file_out, 'w') as fout:\n write = fout.write\n for line in fin:\n write(''.join(c for i, c in enumerate(line) if i not in index_set))\n</code></pre>\n\n<p>This is about twice as fast (in my test case):</p>\n\n<pre><code>&gt;&gt;&gt; timeit(lambda:remove_indices('in.txt', 'out.txt', indices), number=1)\n17.147783935997722\n</code></pre>\n\n<h3>3. Use slices instead of indices</h3>\n\n<p>The next improvement is to represent the parts of the line to be <em>kept</em> (rather than the parts to be <em>removed</em>) in the form of Python <a href=\"http://docs.python.org/3/library/functions.html#slice\"><code>slice</code></a> objects. A slice object represents a range of indices in the same form as an array slice, that is, as <em>start</em> and <em>stop</em> indices together with a <em>step</em>.</p>\n\n<p>So if you are going to <em>remove</em> indices 0–2 and 18–28, then you are going to <em>keep</em> indices 3–17 and 29–. In slice notation that would be:</p>\n\n<pre><code>&gt;&gt;&gt; slices = [slice(3, 18), slice(29, None)]\n</code></pre>\n\n<p>Note that the <em>stop</em> for the first slice is 18, because ranges of integers in Python are always <em>exclusive</em> at the top.</p>\n\n<p>Here's a version of your function that takes slices to keep instead of indices to remove:</p>\n\n<pre><code>def keep_slices(file_in, file_out, slices):\n \"\"\"Copy file_in to file_out, keeping the given slices.\"\"\"\n with open(file_in) as fin, open(file_out, 'w') as fout:\n write = fout.write\n for line in fin:\n for s in slices:\n write(line[s])\n</code></pre>\n\n<p>This is substantially faster:</p>\n\n<pre><code>&gt;&gt;&gt; timeit(lambda:keep_slices('in.txt', 'out.txt', slices), number=1)\n1.877711878001719\n</code></pre>\n\n<p>That's about an 18 times speedup (on this test case; it might be different on other test cases). Is that good enough for you? It ought to reduce your 20 hour runtime to an hour or so.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-02-04T15:37:33.807", "Id": "69966", "Score": "0", "body": "Thank you very much for all the advice, it is very much appreciated! I will certainly work on my style and documentation. I can see a lot of useful methods that I hope to carry on through with my work! Again thank you!" } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-02-03T23:27:40.397", "Id": "40796", "ParentId": "40773", "Score": "7" } } ]
{ "AcceptedAnswerId": "40796", "CommentCount": "9", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-02-03T20:07:30.047", "Id": "40773", "Score": "7", "Tags": [ "python", "python-3.x" ], "Title": "More efficient way of removing line indices?" }
40773
<p>I'm using Microsoft's <a href="http://msdn.microsoft.com/en-us/library/ms172831%28v=vs.100%29.aspx" rel="nofollow">example</a> for encrypting/decripting a string. In their example, they are using Tripple DES. I'm trying to convert their code to use AES. </p> <p>The modified code, listed below, works. However, I am wondering if I need to change anything in the TruncateHash function or in the AES.Key and AES.IV value. </p> <p>This is all new to me, so I am still learning.</p> <pre><code>Imports System.Security.Cryptography Public NotInheritable Class AesCrypto ' Private TripleDes As New TripleDESCryptoServiceProvider ' Changed from Triple DES to AES Private AES As New AesCryptoServiceProvider Private Function TruncateHash(ByVal key As String, ByVal length As Integer) As Byte() ' Creates a byte array of a specified length from the hash of the specified key. Dim sha1 As New SHA1CryptoServiceProvider ' Hash the key. Dim keyBytes() As Byte = System.Text.Encoding.Unicode.GetBytes(key) Dim hash() As Byte = sha1.ComputeHash(keyBytes) ' Truncate or pad the hash. ReDim Preserve hash(length - 1) Return hash End Function Sub New(ByVal key As String) ' Initialize the crypto provider. AES.Key = TruncateHash(key, AES.KeySize \ 8) AES.IV = TruncateHash("", AES.BlockSize \ 8) End Sub Public Function EncryptData(ByVal plaintext As String) As String ' Encrypt the data. ' Convert the plaintext string to a byte array. Dim plaintextBytes() As Byte = System.Text.Encoding.Unicode.GetBytes(plaintext) ' Create the stream. Dim ms As New System.IO.MemoryStream ' Create the encoder to write to the stream. Dim encStream As New CryptoStream(ms, AES.CreateEncryptor(), System.Security.Cryptography.CryptoStreamMode.Write) ' Use the crypto stream to write the byte array to the stream. encStream.Write(plaintextBytes, 0, plaintextBytes.Length) encStream.FlushFinalBlock() ' Convert the encrypted stream to a printable string. Return Convert.ToBase64String(ms.ToArray) End Function Public Function DecryptData(ByVal encryptedtext As String) As String 'Decrypt the data. ' Convert the encrypted text string to a byte array. Dim encryptedBytes() As Byte = Convert.FromBase64String(encryptedtext) ' Create the stream. Dim ms As New System.IO.MemoryStream ' Create the decoder to write to the stream. Dim decStream As New CryptoStream(ms, AES.CreateDecryptor(), System.Security.Cryptography.CryptoStreamMode.Write) ' Use the crypto stream to write the byte array to the stream. decStream.Write(encryptedBytes, 0, encryptedBytes.Length) decStream.FlushFinalBlock() ' Convert the plaintext stream to a string. Return System.Text.Encoding.Unicode.GetString(ms.ToArray) End Function End Class </code></pre>
[ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-01-22T18:15:27.247", "Id": "68775", "Score": "0", "body": "Very minor notes: variables and fields should use lowercase (so use `aes` instead of `AES`. Futhermore you can make the code easier to understand by not relying on defaults, so set the mode of encryption (CBC) and the padding (PKCS#7 padding) explicitly using the properties of the `AesCryptoServiceProvider` class." } ]
[ { "body": "<p>It seems you did a good job getting the same functionality using AES. The problem is that Microsoft is not using good practices themselves.</p>\n\n<p>They confuse a password with a key, and they do not use a good key derivation function such as PBKDF2 (implemented in .NET by the class <a href=\"http://msdn.microsoft.com/en-us/library/system.security.cryptography.rfc2898derivebytes%28v=vs.110%29.aspx\" rel=\"nofollow noreferrer\">RFC2898DeriveBytes</a>). This you should only use if you do not have access to a shared AES key, which can just consist of 16 cryptographic random bytes.</p>\n\n<p>Furthermore, they did not use a random IV. The IV has the right size (the block size of the block cipher) but it has been set to a constant value. This means all the security benefits of having an IV are negated. The IV should be a cryptographic random (or at least fully unpredictable to an adversary), and could be written in front of the ciphertext (e.g. by supplying it to the unencrypted stream). Static IV's are only secure if the AES key is randomized or if the plaintext is sufficiently random itself.</p>\n\n<p>They use UTF-16 (incorrectly called Unicode in .NET) to create plaintext bytes from the input. UTF-16 uses 16 bits for each normal character, instead of the 8 bits used by UTF-8. So their encoding method is not very efficient.</p>\n\n<p>Note that if you want to use this in a communication protocol that you may need to add a MAC to protect the integrity and authenticity of the plaintext. If you do not, you may even loose the confidentiality of the plaintext (as the default CBC mode of encryption is vulnerable to padding oracle attacks).</p>\n\n<p>So good job, cannot say the same thing of Microsoft.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-01-22T20:22:07.693", "Id": "68776", "Score": "0", "body": "Would using [this](http://msdn.microsoft.com/en-us/library/system.security.cryptography.rfc2898derivebytes.aspx) key derivation function be a better alternative?" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-01-22T22:32:16.210", "Id": "68777", "Score": "0", "body": "*If* you require a password to be used it is probably the best one available in .NET (the others are bcrypt and scrypt, but they are not in the standard libs). But as said, a password is almost never better than a fully random key." } ], "meta_data": { "CommentCount": "2", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2014-01-22T18:09:59.897", "Id": "40775", "ParentId": "40774", "Score": "5" } } ]
{ "AcceptedAnswerId": "40775", "CommentCount": "1", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-01-22T16:40:35.323", "Id": "40774", "Score": "5", "Tags": [ "vb.net", "cryptography", "aes" ], "Title": "Encrypt Using AES" }
40774
<p>This is a very long solution I've been working on to a Number to Words problem. I've identified that there's a lot of repeating logic (e.g. 'if writing > 0', 'writing = integer /',).</p> <ul> <li>How would you refactor this? </li> <li>When refactoring is there a process you use?</li> <li>For readability sake would it be better to break this method into various pieces? Why?</li> </ul> <p></p> <pre><code>def in_words (integer) ones_array = ['zero','one','two','three','four','five','six','seven','eight','nine'] teens_array = ['blank','eleven','twelve','thirteen','fourteen','fifteen','sixteen','seventeen','eighteen','nineteen'] tens_array = ['blank','ten','twenty','thirty','fourty','fifty','sixty','seventy','eighty','ninety'] result = "" #FOR MILLIONS writing = integer / 1_000_000 left_over = integer % 1_000_000 if writing &gt; 0 result &lt;&lt; in_words(writing) &lt;&lt; "million " integer = left_over end #FOR THOUSANDS writing = integer / 1000 left_over = integer % 1000 if writing &gt; 0 result &lt;&lt; in_words(writing) &lt;&lt; "thousand " integer = left_over end #FOR HUNDREDS writing = integer / 100 left_over = integer % 100 if writing &gt; 0 result &lt;&lt; in_words(writing) &lt;&lt; "hundred " integer = left_over end #FOR TENS!!! writing = integer / 10 left_over = integer % 10 if writing &gt; 0 if writing == 1 &amp;&amp; left_over &gt; 0 result &lt;&lt; teens_array[left_over] left_over = 0 else result &lt;&lt; tens_array[writing] end end writing = left_over #FOR ONES!!!! if writing &gt; 0 result &lt;&lt; ones_array[writing] end result end p in_words(4) # =&gt; "four" p in_words(15) # =&gt; "fifteen" p in_words(92) # =&gt; "ninety two" or "ninety-two" p in_words(101) # =&gt; "one hundred one" p in_words(9915) # =&gt; "nine thousand nine hundred fifteen" p in_words(1456789) # =&gt; #"one million four hundred fifty six thousand seven hundred eighty nine" </code></pre>
[]
[ { "body": "<p>I would refactor by using a loop, which has the advantage of letting you easily add new words (i.e. billions). Here is a quick version I wrote up to demonstrate using a loop to reduce the repetition. Just did some basic testing and I'm sure it has some issues, but hopefully it sets you on the right path in your refactoring.</p>\n\n<p>Unfortunately due to the lack of regularity in english the resulting loop is not all that readable :) Its possible that pulling the 'tens', 'teens', etc logic into methods might make this more readable, but ultimately it will still have special cases. </p>\n\n<pre><code>def in_words(integer)\n result = \"\"\n [[1_000_000, 'million'], [1000, 'thousand'], [100, 'hundred'], [10, ''], [1, '']].each do |n, s|\n next if integer &lt; n\n writing = integer / n\n integer = integer % n\n\n case n\n when 10\n if writing == 1 &amp;&amp; integer != 0\n result &lt;&lt; ['eleven','twelve','thirteen','fourteen','fifteen','sixteen','seventeen','eighteen','nineteen'][integer - 1]\n break\n else\n result &lt;&lt; ['ten','twenty','thirty','fourty','fifty','sixty','seventy','eighty','ninety'][writing - 1]\n end\n when 1\n result &lt;&lt; ['zero','one','two','three','four','five','six','seven','eight','nine'][writing]\n else \n result &lt;&lt; \"#{in_words(writing)} #{s}\" if writing &gt; 0\n end\n end\n\n result\nend\n</code></pre>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-01-22T20:26:45.730", "Id": "40777", "ParentId": "40776", "Score": "2" } }, { "body": "<p>You should use Ruby's <a href=\"http://ruby-doc.org/core-1.9.3/Numeric.html#method-i-divmod\" rel=\"nofollow\"><code>Numeric#divmod</code></a> function:</p>\n\n<pre><code>writing, integer = integer.divmod(1_000_000)\n</code></pre>\n\n<p>Your function parameter claims to accept an <code>integer</code>, so you should also handle negative inputs. (It shouldn't be hard to prepend <code>\"negative \"</code> and flip the sign.)</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-02-03T23:31:44.827", "Id": "40799", "ParentId": "40776", "Score": "3" } }, { "body": "<p>I would take a different approach. First I would convert the number to words using an idealized numbering system, with none of the complications of the tens or teens. By way of example, 413,230 would be <code>4 ones hundred 1 tens 3 ones thousand 2 ones hundred 3 tens</code>. Here <code>1 tens 3 ones</code> would be <code>13</code>. (I have shown the results of this first step in the examples below.) Then I would use the hash <code>GRAMMAR</code> to correct the grammar. This results in there being relatively little code, but a fair amount of data.</p>\n\n<p>Note that the order of the elements in the hash <code>GRAMMAR</code> is important. (Insertion order of hash elements is maintained in Ruby 1.9+. This is the first time I have found that change useful, but useful it is.) The <code>i tens</code> substrings must be replaced first, then the <code>ten i ones</code> substrings (the numbers 11-19) and lastly the <code>i ones</code> substrings. Please let me know if what I have is not quite correct.</p>\n\n<pre><code>GRAMMAR={\n '1 tens' =&gt; 'ten' , '2 tens' =&gt; 'twenty' , '3 tens' =&gt; 'thirty' ,\n '4 tens' =&gt; 'fourty' , '5 tens' =&gt; 'fifty' , '6 tens' =&gt; 'sixty' ,\n '7 tens' =&gt; 'seventy' , '8 tens' =&gt; 'eighty' , '9 tens' =&gt; 'ninety' ,\n 'ten 1 ones' =&gt; 'eleven' , 'ten 2 ones' =&gt; 'twelve' , 'ten 3 ones' =&gt; 'thirteen',\n 'ten 4 ones' =&gt; 'fourteen' , 'ten 5 ones' =&gt; 'fifteen' , 'ten 6 ones' =&gt; 'sixteen' ,\n 'ten 7 ones' =&gt; 'seventeen', 'ten 8 ones' =&gt; 'eighteen', 'ten 9 ones' =&gt; 'nineteen',\n '1 ones' =&gt; 'one' , '2 ones' =&gt; 'two' , '3 ones' =&gt; 'three' ,\n '4 ones' =&gt; 'four' , '5 ones' =&gt; 'five' , '6 ones' =&gt; 'six' ,\n '7 ones' =&gt; 'seven' , '8 ones' =&gt; 'eight' , '9 ones' =&gt; 'nine' ,\n }\n\nUNITS=['ones million','ones hundred','tens','ones thousand','ones hundred','tens','ones']\n\ndef in_words(n)\n raise ArgumentError, \"n = #{n} is not a Fixnum\" unless n.is_a? Fixnum\n raise ArgumentError, \"n = #{n} not &gt;= 0 and &lt; 10,000,000\" if n &lt; 0 || n &gt;= 10_000_000\n return \"zero\" if n.zero?\n y = 1_000_000\n str = UNITS.each_with_object('') do |t,str|\n x, n = n.divmod(y)\n str &lt;&lt; \" #{x} #{t}\" if x &gt; 0\n y /= 10\n end.lstrip!\n GRAMMAR.each { |k,v| str.gsub!(k,v) }\n str\nend\n\nin_words(3_464_284)\n# =&gt; three million four hundred sixty four thousand two hundred eighty four\n# str before LABELS.each ...\n# =&gt; 3 ones million 4 ones hundred 6 tens 4 ones thousand 2 ones hundred 8 tens 4 ones\n\nin_words(3_413_230)\n# =&gt; three million four hundred thirteen thousand two hundred thirty\n# str before LABELS.each...\n# =&gt; 3 ones million 4 ones hundred 1 tens 3 ones thousand 2 ones hundred 3 tens\n\nin_words(9_000_064)\n# =&gt; nine million sixty four\n# str before LABELS.each ...\n# =&gt; # 9 ones million 6 tens 4 ones\n\nin_words(818_000) \n# =&gt; eight hundred eighteen thousand\n# str before LABELS.each ...\n# =&gt; 8 ones hundred 1 tens 8 ones thousand\n</code></pre>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-02-04T09:05:45.673", "Id": "40832", "ParentId": "40776", "Score": "3" } } ]
{ "AcceptedAnswerId": "40777", "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-01-22T19:39:26.477", "Id": "40776", "Score": "5", "Tags": [ "strings", "ruby", "converting", "integer", "numbers-to-words" ], "Title": "Number to words problem" }
40776
<p>I wrote this function last year to convert between the two encodings and just found it. It takes a text buffer and its size, then converts to UTF-8 if there's enough space.</p> <p>What should be changed to improve quality?</p> <pre><code>int iso88951_to_utf8(unsigned char *content, size_t max_size) { unsigned char *copy; size_t conversion_count; //number of chars to convert / bytes to add copy = content; conversion_count = 0; //first run to see if there's enough space for the new bytes while(*content) { if(*content &gt;= 0x80) { ++conversion_count; } ++content; } if(content - copy + conversion_count &gt;= max_size) { return ERROR; } while(content &gt;= copy &amp;&amp; conversion_count) { //repositioning current characters to make room for new bytes if(*content &lt; 0x80) { *(content + conversion_count) = *content; } else { *(content + conversion_count) = 0x80 | (*content &amp; 0x3f); //last byte *(content + --conversion_count) = 0xc0 | *content &gt;&gt; 6; //first byte } --content; } return SUCCESS; } </code></pre>
[]
[ { "body": "<p>Minor quibbles.</p>\n\n<ol>\n<li>I would prefer to see the variables assigned to when defined.</li>\n<li>Use a macro instead of the hard coded value of 0x80 or 0x3F. For someone who is not familiar with the ins and outs of UTF-8 or ISO-8895-1 naming them something like MASK_END or UPPER_VALUE makes for easier understanding.</li>\n</ol>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-02-03T22:34:30.030", "Id": "40791", "ParentId": "40780", "Score": "3" } }, { "body": "<p>The character set is named ISO-8859-1, not ISO-8895-1. Rename your function accordingly.</p>\n\n<p>Change the return value to be more informative:</p>\n\n<ul>\n<li>Return 0 on success.</li>\n<li>If <code>max_size</code> is too small, return the minimum value of <code>max_size</code> that would be sufficient to accommodate the output (including the trailing <code>\\0</code>).</li>\n</ul>\n\n<p>I would also change the parameter to take a signed <code>char *</code> to be a bit more natural.</p>\n\n<p>I think that the implementation could look tidier if you dealt with pointers instead of offsets.</p>\n\n<p>It would be nice if you NUL-terminated the result, so that the caller does not have to zero out the entire buffer before calling this function.</p>\n\n<pre><code>size_t iso8859_1_to_utf8(char *content, size_t max_size)\n{\n char *src, *dst;\n\n //first run to see if there's enough space for the new bytes\n for (src = dst = content; *src; src++, dst++)\n {\n if (*src &amp; 0x80)\n {\n // If the high bit is set in the ISO-8859-1 representation, then\n // the UTF-8 representation requires two bytes (one more than usual).\n ++dst;\n }\n }\n\n if (dst - content + 1 &gt; max_size)\n {\n // Inform caller of the space required\n return dst - content + 1;\n }\n\n *(dst + 1) = '\\0';\n while (dst &gt; src)\n {\n if (*src &amp; 0x80)\n {\n *dst-- = 0x80 | (*src &amp; 0x3f); // trailing byte\n *dst-- = 0xc0 | (*((unsigned char *)src--) &gt;&gt; 6); // leading byte\n }\n else\n {\n *dst-- = *src--;\n }\n }\n return 0; // SUCCESS\n}\n</code></pre>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-02-03T22:37:10.603", "Id": "40792", "ParentId": "40780", "Score": "12" } }, { "body": "<p>I'm not sure why you have <code>content &gt;= copy</code> in your second while loop. I would hope that <code>while(conversion_count)</code> should be sufficient.</p>\n\n<p>Your <code>while</code> loops could be <code>for</code> loops.</p>\n\n<p>More comments would make it easier to read:</p>\n\n<ul>\n<li><code>//first run to see how many extra bytes we'll need</code></li>\n<li><code>//convert bytes from last to first to avoid altering not-yet-converted bytes</code></li>\n<li>I'd appreciate a link to whichever section of an ISO-8895-1 specification which states what bit-twiddling is needed (I can see what the code does in the final loop, but have not seen the specification of what it's supposed to do so haven't verified that).</li>\n</ul>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-02-03T23:30:31.127", "Id": "40798", "ParentId": "40780", "Score": "4" } }, { "body": "<p>How usable is the function? It relies on the <code>content</code> string occupying a\nbuffer large enough to be extended. And if you take the suggestion from\n@200_success that on error the function returns the minimum size necessary,\nthe user then has the added complexity of having to handle that error by\nallocating a buffer and it must free the allocated buffer later - but it\nmust keep a note of whether the buffer was allocated. </p>\n\n<p>Although I dislike dynamic allocation, I think this is a case where it makes \nsense always to allocate a new string in the function.</p>\n\n<p>Here is a version that allocates space:</p>\n\n<pre><code>char* iso88959_to_utf8(const char *str)\n{\n char *utf8 = malloc(1 + (2 * strlen(str)));\n\n if (utf8) {\n char *c = utf8;\n for (; *str; ++str) {\n if (*str &amp; 0x80) {\n *c++ = *str;\n } else {\n *c++ = (char) (0xc0 | (unsigned) *str &gt;&gt; 6);\n *c++ = (char) (0x80 | (*str &amp; 0x3f));\n }\n }\n *c++ = '\\0';\n }\n return utf8;\n}\n</code></pre>\n\n<p>You could add a <code>realloc</code> call at the end to trim the excess space if you\nthought it necessary (I'm not sure that it is, but it might depend upon the\napplication). </p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-02-04T17:00:50.077", "Id": "69979", "Score": "0", "body": "the cast on the second statement in the else block is unnecessary, isn't it? Also, I am not a fan of magic numbers without names and bit twiddling without comments." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-02-04T17:16:02.053", "Id": "69984", "Score": "2", "body": "There is an `int` to `char` conversion that causes a warning from `clang` with `-Wsign-conversion`. I just added the cast to keep that quiet :-)" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-02-07T23:10:58.810", "Id": "70693", "Score": "2", "body": "Swap `*c++ = *str;` with `*c++ = (char) (0xc0 | (unsigned ... & 0x3f));`." } ], "meta_data": { "CommentCount": "3", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-02-04T16:35:48.297", "Id": "40857", "ParentId": "40780", "Score": "8" } } ]
{ "AcceptedAnswerId": "40792", "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-02-03T20:54:56.010", "Id": "40780", "Score": "10", "Tags": [ "c", "strings", "converting", "unicode", "utf-8" ], "Title": "Function to convert ISO-8859-1 to UTF-8" }
40780
<p>I am trying to get a better understanding of the modular design pattern and I am using Requirejs to manage my dependencies.</p> <p>I understand separating code into modules (using define with RequireJS) so they take on only single responsibilities and also splitting them into separate JavaScript files so Require JS can load them.</p> <p>In my main.js, the entry points looks like this (which depends on work module). For brevity, I have left out the require.config, paths, etc.:</p> <pre><code>require( ['work'], function(work) { var url = "urlstring"; work.buildHTMLTable(url); } ); </code></pre> <p>the method buildHTMLTable will append html table to a div tag.</p> <p>I want to build a re-usable generic js library that will handle vertical/horizontal scroll event and arrow key navigation event. I need direction on how to incorporate these events. The below method is working, but I wanted to make sure I was setting everything up correctly.</p> <ol> <li><p>Should I have one define method that has a function which takes care of handling the scrolling like so?</p> <pre><code>define('scrollingGrid', ['jquery'], function ($) { var bindScroll = function (hs, vs) { $(hs).on('scroll', function (e) { } $(vs).on('scroll', function (e) { } }; return { bindScroll: bindScroll }; } ); </code></pre> <p>and then I can call it from the main as so:</p> <pre><code>require( ['work', 'grid'], function(work) { var url = "urlstring"; work.buildHTMLTable(url); grid.bindScroll('#hscroll', '#vscroll'); } ); </code></pre></li> <li><p>Should I also handle the arrow key navigation in the same <code>scrollingGrid</code> module (see below)? </p> <pre><code>require( ['work', 'grid'], function(work) { var url = "urlstring"; work.buildHTMLTable(url); grid.bindScroll('#hscroll', '#vscroll'); grid.bindArrow('#tab'); } ); </code></pre></li> </ol> <p>In summary, I am creating a re-usable JavaScript control that could handle events on an HTML table. Is what I am doing okay or is there a better way?</p>
[]
[ { "body": "<p>First, unless the <code>work</code> module is about force times distance in a physics simulator, it is a terribly over-generic name! What does the name <code>work</code> communicate to someone who is sitting down with your application for the first time? Name modules after what they do and be as specific as possible but not more so.</p>\n\n<p>Second, if you're only exposing a single method in that module just return that method directly, no need for an object.</p>\n\n<p>Next, won't your scrolling handlers depend on a specific structure being present already? You might want to make it explicit. I can't really make a recommendation how without understanding better how you plan to use this (I'm really confused what <code>work.buildHTMLTable(url)</code> could possibly do). </p>\n\n<p>As for where key navigation should go, it really is all about naming. So if you view the arrow key navigation to be a part of the grid scrolling then yes, it should be in the module that sets that up, otherwise it should not be.</p>\n\n<p>Finally, What if you have two grids on the same page? seems like you're trying to apply a lot of stuff globally? Perhaps your modules can accept the grid you want to modify as a parameter?</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-02-03T21:49:41.023", "Id": "40785", "ParentId": "40783", "Score": "6" } }, { "body": "<p>It seems like this is creating an unnecessary namespace:</p>\n\n<pre><code>return {\n bindScroll: bindScroll\n};\n</code></pre>\n\n<p>When it might as well be:</p>\n\n<pre><code>return bindScroll;\n</code></pre>\n\n<p>Initialised with:</p>\n\n<pre><code>bindScroll('#hscroll', '#vscroll');\n</code></pre>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-02-03T21:51:50.630", "Id": "40786", "ParentId": "40783", "Score": "4" } } ]
{ "AcceptedAnswerId": "40785", "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-02-03T21:40:56.713", "Id": "40783", "Score": "7", "Tags": [ "javascript", "require.js" ], "Title": "Modular design with Require.js" }
40783
<p>I am reading a beginning Python programming book and in it the author says that you want to avoid accessing a class' attributes directly, but instead to create methods that return attribute values. However, I am finding there are times this seems a little redundant and I am wondering if am just going about this in the wrong way.</p> <p>An example of this is in the battle function where I access <code>player1.hand</code> directly. Is this a bad idea? Also, does everything else look okay in this or are there any bad practices I should be nipping in the bud?</p> <pre><code>#a game of rock paper scissors for two computers #imports import random class Hand(object): """A hand with which to rock paper scissor""" HANDS = ("rock", "paper", "scissors") def __init__(self, name, wins = 0, hand = None): self.name = name self.wins = wins self.hand = hand def choose_hand(self): """Chooses hand for player""" self.hand = random.choice(self.HANDS) print self.name + " picks " + self.hand + "." def increase_wins(self): """Increases players wins and declares them this rounds winner""" self.wins += 1 print self.name + " wins." def total_wins(self): """shows total wins of all rounds played""" print self.name + " won " + str(self.wins) + " rounds." def battle(player1, player2): """plays one round of rock paper scissor""" #players choose their hands player1.choose_hand() player2.choose_hand() #see who wins the battle if player1.hand == "rock" and player2.hand == "scissors": player1.increase_wins() elif player1.hand == "paper" and player2.hand == "rock": player1.increase_wins() elif player1.hand == "scissors" and player2.hand == "paper": player1.increase_wins() elif player1.hand == player2.hand: print "It's a tie." else: player2.increase_wins() def main(): player1 = Hand("HAL") player2 = Hand("WOPR") rounds = 10 for i in range(rounds): print "\nRound " + str(i + 1) + ":" battle(player1, player2) print "\nFinal Score:" player1.total_wins() player2.total_wins() if player1.wins &gt; player2.wins: print player1.name + " wins." elif player1.wins == player2.wins: print "It's a tie." else: print player2.name + " wins." #play the game main() </code></pre>
[]
[ { "body": "<p>As has been pointed out, overriding the <code>__call__</code> method is not the best way to improve the readability of your code.</p>\n\n<p>Using attributes is not, in itself, a problem.</p>\n\n<p>What you may want to consider is a trick you can play with Rock/Paper/Scissors.</p>\n\n<p>If you create an array in the order:</p>\n\n<pre><code>Rock -&gt; Scissors -&gt; Paper -&gt; Rock\n</code></pre>\n\n<p>Then, if you have two hands, and they select a random 'hand' from the three options Rock, Scissors, Paper.... then, you can find the first index of the first hand's value in the size-4 array above.... then if the next value is the opponent's hand, you win. If it is the same as your hand, it's a draw. Otherwise it's a loss.</p>\n\n<pre><code>winconditions = ['Rock', 'Scissors', 'Paper', 'Rock']\np1index = winconditions.index(player1.hand)\np2index = winconditions.index(player2.hand)\nif p1index == p2index:\n # draw\nelif p1index + 1 == p2index:\n # p1 wins!\nelse\n # p2 wins.\n</code></pre>\n\n<hr>\n\n<p><strike>\nSince this is probably the most common method to call when accessing the player, it may make sense to make the hand the result of the <code>__call__</code> function ..... and it would make the code read pretty nicely....</p>\n\n<pre><code>def __call__(self):\n return self.hand\n</code></pre>\n\n<p>and then you can use it like:</p>\n\n<pre><code>def battle(player1, player2):\n \"\"\"plays one round of rock paper scissor\"\"\"\n #players choose their hands\n player1.choose_hand()\n player2.choose_hand()\n\n #see who wins the battle\n if player1() == \"rock\" and player2() == \"scissors\":\n player1.increase_wins()\n elif player1() == \"paper\" and player2() == \"rock\":\n player1.increase_wins()\n elif player1() == \"scissors\" and player2() == \"paper\":\n player1.increase_wins()\n elif player1() == player2():\n print \"It's a tie.\"\n else:\n player2.increase_wins()\n</code></pre>\n\n<p></strike></p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-02-04T13:10:36.450", "Id": "69932", "Score": "0", "body": "I disagree; making it look like a method call implies certain things about it that don't apply here. I can't read your sample without thinking it's making tons of player1 and player2 objects. Now, on the other hand, if you overrode `__eq__` that *might* make sense." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-02-04T15:16:49.460", "Id": "69959", "Score": "0", "body": "@MichaelUrman - you are right, it is abuse of the `__call__` to use it this way.... hmmm, and I don't particularly like the `__eq__` option either.... since the players are not equal, but their hands are..... still stewing." } ], "meta_data": { "CommentCount": "2", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-02-03T22:20:09.600", "Id": "40787", "ParentId": "40784", "Score": "2" } }, { "body": "<p>The point of using classes is to encapsulate behavior and data. Exposing <code>hand</code> means if you change the internal representation -- say from a string to a class -- you then have to update any code using class <code>Hand</code>. Also, you imply that <code>foo.hand = thing</code> is valid.</p>\n\n<p>Consider instead having a method which tests if the <code>Hand</code> defeats a supplied option:</p>\n\n<pre><code>def defeats(self, value):\n if self.hand == value:\n return 0 # aka tie\n elif self.hand == \"rock\" and value == \"paper\":\n return -1 # lose\n elif self.hand == \"paper\" and value == \"rock\":\n return 1 # win\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-02-04T00:31:07.133", "Id": "68838", "Score": "0", "body": "This answer might be good advice in some languages, but in Python if you need to change the implementation of an attribute you can replace it with a property." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-02-04T06:45:41.883", "Id": "69895", "Score": "0", "body": "True, but it does not change the point of OO and classes. Properties are nice and exposed data makes for rapid prototyping. But when you are designing an API it makes sense to make things that are easy, obvious, and maintainable. Might as well get into the habit so doing the \"right\" thing just becomes how you code." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-02-04T10:01:49.590", "Id": "69908", "Score": "0", "body": "This begs the question (how do you know that avoiding attributes is the \"right\" thing?). [See my answer.](http://codereview.stackexchange.com/a/40835/11728)" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-02-04T13:14:57.857", "Id": "69933", "Score": "0", "body": "While `player1.defeats(player2.hand)` fails to prevent direct access to `hand`, I like where this thought leads. I could totally see making hand an instance of a type that lets you compare `player1.hand < player2.hand` meaningfully, or even `player1.hand.defeats(player2.hand)`." } ], "meta_data": { "CommentCount": "4", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-02-03T22:20:34.460", "Id": "40788", "ParentId": "40784", "Score": "2" } }, { "body": "<p>There's nothing wrong with using attributes in Python. The author of your book is mistaken on this point. He or she must have half-remembered a rule about not using attributes, but doesn't know (or has forgotten) that this rule applies:</p>\n\n<ol>\n<li><p>to programming languages like Java, in which attribute (member) access <em>cannot later be changed</em> to use a method call, without rewriting all the callers; and</p></li>\n<li><p>when you are <em>publishing an API</em> for use by other programmers, so that there will be a body of code that depends on the published details of the API, which needs to be kept compatible.</p></li>\n</ol>\n\n<p>But point 1 does not apply to Python: if at some later time you realise that you need to replace an attribute with a method, you can do so easily via the <a href=\"http://docs.python.org/3/library/functions.html#property\" rel=\"nofollow\"><code>@property</code></a> decorator. And point 2 does not apply to the code in the question: there is no public or published API here. If you later want to change <code>Player.hand</code> to <code>Player.hand()</code>, it's an easy change to make, because all the code is yours.</p>\n\n<p>Python uses attributes in many places in the standard library, for example, <a href=\"http://docs.python.org/3/library/subprocess.html#subprocess.Popen.returncode\" rel=\"nofollow\"><code>subprocess.Popen.returncode</code></a>, <a href=\"http://docs.python.org/3/library/tempfile.html#tempfile.NamedTemporaryFile\" rel=\"nofollow\"><code>tempfile.NamedTemporaryFile.name</code></a>, <a href=\"http://docs.python.org/3/library/datetime.html#datetime.date.year\" rel=\"nofollow\"><code>datetime.date.year</code></a>, <a href=\"http://docs.python.org/3/library/threading.html#threading.Thread.daemon\" rel=\"nofollow\"><code>threading.Thread.daemon</code></a>. (You'll see that in the last case, the old getter/setter API has been <em>deprecated in favour of the attribute</em>, because attribute access is simpler and clearer.)</p>\n\n<p>It's important to know, when applying a rule like \"avoid attributes and use methods instead\", the reasons behind the rule, and the situations where it is and isn't appropriate. Don't apply rules blindly!</p>\n\n<p>(A note on terminology: you talk about \"class attributes\" in the question: but properly speaking, the <code>hand</code> attribute belongs to <em>instances</em> of the class, not to the class itself: that is, <code>Player(...).hand</code> is OK but <code>Player.hand</code> is not.)</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-02-04T13:16:26.613", "Id": "69934", "Score": "1", "body": "Strongly agreed. Other languages bake in the kind of access in a way that differs for what python calls attributes and properties. But since in python the mechanism is the same in the calling code, there's no pain when you have to change an attribute to a property or vice versa." } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-02-04T10:01:35.920", "Id": "40835", "ParentId": "40784", "Score": "2" } } ]
{ "AcceptedAnswerId": "40835", "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-02-03T21:49:29.997", "Id": "40784", "Score": "7", "Tags": [ "python", "game", "classes", "rock-paper-scissors" ], "Title": "Directly accessing class attributes in Rock Paper Scissors" }
40784
<p>I have a test which looks like this:</p> <ul> <li>Create a base class <code>Human</code> </li> <li><code>Human class</code> needs to have a method <code>Talk</code></li> <li>The <code>Human</code> class needs to have to descendant class <code>Man</code> and <code>Woman</code></li> <li>Both <code>Man</code> and <code>Woman</code> should have their own <code>Talk</code> method (basically rewrite the method)</li> <li>The <code>Man</code> class should have a <code>private</code> property <code>_foo</code></li> <li>It should have a method <code>getInfo</code> (which needs to be an Ajax call and log the response)</li> <li>I need to make 1000 instances of the <code>Women</code> class in the <code>window</code> namespace (I mean global)</li> <li>On <code>document.body</code> single click, a random <code>Woman</code> should call the <code>Talk</code> method</li> <li>On <code>document.body</code> double click, the <code>Man</code>'s <code>getInfo</code> method should be called</li> </ul> <p></p> <pre><code>function Human(){}; Human.prototype.talk = function(){ console.log('Make an Human sound'); } function Woman(){ Human.call(this); } Woman.prototype = Object.create(Human.prototype); Woman.prototype.constructor = Woman; Woman.prototype.talk = function(){ console.log('Miau'); } function Man(){ var foo = 10; Human.call(this); } Man.prototype = Object.create(Human.prototype); Man.prototype.constructor = Man; Man.prototype.talk = function(){ console.log('Wuff'); } Man.prototype.getInfo = function(method, url){ var xhr = new XMLHttpRequest(); xhr.open(method, url); xhr.send(null); xhr.onreadystatechange = function() { console.log('Ajax response: ' + xhr.readyState); }; } var woman = new Woman(); console.log('woman instance of Woman ' + (woman instanceof Woman)); console.log('woman instance of Human ' + (woman instanceof Human)); woman.talk(); var man = new Man(); console.log('man instance of Man ' + (man instanceof Man)); console.log('man instance of Human ' + (man instanceof Human)); man.talk(); womans = []; for(var i = 0; i &lt; 1000; i++) { womans[i] = new Woman(); } document.body.onclick = function(){ var randNr = Math.floor((Math.random()*1000)+1); womans[randNr].talk(); console.log('Random Woman: ' + randNr); } document.body.ondblclick = function(){ Man.prototype.getInfo(); } </code></pre>
[]
[ { "body": "<p>Some opinions:</p>\n\n<blockquote>\n<pre><code>function Woman(){\n Human.call(this);\n}\nWoman.prototype = new Human();\n</code></pre>\n</blockquote>\n\n<p><a href=\"https://stackoverflow.com/q/12592913/1048572\">Don't use <code>new</code> for prototype</a> (even when it doesn't matter here as long as <code>Human</code> is empty, but the <code>Huma.call(this)</code> suggests otherwise). Check <a href=\"https://stackoverflow.com/q/10898786/1048572\">https://stackoverflow.com/q/10898786/1048572</a></p>\n\n<blockquote>\n<pre><code>// Woman subClass\nfunction Man(){\n</code></pre>\n</blockquote>\n\n<p>Apparently not.</p>\n\n<blockquote>\n<pre><code> var _foo = 10;\n</code></pre>\n</blockquote>\n\n<p>It's a local-scoped (\"private\") variable anyway, you don't need to prefix it with an underscore. Notice that it is only accessible from functions declared within the constructor, of which you don't have any.</p>\n\n<blockquote>\n<pre><code> return Human.call(this);\n</code></pre>\n</blockquote>\n\n<p>No reason to <code>return</code> anything here. It might even be wrong it <code>Human</code> did return an object.</p>\n\n<blockquote>\n<pre><code>Man.prototype.getInfo = function(method, url){\n […]\n}\n</code></pre>\n</blockquote>\n\n<p>This doesn't seem to have anything to do with instances of <code>Man</code>, so I wonder why it is a method? But that's probably just the design of your test case.</p>\n\n<blockquote>\n<pre><code>console.log('man private variable _foo: ' + (man._foo));\n</code></pre>\n</blockquote>\n\n<p>Not sure what you did expect, but yes, since <code>_foo</code> has been a variable and not a property of the object so this is <code>undefined</code>.</p>\n\n<blockquote>\n<pre><code>document.body.onclick = function(){ \n […]\n</code></pre>\n</blockquote>\n\n<p>…is missing a closing brace.</p>\n\n<blockquote>\n<pre><code>var randNr = Math.floor((Math.random()*1000)+1);\nwomans[randNr].talk();\n</code></pre>\n</blockquote>\n\n<p>No. That <code>randNr</code> will be in the range 1-1000 (both inclusive), while your array indices are 0-999. With a small chance, this will throw an exception. Remove the <code>+1</code>.</p>\n\n<blockquote>\n<pre><code>console.log('Random Woman: ' + randNr);\n</code></pre>\n</blockquote>\n\n<p>…and add it here if you want that output one-based.</p>\n\n<blockquote>\n<pre><code>Man.prototype.getInfo();\n</code></pre>\n</blockquote>\n\n<p>That confirms what I said above - you don't use an instance for that method. You should hardly ever call methods on the prototype object - <code>man.getInfo()</code> would be better. But if you really intended this to be a static function, you might write <code>Man.getInfo = function() {…};</code> and then call <code>Man.getInfo();</code>.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-01-30T08:19:02.503", "Id": "68806", "Score": "0", "body": "I edited the code, please could you take a second and check if now the code is suffice for the test above. i would highly appreciate it." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-01-30T13:51:02.390", "Id": "68807", "Score": "1", "body": "Uh, actually I had only looked at the code since you can check whether it meets your expectatations by simply executing it :-) I'd say it does what is described, the only term that striked me was \"*private property*\" as such by definition don't exist :-)" } ], "meta_data": { "CommentCount": "2", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-01-29T22:13:25.783", "Id": "40790", "ParentId": "40789", "Score": "3" } } ]
{ "AcceptedAnswerId": "40790", "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-01-29T21:55:42.740", "Id": "40789", "Score": "1", "Tags": [ "javascript", "inheritance" ], "Title": "Subclasses instantiating superclass of class Human" }
40789
<p>I have three functions, each assigned to an anchor tag which gets called <code>onclick</code>.</p> <p>Is there a way to condense this code? It seems redundant to have three function calls which do the same thing except the value is different for each.</p> <pre><code>var winnings = 0; function add20() { winnings += 20; document.getElementById("winnings").innerHTML = winnings; } function add40() { winnings += 40; document.getElementById("winnings").innerHTML = winnings; } function add60() { winnings += 60; document.getElementById("winnings").innerHTML = winnings; } </code></pre>
[ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-01-31T23:42:13.700", "Id": "68822", "Score": "1", "body": "Sure: `function addWinnings(amount) { winnings += amount; .. }` Generally, one should keep *data* out of identifiers - and the amount 20/40/60 (which is data) should likely come from another source (e.g. the 'bet' and subsequent 'payout')." } ]
[ { "body": "<pre><code>function add(val) {\n winnings += val;\n document.getElementById(\"winnings\").innerHTML = winnings;\n}\n</code></pre>\n\n<p>Calling it with</p>\n\n<pre><code>add(20); // Adding 20\n</code></pre>\n\n<p>Or</p>\n\n<pre><code>add(40); // Adding 40\n</code></pre>\n\n<p>Etc</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-01-31T23:45:37.200", "Id": "68823", "Score": "0", "body": "Worked! Just what I needed. Looking at the solution now, it's pretty simple but I am fairly new to programming so I guess I can give myself some slack." } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-01-31T23:38:29.050", "Id": "40803", "ParentId": "40802", "Score": "1" } }, { "body": "<p>You could just create one function, like this:</p>\n\n<pre><code>function add(x) { \n winnings += x; \n document.getElementById(\"winnings\").innerHTML = winnings;\n}\n</code></pre>\n\n<p>But if you <em>need</em> three different versions, you could always do this:</p>\n\n<pre><code>var winnings = 0;\nfunction addX(x) { \n return function() { \n winnings += x; \n document.getElementById(\"winnings\").innerHTML = winnings;\n }\n}\n\nvar add20 = addX(20);\nvar add40 = addX(40);\nvar add60 = addX(60);\n</code></pre>\n\n<p>Or even more simply:</p>\n\n<pre><code>function add(x) { \n winnings += x; \n document.getElementById(\"winnings\").innerHTML = winnings;\n}\nfunction add20() { add(20); }\nfunction add40() { add(40); }\nfunction add60() { add(60); }\n</code></pre>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-01-31T23:38:37.160", "Id": "40804", "ParentId": "40802", "Score": "5" } }, { "body": "<p>You could pass parameters like this</p>\n\n<pre><code>function addWinnings(amount) {\n winnings+=amount;\n document.getElementById(\"winnings\").innerHTML=winnings;\n}\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-01-31T23:41:21.590", "Id": "68824", "Score": "0", "body": "better move getElementById out of procedure. From perfomance perspective, imagine, having 10 calls of addWinnings will raise 10 DOM updates. not good." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-01-31T23:41:52.923", "Id": "68825", "Score": "0", "body": "@EugeneP Sorry, what? How else could he do it" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-01-31T23:44:56.947", "Id": "68826", "Score": "0", "body": "Once again: Imagine case I do need to call procedure 10 times in a row. It will mean DOM get update 10 times. If you move getElementById away from procedure. update will be done 1 time. It's just perfomance note, applicable for all provided solutions posted here" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-02-01T00:04:21.050", "Id": "68827", "Score": "0", "body": "But that's what the OP wants to do" } ], "meta_data": { "CommentCount": "4", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-01-31T23:38:47.157", "Id": "40805", "ParentId": "40802", "Score": "0" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "1", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-01-31T23:36:49.103", "Id": "40802", "Score": "1", "Tags": [ "javascript" ], "Title": "Is it possible to condense this code?" }
40802
<p>I was looking for a review on my coding. Since I'm planning to get a job as a Android Programmer in the long run.</p> <p>This is my first calculator app, which I did by self learning Programming. I have no other Programming Langauge experience.</p> <p>So I would love to hear how bad my coding is? Which areas I need improving on? What I should have used instead of repeating my self, which is bad coding as I understand.</p> <pre><code>private Button btn1, btn2, btn3, btn4, btn5, btn6, btn7, btn8, btn9, btnZero, btnDoubleZero, btnEqual, btnMultiply, btnDevide, btnPlus, btnMinus, btnClean, btnPoint; private TextView textView1, totalSum; private String lastInputNumber = ""; private double num1 = 0; private double num2 = 0; private double tempCount = 0; private double tempSum = 0; private int myClickCount = 0; private boolean nSwitch = true; private boolean equalSwitch = false; String stringMinus = " - "; String[] operation = { }; String[] lastNumber = { }; ArrayList&lt;String&gt; op = new ArrayList&lt;String&gt;(); ArrayList&lt;String&gt; ln = new ArrayList&lt;String&gt;(); @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); btn1 = (Button) findViewById(R.id.button3); btn2 = (Button) findViewById(R.id.button7); btn3 = (Button) findViewById(R.id.button11); btn4 = (Button) findViewById(R.id.button2); btn5 = (Button) findViewById(R.id.button6); btn6 = (Button) findViewById(R.id.button10); btn7 = (Button) findViewById(R.id.button1); btn8 = (Button) findViewById(R.id.button5); btn9 = (Button) findViewById(R.id.button9); btnZero = (Button) findViewById(R.id.button4); btnDoubleZero = (Button) findViewById(R.id.button8); btnEqual = (Button) findViewById(R.id.button20); btnMultiply = (Button) findViewById(R.id.button14); btnDevide = (Button) findViewById(R.id.button13); btnPlus = (Button) findViewById(R.id.button16); btnMinus = (Button) findViewById(R.id.button15); btnClean = (Button) findViewById(R.id.button19); btnPoint = (Button) findViewById(R.id.button12); btn1.setOnClickListener(this); btn2.setOnClickListener(this); btn3.setOnClickListener(this); btn4.setOnClickListener(this); btn5.setOnClickListener(this); btn6.setOnClickListener(this); btn7.setOnClickListener(this); btn8.setOnClickListener(this); btn9.setOnClickListener(this); btnZero.setOnClickListener(this); btnDoubleZero.setOnClickListener(this); btnEqual.setOnClickListener(this); btnMultiply.setOnClickListener(this); btnDevide.setOnClickListener(this); btnPlus.setOnClickListener(this); btnMinus.setOnClickListener(this); btnClean.setOnClickListener(this); btnPoint.setOnClickListener(this); textView1 = (TextView) findViewById(R.id.textView1); totalSum = (TextView) findViewById(R.id.textView3); Typeface tf = Typeface.createFromAsset(getAssets(), "fonts/Roboto-Light.ttf"); textView1.setTypeface(tf); totalSum.setTypeface(tf); Typeface btnTf = Typeface.createFromAsset(getAssets(), "fonts/Roboto-Light.ttf"); btnMultiply.setTypeface(btnTf); btnDevide.setTypeface(btnTf); btnEqual.setTypeface(btnTf); btnClean.setTypeface(btnTf); btnMinus.setTypeface(btnTf); btnPlus.setTypeface(btnTf); btnZero.setTypeface(btnTf); btnDoubleZero.setTypeface(btnTf); btn1.setTypeface(btnTf); btn2.setTypeface(btnTf); btn3.setTypeface(btnTf); btn4.setTypeface(btnTf); btn5.setTypeface(btnTf); btn6.setTypeface(btnTf); btn7.setTypeface(btnTf); btn8.setTypeface(btnTf); btn9.setTypeface(btnTf); // makes the textviews scrollable textView1.setMovementMethod(new ScrollingMovementMethod()); totalSum.setMovementMethod(new ScrollingMovementMethod()); } @Override public void onClick(View v) { switch (v.getId()) { case R.id.button3: // log that you clicked one Log.d("OSSI", "button 1 was clicked"); // First if switch is to check of equal was used if (equalSwitch == true) { } else { // add one to the existing textView1 string textView1.setText(textView1.getText().toString() + "1"); // my click counter plus one myClickCount++; // Bollean switch so operators cant be called twice nSwitch = false; } break; case R.id.button7: // log that you clicked two Log.d("OSSI", "button 2 was clicked"); // First if switch is to check of equal was used if (equalSwitch == true) { } else { // add two to the existing textView1 string textView1.setText(textView1.getText().toString() + "2"); // my click counter plus one myClickCount++; // Bollean switch so operators cant be called twice nSwitch = false; } break; case R.id.button11: // log that you clicked three Log.d("OSSI", "button 3 was clicked"); // First if switch is to check of equal was used if (equalSwitch == true) { } else { // add three to the existing textView1 string textView1.setText(textView1.getText().toString() + "3"); // my click counter plus one myClickCount++; // Bollean switch so operators cant be called twice nSwitch = false; } break; case R.id.button2: // log that you clicked four Log.d("OSSI", "button 4 was clicked"); // First if switch is to check of equal was used if (equalSwitch == true) { } else { // add four to the existing textView1 string textView1.setText(textView1.getText().toString() + "4"); // my click counter plus one myClickCount++; // Bollean switch so operators cant be called twice nSwitch = false; } break; case R.id.button6: // log that you clicked five Log.d("OSSI", "button 5 was clicked"); // First if switch is to check of equal was used if (equalSwitch == true) { } else { // add five to the existing textView1 string textView1.setText(textView1.getText().toString() + "5"); // my click counter plus one myClickCount++; // Bollean switch so operators cant be called twice nSwitch = false; } break; case R.id.button10: // log that you clicked six Log.d("OSSI", "button 6 was clicked"); // First if switch is to check of equal was used if (equalSwitch == true) { } else { // add six to the existing textView1 string textView1.setText(textView1.getText().toString() + "6"); // my click counter plus one myClickCount++; // Bollean switch so operators cant be called twice nSwitch = false; } break; case R.id.button1: // log that you clicked seven Log.d("OSSI", "button 7 was clicked"); // First if switch is to check of equal was used if (equalSwitch == true) { } else { // add seven to the existing textView1 string textView1.setText(textView1.getText().toString() + "7"); // my click counter plus one myClickCount++; // Bollean switch so operators cant be called twice nSwitch = false; } break; case R.id.button5: // log that you clicked eight Log.d("OSSI", "button 8 was clicked"); // First if switch is to check of equal was used if (equalSwitch == true) { } else { // add eight to the existing textView1 string textView1.setText(textView1.getText().toString() + "8"); // my click counter plus one myClickCount++; // Bollean switch so operators cant be called twice nSwitch = false; } break; case R.id.button9: // log that you clicked nine Log.d("OSSI", "button 9 was clicked"); // First if switch is to check of equal was used if (equalSwitch == true) { } else { // add nine to the existing textView1 string textView1.setText(textView1.getText().toString() + "9"); // my click counter plus one myClickCount++; // Bollean switch so operators cant be called twice nSwitch = false; } break; case R.id.button4: // log that you clicked zero Log.d("OSSI", "button 0 was clicked"); // First if switch is to check of equal was used if (equalSwitch == true) { } else { // add zero to the existing textView1 string textView1.setText(textView1.getText().toString() + "0"); // my click counter plus one myClickCount++; // Bollean switch so operators cant be called twice nSwitch = false; } break; case R.id.button8: // log that you clicked doublezero Log.d("OSSI", "button 00 was clicked"); if (myClickCount == 0) { } else if (equalSwitch == true) { } else { // add doublezero to the existing textView1 textView1.setText(textView1.getText().toString() + "00"); // my click counter plus one myClickCount += 2; // Bollean switch so operators cant be called twice nSwitch = false; } break; case R.id.button13: Log.d("OSSI", "button / was clicked"); // checks if ln arraylist has something stored before executing the math code if (textView1.length() &lt; 1) { } else if (ln.isEmpty()) { // Log ln array is Empty Log.d("OSSI", "ln is empty"); // Getting textView1 and parse into an int num1 = Double.parseDouble(textView1.getText().toString()); // Saving the int num1 in sum1 as a String String sum1 = Double.toString(num1); // Setting text from sum1 to totalSum totalSum.setText(sum1); // Adding sum1 inside ln string arraylist ln.add(sum1); // Adding devide symbol to the exsiting textView1 text textView1.setText(textView1.getText().toString() + " / "); // Adding devide to the op array list op.add("/"); } else if (nSwitch == true) { // Save textView1 into lastOperator String String lastOperator = textView1.getText().toString(); // Save String without the last Operator String deleteLastOperator = lastOperator.substring(lastOperator.length() - (lastOperator.length()), lastOperator.length() - 3); // Saving the new String without the last Operator textView1.setText(deleteLastOperator); // Adding new operator to textView1 String textView1.setText(textView1.getText().toString() + " / "); // Adding to the op array list op.add("/"); // Removes the first operator from op arraylist op.remove(0); } else { // Saving textView1 as lastNumb String lastNumb = textView1.getText().toString(); // A substring of lastNumb String will be saved as lastIput // (lastnumb minus the click counter, till the last lastnumb) String lastInput = lastNumb.substring(lastNumb.length() - myClickCount, lastNumb.length()); // Parsing lastInput to into num2 integer num2 = Double.parseDouble(lastInput); // Parsing String of totalSum into tempSum integer tempSum = Double.parseDouble(totalSum.getText().toString()); if (op.get(0) == "+") { Log.d("OSSI", "if plus operator worked"); // Calculating tempSum + sum2 tempSum = tempSum + num2; } else if (op.get(0) == "-") { Log.d("OSSI", "if minus operator worked"); // Calculating tempSum - sum2 tempSum = tempSum - num2; } else if (op.get(0) == "/") { Log.d("OSSI", "if devide operator worked"); // Calculating tempSum / sum2 tempSum = tempSum / num2; } else if (op.get(0) == "*") { Log.d("OSSI", "if multiply operator worked"); // Calculating tempSum * sum2 tempSum = tempSum * num2; } // Math to round 2 decimal number before tempSum will be set into totalSum double mathRound = tempSum; double tempSum = Math.round(mathRound*100.0)/100.0; // Changing tempSum to a String String sumDevide = Double.toString(tempSum); // String sumDevide will be the new totalSum text totalSum.setText(sumDevide); // Adding devide symbol to the exsiting textView1 text textView1.setText(textView1.getText().toString() + " / "); // Adding to the op array list op.add("/"); // Removes the first operator from op arraylist op.remove(0); } // my click counter reset to zero myClickCount = 0; // Equal Switch to false so numbers can be used again equalSwitch = false; nSwitch = true; break; case R.id.button14: Log.d("OSSI", "button * was clicked"); if (textView1.length() &lt; 1) { } // checks if ln arraylist has something stored before executing the math code else if (ln.isEmpty()) { // Log ln array is Empty Log.d("OSSI", "ln is empty"); // Getting textView1 and parse into an int num1 = Double.parseDouble(textView1.getText().toString()); // Saving the int num1 in sum1 as a String String sum1 = Double.toString(num1); // Setting text from sum1 to totalSum totalSum.setText(sum1); // Adding sum1 inside ln string arraylist ln.add(sum1); // Adding multiply symbol to the exsiting textView1 text textView1.setText(textView1.getText().toString() + " * "); // Adding multiply to the op array list op.add("*"); } else if (nSwitch == true) { // Save textView1 into lastOperator String String lastOperator = textView1.getText().toString(); // Save String without the last Operator String deleteLastOperator = lastOperator.substring(lastOperator.length() - (lastOperator.length()), lastOperator.length() - 3); // Saving the new String without the last Operator textView1.setText(deleteLastOperator); // Adding new operator to textView1 String textView1.setText(textView1.getText().toString() + " * "); // Adding to the op array list op.add("*"); // Removes the first operator from op arraylist op.remove(0); } else { // Saving textView1 as lastNumb String lastNumb = textView1.getText().toString(); // A substring of lastNumb String will be saved as lastIput // (lastnumb minus the click counter, till the last lastnumb) String lastInput = lastNumb.substring(lastNumb.length() - myClickCount, lastNumb.length()); // Parsing lastInput to into num2 integer num2 = Double.parseDouble(lastInput); // Parsing String of totalSum into tempSum integer tempSum = Double.parseDouble(totalSum.getText().toString()); if (op.get(0) == "+") { Log.d("OSSI", "if plus operator worked"); // Calculating tempSum + sum2 tempSum = tempSum + num2; } else if (op.get(0) == "-") { Log.d("OSSI", "if minus operator worked"); // Calculating tempSum - sum2 tempSum = tempSum - num2; } else if (op.get(0) == "/") { Log.d("OSSI", "if devide operator worked"); // Calculating tempSum / sum2 tempSum = tempSum / num2; } else if (op.get(0) == "*") { Log.d("OSSI", "if multiply operator worked"); // Calculating tempSum * sum2 tempSum = tempSum * num2; } // Math to round 2 decimal number before tempSum will be set into totalSum double mathRound = tempSum; double tempSum = Math.round(mathRound*100.0)/100.0; // Changing tempSum to a String String sumMulitply = Double.toString(tempSum); // String sumMultiply will be the new totalSum text totalSum.setText(sumMulitply); // Adding multiply symbol to the exsiting textView1 text textView1.setText(textView1.getText().toString() + " * "); // Adding to the op array list op.add("*"); // Removes the first operator from op arraylist op.remove(0); } // my click counter reset to zero myClickCount = 0; nSwitch = true; // Equal Switch to false so numbers can be used again equalSwitch = false; break; case R.id.button15: Log.d("OSSI", "button - was clicked"); if (textView1.length() &lt; 1) { } // checks if ln arraylist has something stored before executing the math code else if (ln.isEmpty()) { // Log ln array is Empty Log.d("OSSI", "ln is empty"); // Getting textView1 and parse into an int num1 = Double.parseDouble(textView1.getText().toString()); // Saving the int num1 in sum1 as a String String sum1 = Double.toString(num1); // Setting text from sum1 to totalSum totalSum.setText(sum1); // Adding sum1 inside ln string arraylist ln.add(sum1); // Adding minus symbol to the exsiting textView1 text textView1.setText(textView1.getText().toString() + stringMinus); // Adding minus to the op array list op.add("-"); } else if (nSwitch == true) { // Save textView1 into lastOperator String String lastOperator = textView1.getText().toString(); // Save String without the last Operator String deleteLastOperator = lastOperator.substring(lastOperator.length() - (lastOperator.length()), lastOperator.length() - 3); // Saving the new String without the last Operator textView1.setText(deleteLastOperator); // Adding new operator to textView1 String textView1.setText(textView1.getText().toString() + stringMinus); // Adding to the op array list op.add("-"); // Removes the first operator from op arraylist op.remove(0); } else { // Saving textView1 as lastNumb String lastNumb = textView1.getText().toString(); // A substring of lastNumb String will be saved as lastIput // (lastnumb minus the click counter, till the last lastnumb) String lastInput = lastNumb.substring(lastNumb.length() - myClickCount, lastNumb.length()); // Parsing lastInput to into num2 integer num2 = Double.parseDouble(lastInput); // Parsing String of totalSum into tempSum integer tempSum = Double.parseDouble(totalSum.getText().toString()); if (op.get(0) == "+") { Log.d("OSSI", "if plus operator worked"); // Calculating tempSum + sum2 tempSum = tempSum + num2; } else if (op.get(0) == "-") { Log.d("OSSI", "if minus operator worked"); // Calculating tempSum - sum2 tempSum = tempSum - num2; } else if (op.get(0) == "/") { Log.d("OSSI", "if devide operator worked"); // Calculating tempSum / sum2 tempSum = tempSum / num2; } else if (op.get(0) == "*") { Log.d("OSSI", "if multiply operator worked"); // Calculating tempSum * sum2 tempSum = tempSum * num2; } // Math to round 2 decimal number before tempSum will be set into totalSum double mathRound = tempSum; double tempSum = Math.round(mathRound*100.0)/100.0; // Changing tempSum to a String String sumMinus = Double.toString(tempSum); // String sumMinus will be the new totalSum text totalSum.setText(sumMinus); // Adding multiply symbol to the exsiting textView1 text textView1.setText(textView1.getText().toString() + stringMinus); // Adding to the op array list op.add("-"); // Removes the first operator from op arraylist op.remove(0); } // my click counter reset to zero myClickCount = 0; nSwitch = true; // Equal Switch to false so numbers can be used again equalSwitch = false; break; case R.id.button16: Log.d("OSSI", "button + was clicked"); if (textView1.length() &lt; 1) { } // checks if ln arraylist has something stored before executing the math code else if (ln.isEmpty()) { // Log ln array is Empty Log.d("OSSI", "ln is empty"); // Getting textView1 and parse into an int num1 = Double.parseDouble(textView1.getText().toString()); // Saving the int num1 in sum1 as a String String sum1 = Double.toString(num1); // Setting text from sum1 to totalSum totalSum.setText(sum1); // Adding sum1 inside ln string arraylist ln.add(sum1); // Adding plus symbol to the exsiting textView1 text textView1.setText(textView1.getText().toString() + " + "); // Adding plus to the op array list op.add("+"); } else if (nSwitch == true) { // Save textView1 into lastOperator String String lastOperator = textView1.getText().toString(); // Save String without the last Operator String deleteLastOperator = lastOperator.substring(lastOperator.length() - (lastOperator.length()), lastOperator.length() - 3); // Saving the new String without the last Operator textView1.setText(deleteLastOperator); // Adding new operator to textView1 String textView1.setText(textView1.getText().toString() + " + "); // Adding to the op array list op.add("+"); // Removes the first operator from op arraylist op.remove(0); } else { // Saving textView1 as lastNumb String lastNumb = textView1.getText().toString(); // A substring of lastNumb String will be saved as lastIput // (lastnumb minus the click counter, till the last lastnumb) String lastInput = lastNumb.substring(lastNumb.length() - myClickCount, lastNumb.length()); // Parsing lastInput to into num2 integer num2 = Double.parseDouble(lastInput); // Parsing String of totalSum into tempSum integer tempSum = Double.parseDouble(totalSum.getText().toString()); if (op.get(0) == "+") { Log.d("OSSI", "if plus operator worked"); // Calculating tempSum + sum2 tempSum = tempSum + num2; new DecimalFormat("#.##").format(tempSum); } else if (op.get(0) == "-") { Log.d("OSSI", "if minus operator worked"); // Calculating tempSum - sum2 tempSum = tempSum - num2; } else if (op.get(0) == "/") { Log.d("OSSI", "if devide operator worked"); // Calculating tempSum / sum2 tempSum = tempSum / num2; } else if (op.get(0) == "*") { Log.d("OSSI", "if multiply operator worked"); // Calculating tempSum * sum2 tempSum = tempSum * num2; } // Math to round 2 decimal number before tempSum will be set into totalSum double mathRound = tempSum; double tempSum = Math.round(mathRound*100.0)/100.0; // Changing tempSum to a String String sumAdition = Double.toString(tempSum); // String sumAdition will be the new totalSum text totalSum.setText(sumAdition); // Adding multiply symbol to the exsiting textView1 text textView1.setText(textView1.getText().toString() + " + "); // Adding to the op array list op.add("+"); // Removes the first operator from op arraylist op.remove(0); } // my click counter reset to zero myClickCount = 0; // Equal Switch to false so numbers can be used again equalSwitch = false; nSwitch = true; break; case R.id.button20: Log.d("OSSI", "button = was clicked"); if (myClickCount == 0) { } else if (ln.isEmpty()) { } else if (nSwitch == true) { } else { // Saving textView1 as lastNumb String lastNumb = textView1.getText().toString(); // A substring of lastNumb String will be saved as lastIput // (lastnumb minus the click counter, till the last lastnumb) String lastInput = lastNumb.substring(lastNumb.length() - myClickCount, lastNumb.length()); // Parsing lastInput to into num2 integer num2 = Double.parseDouble(lastInput); // Parsing String of totalSum into tempSum integer tempSum = Double.parseDouble(totalSum.getText().toString()); if (op.get(0) == "+") { Log.d("OSSI", "if plus operator worked"); // Calculating tempSum + sum2 tempSum = tempSum + num2; } else if (op.get(0) == "-") { Log.d("OSSI", "if minus operator worked"); // Calculating tempSum - sum2 tempSum = tempSum - num2; } else if (op.get(0) == "/") { Log.d("OSSI", "if devide operator worked"); // Calculating tempSum / sum2 tempSum = tempSum / num2; } else if (op.get(0) == "*") { Log.d("OSSI", "if multiply operator worked"); // Calculating tempSum * sum2 tempSum = tempSum * num2; } // Math to round 2 decimal number before tempSum will be set into totalSum double mathRound = tempSum; double tempSum = Math.round(mathRound*100.0)/100.0; // Changing tempSum to a String String sumEqual = Double.toString(tempSum); // String sumMultiply will be the new totalSum text totalSum.setText(sumEqual); // Adding to the op array list op.add("tF"); // Removes the first operator from op arraylist op.remove(0); // checks if equal was pressed so no number can be pressed equalSwitch = true; } break; case R.id.button12: Log.d("OSSI", "button Point was clicked"); // sets the textView1 to a string String string = textView1.getText().toString(); String pointChecker = string.substring(string.length() - myClickCount, string.length()); if (equalSwitch == true) { } else if (string.length() == 0){ // If string length is 0 no point will added } else if (myClickCount == 0) { } else if (pointChecker.contains(".")) { // If string contains a point, no new point will added } else { // Adds one point in the TextView after any given number textView1.setText(textView1.getText().toString() + "."); myClickCount++; } break; case R.id.button19: Log.d("OSSI", "button C was clicked"); textView1.setText(""); totalSum.setText(""); this.num1 = 0; this.num2 = 0; this.tempCount = 0; this.tempSum = 0; this.myClickCount = 0; this.nSwitch = true; this.equalSwitch = false; op.removeAll(op); ln.removeAll(ln); break; default: break; } } </code></pre>
[ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-02-04T18:43:36.413", "Id": "70002", "Score": "0", "body": "Once you've fixed the things @rolfl suggested below, please post a [follow-up question](http://meta.codereview.stackexchange.com/questions/1065/how-to-post-a-follow-up-question) as I think there will be more stuff that can be fixed then!" } ]
[ { "body": "<p>You have a large amount of code duplication. The highly technical description of your problem is 'DRY' or Don't Repeat Yourself.</p>\n\n<p>I would say that fixing three issues in your code would make the rest of the code a lot simpler to manage. Once those three are done, you should bring your code back for review.</p>\n\n<h2>1. Resources</h2>\n\n<p>You have completely munged the names of the resources in your Layout.xml file. Your button resources should have ID's that match the button. Why is <code>R.id.button3</code> actually <code>Button btn1</code>? You should re-identify all your resources and make the resource names match the use of the resource. This is a simple fix, but would have been better to get right the first time around.</p>\n\n<h2>2. Button Arrays</h2>\n\n<p>You should specify your buttons as an array of <code>Button</code> and you should populate it accordingly. Even better would be an enum of Button.</p>\n\n<pre><code>public enum CalculatorButton {\n ZERO(R.id.CalcZero),\n ONE(R.id.CalcOne),\n ....\n POINT(R.id.CalcPoint),\n ...\n ;\n\n\n public static final CalculatorButton getOwner(int buttonid) {\n for (CalculatorButton cb : values()) {\n if (cb.getButtonID() == button) {\n return cb;\n }\n }\n return null;\n }\n\n private final int calcbutton;\n private CalculatorButton(int calcbutton) {\n this.calcbutton = caclbutton;\n }\n\n public int getButtonID() {\n return calcbutton;\n }\n\n}\n</code></pre>\n\n<p>Then, when you set up your Activity, you can loop over the enum members:</p>\n\n<pre><code>for (CalculatorButton cb : CalculatorButton.values()) {\n cb.getButton().setOnClickListener(this);\n cb.getButton().setTypeface(btnTf)\n}\n</code></pre>\n\n<p>Similarly, there are a lot of other places where you can reduce the code footprint using the loop.</p>\n\n<h2>Switch on Enum</h2>\n\n<p>With your buttons represented as enum members, your big switch statement can become:</p>\n\n<pre><code>public void onClick(View v) {\n\n switch (CalculatorButton.getOwner(v.getId())) {\n case ONE:\n ....\n case POINT:\n ....\n\n}\n</code></pre>\n\n<p>You should have better handling for what you do with the buttons as well, but these three changes will go a long way to making your code more readable.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-02-04T00:36:19.353", "Id": "40814", "ParentId": "40807", "Score": "5" } } ]
{ "AcceptedAnswerId": "40814", "CommentCount": "1", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-02-03T23:58:22.980", "Id": "40807", "Score": "6", "Tags": [ "java", "android", "calculator" ], "Title": "Calculator Android App" }
40807
<p>I feel like this bit of code could be condensed or made better in some way. It may in fact not be, but figured I'd get some people to have a look. I have multiple pages on my site and in certain pages I'm setting a JavaScript variable:</p> <pre><code>var header_check = "user-profile"; </code></pre> <p>Some pages I'm not setting that variable. In another JavaScript file that gets loaded on the page I check if that variable exists and perform various actions if it does.</p> <p>Is this the best way to check if the variable exists? Also, is this the best way to see if <code>user-profile</code> is set?</p> <pre><code>var header_cookie = typeof header_check !== 'undefined' ? 'user-profile' : 'admin-profile'; var cookie_check = header_cookie == 'user-profile' ? true : false; var city_profile = cookie_check ? 'userCity' : 'city'; var state_profile = cookie_check ? 'userState' : 'state'; </code></pre>
[]
[ { "body": "<p>First off, your code really breaks down to this logic and I find it helpful to write it out the longer version to full understand the logic flow before trying to shorten it:</p>\n\n<pre><code>var header_cookie, cookie_check, city_profile, state_profile;\nif (typeof header_check !== \"undefined\") {\n header_cookie = 'user_profile';\n cookie_check = true;\n city_profile = 'userCity';\n state_profile = 'userState';\n} else {\n header_cookie = 'admin_profile';\n cookie_check = false;\n city_profile = 'city';\n state_profile = 'state;\n}\n</code></pre>\n\n<p>FYI, I also find this a LOT easier to follow what's actually happening than the code you have. It also saves several comparisons on the <code>cookie_check</code> value.</p>\n\n<hr>\n\n<p>There are some ways to shorten this, but it's not entirely clear that any are \"better\" where the definition of better includes readability by someone who has never seen this code before, but you can decide what you think of that issue for the alternatives:</p>\n\n<p>Since you really only have two states, you could predefine each state and then just pick which one to use and access the properties off a single state object:</p>\n\n<pre><code>var userState = {\n header_cookie: 'user_profile', city_profile: 'userCity', state_profile: 'userState';\n};\nvar adminState = {\n header_cookie: 'admin_profile', city_profile: 'city', state_profile: 'state';\n};\nvar state = typeof header_check !== \"undefined\" ? userState: adminState;\n</code></pre>\n\n<p>Done this way, you'd access <code>state.header_cookie</code>, <code>state.city_profile</code> and <code>state.state_profile</code> rather than your standalone variables.</p>\n\n<hr>\n\n<p>Or, if you wanted to keep the individual variables, you could do this:</p>\n\n<pre><code>var states = {\n header_cookie: ['user_profile', 'admin_profile'], \n city_profile: ['userCity', 'city'],\n state_profile: 'userState', 'state'];\n};\n\nvar stateIndex = typeof header_check !== \"undefined\" ? 0 : 1;\nvar header_cookie = states.header_cookie[stateIndex];\nvar city_profile = states.city_profile[stateIndex];\nvar state_profile = state.state_profile[stateIndex];\n</code></pre>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-02-04T00:24:59.803", "Id": "40810", "ParentId": "40808", "Score": "11" } } ]
{ "AcceptedAnswerId": "40810", "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-02-04T00:01:10.630", "Id": "40808", "Score": "6", "Tags": [ "javascript", "jquery" ], "Title": "Check if a JavaScript variable exists and checking its value" }
40808
<p>Implementing basic sorting algorithms to learn them, and coding, better. Criticisms/ critiques welcome. Also possible optimizations. </p> <pre><code>import unittest import random def insertion_sort(seq): """Accepts a mutable sequence, utilizes insertion sort algorithm to sort in place. Returns an ordered list""" #marks point between ordered sublist &amp; unordered list partition = 1 while partition &lt; len(seq): temp = partition #while temp not in correct pos in sublist, decrement pos while temp != 0 and seq[temp] &lt; seq[temp-1]: seq[temp], seq[temp-1] = seq[temp-1], seq[temp] temp -= 1 partition += 1 return seq class test_insertionsort(unittest.TestCase): def test_insertionsort(self): """Test insertion_sort()""" seq = [random.randrange(0, 1000) for _ in range(1000)] self.assertEqual(insertion_sort(seq), sorted(seq)) if __name__ == '__main__': unittest.main() </code></pre>
[ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-02-04T05:39:16.103", "Id": "69891", "Score": "0", "body": "I don't know much python so this maybe don't apply, but usually instead of inserting things to the array, the correct approach is to build a new one from scratch." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-02-04T10:12:28.197", "Id": "69910", "Score": "2", "body": "@ajax: [Insertion sort](https://en.wikipedia.org/wiki/Insertion_sort) is usually described as an \"in-place sort\" so there's nothing wrong with the OP's approach." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-02-04T10:16:26.100", "Id": "69912", "Score": "0", "body": "But I do think that using `seq.pop` and `seq.insert` is not really in the spirit of the exercise. These methods hide significant details of what the algorithm is doing. To really understand what is going on, you should try to implement it using only list assignment." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-02-04T16:01:33.210", "Id": "69972", "Score": "0", "body": "@GarethRees I've updated the code to implement your critique. Also, thank you for all the feedback you've been providing, I've been learning quite a bit from it." } ]
[ { "body": "<p>Answers from <a href=\"https://codereview.stackexchange.com/users/11728/gareth-rees\">Gareth Rees</a> to your other questions about <a href=\"https://codereview.stackexchange.com/questions/40734/selection-sort-algorithm-in-python\">selection sort</a> and <a href=\"https://codereview.stackexchange.com/questions/40699/bubble-sort-algorithm-in-python\">bubble sort</a> still apply here but it is clear that you tried to take them into account already.</p>\n\n<p>You can loop with <code>for partition in range(1, len(seq)):</code>. Also, it removes the need for an additional variable as it doesn't really matter anymore if you lose the current value of <code>partition</code> : it will have the right value at the beginning of the next iteration anyway.</p>\n\n<p>Here's what you could do :</p>\n\n<pre><code>for p in range(1, len(seq)):\n while p != 0 and seq[p] &lt; seq[p-1]:\n seq[p], seq[p-1] = seq[p-1], seq[p]\n p -= 1\nreturn seq\n</code></pre>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-02-04T17:43:15.537", "Id": "40864", "ParentId": "40809", "Score": "2" } }, { "body": "<p>One thing that can speed up insertion sort is to pull the partition value to the side and slide elements up into the vacancy until the correct location is found, then drop the partition value into that location. This eliminates one of the three assignments in the <code>while</code> loop:</p>\n\n<pre><code>for p in range(1, len(seq)):\n if seq[p] &gt;= seq[p-1]:\n continue\n p_value = seq[p]\n while p != 0 and p_value &lt; seq[p-1]:\n seq[p] = seq[p-1]\n p -= 1\n seq[p] = p_value\nreturn seq\n</code></pre>\n\n<p>The unit test shows a substantial speed improvement from doing this.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-02-04T20:42:30.510", "Id": "40887", "ParentId": "40809", "Score": "3" } }, { "body": "<p>Insertion sorts get a bad rap, mostly because people use them the wrong way. Sure the bench mark for all sorting algorithms is to sort an array in place, but in the real world your data doesn't always come to you in a complete package, sometimes it arrives asynchronously.</p>\n\n<p>Instead of force-fitting an insertion sort to existing data, let's redefine the problem to find the best <em>context</em> for an insertion sort:</p>\n\n<pre><code>import unittest\nimport random\n\nclass SortedList(list):\n def insert_item(self, new_item):\n insertion_point = len(self)\n for i, item in enumerate(self):\n if new_item &lt; item:\n insertion_point = i\n break\n self.insert(insertion_point, new_item)\n\nclass test_insertionsort(unittest.TestCase):\n def test_insertionsort(self):\n \"\"\"Test insertion_sort()\"\"\"\n sl = SortedList()\n seq = []\n for i in range(10000):\n item = random.randrange(0, 10000)\n sl.insert_item(item)\n seq.append(item)\n self.assertEqual(sl, sorted(seq))\n\nif __name__ == '__main__':\n unittest.main()\n</code></pre>\n\n<p>Here, instead of generating all the data before the sort, it is fed into the sort as it appears.</p>\n\n<p>(And note that a ~2x improvement is possible to optimize the insertion by starting in the middle of the list instead of always from the beginning).</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2015-10-29T08:16:42.863", "Id": "200680", "Score": "1", "body": "Hi, welcome to Code Review! Here, an answer should be about the code in the question. It's ok to present an alternative implementation, but then you should explain what issues it fixes, or in what way it's more optimal than the code in the question." } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2015-10-29T07:30:48.457", "Id": "109082", "ParentId": "40809", "Score": "1" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "4", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-02-04T00:18:21.600", "Id": "40809", "Score": "5", "Tags": [ "python", "beginner", "algorithm", "sorting", "insertion-sort" ], "Title": "Insertion Sort Algorithm in Python" }
40809
<p>I have a big in-memory collection of following simplified class:</p> <pre><code>public class Product { public int Id { get; set; } public string UserName { get; set; } public int CategoryId { get; set; } public string Title { get; set; } public string Description { get; set; } } </code></pre> <p>I need to search for products based on different properties like UserName or CategoryId. One way of searching would be using linq to objects like:</p> <pre><code>var userProducts = products.Where(x =&gt; x.UserName == "SomeValue") </code></pre> <p>This takes some processing when collection is too big and in my case it would be called hundreds of time each second.</p> <p>What I came up with was to introduce a new collection that supports indexing over different properties:</p> <pre><code>public class FastCollection&lt;T&gt; : IEnumerable&lt;T&gt; { private IList&lt;T&gt; _items; private IList&lt;Expression&lt;Func&lt;T, object&gt;&gt;&gt; _lookups; private Dictionary&lt;string, ILookup&lt;object, T&gt;&gt; _indexes; public FastCollection(IList&lt;T&gt; data) { _items = data; _lookups = new List&lt;Expression&lt;Func&lt;T, object&gt;&gt;&gt;(); _indexes = new Dictionary&lt;string, ILookup&lt;object, T&gt;&gt;(); } public void AddIndex(Expression&lt;Func&lt;T, object&gt;&gt; property) { _lookups.Add(property); _indexes.Add(property.ToString(), _items.ToLookup(property.Compile())); } public void Add(T item) { _items.Add(item); RebuildIndexes(); } public void Remove(T item) { _items.Remove(item); RebuildIndexes(); } public void RebuildIndexes() { if (_lookups.Count &gt; 0) { _indexes = new Dictionary&lt;string, ILookup&lt;object, T&gt;&gt;(); foreach (var lookup in _lookups) { _indexes.Add(lookup.ToString(), _items.ToLookup(lookup.Compile())); } } } public IEnumerable&lt;T&gt; FindValue&lt;TProperty&gt;(Expression&lt;Func&lt;T, TProperty&gt;&gt; property, TProperty value) { var key = property.ToString(); if(_indexes.ContainsKey(key)) { return _indexes[key][value]; } else { var c = property.Compile(); return _items.Where(x =&gt; c(x).Equals(value)); } } public IEnumerator&lt;T&gt; GetEnumerator() { return _items.GetEnumerator(); } System.Collections.IEnumerator System.Collections.IEnumerable.GetEnumerator() { return GetEnumerator(); } } </code></pre> <p>You can initialize the collection like this:</p> <pre><code>var fc = new FastCollection&lt;Product&gt;(products); fc.AddIndex(x =&gt; x.Id); fc.AddIndex(x =&gt; x.UserName); fc.AddIndex(x =&gt; x.CategoryId); </code></pre> <p>And finally you can search the collection like this:</p> <pre><code>var userProducts = gc.FindValue(x =&gt; x.UserName, "SomeValue"); </code></pre> <p>The fast collection makes a big difference when it comes to performance.</p> <p>My question is if I'm doing it right? I have used delegates and expressions to make it as generic as possible but I have this feeling that there is room for improvement!</p>
[ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-02-04T11:52:10.100", "Id": "69926", "Score": "0", "body": "Im not entirely sure but doesnt .Where do some kind of hashing tables to speed up comparing? Possibly the hashing causes issues on massive collection." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-02-04T13:38:34.227", "Id": "69937", "Score": "1", "body": "@ppumkin No, `Where()` doesn't do any kind of hashing. Doing that wouldn't make sense, because it would have to create a separate hash table for each query." } ]
[ { "body": "<p>Using <code>ToString()</code> to compare expressions for equality might work in simple cases, but:</p>\n\n<ul>\n<li>It requires you to always use the same parameter name, for example, it would consider <code>x =&gt; x.Id</code> and <code>product =&gt; product.Id</code> to be different expressions.</li>\n<li>Expressions with different meaning can produce the same string, for example <code>(int i) =&gt; (float)i</code> and <code>(int i) =&gt; (double)i</code> both produce <code>i =&gt; Convert(i)</code>. Because of this, it might make sense to ensure that the used expressions contain only property accesses and nothing else.</li>\n</ul>\n\n<p>Instead you should <a href=\"https://stackoverflow.com/a/673246/41071\">compare <code>Expression</code>s properly</a>.</p>\n\n<hr>\n\n<p>It seems wasteful to me to rebuild all indexes after each change. If you change the collection often, consider changing only the relevant part of each index.</p>\n\n<hr>\n\n<p>Fields that are set in the constructor and then never modified should be <code>readonly</code>.</p>\n\n<hr>\n\n<pre><code>IList&lt;T&gt; data\n</code></pre>\n\n<p>If you're on .Net 4.5, you could use <code>IReadOnlyList&lt;T&gt;</code> here.</p>\n\n<hr>\n\n<pre><code>if (_lookups.Count &gt; 0)\n</code></pre>\n\n<p>This check is pretty much useless. It saves you from unnecessarily creating an empty dictionary, but doing that is very cheap, so I think shorter code should take the priority here.</p>\n\n<hr>\n\n<p>You could replace the whole <code>RebuildIndexes()</code> method with a single <code>ToDictionary()</code>:</p>\n\n<pre><code>_indexes = _lookups.ToDictionary(\n lookup =&gt; lookup.ToString(), lookup =&gt; _items.ToLookup(lookup.Compile()));\n</code></pre>\n\n<hr>\n\n<pre><code>c(x).Equals(value)\n</code></pre>\n\n<p>This won't work correctly when <code>c(x)</code> returns <code>null</code>. You should probably use <code>object.Equals(c(x), value)</code> instead.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-02-04T02:25:54.300", "Id": "40818", "ParentId": "40811", "Score": "17" } }, { "body": "<p>When I test your collection against a list using <code>Where</code>. <code>Where</code> out performs your collection by a large factor. For instance 1,000 queries, with each one returning 1,000 records from a collection with 1,000,000 random elements takes less than 1 ms, whereas FindValue takes about 15 ms.</p>\n\n<p>EDIT:</p>\n\n<p>Ok with iterating the FastCollection does individual searches better. </p>\n\n<p>Did some more thinking on it. One of the reasons it seems so blindingly fast, is you're hiding the extra time and resources building a lookup table for each property you want to search by.</p>\n\n<p>One thing to consider is keeping your data in a DataTable instead of a list and use the Select method. This allows for very fast searches with times that are comparable to your class, when you factor in the extra time building the lookup table. However now it's in a format ready made for display in a DataGridView, or exporting to an xml file. One caveat is that the data is returned as a collection of DataRow, which might be a bother depending on what you intend for the data.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-02-04T10:34:39.743", "Id": "69919", "Score": "0", "body": "That's weird, my timings show agree with your that iterating `FindValue` takes 15 ms, but on my computer, iterating `Where()` takes 10 ms. It's still faster, but the difference is not that big." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-02-04T15:32:56.127", "Id": "69965", "Score": "0", "body": "@svick I added my test code in case my test was incomplete." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-02-04T16:42:17.830", "Id": "69976", "Score": "3", "body": "`var temp = products.Where(x => x.UserName == searchindexes[i]);` That's your problem right there, you call `Where()`, but you never iterate the result. But since `Where()` is lazy, that doesn't do almost anything, so your comparison is not fair. Instead, you should compare iterating over the results of `Where()` with iterating results of `FindValue()`." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-02-04T22:41:04.310", "Id": "70055", "Score": "0", "body": "@svick is right. Until you don't iterate over the result the query is not executed. If you append ToList() to the end of Where and FindValue statements it will execute the queries and the results would be accurate. I did run above test and FindValue is extremely faster." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-02-05T18:54:31.707", "Id": "70246", "Score": "0", "body": "@Atashbahar added some more thoughts for you to consider." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-02-05T22:07:14.283", "Id": "70280", "Score": "0", "body": "@tinstaafl: I agree that creating the fast collection is a bit heavy and it's more suitable for collections that won't be changed that often. Compared to DataTable this is a strongly typed collection which might be used for purposes other than displaying in a tabular format." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-11-23T11:50:13.397", "Id": "402271", "Score": "0", "body": "Along with DataTable to hold the data, consider using [DataView class](https://docs.microsoft.com/en-us/dotnet/api/system.data.dataview) per secondary index. As for having a \"strongly typed collection\" as mentioned by @Atashbahar, this is possible using xsd.exe: [Generating Strongly Typed DataSets](https://docs.microsoft.com/en-us/dotnet/framework/data/adonet/dataset-datatable-dataview/generating-strongly-typed-datasets). Not sure if anyone has written code to use reflection to generate the strongly typed classes from a .Net class - that would make this more practical for general .Net coding." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-11-23T11:54:54.133", "Id": "402272", "Score": "0", "body": "... I mean given a class like OP's `Product`, and a list of fields to build indices on, it should be possible to *generate* something like his `FastCollection`, built on strongly-typed DataTable and associated DataViews. So coder doesn't have to hand-write the xsd file. The benefit is that these classes handle modifying the internal indices as you change rows." } ], "meta_data": { "CommentCount": "8", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-02-04T07:08:59.547", "Id": "40828", "ParentId": "40811", "Score": "7" } }, { "body": "<p>The FastCollection contains an additional list and a dictionary of lists, so it's memory consumption overhead might become an issue.</p>\n\n<p>I would suggest that you look into representing your data structure (Product) in a data structure which is more optimal for searching than a list. If you into tree-structures or balanced tree structures, you will see that searching cost O(log n), where n is the number of elements in the tree.</p>\n\n<p>You can easily build the tree structure with a custom compare function, and thereby having a very fast generic searchable structure.</p>\n\n<p>Well, just an idea, which you might consider overkill :)</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-11-23T12:12:32.493", "Id": "402274", "Score": "0", "body": "How does this help OP \"search for products based on different properties\"? The data needs to be in a collection that can be looked up O(1) by some master key, so that each property can be represented by an additional collection that provides that master key. O(log n) lookup is moving in the wrong direction, performance-wise." } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-02-16T10:58:18.000", "Id": "41790", "ParentId": "40811", "Score": "3" } } ]
{ "AcceptedAnswerId": "40818", "CommentCount": "2", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-02-04T00:33:13.897", "Id": "40811", "Score": "34", "Tags": [ "c#", "linq", "lookup" ], "Title": "Multiple indexes over an in memory collection for faster search" }
40811
<p>First off, here's the code:</p> <p><strong>main.m</strong></p> <pre><code>#import &lt;Foundation/Foundation.h&gt; #import "PSBoard.h" #import "PSPlayer.h" #import "PSInputHandler.h" int main(int argc, const char * argv[]) { @autoreleasepool { NSLog(@"Enter Player 1 Name:"); NSString *playerOneName = [PSInputHandler getString]; NSLog(@"Enter Player 2 Name:"); NSString *playerTwoName = [PSInputHandler getString]; NSLog(@"How many rows and columns will you play with?"); NSUInteger numberOfRowsAndColumns = [PSInputHandler getInteger]; PSPlayer *playerOne = [[PSPlayer alloc] initWithSymbol:PSBoardSymbolX name:playerOneName]; PSPlayer *playerTwo = [[PSPlayer alloc] initWithSymbol:PSBoardSymbolO name:playerTwoName]; PSBoard *board = [[PSBoard alloc] initWithRows:numberOfRowsAndColumns columns:numberOfRowsAndColumns players:@[playerOne, playerTwo]]; do { PSPlayer *currentPlayer = [board playerUp]; BOOL validInputEntered = NO; //Loop until valid input is entered while(!validInputEntered) { //Get input coordinates NSLog(@"%@, enter a row (1-%lu).", currentPlayer.name, (unsigned long)numberOfRowsAndColumns); NSUInteger row = [PSInputHandler getInteger]; NSLog(@"Now enter a column (1-%lu).", (unsigned long)numberOfRowsAndColumns); NSUInteger column = [PSInputHandler getInteger]; //Verify that nothing is already placed there PSBoardSymbol symbolOfPlayerAtCoordinates = [board playerAtRow:row-1 column:column-1].symbol; if((symbolOfPlayerAtCoordinates != PSBoardSymbolX &amp;&amp; symbolOfPlayerAtCoordinates != PSBoardSymbolO) &amp;&amp; row &gt; 0 &amp;&amp; row &lt;= numberOfRowsAndColumns &amp;&amp; column &gt; 0 &amp;&amp; column &lt;= numberOfRowsAndColumns) { [board setPlayer:currentPlayer atRow:(row-1) column:(column-1)]; validInputEntered = YES; } } //Show the board [board display]; } while(!board.winner); NSLog(@"Congrats %@! You won.", [board winner].name); } return 0; } </code></pre> <p><strong>PSBoard.h</strong></p> <pre><code>#import &lt;Foundation/Foundation.h&gt; @class PSPlayer; @interface PSBoard : NSObject @property (nonatomic) NSUInteger rows; @property (nonatomic) NSUInteger columns; @property (nonatomic, strong) PSPlayer *winner; -(instancetype)initWithRows:(NSUInteger)rows columns:(NSUInteger)columns players:(NSArray *)players; -(PSPlayer *)playerAtRow:(NSUInteger)row column:(NSUInteger)column; -(void)setPlayer:(PSPlayer *)player atRow:(NSUInteger)row column:(NSUInteger)column; -(void)display; -(PSPlayer *)playerUp; @end </code></pre> <p><strong>PSBoard.m</strong></p> <pre><code>#import "PSBoard.h" #import "PSPlayer.h" @interface PSBoard () @property (nonatomic, strong) NSMutableArray *internalBoardRepresentation; @property (nonatomic, strong) NSArray *players; @property (nonatomic, strong) PSPlayer *oldPlayerUp; @end @implementation PSBoard -(instancetype)initWithRows:(NSUInteger)rows columns:(NSUInteger)columns players:(NSArray *)players { if(self = [super init]) { self.rows = rows; self.columns = columns; self.players = players; self.internalBoardRepresentation = [[NSMutableArray alloc] initWithCapacity:rows]; PSPlayer *null = [[PSPlayer alloc] initWithSymbol:PSBoardSymbolNone name:nil]; for(NSUInteger row = 0; row &lt; rows; row++) { NSMutableArray *currentColumn = [NSMutableArray array]; for(NSUInteger column = 0; column &lt; columns; column++) { [currentColumn addObject:null]; } [self.internalBoardRepresentation addObject:currentColumn]; } self.oldPlayerUp = players[0]; } return self; } -(PSPlayer *)playerAtRow:(NSUInteger)row column:(NSUInteger)column { return self.internalBoardRepresentation[row][column]; } -(void)setPlayer:(PSPlayer *)player atRow:(NSUInteger)row column:(NSUInteger)column { self.internalBoardRepresentation[row][column] = player; [self checkForWinner]; } -(void)checkForWinner { NSUInteger numberOfPiecesInARowToWin = MAX(self.rows, self.columns); //Check horizontal lines for(NSUInteger row = 0; row &lt; self.rows; row++) { PSPlayer *playerInFirstColumn = [self playerAtRow:row column:0]; NSUInteger playerPiecesInRow = 0; for(NSUInteger column = 0; column &lt; self.columns; column++) { if([[self playerAtRow:row column:column] isEqualTo:playerInFirstColumn]) { playerPiecesInRow++; } } if(playerPiecesInRow &gt;= numberOfPiecesInARowToWin &amp;&amp; playerInFirstColumn.symbol != PSBoardSymbolNone) { self.winner = playerInFirstColumn; return; } } //Check vertical lines for(NSUInteger column = 0; column &lt; self.columns; column++) { PSPlayer *playerInFirstRow = [self playerAtRow:0 column:column]; NSUInteger playerPiecesInColumn = 0; for(NSUInteger row = 0; row &lt; self.rows; row++) { if([[self playerAtRow:row column:column] isEqualTo:playerInFirstRow]) { playerPiecesInColumn++; } } if(playerPiecesInColumn &gt;= numberOfPiecesInARowToWin &amp;&amp; playerInFirstRow.symbol != PSBoardSymbolNone) { self.winner = playerInFirstRow; return; } } //Check top left to bottom right diagonal PSPlayer *playerInFirstSlotOfLeftDiagonal = [self playerAtRow:0 column:0]; NSUInteger playerPiecesInLeftDiagonal = 0; for(NSUInteger row = 0, column = 0; row &lt; self.rows; column++, row++) { if([[self playerAtRow:row column:column] isEqualTo:playerInFirstSlotOfLeftDiagonal]) { playerPiecesInLeftDiagonal++; } } if(playerPiecesInLeftDiagonal &gt;= numberOfPiecesInARowToWin &amp;&amp; playerInFirstSlotOfLeftDiagonal.symbol != PSBoardSymbolNone) { self.winner = playerInFirstSlotOfLeftDiagonal; return; } //Check bottom left to top right diagonal PSPlayer *playerInFirstSlotOfRightDiagonal = [self playerAtRow:self.rows-1 column:0]; NSUInteger playerPiecesInRightDiagonal = 0; for(NSInteger row = self.rows-1, column = 0; row &gt;= 0; row--, column++) { if([[self playerAtRow:row column:column] isEqualTo:playerInFirstSlotOfRightDiagonal]) { playerPiecesInRightDiagonal++; } } if(playerPiecesInRightDiagonal &gt;= numberOfPiecesInARowToWin &amp;&amp; playerInFirstSlotOfRightDiagonal.symbol != PSBoardSymbolNone) { self.winner = playerInFirstSlotOfRightDiagonal; return; } } -(void)display { NSMutableString *displayString = [NSMutableString stringWithFormat:@"\n"]; for(NSUInteger row = 0; row &lt; self.rows; row++) { NSMutableString *rowDisplayString = [[NSMutableString alloc] init]; NSString *innerFillerString = (row == self.rows-1) ? @" " : @"_"; for(NSUInteger column = 0; column &lt; self.columns; column++) { NSString *columnSeparator = (column == self.columns-1) ? @" " : @"|"; NSString *playerSymbol = ([self playerAtRow:row column:column].symbolStringRepresentation); if(playerSymbol.length == 0) { playerSymbol = innerFillerString; } [rowDisplayString appendString:[NSString stringWithFormat:@"%@%@%@%@", innerFillerString, playerSymbol, innerFillerString, columnSeparator]]; } [displayString appendString:[NSString stringWithFormat:@"%@\n", rowDisplayString]]; [rowDisplayString setString:@""]; } NSLog(@"%@", displayString); } -(PSPlayer *)playerUp { PSPlayer *nextPlayerUp = self.players[1-([self.players indexOfObjectIdenticalTo:self.oldPlayerUp])]; PSPlayer *previousPlayerUp = self.oldPlayerUp; self.oldPlayerUp = nextPlayerUp; return previousPlayerUp; } @end </code></pre> <p><strong>PSPlayer.h</strong></p> <pre><code>#import &lt;Foundation/Foundation.h&gt; typedef NS_ENUM(NSInteger, PSBoardSymbol) { PSBoardSymbolX = 0, PSBoardSymbolO, PSBoardSymbolNone }; @interface PSPlayer : NSObject -(instancetype)initWithSymbol:(PSBoardSymbol)symbol name:(NSString *)name; @property (nonatomic) PSBoardSymbol symbol; @property (nonatomic) NSString *symbolStringRepresentation; @property (nonatomic, strong) NSString *name; @end </code></pre> <p><strong>PSPlayer.m</strong></p> <pre><code>#import "PSPlayer.h" @implementation PSPlayer -(instancetype)initWithSymbol:(PSBoardSymbol)symbol name:(NSString *)name{ if(self = [super init]) { self.symbol = symbol; self.symbolStringRepresentation = (symbol == PSBoardSymbolO) ? @"O" : ((symbol == PSBoardSymbolX) ? @"X" : @""); self.name = name; } return self; } @end </code></pre> <p><strong>PSInputHandler.h</strong></p> <pre><code>#import &lt;Foundation/Foundation.h&gt; @interface PSInputHandler : NSObject +(NSString *)getString; +(NSInteger)getInteger; @end </code></pre> <p><strong>PSInputHandler.m</strong></p> <pre><code>#import "PSInputHandler.h" @implementation PSInputHandler +(NSInteger)getInteger { int temp; scanf("%i", &amp;temp); return (NSInteger)temp; } +(NSString *)getString { char input[256]; scanf("%s", input); return [NSString stringWithUTF8String:input]; } @end </code></pre> <p>So my questions are:</p> <ol> <li>In the <code>PSInputHandler.m</code> class, I wasn't so sure about how to get input from the command line. I read that <code>fgets()</code> is a potential alternative to <code>scanf()</code>, but is there any reason for me to use one over the other?</li> <li>The method in <code>PSBoard.m</code> that checks for a winner, <code>checkForWinner</code>, is very long. Is there a simplified design I can use to shorten it?</li> <li>I struggled to name the <code>playerUp</code> method, which returns the player whose turn it is. Is there a more suitable name?</li> <li>When the user inputs which row and column to place an X or O in, I made it so that the coordinates they enter are from 1 to the number of rows and not 0 to the number of rows minus one (like with zero-based array indexing). Is this more user-friendly, or should I change it to zero-based indexing?</li> <li>In <code>PSPlayer.m</code>, I use nested ternary operators. Is this too hard to understand? Should I change it to if statements? <ol> <li>When getting the user's input for how many rows and columns to use, which I expect to be an integer, how can I sanitize the input so that the program doesn't crash when a string (for example) is inputted?</li> </ol></li> </ol> <p>Any other critique welcome!</p>
[ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-02-04T03:30:48.583", "Id": "68871", "Score": "6", "body": "Hi and welcome to CodeReview. You have just passed the 'First Question' review with flying colours. Good question. You may, by the way, be interested in the current Ultimate-Tic-Tac-Toe [tag:code-challenge] that [is taking place this month](http://meta.codereview.stackexchange.com/questions/1471/weekend-challenge-reboot/1472#1472)." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-02-04T04:11:03.080", "Id": "68886", "Score": "0", "body": "@rolfl - Thanks! Glad to see I'm not violating any rules. That challenge looks interesting. Might take a stab at it." } ]
[ { "body": "<p>I will update this post over the weekend as I go through your question more and come up with some examples to iterate over my points, but I thought for now, I'd answer some of the easier questions.</p>\n\n<hr>\n\n<p><strong>Question 1.</strong></p>\n\n<p>I'm not sure and cannot remember (I will try to find out). At the end of the day, you might consider implementing this with a GUI. If you're using Xcode, it's quite easy to develop a GUI for either OSX or iOS, and most of your logic is already in place. You'd just have to write the logic to hook the GUI up to the business logic.</p>\n\n<hr>\n\n<p><strong>Question 2.</strong></p>\n\n<p>One immediate thought on speeding up this process would be to use a flag to mark whether or not a row/column is a potential winner. AND, if you do find a row that's a winner, immediately return the winner.</p>\n\n<p>For a row to be a winner, every piece in the row must belong to the same player, correct? So set the owner of the piece in the first box, and check every box. As soon as you get to a box that doesn't match the first box, <code>break;</code>. You don't need to check any more boxes in that row/column/diagonal. You can move to the next row/column/diagonal. And if you get to the end of the inner loop and haven't had to <code>break;</code> because you've found the winner, then you can set the winner and <code>return;</code> and stop checking. </p>\n\n<p>So basically, refactor into something more like this:</p>\n\n<pre><code>for(NSUInteger row = 0; row &lt; self.rows; row++) {\n\n PSPlayer *playerInFirstColumn = [self playerAtRow:row column:0];\n BOOL winnerFound;\n\n for(NSUInteger column = 0; column &lt; self.columns; column++) {\n if(![[self playerAtRow:row column:column] isEqualTo:playerInFirstColumn]) {\n winnerFound = false;\n break;\n } else {\n winnerFound = true;\n }\n }\n\n if (winnerFound) {\n self.winner = playerInFirstColumn;\n return;\n }\n}\n</code></pre>\n\n<p>This will improve performance some. You can probably still do better, but this is still a drastic improvement, especially for exceptionally large boards.</p>\n\n<p>Now... the BEST performance improvement I can think of would actually mean you're running this check after every turn (which you're already doing, right?). In this case, you only need to check ONE row, ONE column, and ZERO, ONE, or TWO diagonals. And this would be a massive performance boost. You only need to check a the row the piece was played in, the column the piece was played in, and the diagonal the piece was played in. Every other row, column, and diagonal has been checked on a previous turn and a winner was not found otherwise the game would be over and we wouldn't've had this turn. </p>\n\n<p>AND, even if we modified the rules to continue playing after a winner has been found, you can just use an array to keep track of each row and column and diagonal and who won that row/column/diagonal, and still only need to check the relevant rows (and only check them for the player who played the piece).</p>\n\n<hr>\n\n<p><strong>Question 3.</strong></p>\n\n<p><code>playerUp</code> is probably an alright method name. Maybe <code>activePlayer</code>? If you feel it's not descriptive enough, don't hesitate to leave a comment explaining it. <code>// returns the player whose turn it is</code></p>\n\n<hr>\n\n<p><strong>Question 4.</strong></p>\n\n<p>As a programmer, I am used to 0-based indexing systems, but your assumption is correct. Most people who use programs aren't programs and would be more comfortable with a 1-based coordinate system. Though... back to question 1... if this were given a GUI, it wouldn't matter. ;)</p>\n\n<hr>\n\n<p><strong>Question 5.</strong></p>\n\n<p>Personally, I hate the ternary operators and never use them. Whether or not they're acceptable would depend largely on who you're working with though. In this case, it's a simple one. Again, personally, I hate them and I wouldn't use it, because I never use it, but this one is simple enough that if you and everyone working on the project are comfortable with them, then go ahead and keep it.</p>\n\n<p><strong>Question 5.1.</strong></p>\n\n<p>The exact way you want to handle non-number input is an implementation detail that'd be up to you. Do you want to request another input? Do you want to just strip out the non-numbers and use the numbers that are there?</p>\n\n<p>But as for actually checking the string itself, once you've got it into an <code>NSString</code>, it's quite easy:</p>\n\n<pre><code>NSCharacterSet *nonNumbers = [[NSCharacterSet \n decimalDigitCharacterSet] invertedSet];\n\nif([yourString rangeOfCharactersFromSet:nonNumbers].location == NSNotFound) {\n // string is all numbers and is good to go\n} else {\n // string contains non-number characters\n}\n</code></pre>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-02-07T23:38:50.060", "Id": "41188", "ParentId": "40820", "Score": "13" } } ]
{ "AcceptedAnswerId": "41188", "CommentCount": "2", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-02-04T02:47:09.880", "Id": "40820", "Score": "12", "Tags": [ "optimization", "game", "objective-c" ], "Title": "Tic Tac Toe implementation in Objective-C" }
40820
<p>Problem description. Returns strings with probability determined by the frequency of each of the strings. eg: if "foo" has weight of 50% and "bar" has weight of another 50% then both foo and bar should be 5 and 5 times each given that 10 tries were made.</p> <p>If question is unclear let me know I will reply asap. Looking for code review, optimizations and best practice.</p> <p>Also verifying that complexity of <code>next()</code> is undefined due to probabilistic nature.</p> <pre><code>public final class WeightedRandom&lt;T&gt; { private final List&lt;ItemData&lt;T&gt;&gt; itemDataList; private final int size; private int count; /** * Takes in a list of items. * * @param items the list of items * @throws NullPointerException if items is null. * @throws IllegalArgumentException if the input list size is zero. */ public WeightedRandom (List&lt;T&gt; items) { if (items.size() == 0) throw new IllegalArgumentException("The size of list should be greater than zero."); size = items.size(); itemDataList = new ArrayList&lt;ItemData&lt;T&gt;&gt;(); addAll(items); } private void addAll(List&lt;T&gt; items) { final Map&lt;T, Integer&gt; map = new HashMap&lt;T, Integer&gt;(); for (T item : items) { int val = 0; if (map.containsKey(item)) { val = map.get(item); } map.put(item, val + 1); } for (Entry&lt;T, Integer&gt; entry : map.entrySet()) { itemDataList.add(new ItemData&lt;T&gt;(entry.getKey(), entry.getValue(), 0)); } } private static class ItemData&lt;T&gt; { T item; int frequency; int usedCount; ItemData (T item, int frequency, int usedCount) { this.item = item; this.frequency = frequency; this.usedCount = usedCount; } } /** * Returns strings with probability determined by the frequency * of each of the strings. * eg: if "foo" has weight of 50% and "bar" has weight of another 50% then both foo and * bar should be 5 and 5 times each given that 10 tries were made * * @return the next item in the weighted probabilistic manner. */ public synchronized T next() { if (count == size) { clear(); } ItemData&lt;T&gt; data = getRandomData(); // until we reach the item who is not-exhausted, keep trying. while (data.usedCount == data.frequency) { data = getRandomData(); } data.usedCount++; count++; return data.item; } private ItemData&lt;T&gt; getRandomData() { int random = new Random().nextInt(itemDataList.size()); return itemDataList.get(random); } /** * Resets the weights, which are exptected to be modified * in the duration of the code. */ public synchronized void clear() { count = 0; for (ItemData&lt;T&gt; data : itemDataList) { data.usedCount = 0; } } public static void main(String[] args) { List&lt;String&gt; list = new ArrayList&lt;String&gt;(); list.add("sachin"); list.add("sachin"); list.add("sachin"); list.add("rahul"); list.add("rahul"); list.add("ganguly"); WeightedRandom&lt;String&gt; wrr1 = new WeightedRandom&lt;String&gt;(list); WeightedRandom&lt;String&gt; wrr2 = new WeightedRandom&lt;String&gt;(list); /* * tests the random behavior, by checking output of two objects differ. * This testing too is probablistic. */ boolean result1 = false; int count = 0; while (count &lt; 6) { if (!wrr1.next().equals(wrr2.next())) { result1 = true; break; } count++; } System.out.println(" random ? Answer: " + result1); /* * testing that weights are honored. */ Map&lt;String, Integer&gt; map = new HashMap&lt;String, Integer&gt;(); map.put("sachin", 6); map.put("rahul", 4); map.put("ganguly", 2); count = 0; wrr1.clear(); while (count &lt; 12) { map.remove(wrr1.next()); count++; } boolean result2 = true; for (Entry&lt;String, Integer&gt; entry : map.entrySet()) { if (entry.getValue() != 0) { result2 = false; break; } } System.out.println(" weights obeyed ? : Answer: " + result2); } } </code></pre>
[]
[ { "body": "<p>The code looks nice. A few minor improvements or ideas:</p>\n\n<ol>\n<li><p>You need only two simple methods to make it an <code>Iterator</code>:</p>\n\n<pre><code>public final class WeightedRandom&lt;T&gt; implements Iterator&lt;T&gt; {\n\n ...\n\n @Override\n public boolean hasNext() {\n return true;\n }\n\n @Override\n public void remove() {\n throw new UnsupportedOperationException();\n }\n}\n</code></pre>\n\n<p>It could be useful/convenient for clients.</p></li>\n<li>\n\n<pre><code>if (items.size() == 0) {\n throw new IllegalArgumentException(\"The size of list should be greater than zero.\");\n}\n</code></pre>\n\n<p><code>items.isEmpty()</code> would be a little bit readable and you could use <a href=\"https://code.google.com/p/guava-libraries/wiki/PreconditionsExplained\" rel=\"nofollow\">Guava's <code>Preconditons</code></a> too to make it more fluent and explicit:</p>\n\n<pre><code>checkNotNull(items, \"items cannot be null\");\ncheckArgument(!items.isEmpty(), \"The size of list should be greater than zero.\");\n</code></pre></li>\n<li>\n\n<pre><code>itemDataList = new ArrayList&lt;ItemData&lt;T&gt;&gt;(); \n</code></pre>\n\n<p>This could be in the declaration:</p>\n\n<pre><code>import static com.google.common.collect.Lists.newArrayList;\n\n...\n\n private final List&lt;ItemData&lt;T&gt;&gt; itemDataList = newArrayList();\n</code></pre></li>\n<li><p>The constructor of <code>ItemData</code> is always called with zero <code>usedCount</code>. Consider setting a default value for that parameter and remove it from the signature:</p>\n\n<pre><code>private static class ItemData&lt;T&gt; {\n T item;\n int frequency;\n int usedCount = 0;\n\n ItemData(final T item, final int frequency) {\n this.item = item;\n this.frequency = frequency;\n }\n}\n</code></pre>\n\n<p>Currently the number <code>0</code> is a magic number in the constructor call:</p>\n\n<pre><code>itemDataList.add(new ItemData&lt;T&gt;(entry.getKey(), entry.getValue(), 0));\n</code></pre>\n\n<p>Readers have to check the constructor of <code>ItemData</code> to figure out what it means. An explanatory local variable be an improvement. (<em>Clean Code</em> by <em>Robert C. Martin</em>, <em>G19: Use Explanatory Variables</em>; <em>Refactoring: Improving the Design of Existing Code by Martin Fowler</em>, <em>Introduce Explaining Variable</em>)</p></li>\n<li><p><code>addAll</code> would be a little bit shorter with a <a href=\"http://docs.guava-libraries.googlecode.com/git/javadoc/com/google/common/collect/Multiset.html\" rel=\"nofollow\">Multiset</a>:</p>\n\n<pre><code>private void addAll(final List&lt;T&gt; items) {\n final Multiset&lt;T&gt; multiset = HashMultiset.create();\n multiset.addAll(items);\n\n for (final Entry&lt;T&gt; entry: multiset.entrySet()) {\n itemDataList.add(new ItemData&lt;T&gt;(entry.getElement(), entry.getCount()));\n }\n}\n</code></pre></li>\n<li><p>Javadoc of <code>next</code> speaks about strings but it could be any type (<code>T</code>). It's a little bit confusing.</p></li>\n<li><p>Javadoc typo: <code>exptected</code> (Eclipse has spell check.)</p></li>\n</ol>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-02-04T05:04:22.470", "Id": "40825", "ParentId": "40823", "Score": "3" } }, { "body": "<p>The code looks nice and I think that the <code>main()</code> method has the biggest room for improvements here. You could automatize testing with JUnit. It would make it a <a href=\"http://xunitpatterns.com/Goals%20of%20Test%20Automation.html#Self-Checking%20Test\" rel=\"nofollow\">self-checking test</a> without <a href=\"http://xunitpatterns.com/Manual%20Intervention.html\" rel=\"nofollow\">manual intervention</a> and <a href=\"http://xunitpatterns.com/Manual%20Intervention.html#Manual%20Result%20Verification\" rel=\"nofollow\">manual result verification</a>.</p>\n\n<p>First, you need to make the class deterministic. You can do that with modifying the class to be able to use a mocked <code>Random</code> instance or a <a href=\"http://docs.oracle.com/javase/7/docs/api/java/util/Random.html#Random%28long%29\" rel=\"nofollow\"><code>Random</code> instance with a fixed seed</a>. (If the seed is the same the returned values are predictable.)</p>\n\n<p>A way for that is moving the <code>Random</code> instance to a field:</p>\n\n<pre><code>private final Random random = new Random();\n\n...\n\nprivate ItemData&lt;T&gt; getRandomData() {\n final int randomIndex = random.nextInt(itemDataList.size());\n return itemDataList.get(randomIndex);\n}\n</code></pre>\n\n<p>Then, you could modify it with reflection (Apache Commons Lang has a nice <a href=\"http://commons.apache.org/proper/commons-lang/apidocs/org/apache/commons/lang3/reflect/FieldUtils.html#writeField%28java.lang.Object,%20java.lang.String,%20java.lang.Object,%20boolean%29\" rel=\"nofollow\"><code>FieldUtils</code></a> for that).</p>\n\n<p>Another way is creating a constructor which has a <code>Random</code> parameter:</p>\n\n<pre><code>private final Random random;\n\npublic WeightedRandom(final List&lt;T&gt; items) {\n this(items, new Random());\n}\n\npublic WeightedRandom(final List&lt;T&gt; items, final Random random) {\n checkNotNull(items, \"items cannot be null\");\n checkArgument(!items.isEmpty(), \n \"The size of list should be greater than zero.\");\n size = items.size();\n this.random = checkNotNull(random, \"random cannot be null\");\n\n addAll(items);\n}\n</code></pre>\n\n<p>It's worth noting that </p>\n\n<ul>\n<li>this reduces coupling between the <code>WeightedRandom</code> and <code>Random</code> classes,</li>\n<li>it also could be useful if a client needs to use <code>SecureRandom</code> instead of <code>Random</code>,</li>\n<li>does not require reflection (and doesn't depend on the name of the field),</li>\n<li>it's a quite good example that making code testable improves its design/quality.</li>\n</ul>\n\n<p>Finally, your tests rewritten with extensive use of Google Guava to make them sort:</p>\n\n<pre><code>import static com.google.common.collect.Lists.newArrayList;\nimport static org.hamcrest.CoreMatchers.equalTo;\nimport static org.hamcrest.CoreMatchers.not;\nimport static org.hamcrest.MatcherAssert.assertThat;\nimport static org.junit.Assert.assertTrue;\n\nimport java.util.Iterator;\nimport java.util.List;\nimport java.util.Random;\n\nimport org.junit.Test;\n\nimport com.google.common.collect.HashMultiset;\nimport com.google.common.collect.Iterators;\nimport com.google.common.collect.Lists;\nimport com.google.common.collect.Multiset;\nimport com.google.common.collect.Multisets;\n\npublic class WeightedRandomTest {\n\n // @formatter:off\n private final List&lt;String&gt; list = newArrayList(\n \"sachin\", \n \"sachin\", \n \"sachin\", \n \"rahul\", \n \"rahul\", \n \"ganguly\");\n // @formatter:off\n\n @Test\n public void testRandomBehaviour() throws Exception {\n final long seedOne = 1;\n final long seedTwo = seedOne + 1;\n final WeightedRandom&lt;String&gt; randomOne = \n createWeightedRandomWithSeed(list, seedOne);\n final WeightedRandom&lt;String&gt; randomTwo = \n createWeightedRandomWithSeed(list, seedTwo);\n\n final int elementCount = 6;\n final List&lt;String&gt; elementsOne = \n getElements(randomOne, elementCount);\n final List&lt;String&gt; elementsTwo = \n getElements(randomTwo, elementCount);\n\n assertThat(elementsOne, not(equalTo(elementsTwo)));\n }\n\n @Test\n public void testWeightsAreHonored() {\n final WeightedRandom&lt;String&gt; weightedRandom = \n new WeightedRandom&lt;String&gt;(list);\n final Multiset&lt;String&gt; expectedDistribution = \n HashMultiset.create();\n expectedDistribution.setCount(\"sachin\", 6);\n expectedDistribution.setCount(\"rahul\", 4);\n expectedDistribution.setCount(\"ganguly\", 2);\n\n final List&lt;String&gt; randomElements = \n getElements(weightedRandom, 12);\n\n Multisets.removeOccurrences(expectedDistribution, \n HashMultiset.create(randomElements));\n assertTrue(expectedDistribution.isEmpty());\n }\n\n private List&lt;String&gt; getElements(\n final WeightedRandom&lt;String&gt; weightedRandom, \n final int count) {\n final Iterator&lt;String&gt; limitedIterator = \n Iterators.limit(weightedRandom, count);\n return Lists.newArrayList(limitedIterator);\n }\n\n private WeightedRandom&lt;String&gt; createWeightedRandomWithSeed(\n final List&lt;String&gt; list, final long seed)\n throws IllegalAccessException {\n final Random seededRandom = new Random(seed);\n return new WeightedRandom&lt;String&gt;(list, seededRandom);\n }\n\n}\n</code></pre>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-02-04T06:15:52.687", "Id": "40826", "ParentId": "40823", "Score": "2" } }, { "body": "<p>You are not clear in your question what the purpose of your class is... the code suggests that, for an input list of size <code>k</code>, that once you have 'pulled' k items from the <code>WeightedRandom</code> that the histogram of the results will exactly match the histogram of the input frequencies. Additionally, for every 2k elements you pull, the relative frequency will remain unchanged.</p>\n\n<p>Unfortunately, your code does not actually do a very good job of randomizing the values. For example, consider data with the input frequency of <code>[a, b, b, b, b, b, b, b, b, b]</code> (i.e. 1 <code>a</code> and 9 <code>b</code> values). What your code is supposed to do is:</p>\n\n<p>For every 10 times we pull values from the <code>WeightedRandom</code>:</p>\n\n<ul>\n<li>one value will be <code>a</code></li>\n<li>the remaining 9 will be <code>b</code></li>\n<li>the <code>a</code> value should be randomly distributed among the <code>b</code> values.</li>\n</ul>\n\n<p>The problem you have is with the random distribution. Your code does this:</p>\n\n<ul>\n<li>it creates 2 buckets, one for <code>a</code> with frequency 1, one for <code>b</code> with frequency 9.</li>\n<li>it then does a random selection between the 2 buckets ( <code>int random = new Random().nextInt(itemDataList.size());</code> )</li>\n<li>this means that the odds are 50/50 that it will chose <code>a</code> the first time for every 10</li>\n<li>if it does not choose <code>a</code>, it will 50/50 choose <code>a</code> the next time....</li>\n</ul>\n\n<p>The bottom line is that the odds of <code>a</code> being at the front of the list are 50%, but only 0.2% that it will be the last item. In reality, it should be 10% likely to end up at any location...</p>\n\n<p>The logical way to solve this problem is so much simpler than what you have done:</p>\n\n<ul>\n<li>create an array with the data members</li>\n<li>shuffle it</li>\n<li>walk the shuffled data when you need an item</li>\n<li>when you reach the end, re-shuffle the data, and start again.</li>\n</ul>\n\n<p>The code to do it is:</p>\n\n<pre><code>public final class WeightedRandom&lt;T&gt; {\n\n private final List&lt;T&gt; itemData;\n private int cursor = 0;\n\n public WeightedRandom (List&lt;T&gt; items) {\n if (items.size() == 0) throw new IllegalArgumentException(\"The size of list should be greater than zero.\");\n // take a copy of the list.\n itemData = new ArrayList&lt;T&gt;(items);\n }\n\n public synchronized T next() {\n cursor--;\n if (cursor &lt; 0) {\n Collections.shuffle(itemData);\n cursor = itemData.size() - 1;\n }\n return itemData.get(cursor);\n }\n\n public synchronized void clear() {\n cursor = 0;\n }\n}\n</code></pre>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-02-05T00:50:39.883", "Id": "40907", "ParentId": "40823", "Score": "3" } } ]
{ "AcceptedAnswerId": "40907", "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-02-04T03:57:27.847", "Id": "40823", "Score": "5", "Tags": [ "java", "algorithm", "random" ], "Title": "Weighted probabilistic sampling" }
40823
<p>You guess a word, and if its letter(s) is in the same spot as a hidden word's, you add [] around the letter. If it's in the hidden word, but not in the same spot, you add()).</p> <p>As of now, I have a whole bunch of loops which I find makes the program un-compact. I would love to see some tips on how to shorten this program! Efficiency isn't a problem. I am looking for compactness.</p> <pre><code>word = list("tiger") guesses = 0 holder = 1 while holder == 1: s = list(input("Please input what you think the word is")) while len(s) &gt; 5 or len(s) &lt; 5: print("Please guess a five - letter word!") s = list(input("Please input what you think the word is")) s2 = s for i in range (0, len(word)): if word[i] == s[i]: letter = ("[",s[i],"]") lette = "".join(letter) s2[i] = letter for i in range (0, len(word)): for j in range (0, len(word)): if s[i] == word[j]: letter2 = ("(", s[i],")") letter2 ="".join(letter2) s2[i] = letter2 print(s2) guesses = guesses +1 print ("You have used", guesses, "guesses/guess") s3 = ["[t]", "[i]", "[g]", "[e]", "[r]"] if s2 == s3: print("You WIN!") holder = 2 </code></pre>
[ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-02-04T06:35:08.350", "Id": "69893", "Score": "0", "body": "Compactness? Defined as Simplicity? reduction in lines of code?" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-02-04T06:36:34.603", "Id": "69894", "Score": "1", "body": "Reduction in lines of code. Simplicity is not required, but as a beginner in Python I would like to see some tips I can understand." } ]
[ { "body": "<pre><code>def game(word):\n guesses = 0\n while True:\n user_string = prompt(\"What do you think the word is? \",\n lambda s: len(s) == len(word),\n \"Please guess a {}-letter word.\".format(len(word)))\n\n if user_string == word:\n print(\"You WIN!\")\n break\n\n print([handle_letter(user_string, word, i) for i in user_string])\n\n guesses += 1\n print (\"You have guessed {} times.\".format(guesses))\n\n\ndef handle_letter(user_string, word, i):\n if user_string[i] == word[i]:\n return \"[\" + user_string[i] + \"]\"\n elif user_string[i] in word:\n return \"(\" + user_string[i] + \")\"\n else:\n return user_string[i]\n\n\ndef prompt(statement, condition, warning):\n user_string = input(statement)\n while not condition(user_string):\n print(warning)\n user_string = input(statement)\n return user_string\n\n\ndef main():\n game(\"tiger\")\n\nif __name__ == '__main__':\n main()\n</code></pre>\n\n<p>Assuming you are familiar with functions, there should be only two things here that stand out as \"weird\": the <code>lambda</code> and the list comprehension (this line: <code>print([handle_letter(user_string, word, i) for i in user_string])</code>).</p>\n\n<p><code>lambda</code>s are just anonymous functions, meaning they are functions that don't have name. I could have easily instead written:</p>\n\n<pre><code>def is_correct_length(user_string):\n return len(user_string) == len(word)\n</code></pre>\n\n<p>and replaced the <code>lambda</code> line with <code>is_correct_length</code>. It's just shorter this way.*</p>\n\n<p>The list comprehension is a huge code-lines win, but I'd rather you just read <a href=\"http://docs.python.org/2/tutorial/datastructures.html#list-comprehensions\" rel=\"nofollow\">http://docs.python.org/2/tutorial/datastructures.html#list-comprehensions</a> than me explain it to you.</p>\n\n<p>*Actually this approach would not work because <code>word</code> is not in scope for the sub-function unless you define it inside of game. <code>lambda</code> has the advantage here of having access to all the variables that in the scope of game, including word, which makes life easier.</p>\n\n<p>If you reeeealy wanted to avoid the <code>lambda</code> you could put the definition of <code>is_correct_length</code> indented and inside of the definition of game, but this is probably not a good move stylistically.</p>\n\n<p>It just occurred to me that this is actually MORE lines of code than you originally had, but I'd say it's better code because it's much more modular. The <code>prompt</code> function, for instance, seems ridiculously useful for games like this one and you can use it everywhere. </p>\n\n<p>If you remove the <code>main()</code> and ifmain wrappers and put thing on one line that I have put on two, you could probably make it shorter, though this is usually not a good idea because readability it far more important than lines of code.</p>\n\n<p>(If you really want to make it shorter - no holds barred - you could do this:</p>\n\n<pre><code>print([\"[\" + user_string[i] + \"]\" if user_string[i] == word[i] else \"(\" + user_string[i] + \")\" if user_string[i] in word else user_string[i] for i in range(len(user_string))])\n</code></pre>\n\n<p>Instead of the current line in <code>game</code> and completely remove <code>handle_letter</code>. However, this is much harder to read so I would advise against it.) </p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-02-04T15:42:41.240", "Id": "69967", "Score": "1", "body": "Besides the lamda which I don't really understand, I can use alot of the stuff you showed me. Thank you." } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-02-04T07:57:56.753", "Id": "40830", "ParentId": "40827", "Score": "2" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "2", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-02-04T06:17:58.667", "Id": "40827", "Score": "4", "Tags": [ "python", "beginner", "strings", "array", "game" ], "Title": "Lingo game using Python" }
40827
<p>The code runs fine and takes 100s to complete it for 5 iteration. I need to reduce it to take less time with the same number of iterations. </p> <p>h = 324 by 648 matrix</p> <p>The code is that of FFT Belief Propagation for LDPC codes over gf(8).</p> <pre><code>tic [a2,b2] = size(h); % h is the parity check matrix 324 by 648 %% breaking rn such that each cell contains 3 bits ( soft values from demodulator) as 3 bits will give 1 symbol z = 3; mat = repmat(z,1,b2); sym = mat2cell(rn,1,[mat]); % rn is the received bits that has to be decoded. %%Generating the truth table 0 - 255 TT = dec2bin(0:7)=='1'; TTH([1:8],:) = TT([1 2 3 5 4 7 8 6],:); %% Creating the F matrix (Likelihood) %% this part is concerned about computing the likelihood of each received bits.. for k = 1:(b2) WN = sym{1,k}; for i = 1:8 for j = 1:3 if TTH(i,j)==0 P(i,j) = 1./(1+exp((2*WN(j))/sig^2)); else P(i,j) = 1./(1+exp((-2*WN(j))/sig^2)); end end EN = P(i,:); PN(i,:) = prod(EN); end like{1,k} = PN; end F = cell2mat(like); % size of F = 8 by 648 [a1,b1] = size(F); %% whereever there is a non zero value in the h matrix, one cell of F is placed there for i =1:b2 for j = 1:a2 if h(j,i)~=0 Q_A{j,i} = like{i}; else Q_A{j,i} = zeros(size(like{i})); end end end Q_Original1 = cell2mat(Q_A); for itr = 1:iter [a3,b3] = size(Q_Original1); Q_1strow(1:8:a3,:) = Q_Original1(1:8:a3,:); % saving the rows that will not be permuted Q_Original2=Q_Original1; Q_Original2([1:8:a3],:) = []; % removing the non permuted row from the matrix [a4,b4]= size(Q_Original2); %% breaking the matrix and putting it into cells of 7 by 1 for i =1:b4 for j =1:7:a4 P_Q{j,i} = Q_Original2(j:j+6,i); end end % Removing empty array from P_Q P_QN = P_Q.'; P_Qnew = reshape(P_QN(~cellfun(@isempty,P_QN)),b2,[])'; %removing empty cells %% permuting the each cell according to its position with respect to the H matrix %% suppose H (j,i) = 2, it will be permuted once. the order of the permutation is found in matrix indx indx = [0 1 2 3 4 5 6]; extension = [1 2 4 3 6 7 5] % h matrix will have values within the extension matrix % suppose h = 5, permutation order will be 6 for i = 1:b2 for j=1:a2 W = P_Qnew{j,i}; x0 = h(j,i); if x0 ==0 Q_permute{j,i} = W; else [x2,x3] = find(extension'==x0); Q_permute{j,i} = circshift(W, indx(x2,x3)); end end end Q_per=cell2mat(Q_permute); %Removing rows of zeroes from Q_1strow Q_1stroww = Q_1strow(any(Q_1strow,2),:); [p1,p2] = size(Q_1strow); p3 = p1 -a2; %% here the unpermuted rows are inserted back by using the function Insertrow from mathswork permuted_Q = insertrows(Q_per,Q_1stroww, [0:7:p3]); %% fft method [a5,b5] = size(permuted_Q); YN = hadamard(8); %% hadamard matrix is applied to columns of 7 for i = 1:8:a5 for j = 1:b5 PNN = permuted_Q(i:i+7,j); %Rearranging the rows such that each row differ by one bits PNN1([1:8],:) = PNN([1 2 3 5 4 8 6 7],:); %YN=hadamard(8); % Use of Hadamard matrix to compute fft F_P(i:i+7,j)= YN*PNN1; %F_P(i:i+3,j)= fft(PN); end end [a6,b6] = size(F_P); B(1:a6,1:b6) = inf; for i = 1:a6 for j=1:b6 if (F_P(i,j)~=0) B(i,j)= j; end end end for i = 1:a6 for j=1:b6 AP = find(B(i,:)==j); if (length(AP)~=0) prodt=1; I1= find(B(i,:)~=inf &amp; B(i,:)~=j); for i1 = 1:length(I1) prodt = prodt.*F_P(i,I1(i1)); end rin(i,j) = prodt; end end end [a7,b7] = size(rin); % inverse fft using hadamard matrix to obtain matrix R for i = 1:8:a7 for j =1:b7 XN = rin(i:i+7,j); R_d = (1/8).*(YN*XN); % inverse of the Fast Hadamard Transform R_f([1 2 3 5 4 8 6 7],:) = R_d([1:8],:); % bringing back the values to their original position R(i:i+7,j) = R_f; end end [a8,b8] = size(R); %saving the unpermuted row R_1strow(1:8:a8,:) = R(1:8:a8,:); R_1 = R; %deleting the unpermuted row from the matrix R_1([1:8:a8],:)=[]; [a9,b9]=size(R_1); % putting into cells for i =1:b9 for j = 1:7:a9 R_dper{j,i} = R_1(j:j+6,i); end end R_dperm = R_dper.'; R_dpermut = reshape(R_dperm(~cellfun(@isempty,R_dperm)),b2,[])'; for i = 1:b2 for j =1:a2 Z = R_dpermut{j,i}; x0 = h(j,i); if x0==0 R_dpermuted{j,i} = Z; else [x2,x3] = find(extension'==x0); R_dpermuted{j,i} = circshift(Z,-indx(x2,x3)); end end end R_depermuted = cell2mat(R_dpermuted); R_1stroww = R_1strow(any(R_1strow,2),:); depermuted_R = insertrows(R_depermuted,R_1stroww,[0:7:p3]); %% Vertical Step % Breaking the depermuted_R matrix into 4 matrices [a10,b10] = size(depermuted_R); R1 = depermuted_R(1:8:a10,:); R2 = depermuted_R(2:8:a10,:); R3 = depermuted_R(3:8:a10,:); R4 = depermuted_R(4:8:a10,:); R5 = depermuted_R(5:8:a10,:); R6 = depermuted_R(6:8:a10,:); R7 = depermuted_R(7:8:a10,:); R8 = depermuted_R(8:8:a10,:); C(1:a2,1:b2) = inf; for i = 1:a2 for j = 1:b2 if (h(i,j)~=0) C(i,j)=i; end end end for i = 1:b2 %colums for j = 1:a2 % rows P = find(C(:,i)==j); if (length(P)~=0) prod1 = 1; prod2 = 1; prod3 = 1; prod4 = 1; prod5 = 1; prod6 = 1; prod7 = 1; prod8 = 1; I3 = find(C(:,i)~=inf &amp; C(:,i)~=j); for i3 = 1:length(I3) prod1 = prod1.*R1(I3(i3),i); prod2 = prod2.*R2(I3(i3),i); prod3 = prod3.*R3(I3(i3),i); prod4 = prod4.*R4(I3(i3),i); prod5 = prod5.*R5(I3(i3),i); prod6 = prod6.*R6(I3(i3),i); prod7 = prod7.*R7(I3(i3),i); prod8 = prod8.*R8(I3(i3),i); end const1 = prod1.*F(1,i); const2 = prod2.*F(2,i); const3 = prod3.*F(3,i); const4 = prod4.*F(4,i); const5 = prod5.*F(5,i); const6 = prod6.*F(6,i); const7 = prod7.*F(7,i); const8 = prod8.*F(8,i); constbeta = 1/(const1 + const2 + const3 + const4 + const5 + const6 + const7 + const8); new_Q1(j,i) = constbeta*const1; new_Q2(j,i) = constbeta*const2; new_Q3(j,i) = constbeta*const3; new_Q4(j,i) = constbeta*const4; new_Q5(j,i) = constbeta*const5; new_Q6(j,i) = constbeta*const6; new_Q7(j,i) = constbeta*const7; new_Q8(j,i) = constbeta*const8; end end end for i = 1:a2 AN = new_Q1(i,:); BN = new_Q2(i,:); CN = new_Q3(i,:); DN = new_Q4(i,:); EN = new_Q5(i,:); FN = new_Q6(i,:); GN = new_Q7(i,:); HN = new_Q8(i,:); L{i,:} = vertcat(AN,BN,CN,DN,EN,FN,GN,HN); end Q_Original1 = cell2mat(L); % Pseudo Posterior Probabilities for i =1:b2 for j = 1:a2 CK = find(C(:,i)==j); if (length(CK)~=0) prdt1 = 1; prdt2 = 1; prdt3 = 1; prdt4 = 1; prdt5 = 1; prdt6 = 1; prdt7 = 1; prdt8 = 1; I4 = find(C(:,i)~=inf); for i4 = 1:length(I4) prdt1 = prdt1.*R1(I4(i4),i); prdt2 = prdt2.*R2(I4(i4),i); prdt3 = prdt3.*R3(I4(i4),i); prdt4 = prdt4.*R4(I4(i4),i); prdt5 = prdt5.*R5(I4(i4),i); prdt6 = prdt6.*R6(I4(i4),i); prdt7 = prdt7.*R7(I4(i4),i); prdt8 = prdt8.*R8(I4(i4),i); end cnst1 = prdt1.*F(1,i); cnst2 = prdt2.*F(2,i); cnst3 = prdt3.*F(3,i); cnst4 = prdt4.*F(4,i); cnst5 = prdt5.*F(5,i); cnst6 = prdt6.*F(6,i); cnst7 = prdt7.*F(7,i); cnst8 = prdt8.*F(8,i); cnstbeta = 1 / (cnst1 + cnst2 + cnst3 +cnst4 +cnst5 +cnst6 +cnst7 +cnst8); end end Y1(i)= cnstbeta*cnst1; Y2(i)= cnstbeta*cnst2; Y3(i)= cnstbeta*cnst3; Y4(i)= cnstbeta*cnst4; Y5(i)= cnstbeta*cnst5; Y6(i)= cnstbeta*cnst6; Y7(i)= cnstbeta*cnst7; Y8(i)= cnstbeta*cnst8; end Q_dash = vertcat(Y1,Y2,Y3,Y4,Y5,Y6,Y7,Y8); end [a11,b11] = max(Q_dash); for i = 1:length(b11) if b11(i)==1 decoded_bits(i) = 0; elseif b11(i) ==2 decoded_bits(i)=1; elseif b11(i) ==3 decoded_bits(i)=2; elseif b11(i)==4 decoded_bits(i)=4; elseif b11(i)==5 decoded_bits(i)=3; elseif b11(i)==6 decoded_bits(i)=6; elseif b11(i)==7 decoded_bits(i)=7; elseif b11(i)==8 decoded_bits(i)=5; end end toc </code></pre>
[ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-02-04T12:30:12.717", "Id": "69928", "Score": "6", "body": "Please add an explanation about what the code does, it will be much easier to help you that way." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-02-23T21:43:18.133", "Id": "73460", "Score": "0", "body": "Use `profile` to find which part is the slowest first." } ]
[]
{ "AcceptedAnswerId": null, "CommentCount": "2", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-02-04T12:21:19.773", "Id": "40838", "Score": "2", "Tags": [ "optimization", "matlab", "matrix" ], "Title": "Increasing speed of parity check matrix" }
40838
<p>This my solution to one of the practice problems from <em>Cracking the Coding Interview: 150 Programming Interview Questions and Solutions [Book]</em></p> <blockquote> <p>implement an algorithm to determine of a string has all unique characters. What if you cannot use additional data structures ?</p> </blockquote> <pre><code>public class PracticeProblems { public void questionOne(String input) { /*-- implement an algorithm to determine if a string has all unique characters. * What if you cannot use additional data structures? --*/ boolean[] chars = new boolean[26]; int x = 0; for(int i = 0; i &lt; input.length(); i++) { if(!chars[(int)input.toUpperCase().charAt(i) - 64]) { chars[(int)input.toUpperCase().charAt(i) - 64] = true; } else { System.out.println("not unique"); x = -1; break; } } if(x == 0) System.out.println("unique"); } public static void main(String[] args) { PracticeProblems test = new PracticeProblems(); test.questionOne("dsfdddft"); } } </code></pre> <p>I was wondering if there was a better solution to this, or if there is a better way of handling the last part, where I am initializing an x variable to be able to determine if I all the characters are not unique, not to print "it is unique". If don't have the condition for the x value it always prints "it is unique". </p>
[ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-02-07T11:44:10.940", "Id": "70600", "Score": "3", "body": "You quote says \"unique characters\" not unique letters. In Java `char` can have 2^16 = 65536 different values. What does your program return for this string \"?\"" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-08-21T09:46:37.397", "Id": "110019", "Score": "1", "body": "Yes 'A' and 'a' are not the same if the question says unique characters, so the toUpperCase() is wrong if so." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2015-08-15T06:02:56.180", "Id": "184598", "Score": "0", "body": "What if a string consists of numbers? In this case, we can have a bool array of 256 (assuming ASCII) and use an ASCII value as an index." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2016-07-12T07:40:55.503", "Id": "251931", "Score": "2", "body": "Notice the subtle off-by-one error in the code - you subtract 64 from the Unicode character (presumed in the range `A`-`Z`, i.e. 65-90) but valid indices into `chars` are `0-25`. Including an `a` and a `z` in your test cases would expose this error." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2016-07-12T13:49:49.593", "Id": "252004", "Score": "0", "body": "Isn't an array considered a data structure? You're using it as a simple hash table." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2016-10-02T00:59:46.853", "Id": "268164", "Score": "0", "body": "How about this? public static boolean isStringhasAllUniqueChar(String myString){\n String myStringLC = myString.toLowerCase();\n boolean areAllUnique = false;\n \n for(int i=0; i<myStringLC.length()-1; i++){\n char first = myStringLC.charAt(i);\n char second = myStringLC.charAt(i+1);\n System.out.println(\"first: \"+ first+\" second:\"+ second);\n if(first == second){\n \n areAllUnique = true;\n }\n else {\n \n areAllUnique = false;\n }\n }\n return areAllUnique;\n }" } ]
[ { "body": "<p>You probably shouldn't call <code>toUpperCase()</code> twice on each character.</p>\n\n<p>If you wanted to split your code properly (if it was for a real-life project for instance), it would make sense to make the documentation a bit better and to define a method taking a <code>String</code> as an argument and returning a <code>boolean</code>. Let's keep things simple for the time being; you can return immediately after printing \"not unique\". If you do so, there's no need for the test on <code>x</code> and there's no need for <code>x</code> at all.</p>\n\n<p>You probably should check that the characters are in the right range before accessing <code>chars</code>.</p>\n\n<p>I'd rather read <code>if (c) { A } else { B }</code> than <code>if (!c) { B } else { A }</code> even though it depends from one situation to another. In our case, it also allows to remove a level of nesting because of the <code>return</code>.</p>\n\n<p>You don't need an instance of <code>PracticeProblems</code> at all, and the function could just be static.</p>\n\n<p>Finally, I do not know if Java optimises out the different call to <code>length()</code> so we might ensure we don't call it every time.</p>\n\n<pre><code>public class PracticeProblems {\n public static void questionOne(String input) {\n boolean[] chars = new boolean[26];\n String upper = input.toUpperCase();\n\n for(int i = 0, n = upper.length(); i &lt; n; i++)\n {\n char c = upper.charAt(i);\n if ('A' &lt;= c &amp;&amp; c &lt;= 'Z')\n {\n if(chars[(int)c - 'A'])\n {\n System.out.println(\"not unique\");\n return;\n }\n chars[(int)c - 'A'] = true;\n }\n }\n System.out.println(\"unique\");\n }\n\n public static void main(String[] args) {\n questionOne(\"dsfdddft\");\n }\n}\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-02-06T13:51:21.973", "Id": "70389", "Score": "0", "body": "The JVM does a lot of optimizations *at runtime* based on many factors (and based on *which* JVM it is). Calling that `.length()` function for sure isn't a concern at all." } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-02-04T13:48:37.127", "Id": "40844", "ParentId": "40841", "Score": "6" } }, { "body": "<p>Well, you don't really need the x variable at all. As soon as you read a repeated character, you could print \"not unique\" and return from the function, instead of just breaking the loop. Something like:</p>\n\n<pre><code>public void questionOne(String input) {\n /*-- implement an algorithm to determine if a string has all unique characters. \n * What if you cannot use additional data structures? --*/\n\n boolean[] chars = new boolean[26];\n\n for(int i = 0; i &lt; input.length(); i++) {\n\n if(!chars[(int)input.toUpperCase().charAt(i) - 64]) {\n chars[(int)input.toUpperCase().charAt(i) - 64] = true;\n }\n else {\n System.out.println(\"not unique\");\n return;\n }\n }\n\n System.out.println(\"unique\");\n}\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2017-09-11T08:14:27.730", "Id": "332677", "Score": "0", "body": "Horribly inefficient, and `isUniquelyComposed(\"z\")` doesn't work." } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-02-04T13:48:59.633", "Id": "40845", "ParentId": "40841", "Score": "3" } }, { "body": "<p>I would return a <code>boolean</code> from the method that decides what is unique:</p>\n\n<pre><code>public boolean isUniquelyComposed (String word) {\n\n boolean[] alphabetMap = new boolean[26];\n\n\n for(int index=0, length = word.length(); index &lt; length; index ++) {\n int offsetAsciiCode = (int) word.toUpperCase().charAt(index) - 64;\n\n if(!alphabetMap[offsetAsciiCode])\n alphabetMap[offsetAsciiCode] = true;\n else\n return false;\n }\n\n return true;\n}\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2017-10-05T03:52:43.650", "Id": "336144", "Score": "0", "body": "`isUniquelyComposed(\"z!\")`" } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-06-01T03:48:32.753", "Id": "52178", "ParentId": "40841", "Score": "1" } }, { "body": "<p>If string has only lowercase or upper case characters then you can use this O(1) solution. No extra memory or any additional data structure.</p>\n\n<pre><code>bool checkUnique(string s){\n if(s.size() &gt;26)\n return false;\n int unique=0;\n for (int i = 0; i &lt; s.size(); ++i) {\n int j= s[i]-'a';\n if(unique &amp; (1&lt;&lt;j)&gt;0)\n return false;\n unique=unique|(1&lt;&lt;j);\n }\n return true;\n}\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2015-11-24T21:31:21.180", "Id": "206172", "Score": "3", "body": "Welcome to Code Review! You have presented an alternative solution, but haven't reviewed the code. Please explain your reasoning (how your solution works and how it improves upon the original) so that the author can learn from your thought process." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2015-11-24T22:58:24.430", "Id": "206181", "Score": "0", "body": "I dont think this solution is O(1) ?" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2015-11-25T09:36:19.890", "Id": "206258", "Score": "0", "body": "It is O(1) as O(26) is O(1) asymptotically . Correct me if I am wrong ." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2017-09-08T00:57:29.147", "Id": "332254", "Score": "0", "body": "@Praveen You're wrong. Your solution is \\$O(\\text{s.length()})\\$." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2017-09-29T07:20:04.777", "Id": "335348", "Score": "0", "body": "@Roland The solution is O(len(alphabets size)) --> As the alphabet size is fixed so ,it is ultimately O(1) .Explanation: If the string length is more than the distinct alphabets , then by Pigeon Hole principle , the string has duplicate chars. Also s.size() is O(1) as all the string class has internal counter to track the size of the string [link] (http://www.cplusplus.com/reference/string/string/size/)" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2017-09-29T13:00:03.513", "Id": "335380", "Score": "0", "body": "Oh, that's a really mean trick arguing with the alphabet size fixed. You're completely right then." } ], "meta_data": { "CommentCount": "6", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2015-11-24T21:20:32.883", "Id": "111743", "ParentId": "40841", "Score": "-1" } }, { "body": "<p>I have no idea why all existing answers have the magic number 26 in them, which clearly shows an ASCII- and American-centric world view. A proper solution to this problem must:</p>\n\n<ul>\n<li>First discuss whether the word <em>character</em> means <code>char</code> or Unicode code point.</li>\n<li>Be able to handle arbitrary characters (as defined above).</li>\n<li>Be a single method with appropriate return type.</li>\n</ul>\n\n<p>Then, the following solutions come to mind:</p>\n\n<pre><code>public static boolean hasUniqueChars(String str) {\n char[] chars = str.toCharArray();\n Arrays.sort(chars);\n for (int i = 1; i &lt; chars.length; i++) {\n if (chars[i - 1] == chars[i]) {\n return false;\n }\n }\n return true;\n}\n\npublic static boolean hasUniqueCodePoints(String str) {\n int[] cps = str.codePoints().toArray();\n ...\n}\n</code></pre>\n\n<p>The variant without additional data structures (and no heap memory allocation at all) has theoretical time complexity \\$O(1)\\$ (with a quite large constant factor, <code>MAX_CODE_POINT ** 2</code>), and practical time complexity \\$O(n^2)\\$, where \\$n\\$ is the length of the string.</p>\n\n<pre><code>public static boolean hasUniqueCodePoints(String str) {\n int len = s.length();\n if (len &gt; Character.MAX_CODE_POINT) {\n return false;\n }\n\n for (int i = 0; i &lt; len; ) {\n int cp = s.codePointAt(i);\n if (str.indexOf(cp) != i) {\n return false;\n }\n i += Character.charCount(cp);\n }\n return true;\n}\n</code></pre>\n\n<p>See <a href=\"https://stackoverflow.com/a/1527891\">https://stackoverflow.com/a/1527891</a>.</p>\n\n<p>By the way, the <a href=\"https://github.com/careercup/ctci/blob/master/java/Chapter%201/Question1_1/Question.java\" rel=\"nofollow noreferrer\">official solution</a> (as of 2017-09-08) is as bad as most code from that book, violating the first two of my requirements.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2017-09-08T00:38:26.890", "Id": "175096", "ParentId": "40841", "Score": "0" } } ]
{ "AcceptedAnswerId": "40844", "CommentCount": "6", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-02-04T13:11:24.957", "Id": "40841", "Score": "9", "Tags": [ "java", "algorithm", "strings" ], "Title": "Algorithm to determine if a string is all unique characters" }
40841
<p>I am trying to read a single-columned CSV of doubles into <code>Java</code> with a string header. It is 11 megabytes and takes over 15 minutes to read, which is clearly unacceptable. In <code>R</code> this CSV would take about 3 seconds to load.</p> <p>This CSV file may contain strings so I am parsing it with this in mind.</p> <p>The CSV reading method needs to return <code>Vector&lt;Double&gt;</code> due to reliance on this output by other parts of the application.</p> <p>The issue is not due to the <code>isNumber</code> static method, since each call to that is taking <code>200 nanoseconds</code>, thus contributing approximately 0.2 seconds to the 15 minutes of parsing time.</p> <p>The <code>Double.valueOf()</code> only takes about 500 nanoseconds, so it is not that either.</p> <p><code>csvData.add()</code> is only taking 80 nanoseconds so it is not that.</p> <pre><code>private static Vector&lt;Double&gt; readTXTFileSingle(String csvFileName) throws IOException { String line = null; BufferedReader stream = null; Vector&lt;Double&gt; csvData = new Vector&lt;Double&gt;(); try { stream = new BufferedReader(new FileReader(csvFileName)); while ((line = stream.readLine()) != null) { String[] splitted = line.split(","); if( ! NumberUtils.isNumber(splitted[0])) { continue; } Double dataLine = Double.valueOf(splitted[0]); csvData.add(dataLine); } } finally { if (stream != null) stream.close(); } return csvData; } </code></pre>
[ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-02-04T13:35:25.150", "Id": "69936", "Score": "2", "body": "How is `NumberUtils.isNumber` implemented?" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-02-04T14:03:06.097", "Id": "69939", "Score": "0", "body": "@SimonAndréForsberg This is responsible for 200 milliseconds of the lag (200 nanoseconds per call, 1,000,000 times). So it is not the problem" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-02-04T14:23:09.607", "Id": "69943", "Score": "0", "body": "I'd still like to see it, if you're willing to provide it." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-02-04T14:24:33.957", "Id": "69944", "Score": "0", "body": "@SimonAndréForsberg It's open source `org.apache.commons.lang.math.NumberUtils`. I didn't read the method because it's very long. But can confirm a consistent 60-300 nanoseconds, holding aside accidental garbage collection within the nanoTime() window." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-02-04T14:35:50.560", "Id": "69947", "Score": "1", "body": "Wait a moment, you profiled it but do not know where it is slow?" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-02-04T14:37:38.507", "Id": "69948", "Score": "0", "body": "@Bobby Profiled a bit of it. Running other tests now." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-02-04T14:38:54.417", "Id": "69949", "Score": "1", "body": "Run a profiler on it...I mean, yes, we are doing reviews for performance improvements, but we do not do guess work. Please run it through a profiler and see what takes that long, then add that information to the question." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-02-04T14:41:01.893", "Id": "69951", "Score": "0", "body": "But my first guess would be the resizing of the `Vector`. Creating it with an appropriate default capacity should help." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-02-04T15:07:59.763", "Id": "69954", "Score": "0", "body": "It takes 1.2 seconds to read a 85MB CSV file on my machine. What's your input look like?" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-02-04T15:08:47.257", "Id": "69955", "Score": "0", "body": "@palacsint Are they all doubles?" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-02-04T15:10:15.180", "Id": "69956", "Score": "0", "body": "A sample line: `111.23456789,88,AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA,BBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBB`. The file contains it one million times." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-02-04T22:13:56.587", "Id": "70053", "Score": "0", "body": "May I ask what is your environment? (JVM version, OS, CPU, memory)" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-02-05T12:15:35.637", "Id": "70167", "Score": "0", "body": "As @bowmore pointed out, you must have something else going on. You have accepted 'my' answer... did it help? How much? What else is happening in your code? The suggestions I gave are not enough to fix a 15-minute problem." } ]
[ { "body": "<p>As per Bobby's comment, Vector is your problem, but not for the reason he says...</p>\n\n<p>Vector is a <strong>synchronized</strong> class. Each call to any method on Vector will lock the thread, flush all cache lines, and generally waste a lot of time (in a situation where it's usage is in a single thread only).</p>\n\n<p>The fact that you use Vector indicates that you are running some really old code, or you have not properly <a href=\"http://docs.oracle.com/javase/7/docs/api/java/util/Vector.html\" rel=\"nofollow\">read the JavaDoc for it</a>.</p>\n\n<p>A secondary performance problem is that each value is being converted to a <code>Double</code> Object. In cases where you have large amounts of data, and where there is a primitive available for you to use, it is always faster to use the primitive (in this case, <code>double</code> instead of <code>Double</code>).</p>\n\n<p>You should also be using the Java7 try-with-resources mechanism for your <code>stream</code>.</p>\n\n<p>My recommendation is to change the signature of your method to return a List... actually, no, my recommendation is to return an array of primitive <code>double[]</code>.... if you are interested in speed, this will be a significant improvement:</p>\n\n<pre><code>private static double[] readTXTFileSingle(String csvFileName) throws IOException {\n double[] csvData = new double[4096]; // arbitrary starting size.\n int dcnt = 0;\n\n try (BufferedReader stream = new BufferedReader(new FileReader(csvFileName))) {\n String line = null;\n while ((line = stream.readLine()) != null) {\n String[] splitted = line.split(\",\");\n if( ! NumberUtils.isNumber(splitted[0])) {\n\n continue;\n }\n\n double dataLine = Double.parseDouble(splitted[0]);\n if (dcnt &gt;= csvData.length) {\n // add 50% to array size.\n csvData = Arrays.copyOf(csvData, dcnt + (dcnt / 2));\n }\n csvData[dcnt++] = dataLine;\n\n }\n }\n return Arrays.copyOf(csvData, dcnt);\n}\n</code></pre>\n\n<h2>Edit:</h2>\n\n<p>One other thing, if you want another tweak in performance, use:</p>\n\n<pre><code>String[] splitted = line.split(\",\", 2);\n</code></pre>\n\n<p>since you never access more than the first field in the record, you do not need to look for comma's beyond the first comma</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-02-04T15:32:17.717", "Id": "69964", "Score": "2", "body": "\"Vector is a synchronized class.\" Ah, now I understand that odd \"You shouldn't use that but I can't remember why\" feeling I had." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-02-05T07:42:50.527", "Id": "70121", "Score": "1", "body": "I doubt `Vector`'s synchronization is responsible for a 15 minute run on an 11M file. I've tried this code (with `Vector` in place) on a local file and it consistently returned in under 1 second." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-02-05T11:20:07.157", "Id": "70154", "Score": "0", "body": "@bowmore you are right... by the way, did you run it with a pre-set vector size or did you let it grow? The OP must have something else going on" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-02-05T12:06:11.243", "Id": "70165", "Score": "0", "body": "I've used the code as is in OP. I only supplied a very naive `isNumber()` implementation myself by basically calling `Double.parseDouble()` and catching the exception." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-02-05T15:04:39.693", "Id": "70203", "Score": "0", "body": "@bowmore: [IsNumber() could be one of the problems](http://svn.apache.org/viewvc/commons/proper/lang/trunk/src/main/java/org/apache/commons/lang3/math/NumberUtils.java?view=markup), to me it looks rather heavy weight." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-02-05T19:07:10.173", "Id": "70248", "Score": "0", "body": "Just to make sure, I've run it with that implementation and if anything, it is even faster than my naive `isNumber()` implementation" } ], "meta_data": { "CommentCount": "6", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-02-04T15:10:05.593", "Id": "40851", "ParentId": "40842", "Score": "6" } }, { "body": "<p>You could utilize the open source library <a href=\"http://www.univocity.com/pages/parsers-tutorial\" rel=\"nofollow\">uniVocity-parsers</a> to parse csv data to vector of doubles, as the library provides excellent performance with multi-threading, caching and optimized code.</p>\n\n<p>Try the following lines of code with the help of this library:</p>\n\n<pre><code>private static Vector&lt;Double&gt; readTXTFileSingle(String csvFileName) throws IOException {\n CsvParser parser = new CsvParser(new CsvParserSettings());\n List&lt;String[]&gt; resolvedData = parser.parseAll(new FileReader(csvFileName));\n Vector&lt;Double&gt; csvData = new Vector&lt;Double&gt;();\n\n for (String[] row : resolvedData) {\n if (!NumberUtils.isNumber(row[0])) {\n continue;\n }\n\n csvData.add(Double.valueOf(row[0]));\n }\n\n return csvData;\n}\n</code></pre>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2015-05-15T23:27:34.290", "Id": "90878", "ParentId": "40842", "Score": "3" } } ]
{ "AcceptedAnswerId": "40851", "CommentCount": "13", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-02-04T13:24:44.663", "Id": "40842", "Score": "7", "Tags": [ "java", "parsing", "csv", "io" ], "Title": "Speed up CSV reading code (vector of doubles)" }
40842
<p>Like anything that <em>shouldn't</em> be done, I decided to see if it is possible to match <code>&lt;script&gt;</code> tags robustly using regexes in PHP. Since there is no arbitrary nesting, I figured it should at least be possible.</p> <p>This is what I came up with. It is designed to handle every edge case I could think of, including:</p> <ul> <li>arbitrary attributes in the opening script tag</li> <li>single and multiline comments and single and double-quoted strings (which might include arbitrary escape sequences) in the javascript which may contain the characters <code>&lt;/script&gt;</code></li> <li>Captures the smallest script tag it finds. </li> </ul> <p>Did I miss anything? Ideally, I want it to match exclusively anything a browser would consider a script element (might not be possible), but at the very least, I would like it to match only well-formed script tags with well-formed javascript.</p> <p>Here is the string for the regex that I am passing to preg_match:</p> <pre><code>'#&lt;script(?:[^&gt;"]*(?:"[^"]*")?)*&gt;((?:"(?:[^\\\\\\n"]*(?:\\\\.)*)*"|\'(?:[^\\\\\\n\']*(?:\\\\.)*)*\'|&lt;[^/]?|/\\*(?:[^*]|\\*[^/]?)*\\*/|//.*|/[^/*]|[^\'"&lt;/])*)&lt;/script&gt;#'; </code></pre> <p>Note: I am <strong>not</strong> using this in production.</p>
[ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-02-04T17:34:06.170", "Id": "69989", "Score": "5", "body": "The <center> cannot hold." } ]
[ { "body": "<p>Probably not the review/answer you're looking for, but...</p>\n<blockquote>\n<p>Note: I am <strong>not</strong> using this in production.</p>\n</blockquote>\n<h1>Don't!</h1>\n<blockquote>\n<p><em>Some people, when confronted with a problem, think &quot;I know, I'll use regular expressions.&quot; Now they have two problems.</em></p>\n<p>-- Jamie Zawinski</p>\n</blockquote>\n<p>From Jeff Atwood's <a href=\"http://www.codinghorror.com/blog/2008/06/regular-expressions-now-you-have-two-problems.html\" rel=\"nofollow noreferrer\"><em>Coding Horror</em></a> blog:</p>\n<blockquote>\n<p><em>I couldn't agree more. Regular expressions are like a particularly spicy hot sauce – to be used in moderation and with restraint only when appropriate. Should you try to solve every problem you encounter with a regular expression? Well, no. Then you'd be writing Perl, and I'm not sure you need those kind of headaches. If you drench your plate in hot sauce, you're going to be very, very sorry later.</em></p>\n</blockquote>\n<p>If that doesn't convince you, maybe <a href=\"https://stackoverflow.com/a/1732454/1188513\">this classic Stack Overflow answer</a> will.</p>\n<p>And if that doesn't do it... My most sincere sympathies.</p>\n<p>You want <em>maintainable</em> code. Not just <em>code that works</em>: code that you can read and that your successors can maintain. Just don't. do. that.</p>\n<p>Regular Expressions are a formidable hammer. It's just unfortunate that not every problem is a nail.</p>\n<p>Any decent HTML parser will find the <code>&lt;script&gt;</code> tags, <strong>and</strong> leave you with readable code.</p>\n<hr />\n<p>If I remove the <code>#</code>'s from your string, I can use Expresso to analyze your regular expression:</p>\n<p><img src=\"https://i.stack.imgur.com/ToACU.png\" alt=\"enter image description here\" /></p>\n<p>That's a nasty one, but it seems to effectively work:</p>\n<p><img src=\"https://i.stack.imgur.com/5rOR7.png\" alt=\"enter image description here\" /></p>\n<p>The problem with reviewing complex regular expressions like this, is that something like the <em>&quot;select from 7 alternatives&quot;</em> part, is really hard to decypher.</p>\n<p>If you're going the <a href=\"/questions/tagged/regex\" class=\"post-tag\" title=\"show questions tagged &#39;regex&#39;\" rel=\"tag\">regex</a> way, try to use comments. Comment each alternative, say <em>why</em> you need each one - because at a glance, it's far from obvious!</p>\n<p>I like that you're getting the content of the tag in a capture group though.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-02-04T15:15:28.250", "Id": "69957", "Score": "2", "body": "I think this is a fair answer. Rest easy knowing that you don' t need to convince me. But I _was_ hoping for some feedback on the regex itself." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-02-04T15:27:48.663", "Id": "69961", "Score": "2", "body": "@TimSeguine added some more meat :)" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-02-04T16:50:49.270", "Id": "69978", "Score": "1", "body": "Which flavor of regex does Expresso support, btw? I ask because I didn't design it specially to capture html comments like the one you tested. This tells me important information, namely that there is likely to be a bug. That underscores I think the fact that the first part of your post is the important part." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-02-04T17:12:05.107", "Id": "69982", "Score": "0", "body": "This is not a code review, it's a rant about the unsuitability of regexes for complicated tasks. Theoretical -1." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-02-04T17:28:23.830", "Id": "69987", "Score": "0", "body": "@amon not even the \"use comments\" and \"I like capture groups\" part?" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-02-04T17:42:54.967", "Id": "69991", "Score": "0", "body": "@TimSeguine I use it with .NET, it works fine with C#/VB/C++ syntax, ...probably not the best tool for anything else though, but it's what I had at hand ;)" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-02-04T23:56:42.013", "Id": "70063", "Score": "1", "body": "Ironically I encountered a bug today in an EDI application I wrote a few months ago that parses the data files using... regex! And the bug was? In the most complicated regex pattern, of course! (*look who's talking* answer?)" } ], "meta_data": { "CommentCount": "7", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-02-04T15:08:35.147", "Id": "40850", "ParentId": "40843", "Score": "8" } }, { "body": "<p>Instead of writing a long uncommented regex, compose it out of multiple parts. This makes it easier to understand what you're trying to do.</p>\n\n<p>Let's go through the <a href=\"http://www.w3.org/html/wg/drafts/html/master/syntax.html#start-tags\">spec for a start tag</a>:</p>\n\n<blockquote>\n <ol>\n <li>The first character of a start tag must be a \"&lt;\" (U+003C) character.</li>\n <li>The next few characters of a start tag must be the element's tag name.</li>\n <li>If there are to be any attributes in the next step, there must first be one or more space characters.</li>\n <li>Then, the start tag may have a number of attributes, the syntax for which is described below. Attributes must be separated from each other by one or more space characters.</li>\n <li>After the attributes, or after the tag name if there are no attributes, there may be one or more space characters. (Some attributes are required to be followed by a space. See the attributes section below.)</li>\n <li>Then, if the element is one of the void elements, or if the element is a foreign element, then there may be a single \"/\" (U+002F) character. This character has no effect on void elements, but on foreign elements it marks the start tag as self-closing.</li>\n <li>Finally, start tags must be closed by a \">\" (U+003E) character.</li>\n </ol>\n</blockquote>\n\n<p>Expressed as a regex fragment, with insignificant whitespace:</p>\n\n<pre><code>$start_tag = \"(?: [&lt;] script (?: $ws+ (?:$attribute $ws+)* $attribute)? $ws* [&gt;] )\"\n</code></pre>\n\n<p>Attributes themselves are <a href=\"http://www.w3.org/html/wg/drafts/html/master/syntax.html#syntax-attributes\">rather complex</a>. They can either be empty, unquoted, single-quoted or double-quoted.</p>\n\n<pre><code>$attribute = \"(?: $attr_name\n | $attr_name $ws* [=] $ws* (?:[^${space_characters}\\\"'&lt;&gt;`&amp;]+|$character_reference)+\n | $attr_name $ws* [=] $ws* [\\\"] (?:[^\\\"&amp;]|$character_reference)* [\\\"]\n | $attr_name $ws* [=] $ws* ['] (?:[^'&amp;]|$character_reference)* [']\n )\"\n</code></pre>\n\n<p>Now once we fill in the appropriate values for character references and the space character recognized by HTML5 and possible attribute names, we have finally correctly matched the <code>&lt;script&gt;</code> start tag.</p>\n\n<p>How does your solution hold up? I am led to believe that this part is supposed to match the start tag (I added whitespace for clarity):</p>\n\n<pre><code>&lt;script (?: [^&gt;\"]* (?:\"[^\"]*\")? )* &gt;\n</code></pre>\n\n<p>Err, no. This fails to match single-quoted strings <code>&lt;script title='&lt;You Fail&gt;'&gt;</code>. This will also match some strings that do not contain valid HTML at all, like <code>&lt;script &lt;&lt;&lt;&lt;&lt;&lt;&lt;&gt;</code>.</p>\n\n<p>What is the point of this exercise? It's absolutely possible to correctly match HTML with the PCRE (it's not possible with a <em>regular language</em>, which has a specific computer science meaning. Too many people confuse the theoretical concept with a similarly named practical tool which happens to be more powerful). However, if you do want to do this, you have to follow <a href=\"http://www.w3.org/html/wg/drafts/html/master/Overview.html#contents\">the spec</a>. Don't fudge it, read it. (Actually, I fudged it as well, but to a lesser degree. Do as I say, not as I do).</p>\n\n<p>It is absolutely possible to write readable regexes. Compose them from multiple reusable parts. Use the <code>/x</code> option to include insignificant whitespace. But do not ram them onto a single line. That's just obfuscation, and you wouldn't do that in other languages.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-02-04T17:26:58.433", "Id": "69986", "Score": "0", "body": "Theoretical +1, will come back here when votes reload ;)" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-02-04T18:57:55.470", "Id": "70006", "Score": "0", "body": "Good point about the spec, TBH I was unaware that single quotes were allowed. In defense of the start tag pattern, my working assumption was that the html was a priori valid. If I was to fix the quote issue, then under that assumption it seems like it should be fine. The thing is, I don't want to only capture valid markup. I want to capture anything that the browser might interpret as a script tag." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-02-04T19:11:45.667", "Id": "70008", "Score": "2", "body": "@TimSeguine HTML5 was crafted in a most backwards-compatible way and specifies the handling of many cases that could occur in the wild, but were previously illegal – notice for example that backticks are forbidden in unquoted attribute values, as some browsers historically allowed them as a quote character. Following the HTML5 spec carefully is your best bet of parsing the input like a browser would. Of course many regex-based tools often assume that a tag looks like `<([\\w:]+)[^>]*>` which breaks here, but don't compare yourself to *them*." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-02-04T19:49:29.467", "Id": "70015", "Score": "0", "body": "Good advice all around. The reason I even came up with the idea to try to make a regex for this was due to some pretty terrible ones like that I saw on an old Stack Overflow post. I figured it must be possible to do better." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-02-04T19:55:48.493", "Id": "70016", "Score": "0", "body": "What is the ettiquette on this site, by the way, if I were to have another go at this problem with new insight?" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-02-04T20:03:45.140", "Id": "70017", "Score": "2", "body": "@TimSeguine For smaller details, you can edit your question to *add* newer code (but do not *modify* existing code, as that would invalidate the answers). Usually, you would post a [follow-up question](http://meta.codereview.stackexchange.com/a/1066/21609). In the future, you can ask questions about “site etiquette” on [meta], or in the [chat](http://chat.stackexchange.com/rooms/8595/the-2nd-monitor)." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-02-05T03:33:59.710", "Id": "70084", "Score": "0", "body": "@TimSeguine I'd mark this one as the accepted answer, I find it's a more substantative review of your regex. Feel free to accept whichever though ;)" } ], "meta_data": { "CommentCount": "7", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-02-04T17:07:04.570", "Id": "40860", "ParentId": "40843", "Score": "11" } } ]
{ "AcceptedAnswerId": "40860", "CommentCount": "1", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-02-04T13:44:37.067", "Id": "40843", "Score": "11", "Tags": [ "javascript", "php", "html", "regex" ], "Title": "Matching script tags with regexes" }
40843
<p>My question concerns the following Python code which is already working. As far as I have seen, there are very elegant solutions of compacting code. Do you have any ideas on how to make the following code look smoother? </p> <pre><code>mom = [0.,0.13,0.27,0.53,0.67] strings = ['overview_files/root/file_' + str(e) for e in mom] myfile = [np.loadtxt(s) for s in strings] nbinp = len(mom) nbinomega = len(myfile[0][:,0]) x, y, z = (np.empty(nbinp*nbinomega) for i in range(3)) for i in range(nbinomega): for j in range(nbinp): i_new = i + j*nbinomega y[i_new] = myfile[j][i,0] - 1.4 x[i_new] = mom[j] z[i_new] = myfile[j][i,1] </code></pre>
[ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-02-04T14:56:30.423", "Id": "69952", "Score": "1", "body": "Can you describe what you think is not smooth about this code? It is only 12 lines and is already fairly terse with liberal use of list comprehension." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-02-04T14:56:33.673", "Id": "69953", "Score": "2", "body": "Can you explain what this code is supposed to do?" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-02-04T15:30:07.267", "Id": "69962", "Score": "0", "body": "@unholysampler: Well, I feel that this c++-type for loops are not really the python way." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-02-04T15:31:41.227", "Id": "69963", "Score": "0", "body": "@GarethRees: It is supposed to prepare data for a contour plot with matplotlib. Data is saved as textfiles with format omega-f(omega,p) in different files for different ps." } ]
[ { "body": "<p>You may want to follow PEP8 a bit more closely to learn how to write code that is easily understood by most Python developers. Eg. <code>mom = [0.3, 0.13]</code> instead of <code>mom = [0.3,0.13]</code> and four spaces indentation.</p>\n\n<p>Try to be more careful about variable names. I couldn't understand what most of them meant, which is probably because I don't much about the code you're writing. But think about your readers (including you in three months) and wonder what are the best ways to convey information in your variable names. For example, 'myfile' suggest that this is not a collection. And 'my' doesn't provide any useful information.</p>\n\n<p>There's a common idiom in Python to avoid dealing with ranges explicitely: <code>enumerate()</code>.</p>\n\n<pre><code>for i, this in enumerate(myfile):\n for j, that in enumerate(myfile[i]):\n i_new = ...\n y[i_new] = ...\n x[i_new] = ...\n z[i_new] = ...\n</code></pre>\n\n<p>If you often deal with ranges, it will certainly help you at some point.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-02-14T10:37:49.660", "Id": "41639", "ParentId": "40849", "Score": "3" } } ]
{ "AcceptedAnswerId": "41639", "CommentCount": "4", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-02-04T14:45:24.207", "Id": "40849", "Score": "6", "Tags": [ "python", "numpy", "matplotlib" ], "Title": "Prepare data for a contour plot with matplotlib" }
40849
<p>I have implemented a program to sort a file consisting of numbers. The program generates a different output file with all numbers sorted in it. I have implemented this program using <code>BitSet</code> and want to understand <code>BitSet</code>. </p> <pre><code>public class Application { public static void main(String[] args) throws Exception { String inputFile = "c:\\temp\\numbers.txt"; NumberFileSorter.sort(inputFile, 100); } } class NumberFileSorter { private NumberFileSorter() { } public static void sort(String inputFile, int maxValue) throws Exception { final BitSet bitSet = createBitSet(inputFile, maxValue); final String outputFile = deriveOutputFile(inputFile); writeBitSet(bitSet, outputFile); } private static BitSet createBitSet(String inputFile, int maxValue) throws Exception { final FileInputStream stream = new FileInputStream(inputFile); final InputStreamReader streamReader = new InputStreamReader(stream); final BufferedReader buffReader = new BufferedReader(streamReader); String line = null; int totalBits = maxValue + 1; BitSet bitSet = new BitSet(totalBits); try { while ((line = buffReader.readLine()) != null) { int number = Integer.parseInt(line); bitSet.set(number, true); } } finally { buffReader.close(); streamReader.close(); stream.close(); } return bitSet; } private static String deriveOutputFile(String inputFile) { String outputFileName = Paths.get(inputFile).getParent().toString() + "/output.txt"; return outputFileName; } private static void writeBitSet(BitSet bitSet, String outputFile) throws Exception { final File file = new File(outputFile); file.createNewFile(); final FileOutputStream outputStream = new FileOutputStream(file); final OutputStreamWriter writer = new OutputStreamWriter(outputStream); final BufferedWriter buffWriter = new BufferedWriter(writer); try { for (int bitIndex = 0; bitIndex &lt; bitSet.length(); bitIndex++) { if (bitSet.get(bitIndex)) { buffWriter.write(Integer.toString(bitIndex)); buffWriter.newLine(); } } } finally { buffWriter.close(); writer.close(); outputStream.close(); } } } </code></pre> <p>I request reviewers to provide feedback on the following:</p> <ol> <li>Is existing code readable? What are changes required to make it more readable?</li> <li>Is it advisable to unit test sorting logic by decoupling it from the file-system by introducing appropriate interfaces and using dependency injection?</li> <li>Can this program be made more reliable and robust?</li> <li>Can this code be structured differently for the better?</li> <li>Would you integration test it or unit test it? Could you explain the reason?</li> </ol>
[]
[ { "body": "<p>Overall your code is very well formatted and readable but I have some complaints at the moment:</p>\n\n<ul>\n<li><p>Don't declare all methods with <code>throws Exception</code>. Only declare the Exceptions you really need to declare, such as <code>IOException</code>. Declaring <code>throws Exception</code> will force the caller to also catch all RuntimeExceptions, which I say is a big no-no as that could potentially catch important bugs (NPEs for example) in your code. I prefer to let RuntimeExceptions cascade up the hierarchy, without catching them.</p></li>\n<li><p>Your <code>deriveOutputFile</code> is as far as I can see only called from one place, and consists of only one line. Does it really need to be it's own method? I'd also say that it's name is somewhat ambiguous. <code>deriveOutputFileName</code> would be better.</p></li>\n<li><p>Your entire class is static. I'm not so sure about this decision. If you'd want to test it in any way you would probably want it non-static, as you then could use a mocking framework to simulate the file input.</p></li>\n</ul>\n\n<p>Regarding your questions I have some comments:</p>\n\n<ul>\n<li><p>There's a really good question on StackOverflow about <a href=\"https://stackoverflow.com/questions/856115/should-one-test-internal-implementation-or-only-test-public-behaviour\">Testing internal implementation or public behaviour</a></p></li>\n<li><p>Decoupling the sorting from the file system sounds like a very good idea and would make your code re-usable, so that you could easily use it in another project if needed. By all means, if you really want to then you can abstract things more by making the sorting an interface, and possibly the file system an interface. Remember that there's a risk of over-engineering though. Always remember the rule of <a href=\"http://en.wikipedia.org/wiki/You_aren%27t_gonna_need_it\" rel=\"nofollow noreferrer\">YAGNIT</a>.</p></li>\n</ul>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-02-05T04:21:05.663", "Id": "70090", "Score": "0", "body": "What does NPE stands for?" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-02-05T04:26:10.750", "Id": "70091", "Score": "0", "body": "I always use Exception with throws as a short-cut that saves the need for adding a big list of checked exceptions to the list. I agree that it is bad." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-02-05T07:27:07.207", "Id": "70116", "Score": "2", "body": "@AnandPatel `NPE = NullPointerException`. When it comes to coding, it is dangerous to be lazy. Don't just declare `throws Exception` because it's the easy thing to do. Do the right thing." } ], "meta_data": { "CommentCount": "3", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-02-04T17:32:17.127", "Id": "40863", "ParentId": "40855", "Score": "10" } }, { "body": "<p>This example is a good way to learn <code>BitSet</code>. But it can't handle the case when there may be duplicate integers in the file.</p>\n\n<p>If there are duplicate numbers: for example, 2, 2 in the file. In the output, there would be only one 2.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-03-27T20:22:25.953", "Id": "45543", "ParentId": "40855", "Score": "1" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-02-04T16:17:21.453", "Id": "40855", "Score": "8", "Tags": [ "java", "sorting", "file-system", "file", "bitset" ], "Title": "Sorting a set of numbers in a file using Java BitSet" }
40855
<p>I want to know if this can be trimmed down further. I am repeating myself with <code>this.title</code> and <code>this.position</code>. Also <code>this.position</code> is the corresponding array index, not sure if that is a good idea, if player throws 3 then perhaps I can just denote that as player is currently at <code>positions[3]</code>. I use <code>this.price</code> instead of <code>this.rent</code> because otherwise I would have 2 different object properties, <code>purchaseprice</code> and <code>rentprice</code>, I felt I could merge the 2 into 1 property and use an array.</p> <p>Looking forward to suggestions.</p> <p><strong>Positions</strong></p> <pre><code>positions = [ new Position("Go", 0), new Cities("Cairo", "brown", [60, 2, 10, 30, 90, 160, 250], 1), new CardPosition("Chest", "chest", 2), new Cities("Vienna", "brown", [60, 4, 20, 60, 180, 320, 450], 3), new Tax("Income Tax", 200, 4), new Airport("Schiphol", [200, 25, 50, 100, 200], 5), new Cities("Brussels", "blue", [100, 6, 30, 90, 270, 400, 550], 6), new CardPosition("Chance", "chance", 7), new Cities("Stockholm", "blue", [100, 6, 30, 90, 270, 400, 550], 8), new Cities("Geneva", "blue", [120, 8, 40, 100, 300, 450, 600], 9), new Position("Jailhouse", 10), new Cities("Amsterdam", "pink", [140, 10, 50, 150, 450, 625, 750], 11), new Position("Electric", 12), new Cities("Bangkok", "pink", [140, 10, 50, 150, 450, 625, 750], 13), new Cities("Istanbul", "pink", [160, 12, 60, 180, 500, 700, 900], 14), new Airport("DBX", [200, 25, 50, 100, 200], 15), new Cities("Hong Kong", "orange", [180, 14, 70, 200, 550, 750, 950], 16), new CardPosition("Chest", "chest", 17), new Cities("Madrid", "orange", [180, 14, 70, 200, 550, 750, 950], 18), new Cities("Sydney", "orange", [200, 14, 70, 200, 550, 750, 950], 19), new Position("Free Parking", 20), new Cities("Toronto", "red", [220, 18, 90, 250, 700, 875, 1050], 21), new CardPosition("Chance", "chance", 22), new Cities("Mumbai", "red", [220, 18, 90, 250, 700, 875, 1050], 23), new Cities("Rome", "red", [240, 20, 100, 300, 750, 925, 1100], 24), new Airport("BCN", [200, 25, 50, 100, 200], 25), new Cities("Rio", "yellow", [260, 22, 110, 330, 800, 975, 1150], 26), new Cities("Tokyo", "yellow", [260, 22, 110, 330, 800, 975, 1150], 27), new Position("Water Works", 28), new Cities("Paris", "yellow", [280, 24, 120, 360, 850, 1025, 1200], 29), new Position("Go to Jail", 30), new Cities("Berlin", "green", [300, 26, 130, 390, 900, 1100, 1275], 31), new Cities("Bejing", "green", [300, 26, 130, 390, 900, 1100, 1275], 32), new CardPosition("Chest", "chest", 33), new Cities("Moscow", "green", [320, 28, 150, 450, 1000, 1200, 1400], 34), new Airport("LAX", [200, 25, 50, 100, 200], 35), new CardPosition("Chance", "chance", 36), new Cities("New York", "navy", [350, 35, 175, 500, 1100, 1300, 1500], 37), new Tax("Super Tax", 100, 38), new Cities("London", "navy", [400, 50, 200, 600, 1400, 1700, 2000], 39) ]; function Position (title,position){ this.title = title; this.position = position; this.forsale = false; } function CardPosition (title,type,position){ this.title = title; this.type = type; this.position = position; this.forsale = false; } function Tax (title,tax,position){ this.title = title; this.tax = tax; this.position = position; this.forsale = false; this.type = "tax"; } function Airport(title,prices,position){ this.title = title; this.rating = 0; this.price = prices[this.rating]; this.position = position; this.forsale = true; this.type = "airport"; } function Cities (title,set,prices,position){ this.title = title; this.set = set; this.rating = 0; this.prices = prices; this.price = prices[this.rating]; this.position = position; this.owner = "unowned"; this.forsale = true; this.type = "city"; } </code></pre>
[]
[ { "body": "<p>There are a few places that I think you could simplify the code, but I don't think you are too far off. Let me address each concern:</p>\n\n<ol>\n<li><blockquote>\n <p>I am repeating myself with <code>this.title</code> and <code>this.position</code>.</p>\n</blockquote>\n\n<p>You can set all of these classes up in a class hierarchy, so that they can share common attributes. By using the <code>.call()</code> method, you can set up superclasses, and then reference them them as part of your subclass constructor. For example, <strong>ignoring any other changes</strong>, your first two classes can be reduced to a superclass and a subclass, like this:</p>\n\n<pre><code>function Position(title, position) {\n this.title = title;\n this.position = position;\n this.forsale = false;\n}\n\nfunction CardPosition(title, type, position) {\n Position.call(this, title, position);\n this.type = type;\n}\n</code></pre></li>\n<li><blockquote>\n <p>Also <code>this.position</code> is the corresponding array index, not sure if that\n is a good idea, if player throws 3 then perhaps I can just denote that\n as player is currently at <code>positions[3]</code>.</p>\n</blockquote>\n\n<p>If the positions will always be in the order that they are stored in the array, then, yes, there is no reason to store the position as part of each object . . . the position in the array <strong>is</strong> the position of the \"card\", so storing the value in the object would be redundant. I'd remove all of the <code>position</code> attributes from the entire class structure.</p></li>\n<li><blockquote>\n <p>I use <code>this.price</code> instead of <code>this.rent</code> because otherwise I would have 2\n different object properties, <code>purchaseprice</code> and <code>rentprice</code>, I felt I\n could merge the 2 into 1 property and use an array.</p>\n</blockquote>\n\n<p>Looking at your sample data, I would keep these two prices separate. What you have is one purchase price and a series of scaling rent prices. It makes sense to use an array for the rents (because the are multiple values for the same piece of data), but the purchase price is different data and should really remain separate from the rent array.</p>\n\n<p>However, see my third \"additional suggestion\" below, for another way to group them . . .</p></li>\n<li><p>I'd also have a few of other comments/suggestions, that might streamline your code:</p>\n\n<ul>\n<li><p>make <code>forsale</code> part of <code>Position</code> and pass the value in as a parameter. All of the subclasses under it have a <code>forsale</code> attribute in common.</p></li>\n<li><p>assuming that \"airports\" are like \"railroads\", in Monopoly, don't they also need a <code>owner</code> property?</p></li>\n<li><p>you could consider another superclass called something like \"DevelopmentProperties\" as a parent of any subclass that has <code>pricing</code>, <code>rent</code>, <code>rating</code>, and <code>owner</code> values, in order to consolidate the data that is common to purchasable, update-able properties.</p></li>\n</ul></li>\n</ol>\n\n<p>You could set <code>DevelopmentProperties</code> up like this:</p>\n\n<pre><code>function DevelopmentProperties(price, rents) {\n this.price = price;\n this.rents = rents;\n this.rating = 0;\n this.owner = \"unowned\";\n}\n</code></pre>\n\n<p>. . . and extend it using this:</p>\n\n<pre><code> DevelopmentProperties.call(this, price, rents);\n</code></pre>\n\n<h2>So, finally . . .</h2>\n\n<p>Putting all of that together, here is how the code would end up:</p>\n\n<pre><code>// first, the common, top-level superclasses\nfunction Position(title, forsale) {\n this.title = title;\n this.forsale = forsale;\n}\n\nfunction DevelopmentProperties(price, rents) {\n this.price = price;\n this.rents = rents;\n this.rating = 0;\n this.owner = \"unowned\";\n}\n\n// next, a mid-level subclass, that also acts as a superclass for the subclasses below\nfunction CardPosition(title, type, forsale) {\n Position.call(this, title, forsale);\n this.type = type;\n}\n\n// finally, the low-level, subclasses that extend the superclasses above them\nfunction Tax(title, tax) {\n CardPosition.call(this, title, \"tax\", false);\n this.tax = tax;\n}\n\nfunction Airport(title, price, rents) {\n CardPosition.call(this, title, \"airport\", true);\n DevelopmentProperties.call(this, purchase, rents);\n}\n\nfunction Cities(title, set, price, rents) {\n CardPosition.call(this, title, \"city\", true);\n DevelopmentProperties.call(this, purchase, rents);\n this.set = set;\n}\n</code></pre>\n\n<p>I didn't update the <code>positions</code> array, but, obviously, that would also need to be updated a little bit to match the new structure.</p>\n\n<p>Hope that helps! :)</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-02-04T20:32:22.457", "Id": "70031", "Score": "0", "body": "I am working on this might take me a while, but I have one question. I know that `forsale` is common but it is tedious to add it in every line since its default value will be false. So can the `Position` superclass set `forsale` to false for all its subclasses?" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-02-04T20:46:38.413", "Id": "70034", "Score": "1", "body": "You could, but you do have two instances (`Airport` and `Cities`) where the value defaults to `true` . . . would be nice to be able to pass that in. You could set it up to be an \"optional\" parameter . . . change `this.forsale = forsale` to `this.forsale = forsale || false;` . . . that way, it would default to `false`, but would still assign the value, if it was provided. It's even at the right position in the parameters already, so it could just be left off for `false` values . . . the lines would only need to updated if it was ever `true` and wasn't an `Airport` or `Cities` object." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-02-05T11:30:28.373", "Id": "70156", "Score": "0", "body": "maybe `!!forsale` instead? The goal is to convert to boolean, correct? So why not say _that_ instead of saying \"convert to boolean and then do a no-op\"?" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-02-05T17:24:47.340", "Id": "70234", "Score": "0", "body": "@TimSeguine - actually, I was assuming that the value (if present) would be Boolean already. Elton didn't want to have to pass `false` for all of the cards that were not \"buyable\", when creating their objects. The logic was to make it so that if the parameter was left out (`undefined`) or set to `null`, the value of `forsale` in the object would default to `false`." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-02-05T17:43:31.453", "Id": "70236", "Score": "0", "body": "Okay I recognized then correctly, my argument stands. The thing is: if `forsale` is a boolean then `forsale || false` is a no-op (Or'ing with false is the identity). If `forsale` is not a boolean, then `forsale || false` converts it to one, then performs a no-op." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-02-05T18:00:41.143", "Id": "70240", "Score": "0", "body": "But, if he used `!!forsale`, wouldn't that also be performing an unnecessary \"double not\" on both `true` and `false` values? Seems like the other way, at least only one of those values has the extra operation performed on it." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-02-05T18:02:29.433", "Id": "70242", "Score": "0", "body": "On a side note, I think we have to assume that the value passed in is a Boolean . . . if not, more logic is required, since `!!forsale` would return `true` for a string value of `\"false\"` and `forsale || false` would return the actual string values, rather than a Boolean." } ], "meta_data": { "CommentCount": "7", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-02-04T18:53:57.693", "Id": "40870", "ParentId": "40862", "Score": "5" } }, { "body": "<p>Some minor remarks:</p>\n\n<ul>\n<li>Your <code>Cities</code> class should be called <code>City</code></li>\n<li>If you are willing to use falsey boolean checks, you do not need to initialize <code>forsale</code> to false</li>\n<li><p>I would store the prices separately:<br></p>\n\n<pre><code>var rentPrices = [\n \"brown\" : {\n low : [2, 10, 30, 90, 160, 250],\n high : [60, 4, 20, 60, 180, 320, 450]\n },\n \"blue\" : {\n low : [6, 30, 90, 270, 400, 550],\n high : [8, 40, 100, 300, 450, 600]\n }\n//etc. etc.\n] \n</code></pre>\n\n<p>This way you can indicate the rent prices by providing whether the card should charge low or high rent for that color ( Geneva is high, Stockholm and Brussels are low ). Otherwise you repeat the low price in your positions table for all but brown and navy.</p></li>\n</ul>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-02-04T20:28:34.027", "Id": "40885", "ParentId": "40862", "Score": "6" } }, { "body": "<p>Your code is actually not too bad, in my opinion.</p>\n\n<p>The <code>title</code> and <code>position</code> parameters are common to all of the positions, so put them consistently as the first two arguments. (It's common practice in many languages to put \"optional\" parameters last.)</p>\n\n<p>My first instinctual criticism would be that the <code>position</code> parameter is redundant, since it can be inferred from the element's index in the array. However, I should point out that there is a \"Jail\" and a \"Just Visiting\" space, both at position 10. Therefore, when you eventually get around to implementing the Jail/Visitor split, you will eventually need to have the position explicitly defined.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-02-04T22:56:08.807", "Id": "70057", "Score": "3", "body": "that's a good thought on the jail space.however, it might be worth considering that space to be simply just visiting, and maintain a flag to indicate whether the player is in jail or not. To me, in jail, is more a state of the player than it is a position on the board" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-02-05T03:32:30.707", "Id": "70083", "Score": "0", "body": "@heiserman couldn't have put that any better. The player is either inJail or justVisiting but in either case the player is @ Jailhouse." } ], "meta_data": { "CommentCount": "2", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-02-04T22:30:01.580", "Id": "40899", "ParentId": "40862", "Score": "2" } } ]
{ "AcceptedAnswerId": "40870", "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-02-04T17:23:23.337", "Id": "40862", "Score": "5", "Tags": [ "javascript", "game" ], "Title": "Monopoly: Positions" }
40862
<p>I've written a Python client for a new NoSQL database as a service product called Orchestrate.io. The client is very straightforward and minimal. It uses the <a href="http://docs.python-requests.org/en/latest/" rel="nofollow">requests</a> library, making the underlying code even more streamlined. </p> <p>I've been using the service as part of the private beta. However, Orchestrate.io went live to the public today. They have added a few new features to the API and I would like to include them in the Python client. With these updates, I'm considering other design choices as well.</p> <p>I am relatively new to writing such an API and I would like to get feedback on the current design and perhaps suggestions for how it can be improved. Personally, I like where it is now because it is super simple/minimal. That said, I am open to making changes that will make the code most useful to the community.</p> <p>Below are few things that I'm considering in the next round of updates:</p> <ul> <li>Putting the client and each service (Key/Value, Search, Events, ect...) into their own classes</li> <li>Implementing optional success and error callbacks</li> <li>Providing an asynchronous option (currently requests are blocking)</li> <li>Improved error handling</li> </ul> <p>Here is the code in its current state (also available <a href="https://github.com/jeremynealbrown/orchestrate-py/blob/master/orchestrate/client.py" rel="nofollow">here</a>):</p> <pre><code>''' A minimal implementation of an Orchestrate.io client ''' import requests # Settings logging = False auth = ('YOUR API KEY HERE', '') root = 'https://api.orchestrate.io/v0/' header = {'Content-Type':'application/json'} # Auth def set_auth(api_key): global auth auth = (api_key, '') # Collections def delete_collection(collection): ''' Deletes an entire collection ''' return delete(root + collection + '?force=true') # Key/Value def format_key_value_url(collection, key): ''' Returns the url for key/value queries ''' return root + '%s/%s' % (collection, key) def get_key_value(collection, key): ''' Returns the value associated with the supplied key ''' return get(format_key_value_url(collection, key)) def put_key_value(collection, key, data): ''' Sets the value for the supplied key ''' return put(format_key_value_url(collection, key), data) def delete_key_value(collection, key): ''' Deletes a key value pair ''' return delete(format_key_value_url(collection, key)) # Search def format_search_query(properties = None, terms = None, fragments = None): ''' propertes - dict: {'Genre' : 'jazz'} terms - list, tuple: ['Monk', 'Mingus'] fragments - list, tuple: ['bari', 'sax', 'contra'] ''' def formatter(items, pattern=None): result = '' for i in range(0, len(items)): item = items[i] if pattern: result += pattern % item else: result += item if i &lt; len(items) - 1: result += ' AND ' return result query = '' if properties: query += formatter(properties.items(), '%s:%s') if terms: if properties: query += ' AND ' query += formatter(terms) if fragments: if properties or terms: query += ' AND ' query += formatter(fragments, '*%s*') return query def format_event_search(span, start, end, start_inclusive = True, end_inclusive = True): ''' Formats a query string for event searches. Example output: Year:[1999 TO 2013} span - string: YEAR, TIME start - string: beginning date or time end - string: ending date or time start_inclusive - boolean: whether or not to include start end_inclusive - boolean: whether or not to include end ''' result = span + ':' result += '[' if start_inclusive else '{' result += start + ' TO ' + end result += ']' if end_inclusive else '}' return result def search(collection, query): ''' Searches supplied collection with the supplied query ''' return get(root + "%s/?query=%s" % (collection, query)) # Events def format_event_url(collection, key, event_type): ''' Returns the base url for events ''' return root + '%s/%s/events/%s' % (collection, key, event_type) def get_event(collection, key, event_type, start='', end=''): ''' Returns an event ''' return get(format_event_url(collection, key, event_type) + '?start=%s&amp;end=%s' % (start, end)) def put_event(collection, key, event_type, time_stamp, data): ''' Sets an event ''' return put(format_event_url(collection, key, event_type) + '?timestamp=%s' % (time_stamp), data) def delete_event(collection, key, event_type, start='', end=''): ''' Delets an event ''' return delete(format_event_url(collection, key, event_type) + '?start=%s&amp;end=%s' % (start, end)) # Graph def format_graph_url(collection, key, relation): ''' Returns the base url for a graph ''' return root + '%s/%s/relations/%s/' % (collection, key, relation) def get_graph(collection, key, relation): ''' Returns a graph retlationship ''' return get(format_graph_url(collection, key, relation)) def put_graph(collection, key, relation, to_collection, to_key): ''' Sets a graph relationship ''' return put(format_graph_url(collection, key, relation) + ('%s/%s') % (to_collection, to_key)) def delete_graph(collection, key, relation): ''' Deletes a graph relationship ''' return delete(format_graph_url(collection, key, relation)) ''' Convenience methods used by client for generic, get, put and delete. ''' def get(url): log('GET', url) return requests.get(url, headers=header, auth=auth) def put(url, data=None): log('PUT', url) return requests.put(url, headers=header, auth=auth, data=data) def delete(url): log('DEL', url) return requests.delete(url, auth=auth) def log(op, url): if logging: print '[Orchestrate.io] :: %s :: %s' % (op, url.replace(root, "")) </code></pre>
[]
[ { "body": "<ol>\n<li><p>This is a very \"thin\" layer around the Orchestrate.io database. By \"thin\" I mean that it provides no abstraction and no mapping of concepts between the Orchestrate and Python worlds. Without your module, someone might have written a sequence of operations like this:</p>\n\n<pre><code>import requests\nvalue = requests.get(root + collection_name + '/' + key, headers=header, auth=auth)\nrequests.delete(root + collection_name + '/' + key, headers=header, auth=auth)\n</code></pre>\n\n<p>but with your module they can write it like this:</p>\n\n<pre><code>import orchestrate\norchestrate.auth = auth\norchestrate.root = root\nvalue = orchestrate.get(collection_name, key)\norchestrate.delete(collection_name, key)\n</code></pre>\n\n<p>which you have to admit is not much of an improvement. All you've done is factor out a bit of boilerplate, which any Python programmer could easily have done for themselves.</p>\n\n<p>What you should do is figure out some way to map concepts back and forth between the Orchestrate and Python worlds. For example, a key-value store is very like a Python dictionary, so wouldn't it be nice to be able to write the above sequence of operations like this:</p>\n\n<pre><code>import orchestrate\nconn = orchestrate.Connection(root, api_key)\ncollection = conn.Collection(collection_name)\nvalue = collection[key]\ndel collection[key]\n</code></pre>\n\n<p>The advantage of this kind of approach is not just that it results in shorter code, but that it interoperates with other Python functions. For example, you'd be able to write:</p>\n\n<pre><code>sorted(data, key=collection.__getitem__)\n</code></pre>\n\n<p>or:</p>\n\n<pre><code>\"{product} has {stock_count} items.\".format_map(collection)\n</code></pre></li>\n<li><p>By using the <a href=\"http://docs.python-requests.org/en/latest/\" rel=\"nofollow\"><code>requests</code> module</a>, you require all your users to install that module. If you are trying to write something for general use, you should strive to use only features from Python's standard library. Even if <code>requests</code> is easier to use than <a href=\"http://docs.python.org/3/library/urllib.request.html\" rel=\"nofollow\"><code>urllib.request</code></a>, a bit of inconvenience for you could save a lot of inconvenience for your users if it would enable them to run your code on a vanilla Python installation.</p></li>\n<li><p>There doesn't seem to be any attention to security or validation. You should strive to make your interface robust against erroneous or malicious data. Some examples I spotted:</p>\n\n<ol>\n<li><p>What if <code>root</code> doesn't end with a <code>/</code>? It would be safer to use <a href=\"http://docs.python.org/3/library/urllib.parse.html#urllib.parse.urljoin\" rel=\"nofollow\"><code>urllib.parse.urljoin</code></a> instead of string concatenation.</p></li>\n<li><p>What if <code>collection</code> or <code>key</code> contains a <code>/</code> or a <code>?</code> or a <code>%</code>? You might consider using <a href=\"http://docs.python.org/3/library/urllib.parse.html#urllib.parse.quote_plus\" rel=\"nofollow\"><code>urllib.parse.quote_plus</code></a>.</p></li>\n<li><p>Instead of appending <code>?force=true</code>, why not use the <code>requests</code> module's <a href=\"http://docs.python-requests.org/en/latest/user/quickstart/#passing-parameters-in-urls\" rel=\"nofollow\">params interface</a>?</p></li>\n<li><p>Similarly for <code>?query=%s</code>. Using the params interface would ensure that the query is properly encoded. </p></li>\n<li><p><code>format_search_query</code> and <code>format_event_search</code> look vulnerable to code injection attacks.</p></li>\n</ol></li>\n</ol>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-02-06T15:48:41.207", "Id": "70417", "Score": "0", "body": "This is great feedback and I really appreciate you taking the time to reply. I really like the idea of building a mapping to the Python language. I think that I will stick w/ the requests module. I have included a setup.py file that installs the dependency. The security/validation points are very helpful and I will address each one. Thank you!" } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-02-06T15:10:42.910", "Id": "41074", "ParentId": "40865", "Score": "2" } } ]
{ "AcceptedAnswerId": "41074", "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-02-04T18:11:21.517", "Id": "40865", "Score": "1", "Tags": [ "python", "api" ], "Title": "Orchestrate.io Client API Design" }
40865
<p>I'm in the process of structuring a model for conjugation tables for French. There are noun inflections, adverb inflections, and 19 verb conjugations. I'm trying to model the data so that every piece of data is accessible in the same manner as one would traverse the following XML tree (taken from my XML dictionary file):</p> <pre class="lang-xml prettyprint-override"><code>&lt;Word word="être" aspirate="false"&gt; &lt;GrammaticalForms&gt; &lt;GrammaticalForm form="nm" definition="A being (e.g. animal, insect)."&gt;&lt;/GrammaticalForm&gt; &lt;GrammaticalForm form="vi" definition="The be (a state of existence)."&gt;&lt;/GrammaticalForm&gt; &lt;/GrammaticalForms&gt; &lt;ConjugationTables&gt; &lt;NounTable ms="être" fs="" mpl="êtres" fpl="" gender="m"&gt;&lt;/NounTable&gt; &lt;AdjectiveTable ms="" fs="" mpl="" fpl="" na=""&gt;&lt;/AdjectiveTable&gt; &lt;VerbTable group="e" auxillary="a" prepositions="à, de, des, en" transitive="false" pronominal="false"&gt; &lt;Indicative&gt; &lt;Present fps="suis" sps="es" tps="est" fpp="sommes" spp="êtes" tpp="sont"&gt;&lt;/Present&gt; &lt;SimplePast fps="fus" sps="fus" tps="fut" fpp="fûmes" spp="fûtes" tpp="furent"&gt;&lt;/SimplePast&gt; &lt;PresentPerfect fps="ai été" sps="as été" tps="a été" fpp="avons été" spp="avez été" tpp="ont été"&gt;&lt;/PresentPerfect&gt; &lt;PastPerfect fps="eus été" sps="eus été" tps="eut été" fpp="eûmes été" spp="eûtes été" tpp="eurent été"&gt;&lt;/PastPerfect&gt; &lt;Imperfect fps="étais" sps="étais" tps="était" fpp="étions" spp="étiez" tpp="étaient"&gt;&lt;/Imperfect&gt; &lt;Pluperfect fps="avais été" sps="avais été" tps="avait été" fpp="avions été" spp="aviez été" tpp="avaient été"&gt;&lt;/Pluperfect&gt; &lt;Future fps="serai" sps="seras" tps="sera" fpp="serons" spp="serez" tpp="seront"&gt;&lt;/Future&gt; &lt;PastFuture fps="aurai été" sps="auras été" tps="aura été" fpp="aurons été" spp="aurez été" tpp="auront été"&gt;&lt;/PastFuture&gt; &lt;/Indicative&gt; &lt;Subjunctive&gt; &lt;Present fps="sois" sps="sois" tps="soit" fpp="soyons" spp="soyez" tpp="soient"&gt;&lt;/Present&gt; &lt;Past fps="aie été" sps="aies été" tps="ait été" fpp="ayons été" spp="ayez été" tpp="aient été"&gt;&lt;/Past&gt; &lt;Imperfect fps="fusse" sps="fusses" tps="fût" fpp="fussions" spp="fussiez" tpp="fussent"&gt;&lt;/Imperfect&gt; &lt;Pluperfect fps="eusse été" sps="eusses été" tps="eût été" fpp="eussions été" spp="eussiez été" tpp="eussent été"&gt;&lt;/Pluperfect&gt; &lt;/Subjunctive&gt; &lt;Conditional&gt; &lt;Present fps="serais" sps="serais" tps="serait" fpp="serions" spp="seriez" tpp="seraient"&gt;&lt;/Present&gt; &lt;FirstPast fps="aurais été" sps="aurais été" tps="aurait été" fpp="aurions été" spp="auriez été" tpp="auraient été"&gt;&lt;/FirstPast&gt; &lt;SecondPast fps="eusse été" sps="eusses été" tps="eût été" fpp="eussions été" spp="eussiez été" tpp="eussent été"&gt;&lt;/SecondPast&gt; &lt;/Conditional&gt; &lt;Imperative&gt; &lt;Present sps="sois" fpp="soyons" spp="soyez"&gt;&lt;/Present&gt; &lt;Past sps="aie été" fpp="ayons été" spp="ayez été"&gt;&lt;/Past&gt; &lt;/Imperative&gt; &lt;Infinitive present="être" past="avoir été"&gt;&lt;/Infinitive&gt; &lt;Participle present="étant" past="été"&gt;&lt;/Participle&gt; &lt;/VerbTable&gt; &lt;/ConjugationTables&gt; &lt;/Word&gt; </code></pre> <p>Here is the way that I've found to model the data. This is <em>simply a storage mechanism</em>. Basically it's necessary to have the entire dictionary in memory (maybe excluding standard verb conjugations but that just makes things more complicated - I can optimize on that later). This will allow instant lookup of a word in the application. The <code>Word</code>s will be stored in a <code>SortedDictionary</code> as a data member of another class. There will also be a separate implementation of a spell checker.</p> <p><em>Grammar-specific data should not be a part of this schema</em>. Simply put, special exceptions such as the word <em>bel</em> (inflection of <em>beau</em> coming before a word that starts with a vowel) will be handled separately in the <em>grammar interface of the application</em>. This design is meant to store common attributes among all words in a dictionary, such as noun/adjective inflections, verb conjugations, and other small pieces of data like definition(s), grammatical forms the word has, etc.</p> <p>Here's what I have, and will improve upon based on other answers noted here (at least to the best of my ability):</p> <pre class="lang-cs prettyprint-override"><code>class Word { // the infinitive Word in the Dictionary public string word { get; set; } // Whether or not the Word is aspirate - adjective forms and phonetics change. public bool aspirate { get; set; } /* * The list of grammatical forms that this Word can have. For example, 'être': * 'être' --&gt; vi (verb intransitive) "to be". * '(un) être' --&gt; nm (noun masculin) "(a) being". */ public List&lt;GrammaticalForm&gt; forms { get; set; } public struct GrammaticalForm { // The grammatical identifier of the form (e.g., 'vi' or 'nm'). --&gt; ENUM LATER public string form { get; set; } // The definition (meaning) of the Word in a particular form. public string definition { get; set; } } // The table of noun INFLECTIONS, if the Word has a grammatical form of a noun. public NounTable nounTable { get; set; } // The table of adjective INFLECTIONS, if the Word has a grammatical form of an adjective. public AdjectiveTable adjectiveTable { get; set; } // The table of verb conjugations, if the Word has a grammatical form of a verb. public VerbTable verbTable { get; set; } } abstract class ConjugationTable { // If there are any properties that would eventually be shared among all conjugation // types, they would go here. } class NounTable : ConjugationTable { /* * The gender of the noun: * 'ms' (masculin singular) * 'fs' (feminin singular) * 'mpl' (masculin plural) * 'fpl' (feminin plural) */ public string gender { get; set; } public string ms { get; set; } public string fs { get; set; } public string mpl { get; set; } public string fpl { get; set; } } class AdjectiveTable : ConjugationTable { /* * The gender of the adjective: * 'ms' (masculin singular) * 'fs' (feminin singular) * 'mpl' (masculin plural) * 'fpl' (feminin plural) * 'na' (non-aspirate) */ public string ms { get; set; } public string fs { get; set; } public string mpl { get; set; } public string fpl { get; set; } public string na { get; set; } /* * The location of the adjective around the noun: * 'b' (before) * 'a' (after) * 'n' (neutral) --&gt; the adjective can come before OR after the noun. */ public char location { get; set; } } class VerbTable : ConjugationTable { /* * The group the verb belongs to: * 'f' (first) --&gt; er. * 's' (second) --&gt; ir. * 't' (third) --&gt; ir, oir, re. * 'e' (exception) --&gt; être, avoir, etc. */ public char group { get; set; } /* * The auxillary verb the verb takes: * 'e' (être). * 'a' (avoir). */ public char auxillary { get; set; } // A list of grammatically-valid prepositions the verb can take. public string[] prepositions { get; set; } // Whether or not the verb is transitive. public bool transitive { get; set; } /* * Whether or not the verb has a pronominal form. If true, a function will later * conjugate the pronominal infinitive of the verb for lookup in the Dictionary. * This saves space over allocating a string of the conjugated pronominal infinitive. */ public bool pronominal { get; set; } /* * The subject of the verb determined by the markers: * 'fps' (first person singular) * 'sps' (second person singular) * 'tps' (third person singular) * 'fpp' (first person plural) * 'spp' (second person plural) * 'tpp' (third person plural) * 'present' (present tense) * 'past' (past tense) * and their accompanying conjugations. */ // All of the different conjugation types are instantiated // when a VerbTable is instantiated. public IndicativePresent indicativePresent = new IndicativePresent(); public IndicativeSimplePast indicativeSimplePast = new IndicativeSimplePast(); public IndicativePresentPerfect indicativePresentPerfect = new IndicativePresentPerfect(); public IndicativePastPerfect indicativePastPerfect = new IndicativePastPerfect(); public IndicativeImperfect indicativeImperfect = new IndicativeImperfect(); public IndicativePluperfect indicativePluperfect = new IndicativePluperfect(); public IndicativeFuture indicativeFuture = new IndicativeFuture(); public IndicativePastFuture indicativePastFuture = new IndicativePastFuture(); public SubjunctivePresent subjunctivePresent = new SubjunctivePresent(); public SubjunctivePast subjunctivePast = new SubjunctivePast(); public SubjunctiveImperfect subjunctiveImperfect = new SubjunctiveImperfect(); public SubjunctivePluperfect subjunctivePluperfect = new SubjunctivePluperfect(); public ConditionalPresent conditionalPresent = new ConditionalPresent(); public ConditionalFirstPast conditionalFirstPast = new ConditionalFirstPast(); public ConditionalSecondPast conditionalSecondPast = new ConditionalSecondPast(); public ImperativePresent imperativePresent = new ImperativePresent(); public ImperativePast imperativePast = new ImperativePast(); public Infinitive infinitive = new Infinitive(); public Participle participle = new Participle(); } abstract class Indicative { // Any common elements that indicative tenses share. public abstract string fps { get; set; } public abstract string sps { get; set; } public abstract string tps { get; set; } public abstract string fpp { get; set; } public abstract string spp { get; set; } public abstract string tpp { get; set; } } abstract class Subjunctive { // Any common elements that subjunctive tenses share. public abstract string fps { get; set; } public abstract string sps { get; set; } public abstract string tps { get; set; } public abstract string fpp { get; set; } public abstract string spp { get; set; } public abstract string tpp { get; set; } } abstract class Conditional { // Any common elements that conditional tenses share. public abstract string fps { get; set; } public abstract string sps { get; set; } public abstract string tps { get; set; } public abstract string fpp { get; set; } public abstract string spp { get; set; } public abstract string tpp { get; set; } } abstract class Imperative { // Any common elements that imperative tenses share. public abstract string sps { get; set; } public abstract string fpp { get; set; } public abstract string spp { get; set; } } class IndicativePresent : Indicative { public override string fps { get; set; } public override string sps { get; set; } public override string tps { get; set; } public override string fpp { get; set; } public override string spp { get; set; } public override string tpp { get; set; } } class IndicativeSimplePast : Indicative { public override string fps { get; set; } public override string sps { get; set; } public override string tps { get; set; } public override string fpp { get; set; } public override string spp { get; set; } public override string tpp { get; set; } } class IndicativePresentPerfect : Indicative { public override string fps { get; set; } public override string sps { get; set; } public override string tps { get; set; } public override string fpp { get; set; } public override string spp { get; set; } public override string tpp { get; set; } } class IndicativePastPerfect : Indicative { public override string fps { get; set; } public override string sps { get; set; } public override string tps { get; set; } public override string fpp { get; set; } public override string spp { get; set; } public override string tpp { get; set; } } class IndicativeImperfect : Indicative { public override string fps { get; set; } public override string sps { get; set; } public override string tps { get; set; } public override string fpp { get; set; } public override string spp { get; set; } public override string tpp { get; set; } } class IndicativePluperfect : Indicative { public override string fps { get; set; } public override string sps { get; set; } public override string tps { get; set; } public override string fpp { get; set; } public override string spp { get; set; } public override string tpp { get; set; } } class IndicativeFuture : Indicative { public override string fps { get; set; } public override string sps { get; set; } public override string tps { get; set; } public override string fpp { get; set; } public override string spp { get; set; } public override string tpp { get; set; } } class IndicativePastFuture : Indicative { public override string fps { get; set; } public override string sps { get; set; } public override string tps { get; set; } public override string fpp { get; set; } public override string spp { get; set; } public override string tpp { get; set; } } class SubjunctivePresent : Subjunctive { public override string fps { get; set; } public override string sps { get; set; } public override string tps { get; set; } public override string fpp { get; set; } public override string spp { get; set; } public override string tpp { get; set; } } class SubjunctivePast : Subjunctive { public override string fps { get; set; } public override string sps { get; set; } public override string tps { get; set; } public override string fpp { get; set; } public override string spp { get; set; } public override string tpp { get; set; } } class SubjunctiveImperfect : Subjunctive { public override string fps { get; set; } public override string sps { get; set; } public override string tps { get; set; } public override string fpp { get; set; } public override string spp { get; set; } public override string tpp { get; set; } } class SubjunctivePluperfect : Subjunctive { public override string fps { get; set; } public override string sps { get; set; } public override string tps { get; set; } public override string fpp { get; set; } public override string spp { get; set; } public override string tpp { get; set; } } class ConditionalPresent : Conditional { public override string fps { get; set; } public override string sps { get; set; } public override string tps { get; set; } public override string fpp { get; set; } public override string spp { get; set; } public override string tpp { get; set; } } class ConditionalFirstPast : Conditional { public override string fps { get; set; } public override string sps { get; set; } public override string tps { get; set; } public override string fpp { get; set; } public override string spp { get; set; } public override string tpp { get; set; } } class ConditionalSecondPast : Conditional { public override string fps { get; set; } public override string sps { get; set; } public override string tps { get; set; } public override string fpp { get; set; } public override string spp { get; set; } public override string tpp { get; set; } } class ImperativePresent : Imperative { public override string sps { get; set; } public override string fpp { get; set; } public override string spp { get; set; } } class ImperativePast : Imperative { public override string sps { get; set; } public override string fpp { get; set; } public override string spp { get; set; } } class Infinitive { public string present { get; set; } public string past { get; set; } } class Participle { public string present { get; set; } public string past { get; set; } } </code></pre>
[ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-02-04T18:53:52.307", "Id": "70004", "Score": "2", "body": "Theoretical upvote (ran out of votes!) - I somewhat hope this one doesn't get answered before I get home... for now I'll just say you need `enum`s and more descriptive naming. Identifiers shouldn't need a comment to explain what they mean ;)" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-02-04T19:02:36.853", "Id": "70007", "Score": "0", "body": "Also, design for simplicity, maintainability and readability. Performance optimizations are a distant last concern." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-02-04T19:40:22.433", "Id": "70014", "Score": "0", "body": "I'm just trying to think ahead a bit because there will be at least 25,000 words in the standard French dictionary that will have one or more of these tables filled out (3,000+ verbs), so I'm trying to make memory management one of my concerns early on :) as for the *descriptive naming*... I named things like `fps` in lieu of `firstPersonSingular` because I imagined that declarations like: `Word.VerbTable.IndicativePresent.firstPersonSingluar` was a bit long... there are only 13 identifiers like `fps`, and they seem to me to be logical shorthand, and can be explained in a total of 3 comments." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-02-05T11:55:55.387", "Id": "70163", "Score": "1", "body": "In common usage, [_conjugation_](http://en.wikipedia.org/wiki/Grammatical_conjugation) applies only to verbs. [_Inflection_](http://en.wikipedia.org/wiki/Inflection) is the general term for all grammatically required word modifications." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-02-05T14:25:48.907", "Id": "70196", "Score": "0", "body": "Good point about the conjugation vs inflection - Perhaps I should modify my structure to reflect that; in fact, that makes things a lot less confusing, I can't believe I didn't think about that. When I started learning French, they never use the word 'inflection' even once, just the *forms* (masculin singular, feminin plural, etc.). And since I never took any classes about English grammar, I never even though about that :P" } ]
[ { "body": "<p>Let's see what we've got here: a <code>NounTable</code>, inherited from a <code>ConjugationTable</code>. As I mentioned in the comments, this huge comment is unnecessary.</p>\n\n<p>You say you're worried about memory? <code>string</code> is a reference type, with the overhead it incurs. Consider this (I renamed the identifiers just to <s>mess you up</s> see what it would look like):</p>\n\n<pre><code>public enum Genre\n{\n Indéterminé,\n Masculin,\n Feminin\n}\n\npublic enum Nombre\n{\n Singulier,\n Pluriel\n}\n\npublic struct Nom\n{\n public Genre Genre { get; set; }\n public Nombre Nombre { get; set; }\n}\n</code></pre>\n\n<p>Notice I haven't derived the <code>NounTable</code> class from a base type. <em>You Ain't Gonna Need It</em>. Besides, you don't derive a bunch of classes because you want to <em>share functionality</em> - remember, a base class puts your type in a <strong>is-a</strong> inheritance scheme, and if all you want is shared functionality you should favor <em>composition over inheritance</em>. Anyway I made it a <code>struct</code> that stores what can be seen as two <code>int</code> values. It's just fortunate that this happens to mootinate the long comment ;)</p>\n\n<hr>\n\n<p>What's your spec? Are you implementing the French grammar? I was going to make a long rewrite of the thing - given how simple it is to conjugate 90% of French verbs (1st group), I was going to suggest <em>coding the grammar</em> for it - this could spare you from storing 90% of your verbs dictionary.</p>\n\n<p>And then I deleted it all, it wasn't going to be a helpful answer.</p>\n\n<p>Your code is making <a href=\"/questions/tagged/beginner\" class=\"post-tag\" title=\"show questions tagged &#39;beginner&#39;\" rel=\"tag\">beginner</a> mistakes that ought to be addressed first.</p>\n\n<p><strong>If you're copying code, you're doing it wrong.</strong></p>\n\n<p>When you create a base class, its inheritors <em>actually inherit</em> the base members, so any class derived from <code>Indicative</code> does not need to re-implement the base members... but because you have declared them <code>abstract</code>, now you <em>have</em> to. They could have been <code>virtual</code> and that would have left you with classes that look like this:</p>\n\n<pre><code>class IndicativePresent : Indicative\n{\n}\n</code></pre>\n\n<p>Not very useful is it? I think all these classes are trying to do one thing: store a string value for the result of the conjugation of a <em>verb</em> at a specified <em>tense</em>, for each <em>person</em>. If that's the case, you could have a <code>IReadOnlyDictionary&lt;IPronoun, string&gt;</code> as a sole member.</p>\n\n<p>I'll end this with a bit of abstract food for thought - if what you're trying to do is really <em>modelize</em> French and <em>implement its grammar</em>, you're probably better off defining every concept as an <em>abstraction</em>:</p>\n\n<pre><code>public enum Person\n{\n First,\n Second,\n Third\n}\n\npublic enum Gender\n{\n Undetermined,\n Masculine,\n Feminine\n}\n\npublic enum Number\n{\n Singular,\n Plural\n}\n\npublic interface IPronoun\n{\n Person Person { get; }\n Gender Gender { get; }\n Number Number { get; }\n string Text { get; }\n}\n\npublic enum VerbGroup\n{\n First,\n Second,\n Third\n}\n\npublic enum VerbAuxiliary\n{\n ToHave,\n ToBe\n}\n\npublic enum VerbTense\n{\n Present,\n Past,\n Future\n}\n\npublic enum VerbMood\n{\n Infinitive,\n Indicative,\n Imperative,\n Conditional,\n Subjonctive,\n Participle,\n Gerundive\n}\n\npublic enum VerbTransitivity\n{\n Intransitive,\n Direct,\n Indirect,\n //...\n}\n\npublic interface IVerb\n{\n string InfinitivePresent { get; }\n VerbGroup { get; }\n bool IsPronomial { get; }\n\n // having these below members here implies the transitive and intransitive forms of\n // { descendre, monter, passer, redescendre, remonter, rentrer, \n // repasser, ressortir, ressusciter, retourner, sortir, tomber}\n // must be implemented as distinct instances.\n VerbAuxiliary { get; }\n VerbTransitivity Transitivity { get; }\n}\n\npublic interface IConjugable\n{\n // an overload taking an IVerb with VerbAuxiliary and VerbTransitivity parameters\n // would allow us to remove these two members from the IVerb implementations,\n // allowing verbs like \"passer\" and \"sortir\" (^^^) to only be implemented once.\n string Conjugate(IPronoun subject);\n}\n</code></pre>\n\n<hr>\n\n<p>If all you're trying to do is to read data from a source, your <a href=\"/questions/tagged/data-structures\" class=\"post-tag\" title=\"show questions tagged &#39;data-structures&#39;\" rel=\"tag\">data-structures</a> should simply reflect it. It feels to me that the inheritance hierarchy obscures the intent of the code, which makes it hard to review without a bit more context.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-02-05T07:13:10.713", "Id": "70115", "Score": "0", "body": "This, at first glance looks like a very useful answer, so thanks first off! But right now I don't have time to read it fully - I will definitely take a look when I get back from class today! I likely made a lot of design mistakes because this is actually my first-ever project in C#, and I've never really done Object-Oriented programming so concepts like `abstract`, `composition`, `inheritence` and the like are all unfamiliar to me." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-02-05T08:08:32.677", "Id": "70125", "Score": "0", "body": "How about `: byte` in the enums?" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-02-05T08:10:12.937", "Id": "70127", "Score": "0", "body": "Also, every tense has either one, three or six pronouns, I wouldn't use a dictionary (dictionaries have a significant overhead)" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-02-05T14:49:28.200", "Id": "70199", "Score": "0", "body": "I added a *lot* more context to my answer, as well as an example of XML data that I will be storing in the application, and what the intent of this organizational schema is. I hope this helps! I'm also thinking that, although `Enum`s are great, I need to store *actual `string` data* in most of these cases, so `Enum`s would only be effective for modeling grammar patterns (which I eventually intend to do!), and not *store data*. Does this significantly change the domain of the problem?" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-02-05T15:05:56.983", "Id": "70204", "Score": "0", "body": "@ChrisCirefice absolutely! Now we're talking more about *xml deserialization* than anything else - I think. (only glanced at your update)" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-02-05T15:11:19.307", "Id": "70207", "Score": "0", "body": "That's exactly what it is haha, *not grammar yet*! I would like to retain, as much as possible, the structure of the XML file. I think I did a fairly good job then - as I remember you saying, `abstract` is a way to say **is-a** in a relational sense. That being said, I guess I'm still not sure that I did the abstraction correctly, because I feel that repeating the `public override` several times throughout the classes is a bit tedious and sloppy - however, isn't it *necessary* when you implement `abstract` class members? **That** structure will stay **static** so maybe it's a non-issue..." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-02-05T15:15:42.223", "Id": "70210", "Score": "0", "body": "There are tools for this! You can create a schema from your xml, and from the schema you can *generate* classes that perfectly map to your xml structure - you don't even have to actually write any of these classes yourself :) research what xsd.exe can do for you :)" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-02-05T15:30:51.267", "Id": "70218", "Score": "0", "body": "As for `abstract` members, you are right - they **must** be overridden. But who said an `abstract` class *had* to have `abstract` members? You make a class `abstract` because you don't want that class directly instantiated; this buys you the *possibility* to have `abstract` members - they don't *have* to be. And by *not being abstract*, the members are simply inherited. If you want them overridable, you can make them `virtual`, but I don't think I see an immediate need for that." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-02-06T15:48:41.530", "Id": "70418", "Score": "0", "body": "@lol.upvote It's interesting... there is a guy collaborating with me on this, building the UI and stuff - I guess he didn't know about that feature but it's funny because he just mentioned in an email to me that he designed a .xaml file, and Visual Studio generated a bunch of other code for him. I guess I just don't know all the power that's at my fingertips ;) in any case, I'll take a look at the auto-generation stuff. Your answer, as well as 200_success' will be very useful for modeling the *grammar*, so thank you :)" } ], "meta_data": { "CommentCount": "9", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-02-05T04:40:35.603", "Id": "40917", "ParentId": "40868", "Score": "6" } }, { "body": "<p>I'll comment mainly on the <em>querying interface</em>, as I don't have good ideas for how to <em>store</em> all those word forms at this point.</p>\n\n<p>You have a small combinatorial explosion problem that you should probably acknowledge. In French, inflection of nouns and adjectives depends mainly on gender and number, so you should expose an <code>Inflect()</code> method that accepts two independent arguments, rather than four no-argument getters. The interface with independent arguments becomes more obviously superior when it comes to verbs, which also depend on the person, tense, and mood.</p>\n\n<p>As is common in human languages, there are some exceptional cases that you may wish to consider. For example, the adjective <a href=\"http://fr.wiktionary.org/wiki/beau\" rel=\"nofollow\"><em>beau</em></a> comes in forms</p>\n\n<ul>\n<li><em>beau</em> (masculine singular)</li>\n<li><em>belle</em> (feminine singular)</li>\n<li><em>beaux</em> (masculine plural)</li>\n<li><em>belles</em> (feminine plural)</li>\n</ul>\n\n<p>However, the masculine singular becomes <em>bel</em> when it precedes a word that begins with a vowel or silent h. Furthermore, the following word doesn't necessarily have to be the noun being modified (e.g. <em>un bel et vaste salon</em>). There are probably other examples and arguments for keeping the interfaces flexible enough to handle such language warts.</p>\n\n<p>Verb groups should probably be first, second, third, irregular (e.g. <em>être</em>), and defective (e.g. <em>falloir</em>).</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-02-05T14:20:40.663", "Id": "70194", "Score": "0", "body": "I do like your idea of having an interface for inflections - however, this design is simply to store all data for a word. Grammatically-related topics are not part of this code at all, aside from the *common attributes* that these types of words share. For example, your remark about the word *bel* (from *beau) in `ms` form, when in front of (any) word that starts with a vowel, is purely grammatical, and should thus be omitted from this structure, especially because it is a rare exception. Non-aspirate forms are much more common, so I decided to store them in the table." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-02-05T14:23:29.350", "Id": "70195", "Score": "0", "body": "In fact, the verb groups follow a similar pattern - there are *first*, *second*, *third*, and *irregular* verb groups. I'll eventually write an algorithm to conjugate the regular verbs to auto-fill data in my XML dictionary file for me, but *falloir* is a very rare exception, such that the only real difference between it and *être* is that *falloir* will have 'empty data' in many of its verb tables. This is an exception that, in the *storage* schema, is really irrelevant, because this is going to be a \"click here to get all data about a word\" schema. Grammar is coming later :)" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-02-05T14:52:29.137", "Id": "70201", "Score": "0", "body": "Sorry for multiple comments in a row - but last thing: I updated my question to reflect the *goal* of this organizational structure, as well as an example of the data that I will be storing. I think that will help clarify what I'm trying to do here - your suggestions are more *grammar*-related, which I will definitely thoroughly consider when I actually start writing that interface! For now though, it's just getting all the data into the application, so that it is accessible in a manner that makes sense (following the XML data, which has a hierarchical pattern that I want to follow)." } ], "meta_data": { "CommentCount": "3", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-02-05T13:30:41.227", "Id": "40955", "ParentId": "40868", "Score": "4" } } ]
{ "AcceptedAnswerId": "40917", "CommentCount": "5", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-02-04T18:30:27.803", "Id": "40868", "Score": "5", "Tags": [ "c#", "lookup" ], "Title": "Conjugation tables for French" }
40868
<p><strong>Questions:</strong> </p> <ul> <li>How could this code be written better?</li> <li>Could this be written in less lines of code if constructed using classes?</li> <li>Also, If the user-created menu items were to be saved to a file for later use, which would be the best approach to use? (pickle? plain text file? etc.)</li> </ul> <p><strong>Problems:</strong> </p> <ul> <li>How do I dynamically draw the fixed menu items in the settings menu from a list or dict?</li> <li>How to make items selectable by number or a specific character?</li> <li>My main struggle came with dynamically displaying and executing sub-menu items.</li> </ul> <hr> <p><strong>Preface:</strong> </p> <p>After about 3 weeks of research, trial and error, playing with different approaches and data structures, I ended up scrapping all my code and resigning myself to writing the following code. </p> <p>This problem originated as a programming that challenged I created for myself and it now haunts me because I am having to admit defeat by asking you guys for guidance. This drives me crazy since I know there are probably very elegant ways of writing this script, but this was the only way I could make it work and produce the desired outputs. </p> <p>I have spent hours researching stackoverflow and other sites for similar answers, but none fully addressed my particular design goals, such as dealing with sub-menus and the dynamic nature of this menu system. </p> <p>I should also mention that I have not fully coded every aspect of this script, but there is enough here to allow the creation of menu items and demonstrate what i'm trying to achieve.</p> <hr> <pre><code>#!/usr/bin/python import sys, os menu_actions = {} user_menu_items = [] def add_userItem(item): returnitem = "item " + item + " created..." return returnitem def show_settings(): os.system('clear') print "\nEdit" print "Default Settings" print "\nBack" choice = raw_input(" &gt;&gt; ") if choice.lower() == 'back': main_menu() else: decision(choice) return def quit(): raise SystemExit() def s_edit(): os.system('clear') print "\nCreate" print "Modify" print "\nBack\n" choice = raw_input(" &gt;&gt; ") if choice.lower() == 'back': show_settings() else: decision(choice) return def s_default(): os.system('clear') choice = raw_input("(**All user created menus will be erased**)\nAre you sure? (YES / NO) or Back\n &gt;&gt; ") if choice.lower() == 'back': show_settings() elif choice.lower() == 'yes': print 'all settings have been set to default' del user_menu_items[:] # removing all items from user menu show_settings() elif choice.lower() == 'no': show_settings() return def e_create(): go = True addeditem = [] global user_menu_items while go: badinput = False if badinput == True: print "That's not a selection. Please try again..." else: os.system('clear') if addeditem != '': z = 0 for i in addeditem: print(addeditem[z]) z += 1 if not user_menu_items: print print "\n**Menu Items**" z = 0 for i in user_menu_items: print(user_menu_items[z]) z += 1 choice = raw_input("\nCreate New Item? (YES / NO)\n &gt;&gt; ") if choice.lower() == 'yes': additem = raw_input("\n\nSpecify Name of New Menu Item: ") addeditem.append(add_userItem(additem)) user_menu_items.append(additem) else: if choice.lower() == 'no': go = False else: badinput = True s_edit() return def e_modify(): os.system('clear') print "Rename" print "Delete" print "Move Item" print "\nBack\n" choice = raw_input("Choose an action: ") return choice def m_rename(): os.system('clear') print "\nBack\n" choice = raw_input("Enter a new name: ") return choice def m_delete(): os.system('clear') print "\nBack\n" choice = raw_input("Select Menu Item to Delete: ") return choice def m_move(): os.system('clear') print "\nBack\n" choice = raw_input("Specify new location: ") return choice def goback(): os.system('clear') print "\nBack\n" decision('') return def user_menu(): z = 0 for i in user_menu_items: print(user_menu_items[z]) z += 1 return def main_menu(): os.system('clear') user_menu() print "\nSettings" print "Quit" choice = raw_input(" &gt;&gt; ") decision(choice) return def decision(decision): dec = decision.lower() if dec == '': menu_actions['main menu']() else: try: menu_actions[dec]() except KeyError: print "invalid selection, please try again.\n" menu_actions['main menu']() return menu_actions = { 'main': main_menu, 'settings': show_settings, 'quit': quit, 'edit': s_edit, 'default': s_default, 'create': e_create, 'modify': e_modify, 'rename': m_rename, 'delete': m_delete, 'move': m_move, 'back' : goback } main_menu() </code></pre> <p><strong>About:</strong> As you can see, I have designed a menu creator based on user input, while still providing a fixed menu system for creating and modifying the user-created menus. My desire was to display one tier at a time, making menu items numerically selectable (except for "go back" and "quit"). Below is a pseudo code view of my desired menu tree.</p> <p>I should also mention that I am fully aware of the fact that the user-created menu items will not have any particular functionality, but I figured I could use this program to create the menus and then code functionality later on -- if desired.</p> <p><strong>Desired Menu Tree:</strong></p> <blockquote> <ol> <li><p>Settings</p> <ol> <li><p>Edit Menu</p> <ol> <li>Create > # Specify Location of Menu Item. > # Specify Name of New Menu Item.</li> <li>Modify > # Select Menu Item to Modify. > # Pick an Action? <ol> <li>Rename > # Enter a new name</li> <li>Delete > # Select Menu Item to Delete.</li> <li>Move Item > # Where?</li> </ol></li> </ol> <p>x. Go Back</p></li> <li><p>Default Settings (<strong>All user created menus will be erased</strong>) > #Are you sure? (YES / NO?)</p></li> </ol></li> </ol> <p>x. Quit > #exit program</p> </blockquote>
[ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-02-06T18:47:11.530", "Id": "70464", "Score": "0", "body": "Can you fix the indentation so that your initial code and intent can be undetstood ? Your code doesn't runs with current indentation. Start fixing with line#63" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-02-07T08:10:27.213", "Id": "70582", "Score": "0", "body": "All fixed, sorry about that, when I copied the text over and then specified it as code, stackexchange didn't recognize all of my indentions. You should be good to go now." } ]
[ { "body": "<p>Disclaimer : your code is not indented properly and I cannot run it. Also, it seems a bit convoluted to me so I haven't really tried to understand it. However, here are a few comments that might help you if you want to improve your code.</p>\n\n<hr>\n\n<p><strong>Keep it simple</strong></p>\n\n<pre><code>def add_userItem(item):\n returnitem = \"item \" + item + \" created...\"\n return returnitem\n</code></pre>\n\n<p>could be </p>\n\n<pre><code>def add_userItem(item):\n return \"item \" + item + \" created...\"\n</code></pre>\n\n<hr>\n\n<p><code>goback</code> could just call <code>main_menu()</code> instead of <code>decision('')</code>. This would make <code>decision()</code> much simpler as it shouldn't be its duty to try to handle special cases (see <a href=\"http://en.wikipedia.org/wiki/Separation_of_concerns\" rel=\"nofollow\">Separation of Concerns</a>)</p>\n\n<hr>\n\n<p>You don't need to have <code>menu_actions</code> at the top of your file.</p>\n\n<hr>\n\n<p><code>return</code> at the end of the function is not required if you don't plan to return any value.</p>\n\n<hr>\n\n<pre><code> choice = raw_input(\"Choose an action: \")\n return choice\n</code></pre>\n\n<p>could be </p>\n\n<pre><code> return raw_input(\"Choose an action: \")\n</code></pre>\n\n<hr>\n\n<hr>\n\n<p><strong>For Loop</strong></p>\n\n<p>The way Python loops is designed is supposed to help you to write concise and expressive code : what you write should match pretty closely how you think about things : \"I want to do this for each item in this container\" instead of \"I want to have this index and I start at 0 and I increment and I get the element at this index...\".</p>\n\n<pre><code> z = 0\n for i in addeditem:\n print(addeditem[z])\n z += 1\n</code></pre>\n\n<p>should be written :</p>\n\n<pre><code> for i in addeditem:\n print(i)\n</code></pre>\n\n<p>How nice is this ?</p>\n\n<p>Pretty much everytime you initialise a variable at 0 to use it as an index in a loop you are doing it wrong. If you really need to know what is the current index, enumerate is what you are looking for.</p>\n\n<hr>\n\n<hr>\n\n<p><strong>Don't repeat yourself</strong></p>\n\n<pre><code> for i in user_menu_items:\n print(i)\n</code></pre>\n\n<p>appears in your code twice. You should just call <code>user_menu</code>.</p>\n\n<hr>\n\n<p>Multiple methods looks quite similar, it might be worth defining a more generic function and then just calling it everywhere</p>\n\n<hr>\n\n<pre><code> if choice.lower() == 'back':\n show_settings()\n elif choice.lower() == 'yes':\n print 'all settings have been set to default'\n del user_menu_items[:] # removing all items from user menu\n show_settings()\n elif choice.lower() == 'no':\n show_settings()\n</code></pre>\n\n<p>calls <code>lower()</code> and <code>show_settings</code> in 3 different places.\nIt might be easier to do something like :</p>\n\n<pre><code> choice = raw_input(\"(**All user created menus will be erased**)\\nAre you sure? (YES / NO) or Back\\n &gt;&gt; \").lower()\n if choice == 'yes':\n print 'all settings have been set to default'\n del user_menu_items[:] # removing all items from user menu\n show_settings()\n elif choice in ['back','no']:\n show_settings()\n</code></pre>\n\n<hr>\n\n<p>If you ever change the label of <code>menu</code> (which most likely happened already - I assume that <code>main menu</code> is its old name), things will fail and you'll have to fix it in different places in <code>decision</code>.</p>\n\n<p>What about doing :</p>\n\n<pre><code>def decision(decision):\n try:\n menu_actions[decision.lower()]()\n except KeyError:\n print \"invalid selection, please try again.\\n\"\n main_menu()\n</code></pre>\n\n<hr>\n\n<p><strong>Documentation</strong></p>\n\n<p>You should add comments at least to describe the program and the different main functions.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-02-12T17:40:20.117", "Id": "71313", "Score": "0", "body": "This is excellent feedback, thank you Josay. I am new to programming and only recently began being more disciplined with using comments. I will go back and work on it cleaning things up a bit before submitting my edits. Thanks!" } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-02-12T17:14:42.410", "Id": "41486", "ParentId": "40875", "Score": "1" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "2", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-02-04T19:22:03.130", "Id": "40875", "Score": "1", "Tags": [ "python", "console" ], "Title": "Dynamic user-created menus with sub-menus in a command line script" }
40875
<p>I have this object wrapper class, which I will use to implement my Qt OpenGL scene. It is working, but I am looking for a way to:</p> <ul> <li>Improve the API.</li> <li>Remove extra OpenGL calls.</li> <li>Optimize it.</li> </ul> <p>I know that QGL stuff is deprecated and I should switch to newer Qt5 API, but it still has some things missing.</p> <p><strong>GLObject.h:</strong></p> <pre><code>#ifndef GLOBJECT_H #define GLOBJECT_H #ifndef GLEW_STATIC #define GLEW_STATIC #include &lt;GL/glew.h&gt; #endif #include &lt;GL/gl.h&gt; #include &lt;QGLBuffer&gt; #include &lt;QObject&gt; #include &lt;QHash&gt; #include &lt;QVector&gt; #include &lt;QGLShaderProgram&gt; #include &lt;QMatrix4x4&gt; class GLObject : public QObject { Q_OBJECT public: typedef GLfloat VectorType; static constexpr int GLVectorType = GL_FLOAT; typedef QVector&lt;VectorType&gt; VertexArray; typedef QVector&lt;VectorType&gt; ColorArray; static GLObject* getInstancePtr(const QString &amp;name); static GLObject&amp; getIntanceRef(const QString &amp;name); explicit GLObject(const QString &amp;name, QObject *parent = 0); virtual ~GLObject(); void addVertexData(const VertexArray &amp;data); void addColorData(const ColorArray &amp;data); bool buildVBO(); GLuint bufferID() const; bool bind(); void unbind(); bool addVertexShader(const QString &amp;path); bool addFragmentShader(const QString &amp;path); bool linkShaders(); QString programLog() const; QGLShaderProgram &amp;getProgramRef(); bool bindProgram(); void unbindProgram(); void setProjectionMatrix(const QMatrix4x4 &amp;mat); QMatrix4x4 &amp;getProjectionMatrixRef(); QMatrix4x4 getProjectionMatrix() const; void setViewMatrix(const QMatrix4x4 &amp;mat); QMatrix4x4 &amp;getViewMatrixRef(); QMatrix4x4 getViewMatrix() const; void setModelMatrix(const QMatrix4x4 &amp;mat); QMatrix4x4 &amp;getModelMatrixRef(); QMatrix4x4 getModelMatrix() const; void rebindMVPMatrix(); QString objectName() const; virtual void draw(); private: static void initVAO(); void * colorOffset(); static QHash&lt;QString, GLObject*&gt; sInstances; QByteArray mVertexBuffer, mColorBuffer; QGLBuffer mVBO; int nVertexBufferSize, nColorBufferSize; int mVertexCount; QGLShaderProgram mProgram; const QString mName; QMatrix4x4 mProjection, mView, mModel; }; #endif // GLOBJECT_H </code></pre> <p><strong>GLObject.cpp:</strong></p> <pre><code>#include "GLObject.h" QHash&lt;QString, GLObject*&gt; GLObject::sInstances; #include &lt;cstring&gt; using std::memcpy; #include &lt;exception&gt; #include &lt;QDebug&gt; GLObject *GLObject::getInstancePtr(const QString &amp;name) { if(sInstances.contains(name)) return sInstances[name]; else { #ifdef QT_DEBUG qDebug() &lt;&lt; QString("Object with name %1 doesn't exist!").arg(name); #endif return nullptr; } return sInstances[name]; } GLObject &amp;GLObject::getIntanceRef(const QString &amp;name) { using std::invalid_argument; if(sInstances.contains(name)) return *(sInstances[name]); else { QString errMsg = QString("Object with name %1 doesn't exist!").arg(name); #ifdef QT_DEBUG qDebug() &lt;&lt; errMsg; #endif throw std::invalid_argument(errMsg.toStdString()); } } GLObject::GLObject(const QString &amp;name, QObject *parent) : QObject(parent), mVBO(QGLBuffer::VertexBuffer), mName(name) { nVertexBufferSize = nColorBufferSize = 0; mVertexCount = 0; initVAO(); sInstances.insert(name, this); } void GLObject::addVertexData(const GLObject::VertexArray &amp;data) { mVertexCount = data.size() / 3; mVertexBuffer.resize(data.size() * sizeof(VectorType)); memcpy(mVertexBuffer.data(), data.constData(), mVertexBuffer.size()); nVertexBufferSize = mVertexBuffer.size(); } void GLObject::addColorData(const GLObject::ColorArray &amp;data) { Q_ASSERT(data.size() == mVertexCount * 3); mColorBuffer.resize(data.size() * sizeof(VectorType)); memcpy(mColorBuffer.data(), data.constData(), mColorBuffer.size()); nColorBufferSize = mColorBuffer.size(); } bool GLObject::buildVBO() { if(mVBO.isCreated()) mVBO.destroy(); bool ok = mVBO.create(); ok = mVBO.bind(); const QByteArray data = mVertexBuffer + mColorBuffer; mVBO.allocate(data.constData(), data.size()); mColorBuffer.clear(); mVertexBuffer.clear(); unbind(); return ok; } GLuint GLObject::bufferID() const { return mVBO.bufferId(); } GLObject::~GLObject() { unbind(); sInstances.remove(mName); } bool GLObject::bind() { return mVBO.bind(); } void GLObject::unbind() { glBindBuffer(GL_ARRAY_BUFFER, 0); } bool GLObject::addVertexShader(const QString &amp;path) { return mProgram.addShaderFromSourceFile(QGLShader::Vertex, path); } bool GLObject::addFragmentShader(const QString &amp;path) { return mProgram.addShaderFromSourceFile(QGLShader::Fragment, path); } bool GLObject::linkShaders() { bool ok = mProgram.link(); rebindMVPMatrix(); return ok; } QString GLObject::programLog() const { return mProgram.log(); } QGLShaderProgram &amp;GLObject::getProgramRef() { return mProgram; } bool GLObject::bindProgram() { return mProgram.bind(); } void GLObject::unbindProgram() { mProgram.release(); } void GLObject::setProjectionMatrix(const QMatrix4x4 &amp;mat) { mProjection = mat; } QMatrix4x4 &amp;GLObject::getProjectionMatrixRef() { return mProjection; } QMatrix4x4 GLObject::getProjectionMatrix() const { return mProjection; } void GLObject::setViewMatrix(const QMatrix4x4 &amp;mat) { mView = mat; } QMatrix4x4 &amp;GLObject::getViewMatrixRef() { return mView; } QMatrix4x4 GLObject::getViewMatrix() const { return mView; } void GLObject::setModelMatrix(const QMatrix4x4 &amp;mat) { mModel = mat; } QMatrix4x4 &amp;GLObject::getModelMatrixRef() { return mModel; } QMatrix4x4 GLObject::getModelMatrix() const { return mModel; } void GLObject::rebindMVPMatrix() { const QMatrix4x4 MVP = mProjection * mView * mModel; bindProgram(); mProgram.setUniformValue("MVP", MVP); unbindProgram(); } QString GLObject::objectName() const { return mName; } void GLObject::draw() { if(mProgram.isLinked()) bindProgram(); bind(); glVertexAttribPointer( 0, 3, GLVectorType, GL_FALSE, 0, NULL ); glVertexAttribPointer( 1, 3, GLVectorType, GL_FALSE, 0, colorOffset() ); glDrawArrays(GL_TRIANGLES, 0, mVertexCount); unbind(); if(mProgram.isLinked()) unbindProgram(); } void GLObject::initVAO() { static bool done; if(done) return; GLuint vao[2]; glGenVertexArrays(2, vao); glBindVertexArray(vao[0]); glBindVertexArray(vao[1]); glEnableVertexAttribArray(0); glEnableVertexAttribArray(1); done = true; } void *GLObject::colorOffset() { if(mVBO.isCreated()) return reinterpret_cast&lt;void*&gt;(nVertexBufferSize); else return nullptr; } </code></pre> <p><strong>widget.h:</strong></p> <pre><code>#ifndef WIDGET_H #define WIDGET_H #define GLEW_STATIC #include &lt;GL/glew.h&gt; #include &lt;QGLWidget&gt; #include &lt;QHash&gt; #include &lt;QKeyEvent&gt; class Widget : public QGLWidget { Q_OBJECT public: Widget(QWidget *parent = 0); ~Widget(); protected: void initializeGL(); void paintGL(); void resizeGL(int w, int h); void keyPressEvent(QKeyEvent * event); void keyReleaseEvent(QKeyEvent * event); void timerEvent(QTimerEvent *); private: QHash&lt;int, bool&gt; mPressedKeys; }; #endif // WIDGET_H </code></pre> <p><strong>widget.cpp:</strong></p> <pre><code>#include "widget.h" #include "GLObject.h" #include &lt;cstdlib&gt; using std::exit; #include &lt;QGLFormat&gt; #include &lt;QGLContext&gt; #include &lt;QDebug&gt; const int WINDOW_WIDTH = 800; const int WINDOW_HEIGHT = 600; inline float aspect(const int a, const int b) { return (static_cast&lt;float&gt;(a) / static_cast&lt;float&gt;(b)); } QGLFormat appFormat() { QGLFormat fmt; fmt.setVersion(4, 0); fmt.setProfile(QGLFormat::CoreProfile); //fmt.setDepth(true); fmt.setSampleBuffers(true); fmt.setSamples(8); //fmt.setDepthBufferSize(32); return fmt; } Widget::Widget(QWidget *parent) : QGLWidget(appFormat(), parent) { setFixedSize(WINDOW_WIDTH, WINDOW_HEIGHT); //setWindowState(windowState() | Qt::WindowFullScreen); #ifdef QT_DEBUG QGLFormat curFormat = format(); if(curFormat != appFormat()) { qWarning() &lt;&lt; "Warning: using nearest format."; qWarning() &lt;&lt; curFormat; } #endif } Widget::~Widget() { } void Widget::initializeGL() { glewExperimental = GL_TRUE; GLenum ok = glewInit(); if(ok != GLEW_OK) { qCritical() &lt;&lt; "Error, can't initialize GLEW: " &lt;&lt; glewGetErrorString(ok); exit(1); } glEnable(GL_MULTISAMPLE); glClearColor(0.0f, 0.0f, 0.0f, 1.0f); glViewport(0, 0, width(), height()); GLObject *triangle = new GLObject("triangle", this); GLObject::VertexArray triangleVData = { -1, -1, 0, 0, 1, 0, 1, -1, 0, }; GLObject::ColorArray triangleCData = { 1, 0, 0, 0, 1, 0, 0, 0, 1 }; triangle-&gt;addVertexData(triangleVData); triangle-&gt;addColorData(triangleCData); triangle-&gt;buildVBO(); triangle-&gt;addVertexShader(":/shaders/triangle.vert"); triangle-&gt;addFragmentShader(":/shaders/triangle.frag"); triangle-&gt;linkShaders(); QObject::startTimer(10); // start repainting } void Widget::paintGL() { glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT); GLObject::getIntanceRef("triangle").draw(); } void Widget::resizeGL(int w, int h) { glViewport(0, 0, w, h); } void Widget::keyPressEvent(QKeyEvent *event) { int key = event-&gt;key(); mPressedKeys[key] = true; if(key == Qt::Key_Escape) close(); QGLWidget::keyPressEvent(event); } void Widget::keyReleaseEvent(QKeyEvent *event) { int key = event-&gt;key(); mPressedKeys[key] = false; QGLWidget::keyReleaseEvent(event); } void Widget::timerEvent(QTimerEvent *) { updateGL(); } </code></pre>
[]
[ { "body": "<h3>GLObject</h3>\n\n<ol>\n<li><p>You seem to be using C++11, so don't assign <code>0</code> to pointers (in <code>QObject *parent = 0</code> for instance). Use <a href=\"http://en.cppreference.com/w/cpp/language/nullptr\" rel=\"nofollow noreferrer\"><code>nullptr</code></a>.</p></li>\n<li><p><code>GLObject</code> has a virtual destructor. You don't seem to be inheriting from the class, so a virtual destructor wouldn't be necessary. However, you have a virtual <code>draw()</code> method, so this probably means you plan on extending it at some moment. The point here is to avoid virtual destructors unless you are really planning on extending a class. Don't add one \"just in case\".</p></li>\n<li><p>Having a pair of <code>get*()</code> and <code>get*Ref()</code> seems redundant. Following is one such instance:</p>\n\n<blockquote>\n<pre><code>void setProjectionMatrix(const QMatrix4x4 &amp;mat);\nQMatrix4x4 &amp;getProjectionMatrixRef();\nQMatrix4x4 getProjectionMatrix() const;\n</code></pre>\n</blockquote>\n\n<p>The <code>*Ref()</code> overload seems unnecessary. The <code>set*()</code> methods already allow someone to mutate the object state. A single <code>get*()</code> returning by value or <em>const reference</em> would do.</p></li>\n<li><p>Minor nitpicking, but group your typedefs; that constant in the middle breaks the pattern:</p>\n\n<blockquote>\n<pre><code>typedef GLfloat VectorType;\nstatic constexpr int GLVectorType = GL_FLOAT;\ntypedef QVector&lt;VectorType&gt; VertexArray;\ntypedef QVector&lt;VectorType&gt; ColorArray;\n</code></pre>\n</blockquote>\n\n<p>And by-the-way, <code>GL_FLOAT</code> should be assigned to a constant of type <code>GLenum</code>.</p></li>\n<li><p>I personally wouldn't do this at the top level:</p>\n\n<blockquote>\n<pre><code>using std::memcpy;\n</code></pre>\n</blockquote>\n\n<p>It isn't that much more typing calling the function as <code>std::memcpy</code>. You did that in a source file, so it is not a big issue, but still, it is in the global scope.</p>\n\n<p>Another misuse of the <code>using</code> directive in <code>getIntanceRef()</code>:</p>\n\n<blockquote>\n<pre><code>GLObject &amp;GLObject::getIntanceRef(const QString &amp;name)\n{\n using std::invalid_argument;\n</code></pre>\n</blockquote>\n\n<p>I'm perfectly fine with <code>using</code> inside a function, but you go on and reference <code>std::invalid_argument</code> by its namespace qualified name in the next few lines, rendering the <code>using</code> useless (no pun intended, honestly).</p></li>\n<li><p>This is worth for both classes: I recommend consistent use of curly braces <code>{ }</code> on all conditional statements, even the single line ones and in loops. This can prevent bugs (the infamous <code>goto fail</code> bug from SSL could have been detected more easily if they had followed this practice) and it also simplifies maintenance and future expansion.</p></li>\n<li><p>I know that OpenGL doesn't play well with threads, but it is worth noting that the static initialization flag <code>done</code> inside <code>initVAO()</code> is not thread safe. If you ever try to use this class concurrently, that flag could cause multiple initializations.</p></li>\n<li><p>Still talking about <code>initVAO()</code>, the way that function is implemented doesn't really make sense. You create two Vertex Array Objects, binds them and throws away the handles. That is not the way VAOs are meant to be used. They are supposed to serve as wrappers for Vertex Buffers and associated states (vertex layout, etc). Take a look at these resources: <a href=\"https://stackoverflow.com/questions/11821336/what-are-vertex-array-objects\">What are Vertex Array Objects?</a>, <a href=\"https://www.opengl.org/wiki/Vertex_Specification#Vertex_Array_Object\" rel=\"nofollow noreferrer\">Vertex Array Object (OGL wiki)</a> and a <a href=\"http://ogldev.atspace.co.uk/www/tutorial32/tutorial32.html\" rel=\"nofollow noreferrer\">tutorial on the subject</a>. If used properly, <em>they can reduce</em> the number of GL calls during rendering.</p></li>\n<li><p>The use of the boolean flag <code>ok</code> in the <code>buildVBO</code> method has issues:</p>\n\n<blockquote>\n<pre><code>bool ok = mVBO.create();\nok = mVBO.bind();\n</code></pre>\n</blockquote>\n\n<p>The return value of the second call will overwrite the first, which could hide an error. If the objective is to report the error as early as possible, check the return value of each method and bail out with <code>false</code>. There isn't much point in continuing with an error condition. <a href=\"http://en.wikipedia.org/wiki/Fail-fast\" rel=\"nofollow noreferrer\"><em>Failing Fast</em></a> is an important programming principle.</p></li>\n</ol>\n\n<h3>Widget</h3>\n\n<p>Not much to say about <code>Widget</code>. It looks good to me. Just a few minor things:</p>\n\n<ol>\n<li><p>A few dead-code comments that pollute it a little. Get rid of them, since commented-out code adds nothing to readability or information about the program. You don't have to leave commented-out code for future reference either. Your Version Control history does that for you.</p></li>\n<li><p>The destructor of <code>Widget</code> is empty, so it can be omitted.</p></li>\n<li><p><code>exit()</code>ing a program on error is a rather crude way of handling a failure. Consider throwing an exception and let it propagate if the error has no recovery.</p></li>\n<li><p>Apparently, you have a few local constants and functions inside <code>widget.cpp</code>. Consider wrapping them inside an unnamed namespace to make your intentions clear:</p>\n\n<pre><code>namespace \n{\n const int WINDOW_WIDTH = 800;\n const int WINDOW_HEIGHT = 600;\n\n float aspect(const int a, const int b)\n {\n ...\n }\n\n QGLFormat appFormat()\n {\n ...\n }\n} // namespace\n</code></pre>\n\n<p>The constants could also be <code>constexpr</code>.</p></li>\n</ol>\n\n<hr>\n\n<p>This was a very late answer, but I hope some of what was said here can still be of use to you. Cheers!</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2015-03-28T06:15:15.997", "Id": "153492", "Score": "1", "body": "Thank you! Its a bit late but it is still very useful. I ported everything to Qt 5 with `QOpenGL` classes, so I can use stuff like `QOpenGLVertexArrayObject` and it's `Binder` class. Also all of this is now running inside a Qt Quick scene in a sepearate render thread, so I think you found a bug in `initVAO()` function." } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2015-03-27T18:58:08.457", "Id": "85193", "ParentId": "40877", "Score": "3" } } ]
{ "AcceptedAnswerId": "85193", "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-02-04T19:29:33.657", "Id": "40877", "Score": "7", "Tags": [ "c++", "object-oriented", "opengl", "wrapper", "qt" ], "Title": "OpenGL object wrapped in a Qt Widget" }
40877
<p><strong>Objective</strong> <br> Currently I have the flags hardcoded. But want to optimize my code for production. So I am wondering if I have this code done clean enough to leverage CSS inheritance while maintaining support for older browsers. </p> <hr> <p>I have this menu on my <a href="http://codepen.io/JGallardo/pen/nKugj" rel="nofollow noreferrer">CodePen</a></p> <p><img src="https://i.stack.imgur.com/2f2fO.png" alt="menu"></p> <p>whose size will vary per device (media queries not shown yet). I restructured my code from <code>&lt;div&gt;</code>'s to this <code>&lt;ul&gt;</code></p> <p><strong>HTML</strong></p> <pre><code>&lt;ul class="international"&gt; &lt;li class="intlFlag usFlag"&gt;&lt;/li&gt; &lt;li&gt;North America&lt;/li&gt; &lt;li class="intlButton"&gt; &lt;a href="#"&gt; &lt;!-- link pending --&gt; &lt;i class="fa fa-globe"&gt;&lt;/i&gt; &lt;/a&gt; &lt;/li&gt; &lt;/ul&gt; </code></pre> <p>On the div with the flag, I want to be able to pass its CSS rules without giving it the class of <code>intlFlag</code> and for the <code>intlButton</code> I want to also pass rule without giving it the class. I hesitated to use the <code>:last-of-type</code> selector because it is not supported below IE8, and many users of the site will unfortunately use IE8. <hr> <br></p> <p><img src="https://i.stack.imgur.com/LbA28.png" alt="not supported"></p> <p>Image from <a href="http://www.w3schools.com/cssref/sel_last-of-type.asp" rel="nofollow noreferrer">w3schools.com</a></p> <p>As far as the first <code>&lt;li&gt;</code> I want the class to be passed in based on what country they are detected to be coming from. So the script would for example detect that you are in North America. And then pass in that class which then sets your flag. In production I will be using MustacheJS templates. So I plan to do something like this </p> <pre><code>&lt;ul class="international"&gt; &lt;li class="{{{flag}}}"&gt;&lt;/li&gt; &lt;li&gt;{{region}}&lt;/li&gt; &lt;li class="intlButton"&gt; &lt;a href="/international"&gt; &lt;i class="fa fa-globe"&gt;&lt;/i&gt; &lt;/a&gt; &lt;/li&gt; &lt;/ul&gt; </code></pre> <p>my JSON values might be something like </p> <pre><code>"flag":"usFlag", "region":"North America" </code></pre> <p>That <code>usFlag</code> class would add this class to display the respective flag</p> <pre><code>.usFlag { background-position: 0px 0px; } </code></pre> <p>the other rules passed into that <code>&lt;li&gt;</code> are currently passed in with </p> <pre><code>.intlFlag { background-color: #fff; background-image: url('https://s3-us-west-2.amazonaws.com/s.cdpn.io/101702/flag-sprite.png'); height: 28px; width: 44px; } </code></pre> <p>Here are the complete set of my CSS rules for this element</p> <pre><code>.international { background-color: rgba(96, 80, 80, 0.3); font-size: 18px; line-height: 42px; list-style-type: none; margin: auto; padding-left: 0; position: absolute; bottom: 0; left: 0; right: 0; width: 100%; } /* only on tablet */ .international { max-width: 240px; } .international &gt; li { display: inline-block; line-height: 42px; margin-left: 6px; vertical-align: middle; } .intlFlag { background-color: #fff; background-image: url('https://s3-us-west-2.amazonaws.com/s.cdpn.io/101702/flag-sprite.png'); height: 28px; width: 44px; } .usFlag { background-position: 0px 0px; } .intlButton { float: right; font-size: 24px; margin-right: 6px; } .intlButton a { color: #444; } .intlButton i { background-color: rgba(225, 225, 225, .7); border-radius: 3px; padding: 4px; } </code></pre>
[ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-02-04T20:10:38.533", "Id": "70021", "Score": "0", "body": "In my opinion, this is a misuse of the list element. Lists should only contain similar items (eg. groceries, colors, countries). The only appropriate markup choice here would be either a table (if you're showing more than one country) or div/span. Negative bonus points for misusing the `<i>` element for icons." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-02-04T21:17:49.147", "Id": "70043", "Score": "0", "body": "@cimmanon so you think `<span>` s might be more appropriate here?" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-08-11T08:51:08.427", "Id": "107686", "Score": "0", "body": "I’ve noticed that you have a couple of questions without an answer marked as accepted. You should definitely mark the best one as accepted after some time of consideration." } ]
[ { "body": "<p>User \"cimmanon\" pointed out that lists would not be appropriate here. So I went with spans on this <a href=\"http://codepen.io/JGallardo/pen/BlgEe\">CodePen</a></p>\n\n<p><strong>HTML</strong></p>\n\n<pre><code>&lt;div class=\"international\"&gt;\n &lt;span class=\"intlFlag\"&gt;&lt;/span&gt;\n &lt;span&gt;North America&lt;/span&gt;\n &lt;span class=\"intlButton\"&gt;\n &lt;a href=\"#\"&gt; &lt;!-- link pending --&gt;\n &lt;i class=\"fa fa-globe\"&gt;&lt;/i&gt;\n &lt;/a&gt;\n &lt;/span&gt;\n&lt;/div&gt;\n</code></pre>\n\n<p><strong>CSS</strong></p>\n\n<pre><code>.international {\n background-color: rgba(96, 80, 80, 0.3);\n color: #fff;\n font-size: 18px;\n line-height: 42px;\n margin: auto;\n position: absolute;\n bottom: 0; left: 0; right: 0; \n width: 100%;\n}\n/* only on tablet */\n.international { max-width: 240px; }\n\n.international &gt; span {\n display: inline-block;\n line-height: 42px;\n margin-left: 6px;\n vertical-align: middle;\n}\n\n.intlFlag {\n background-color: #fff;\n background-image: url('https://s3-us-west-2.amazonaws.com/s.cdpn.io/101702/flag-sprite.png');\n height: 28px;\n width: 44px;\n}\n\n.usFlag { background-position: 0px 0px; }\n\n.intlButton { \n float: right;\n font-size: 24px;\n margin-right: 6px;\n}\n.intlButton a { color: #444; }\n.intlButton i {\n background-color: rgba(225, 225, 225, .7); \n border-radius: 3px;\n padding: 4px; \n}\n</code></pre>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-02-04T21:56:27.950", "Id": "40897", "ParentId": "40878", "Score": "6" } }, { "body": "<p>Some quick notes:</p>\n\n<ol>\n<li>You can use <code>list-style: none;</code> instead of <code>list-style-type: none;</code> &ndash; Just a bit shorter</li>\n<li><p>You mention in a comment <code>/* only for tablet */</code>, but there are no media queries in sight.</p>\n\n<pre><code>@media screen and (max-width: 480px) {\n .international {\n max-width: 240px;\n }\n}\n</code></pre></li>\n<li><p>It's common practise to use dash-delimited class names in CSS, not CamelCase. This completely personal and you can do whatever you want.</p></li>\n<li>Omit the units on zero values: <code>background-position: 0 0;</code> instead of <code>background-position: 0px 0px;</code></li>\n<li><p>I recommend writing single-line CSS: Every property declaration on a new line. There is no reason to write rule declarations with only one property declaration on one line. Also I don't find it helpful writing <code>top</code>, <code>right</code>, <code>bottom</code> and <code>left</code> on one line.</p>\n\n<p>If you want to save file size and improve performance, you should minimize your CSS. That's so much more efficient plus you keep the legibility and maintainability in your CSS file.</p></li>\n</ol>\n\n<p>That's it for the moment. Feel free to add a comment to discuss something or visit our great <a href=\"http://chat.stackexchange.com/rooms/8595/the-2nd-monitor\">chat</a>.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-02-09T16:27:54.590", "Id": "41288", "ParentId": "40878", "Score": "7" } } ]
{ "AcceptedAnswerId": "40897", "CommentCount": "3", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-02-04T19:42:27.180", "Id": "40878", "Score": "4", "Tags": [ "html", "css", "json", "mustache" ], "Title": "How can this <ul> be set up to maximize inheritance if additional classes will be passed in from a JSON file?" }
40878
<p>I need to print this in Java, but I feel that my code is too big:</p> <blockquote> <pre><code>* ** *** **** *** ** * </code></pre> </blockquote> <pre><code>public static void main(String[] args) { for(int i=0; i&lt;=3; i++) { for(int j=0; j&lt;=i; j++) { System.out.print("*"); } System.out.println(); } for(int j=1; j&lt;=3; j++) { for(int i=3; i&gt;=j; i--) { System.out.print("*"); } System.out.println(); } } </code></pre>
[]
[ { "body": "<p>Here is a lovely way to do it using only one nested for-loop:</p>\n<pre><code>for (int i = 0; i &lt; 7; i++) {\n for (int numStars = 0; numStars &lt; 4 - Math.abs(3 - i); numStars++) {\n System.out.print(&quot;*&quot;);\n }\n System.out.println();\n}\n</code></pre>\n<p>This uses the Math.abs function to perform the calculation of how many stars to print.</p>\n<p>If we take a look at a plot of the classic <a href=\"http://www.wolframalpha.com/input/?i=abs%28x%29&amp;t=mfftb01\" rel=\"noreferrer\">Math.abs</a> we can see that it looks useful. We need to flip it upside-down though, this is done by taking <code>4 - abs(x)</code> which would <a href=\"http://www.wolframalpha.com/input/?i=4+-+abs%28x%29\" rel=\"noreferrer\">look like this</a>. Finally, we need to switch it to the right a bit, so we modify the input to the function call and end up with this: <a href=\"http://www.wolframalpha.com/input/?i=4+-+abs%283+-+x%29\" rel=\"noreferrer\">4 - abs(3 - x)</a></p>\n<p>Images courtesy of <a href=\"http://www.wolframalpha.com\" rel=\"noreferrer\">wolframalpha.com</a></p>\n<h3>4-abs(x)</h3>\n<p><img src=\"https://i.stack.imgur.com/eZAZD.png\" alt=\"enter image description here\" /></p>\n<h3>4-abs(3 - x)</h3>\n<p><img src=\"https://i.stack.imgur.com/XgIfo.png\" alt=\"enter image description here\" /></p>\n<p>Finally, here is a very flexible solution, which also works with even numbers:</p>\n<pre><code>int rows = 20;\ndouble maximumValue = Math.ceil(rows / 2.0);\ndouble shifted = maximumValue - 1;\nfor (int i = 0; i &lt; rows; i++) {\n int count = (int) (maximumValue - Math.abs(shifted - i));\n if (i &gt;= rows / 2 &amp;&amp; rows % 2 == 0) // slight fix for even number of rows\n count++;\n \n for (int numStars = 0; numStars &lt; count; numStars++) {\n System.out.print(&quot;*&quot;);\n }\n System.out.println();\n}\n</code></pre>\n<p>This will output:</p>\n<pre><code>*\n**\n***\n****\n*****\n******\n*******\n********\n*********\n**********\n**********\n*********\n********\n*******\n******\n*****\n****\n***\n**\n*\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-02-05T01:58:09.770", "Id": "70074", "Score": "20", "body": "This is an excellent answer. I am disappointed that @user3272408 was apparently only interested in the code." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-02-05T04:09:49.183", "Id": "70088", "Score": "10", "body": "+5 for charts and graphs! Letterman would be proud." } ], "meta_data": { "CommentCount": "2", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-02-04T20:11:41.803", "Id": "40882", "ParentId": "40880", "Score": "30" } }, { "body": "<p>You've hard-coded <code>3</code> in three places. Yet, the output contains a row with four stars. That's <strong>underhanded programming</strong>. The culprit is this line:</p>\n\n<pre><code>for(int j=0; j&lt;=i; j++)\n</code></pre>\n\n<p>Idiomatic Java would be either</p>\n\n<pre><code>for (int j = 0; j &lt; somelimit; j++)\n</code></pre>\n\n<p>or</p>\n\n<pre><code>for (int j = 1; j &lt;= somelimit; j++)\n</code></pre>\n\n<p>I also find the way that you interchanged <code>i</code> and <code>j</code> between the first and second halves of the program disconcerting.</p>\n\n<hr>\n\n<p>Surely you should define a <strong>function that accepts a parameter</strong>. What varies? The fill character? The size? Otherwise, the simplest solution would be</p>\n\n<pre><code>public static void main(String[] args) {\n System.out.println(\"*\\n**\\n***\\n****\\n***\\n**\\n*\");\n}\n</code></pre>\n\n<hr>\n\n<p>I am in favour of keeping two for-loops, one increasing and one decreasing. Combining those into one loop would likely make it difficult to <strong>see the intent at a glance</strong>. As for how you generate each line of <em>n</em> stars, though, it's not particularly interesting how you accomplish it. I've chosen a one-line hack for the solution below, but you may wish to pick a more traditional approach.</p>\n\n<pre><code>private static String repeat(String s, int n) {\n // A bit of a hack, and not very efficient. Feel free to reimplement.\n return String.format(\"%\" + n + \"s\", \"\").replaceAll(\" \", s);\n}\n\npublic static void printArrow(String fill, int width, PrintStream out) {\n for (int i = 1; i &lt; width; i++) {\n out.println(repeat(fill, i));\n }\n for (int i = width; i &gt;= 1; i--) {\n out.println(repeat(fill, i));\n }\n}\n\npublic static void main(String[] args) {\n printArrow(\"*\", 4, System.out);\n}\n</code></pre>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-02-04T23:28:08.257", "Id": "40900", "ParentId": "40880", "Score": "16" } }, { "body": "<p>You don't need a loop for this.</p>\n\n<pre><code>public static void main(String[] args) {\n String ln = System.getProperty(\"line.separator\");\n System.out.println(\"*\" + ln\n + \"**\" + ln\n + \"***\" + ln\n + \"****\" + ln\n + \"***\" + ln\n + \"**\" + ln\n + \"*\");\n}\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-02-05T00:54:31.927", "Id": "70069", "Score": "3", "body": "That is overkill: `System.out.println(\"*\\n**\\n***\\n****\\n***\\n**\\n*\");` Seriously, what were you thinking? ;-) !" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-02-05T00:57:22.070", "Id": "70071", "Score": "3", "body": "@rolfl: But it looks like the output itself! ;-)" } ], "meta_data": { "CommentCount": "2", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-02-05T00:23:57.183", "Id": "40905", "ParentId": "40880", "Score": "6" } }, { "body": "<p>Using multiple <code>print(\"*\")</code> calls for each star is very inefficient. Print is a slow command, and it also makes what is a relatively simple process (printing a line of stars) become a more complicated loop.</p>\n\n<p>A more efficient way to output the triangle would be to use one <code>println</code> per line. An even better way would be for one println for the whole puzzle, but that has a potential issue of the <code>n</code> value is large.</p>\n\n<p>A real trick here would be to build up one String value for the longest line, and then just print substrings for the shorter ones.</p>\n\n<p>Note, using <code>Math.abs(...)</code> is a clever way to manipulate the substring, but combining it with a loop from <code>negative width</code> to <code>positive width</code> makes it even easier to understand.</p>\n\n<p>Additionally, putting the code in to its own method, instead of the main method, makes the code more reusable.</p>\n\n<pre><code>public static final void triangle(int width) {\n String longest = buildLine(width, '*');\n\n for (int i = -width + 1; i &lt; width; i++) {\n System.out.println(longest.substring(Math.abs(i)));\n }\n}\n\nprivate static String buildLine(int width, char c) {\n char[] chars = new char[width];\n Arrays.fill(chars, c);\n return new String(chars);\n}\n\npublic static void main(String[] args) {\n triangle(5);\n}\n</code></pre>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2015-09-13T14:54:24.823", "Id": "104588", "ParentId": "40880", "Score": "6" } } ]
{ "AcceptedAnswerId": "40882", "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-02-04T20:01:57.653", "Id": "40880", "Score": "14", "Tags": [ "java", "ascii-art" ], "Title": "Printing star greater symbol in Java" }
40880
<p>Reservoir sampling implementation. Reservoir sampling is a family of randomized algorithms for randomly choosing a sample of k items from a list S containing n items, where n is either a very large or unknown number. If question is unclear let me know I will reply asap. Looking for code review, optimizations and best practice. </p> <pre><code>public final class ReservoirSampling&lt;T&gt; { private final int k; /** * Constructs ReservoirSampling object with the input sample size. * * @param k the number of sample elements needed. * @throws IllegalArgumentException if k is not greater than 0. */ public ReservoirSampling(int k) { if (k &lt;= 0) { throw new IllegalArgumentException("The k should be greater than zero"); } this.k = k; }; /** * Returns a list of random `k` samples from the input list. * * @param list of elements from which we chose the k samples from. * @return the list containing k samples, chosen randomly. * @throws NullPointerException if the input list is null. */ public List&lt;T&gt; sample(List&lt;T&gt; list) { final List&lt;T&gt; samples = new ArrayList&lt;T&gt;(k); int count = 0; final Random random = new Random(); for (T item : list) { if (count &lt; k) { samples.add(item); } else { // http://en.wikipedia.org/wiki/Reservoir_sampling // In effect, for all i, the ith element of S is chosen to be included in the reservoir with probability // k/i. int randomPos = random.nextInt(count); if (randomPos &lt; k) { samples.set(randomPos, item); } } count++; } return samples; } public static void main(String[] args) { List&lt;Integer&gt; list = new ArrayList&lt;Integer&gt;(); list.add(1); list.add(2); list.add(3); ReservoirSampling&lt;Integer&gt; reservoirSampling = new ReservoirSampling&lt;Integer&gt;(3); System.out.print("Expected: 1 2 3, Actual: "); for (Integer i : reservoirSampling.sample(list)) { System.out.print(i + " "); } System.out.println(); System.out.print("Expected: random output: "); list.add(4); list.add(5); list.add(6); for (Integer i : reservoirSampling.sample(list)) { System.out.print(i + " "); } } } </code></pre>
[ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-02-04T20:52:40.020", "Id": "70037", "Score": "0", "body": "You *could* add some short description at the top of your post about what exactly \"ReservoirSampling\" is (and please don't just link to the wikipedia article, make life easier for us and describe it in your own words briefly)" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-02-04T21:11:22.410", "Id": "70040", "Score": "0", "body": "Added description, although I am not sure why link to wikipedia would be inconvenient." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-02-05T00:19:00.220", "Id": "70065", "Score": "0", "body": "@JavaDeveloper: Unless a problem description from a 3rd party is too large to embed here, it's best to add it for convenience." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-02-05T00:29:40.153", "Id": "70066", "Score": "0", "body": "noted. will do it" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-02-05T09:39:54.633", "Id": "70136", "Score": "0", "body": "@JavaDeveloper By writing your own explanation, it shows that you care about your question, which will make reviewers also care more about it." } ]
[ { "body": "<p>This is not an accurate implementation of the Reservoir Sampling algorithm.</p>\n\n<p>The Reservoir Algorithm creates a reservoir of size <code>k</code> and fills it from the first <code>k</code> items from the source data.</p>\n\n<p>It then iterates through the remaining source data, and selects a random value for each subsequent item in the data set. If the random value is within the limits of the Reservoir, then the item is placed in the reservoir at that point.</p>\n\n<p>The issue you have is in your details.... Consider a source dataset of size 4 (values a,b, c, and d), and a reservoir of size 3.</p>\n\n<p>There should be a 3-in-4 chance that the 4th item is sampled. Conversely, there should be a 1-in-4 chance that it is not sampled.</p>\n\n<p>In your code, if we applied this example, <code>k</code> would be <code>3</code>. You would create a reservoir of size 3, and you would fill it with the values a, b, and c.</p>\n\n<p>At this point, you would loop again and your <code>item</code> would be 'd', your <code>count</code> would be <code>3</code>, and we would enter the 'else' clause.</p>\n\n<p>You then get your random number with the expression: <code>int randomPos = random.nextInt(count);</code>, or, effectively <code>nextInt(3)</code>.</p>\n\n<p><code>nextInt(3)</code> will never return the value <code>3</code> since <code>nextInt(int)</code> is <a href=\"http://docs.oracle.com/javase/7/docs/api/java/util/Random.html#nextInt%28int%29\" rel=\"nofollow\">an exclusive-of-the-end-range function</a>. As a result, it will always return one of <code>0</code>, <code>1</code>, or <code>2</code>.</p>\n\n<p>These values are all less than 3.</p>\n\n<p>As a consequence, your algorithm will <strong>always</strong> include the k+1 element in your reservoir.</p>\n\n<p>You need to change the way you generate your random number to be: <code>nextInt(count + 1);</code> Alternatively, you should increment your count before it is used to generate the random value.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-02-05T00:12:16.030", "Id": "40903", "ParentId": "40881", "Score": "4" } } ]
{ "AcceptedAnswerId": "40903", "CommentCount": "5", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-02-04T20:07:48.373", "Id": "40881", "Score": "1", "Tags": [ "java", "algorithm", "random" ], "Title": "Reservoir sampling" }
40881
<p>Here's my Python implementation of Conway's Game of Life:</p> <pre><code>class Game(object): def __init__(self, state, infinite_board = True): self.state = state self.width = state.width self.height = state.height self.infinite_board = infinite_board def step(self, count = 1): for generation in range(count): new_board = [[False] * self.width for row in range(self.height)] for y, row in enumerate(self.state.board): for x, cell in enumerate(row): neighbours = self.neighbours(x, y) previous_state = self.state.board[y][x] should_live = neighbours == 3 or (neighbours == 2 and previous_state == True) new_board[y][x] = should_live self.state.board = new_board def neighbours(self, x, y): count = 0 for hor in [-1, 0, 1]: for ver in [-1, 0, 1]: if not hor == ver == 0 and (self.infinite_board == True or (0 &lt;= x + hor &lt; self.width and 0 &lt;= y + ver &lt; self.height)): count += self.state.board[(y + ver) % self.height][(x + hor) % self.width] return count def display(self): return self.state.display() class State(object): def __init__(self, positions, x, y, width, height): active_cells = [] for y, row in enumerate(positions.splitlines()): for x, cell in enumerate(row.strip()): if cell == 'o': active_cells.append((x,y)) board = [[False] * width for row in range(height)] for cell in active_cells: board[cell[1] + y][cell[0] + x] = True self.board = board self.width = width self.height = height def display(self): output = '' for y, row in enumerate(self.board): for x, cell in enumerate(row): if self.board[y][x]: output += ' o' else: output += ' .' output += '\n' return output glider = """ oo. o.o o.. """ my_game = Game(State(glider, x = 2, y = 3, width = 10, height = 10)) print my_game.display() my_game.step(27) print my_game.display() </code></pre> <p><strong>Output:</strong></p> <blockquote> <pre><code> . . . . . . . . . . . . . . . . . . . . . . o o . . . . . . . . o . o . . . . . . . o . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . o . . . . . . . . o o . . . . . . . . o . o . . . . . . . . . . . . . . . . . . . . . . </code></pre> </blockquote> <p>I have several concerns:</p> <ol> <li><p>It feels a bit unnatural to write <code>self.state.board[y][x]</code>, instead of <code>[x][y]</code>. However, I thought it would make sense to let the board be an array of rows rather than columns.</p></li> <li><p>I'm not sure how to divide the tasks between the two classes. For instance, I could have implemented the <code>neighbours()</code> function in the <code>State</code> class, rather than in the <code>Game</code> class.</p></li> <li><p>I know it's good practice to write a lot of comments, but I found most of this code self-explanatory (though that could be because I've just written it).</p></li> <li><p>I used several nested <code>for</code>-loops, but maybe I could replace some with list comprehensions.</p></li> <li><p>I could have left out the <code>display()</code> function of the <code>Game</code> class and just write <code>print my_game.state.display()</code> on the last line. Does this simplify things, or does it only make it more complicated?</p></li> </ol>
[ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-07-27T19:02:08.470", "Id": "104433", "Score": "1", "body": "There seems to be a bug: the x and y variables passed to `State` will be ignored as you are redefining them when you use them as loop variables." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-07-27T21:15:25.923", "Id": "104444", "Score": "0", "body": "@Stuart I'll admit that it's confusing that I used the variables `x` and `y` twice, but it's not a bug. The `x` and `y` variables passed to `State` signify where the passed positions should be placed on the board and they are used in `for cell in active_cells: board[cell[1] + y][cell[0] + x] = True`. Those variables are not affected by the `x` and `y` variables I used in the `for` loops." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-07-27T21:22:47.267", "Id": "104447", "Score": "0", "body": "It is a bug and they are affected by the loops. Try inserting `print x, y` after the loop to see this." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-07-27T22:16:31.650", "Id": "104454", "Score": "0", "body": "@Stuart Oh, you are right. Changing the order of the code in `__init__` should fix it, though choosing different variable names would be better. Thanks!" } ]
[ { "body": "<p>This is excellent code for a Python novice.</p>\n\n<p>To address your questions:</p>\n\n<ol>\n<li>Rather than <code>x</code> and <code>y</code>, try naming your variables <code>row</code> and <code>col</code>. Then it wouldn't feel unnatural to write <code>self.state.board[row][col]</code>.</li>\n<li>In my opinion, the <code>.neighbour()</code> function would be better in the <code>State</code> class, since you're counting neighbours of a cell within that state.</li>\n<li>Your code is easy to understand, partly because the rules of the game are well known. However, you should still write docstrings for your functions. It's not obvious, for example, what to pass for the <code>state</code> parameter to the <code>Game</code> constructor unless you read the code. (Should I pass a 2D array of booleans?)</li>\n<li>You could use list comprehensions, but the current code is not bad either.</li>\n<li><p>I would rename both of your <code>display(self)</code> functions to <code>__str__(self)</code>. In <code>Game</code>, that function would become</p>\n\n<pre><code>def __str__(self):\n return str(self.state)\n</code></pre>\n\n<p>Then you can just <code>print my_game</code>.</p></li>\n</ol>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-02-05T16:28:16.243", "Id": "70223", "Score": "0", "body": "Thanks! Especially the `__str__` method is really useful. :)" } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-02-04T22:13:49.650", "Id": "40898", "ParentId": "40886", "Score": "15" } }, { "body": "<p>To address all your questions in one go, you could consider a very simple implementation using only a couple of functions and the set data structure:</p>\n\n<pre><code>def neighbors(cell):\n x, y = cell\n yield x - 1, y - 1\n yield x , y - 1\n yield x + 1, y - 1\n yield x - 1, y\n yield x + 1, y\n yield x - 1, y + 1\n yield x , y + 1\n yield x + 1, y + 1\n\ndef apply_iteration(board):\n new_board = set([])\n candidates = board.union(set(n for cell in board for n in neighbors(cell)))\n for cell in candidates:\n count = sum((n in board) for n in neighbors(cell))\n if count == 3 or (count == 2 and cell in board):\n new_board.add(cell)\n return new_board\n\nif __name__ == \"__main__\":\n board = {(0,1), (1,2), (2,0), (2,1), (2,2)}\n number_of_iterations = 10\n for _ in xrange(number_of_iterations):\n board = apply_iteration(board)\n print board\n</code></pre>\n\n<p>The main idea behind this solution is to keep track of only live cells. This way we don't have to scan the whole board each time we want to compute an iteration of the game. Another advantage also is we get to model infinite boards this way. </p>\n\n<p>Thus a board is modeled as a set of cells using the <strong>set</strong> data type in python. Each cell is represented by a tuple <strong>(x, y)</strong> denoting the coordinates of the cell. The function <code>neighbors</code> simply takes in a cell and uses list distructering to extract the individual cell coordinates. The <code>yield</code> statement is used to return the eight neighboring cells in the order specified. </p>\n\n<p>The function <code>apply_iteration</code> takes a board as input, applies an iteration and then and returns a new board. The idea is to compute a set of candidate cells (called <strong>candidates</strong> in the function) and then determine the new set of live cells for the next iteration. Notice how we can pass a generator expression as input to the <strong>set</strong> function. The candidate cells can simply be seen to be the union of the board with the set of neighbors of all cells in that board. The inner loop in the function applies the game's rules and adds any new living cells to the <code>new_board</code> variable which is returned as the result after the loop finishes execution. </p>\n\n<p>The entry point of the program contains the initialization part as well as the loop which simulates the game for a specified number of iterations.</p>\n\n<p>The main advantage of this solution over the one proposed by the OP is its simplicity. It also showcases some of Python's most powerful constructs such as parameter destructuring, the set data type and last but not least the <code>yield</code> statement.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2015-10-20T10:07:19.400", "Id": "108121", "ParentId": "40886", "Score": "7" } } ]
{ "AcceptedAnswerId": "40898", "CommentCount": "4", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-02-04T20:36:28.020", "Id": "40886", "Score": "15", "Tags": [ "python", "beginner", "game-of-life" ], "Title": "Conway's Game of Life in Python" }
40886
<p>I've put together a board for <em>Ultimate Tic-Tac-Toe</em> (<a href="http://bejofo.net/ttt" rel="noreferrer">What's that?</a>). This is part of the current <a href="/questions/tagged/code-challenge" class="post-tag" title="show questions tagged &#39;code-challenge&#39;" rel="tag">code-challenge</a>: <a href="https://codereview.meta.stackexchange.com/a/1472/35408"><strong>Code a Ultimate Tic-Tac-Toe</strong></a></p> <p><strong>Resources:</strong></p> <ul> <li><a href="https://jsfiddle.net/jLqru90z/" rel="noreferrer">Live demo of my view</a> &ndash; For you to see what I did there</li> <li><a href="http://www.zomis.net/ttt/TTTWeb.html" rel="noreferrer">Simon's working implementation</a> &ndash; To illustrate that this is going to be a functional game</li> </ul> <p><strong>Questions:</strong></p> <ul> <li>What are your thoughts on the Markup? Overkill? Just right?</li> <li>What would you improve on the CSS side? Especially asking in the direction of absolute dimensions and borders.</li> </ul> <p><strong>HTML:</strong></p> <pre><code>&lt;div class="game"&gt; &lt;div class="area area-0-0"&gt; &lt;div class="tile tile-0-0"&gt; &lt;button type="button" class="tile-button"&gt;&lt;/button&gt; &lt;/div&gt; &lt;div class="tile tile-1-0"&gt; &lt;button type="button" class="tile-button"&gt;&lt;/button&gt; &lt;/div&gt; &lt;div class="tile tile-2-0"&gt; &lt;button type="button" class="tile-button"&gt;&lt;/button&gt; &lt;/div&gt; &lt;div class="tile tile-0-1"&gt; &lt;button type="button" class="tile-button"&gt;&lt;/button&gt; &lt;/div&gt; &lt;div class="tile tile-1-1"&gt; &lt;button type="button" class="tile-button"&gt;&lt;/button&gt; &lt;/div&gt; &lt;div class="tile tile-2-1"&gt; &lt;button type="button" class="tile-button"&gt;&lt;/button&gt; &lt;/div&gt; &lt;div class="tile tile-0-2"&gt; &lt;button type="button" class="tile-button"&gt;&lt;/button&gt; &lt;/div&gt; &lt;div class="tile tile-1-2"&gt; &lt;button type="button" class="tile-button"&gt;&lt;/button&gt; &lt;/div&gt; &lt;div class="tile tile-2-2"&gt; &lt;button type="button" class="tile-button"&gt;&lt;/button&gt; &lt;/div&gt; &lt;/div&gt; &lt;div class="area area-1-0"&gt; &lt;!-- 9 tiles --&gt; &lt;/div&gt; &lt;div class="area area-2-0"&gt; &lt;!-- 9 tiles --&gt; &lt;/div&gt; &lt;div class="area area-0-1"&gt; &lt;!-- 9 tiles --&gt; &lt;/div&gt; &lt;div class="area area-1-1"&gt; &lt;!-- 9 tiles --&gt; &lt;/div&gt; &lt;div class="area area-2-1"&gt; &lt;!-- 9 tiles --&gt; &lt;/div&gt; &lt;div class="area area-0-2"&gt; &lt;!-- 9 tiles --&gt; &lt;/div&gt; &lt;div class="area area-1-2"&gt; &lt;!-- 9 tiles --&gt; &lt;/div&gt; &lt;div class="area area-2-2"&gt; &lt;!-- 9 tiles --&gt; &lt;/div&gt; &lt;/div&gt; </code></pre> <p><strong>CSS:</strong></p> <pre><code>*, *:before, *:after { -webkit-box-sizing: border-box; -moz-box-sizing: border-box; box-sizing: border-box; } body { margin: 0; } /* * GAME * Board size is calculated as follows: * * .game = .area * 3 * 459px = 153px * 3 * * .area = padding-left + .tile * 3 + padding-right + border * 153px = 3px + 48px * 3 + 3px + 3px * * .tile = padding-left + .width + padding-right * 48px = 3px + 42px + 3px */ .game { width: 459px; margin-top: 50px; margin-right: auto; margin-left: auto; } /* Clearfixing .game */ .game:after { content: ""; display: table; clear: both; } @media screen and (max-width: 500px) { .game { width: 315px; } } /* * AREA */ .area { float: left; width: 153px; padding: 3px; } .area:nth-child(3n-1), .area:nth-child(3n-0) { border-left: 3px solid #444; } .area:nth-child(4), .area:nth-child(5), .area:nth-child(6), .area:nth-child(7), .area:nth-child(8), .area:nth-child(9) { border-top: 3px solid #444; } /* Clearfixing .area */ .area:after { content: ""; display: table; clear: both; } @media screen and (max-width: 500px) { .area { width: 105px; } } /* * TILE */ .tile { float: left; padding: 3px; } /* * BUTTONS */ .tile-button { width: 42px; height: 42px; padding: 0; cursor: pointer; vertical-align: middle; border: 1px solid gray; border-radius: 3px; background-color: greenYellow; } @media screen and (max-width: 500px) { .tile-button { width: 26px; height: 26px; } } .tile-button:hover, .tile-button:focus { border-color: #444; background-color: yellowGreen; } </code></pre>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-04-01T20:07:25.913", "Id": "470361", "Score": "1", "body": "Looking back at this I can't help but think, this must be possible to do with CSS-grid these days...?" } ]
[ { "body": "<p>It looks good. I like the way it adapts to smaller windows.</p>\n\n<p>I'm not sure why (except as an aretfact of styling) you have a div around each button; maybe the button alone would do.</p>\n\n<p>Instead of using divs it might be possible/appropriate to use tables instead.</p>\n\n<p>You haven't demonstrated (although Simon's game does demonstrate) how you intend to mark played buttons with an O or X; nor how to draw a line through won games. I'd find it easier if X and O were different colors (e.g. blue and red to reflect the colors you chose for won games); and I don't like the <code>font-size: small</code> used in your clean.css.</p>\n\n<p>To draw a (horizontal, vertical, or diagonal) line through won games, maybe make the buttons semi-transparent so that the line can be a CSS background.</p>\n\n<p>When a quadrant is unplayable (because the opponent played elsewhere), do you still intend to draw buttons in that quadrant, or something else?</p>\n\n<p>Do you need to do anything to adjust the apparent size on a 'retina' (double-density-pixel) display?</p>\n\n<p>Does each button need a name attribute and should they be embedded in a form? Or will you be adding javascript?</p>\n\n<p>Maybe make the index 1-based (1 through 9) instead of 0 based (0 through 8). Have you thought about <a href=\"http://en.wikipedia.org/wiki/Web_accessibility\">accessibility</a> (e.g. someone using a screen-reader)?</p>\n\n<p>Maybe supply the game state in JSON as well as HTML, so that a bot that's playing (e.g. perhaps a Greasemonkey script) doesn't need to scrape the HTML to discover the game state.</p>\n\n<p>Why are you using px instead of em or % to specify CSS dimensions?</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-02-05T10:54:59.557", "Id": "70144", "Score": "0", "body": "I used an additional `div` around the control element (`button` in my version) to have better control over thinks like padding/margin. We discussed the table-topic in the chat. We want the table only for the easier layout handling. Therefor we wanted to use `div`'s instead. Also, it's a Code __Challenge__. :p" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-02-05T10:58:03.667", "Id": "70145", "Score": "0", "body": "I'm only doing the view for Simon's __working__ game, because I'm not a programmer. The `clean.css` you refer to is some generated stuff from Simon's game, not mine. I don't like it either. I will discuss your questions in the chat. Also we agreed on using 0 through 8 based indexing to mirror the logic. I'd prefer 1 through 9, tho." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-02-06T17:30:40.740", "Id": "70438", "Score": "0", "body": "X and O in different colors, that I LIKE! Technically, the buttons require neither names nor specific CSS classes for the logic to work as I've made my implementation in GWT (Google Web Toolkit) and GWT keeps references to the buttons when they are added dynamically. I like the idea of JSON! I don't see what good 1-based indexes would make?" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-02-07T00:39:43.350", "Id": "70540", "Score": "0", "body": "@SimonAndréForsberg 1-based is perhaps a dumb idea, for the human reader (if any) not for the browser. I can 'visualize' the location when it's only 0..2, but it's harder with `0..8`. More important UI-related comments were IMO perhaps not using `px`, displaying lines (perhaps through translucent buttons)." } ], "meta_data": { "CommentCount": "4", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-02-04T21:50:44.733", "Id": "40894", "ParentId": "40888", "Score": "10" } }, { "body": "<p>The one thing I see here that's absolutely unnecessary is the use of the button element. If you're using event delegation properly (I can't tell by looking at the functional version since it's obfuscated), all you should need is a single event handler attached to the game board. Just check to see if your event's target element is a <code>tile</code> and make adjustments as necessary to the tile's attributes or child nodes.</p>\n\n<p>Game boards are one areas where I believe that it is appropriate to use tables, even though it feels like you would be using them for layout. If you consider a game like Chess, the tiles are all named (A1-H8). The use of tables would actually simplify some of your CSS, since you would be able to make use of properties like <code>border-spacing: 5px</code> to get those nice gaps between your individual board tiles.</p>\n\n<p>The naming conventions you've chosen for your tiles' class names leads me to believe that you're using JavaScript to parse their positions. I recommend using <code>data-*</code> attributes instead:</p>\n\n<pre><code>&lt;div class=\"tile\" data-row=\"1\" data-col=\"1\"&gt;&lt;/div&gt;\n&lt;div class=\"tile\" data-row=\"1\" data-col=\"2\"&gt;&lt;/div&gt;\n</code></pre>\n\n<p>Here's a demo that illustrates some of these ideas for a card game (the interactivity is there, but the gameplay isn't): <a href=\"http://codepen.io/cimmanon/pen/lKgpJ\">http://codepen.io/cimmanon/pen/lKgpJ</a></p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-02-05T10:59:26.280", "Id": "70146", "Score": "0", "body": "I'm doing the view for Simon's game, but not the logic. I'm not a programmer. Thank you for your suggestions. I will consider these. Sounds good to me." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-02-06T17:24:22.017", "Id": "70434", "Score": "0", "body": "GWT (Google Web Toolkit) takes care of all the JavaScript stuff for me. It **compiles** my Java code to JavaScript. Therefore, your JS suggestion doesn't help me :) I like the idea of `data-row` instead of the class names though (technically I don't even need all the class names, as GWT automatically keeps references to the elements when they are added). As for the CSS, I let @kleinfreund decide on that :)" } ], "meta_data": { "CommentCount": "2", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-02-04T21:53:34.557", "Id": "40895", "ParentId": "40888", "Score": "10" } }, { "body": "<p>You can simplify this</p>\n\n<pre><code>.area:nth-child(4),\n.area:nth-child(5),\n.area:nth-child(6),\n.area:nth-child(7),\n.area:nth-child(8),\n.area:nth-child(9) {\n border-top: 3px solid #444;\n}\n</code></pre>\n\n<p>to </p>\n\n<pre><code>.area:nth-child(n + 4) {\n border-top: 3px solid #444;\n}\n</code></pre>\n\n<p>Since you are calculating the dimensions according to the game, and later setting media-queries, it will make it more easy to set</p>\n\n<pre><code>area {\n width: 33%;\n}\n\nand \n\ntile {\n width: 28%;\n padding 2%;\n} \n</code></pre>\n\n<p>or something in this line. Then, you don't need to worry to get your queries in sync.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-02-05T10:51:08.867", "Id": "70143", "Score": "0", "body": "I was using `display: inline-block;` instead of `float: left;` in earlier versions and had problems with the the calculated dimensions on mobile devices. So for the first working demo I stuck to pixels. I will use percentages in the next version. Thank you. :)" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-02-06T17:26:49.577", "Id": "70436", "Score": "0", "body": "As for the multiple `.area` selectors, I agree that didn't look very optimal, I think I will apply specific class names such as `has-top-border` and `has-left-border` and apply those dynamically from my GWT (Google Web Toolkit) code." } ], "meta_data": { "CommentCount": "2", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-02-04T21:53:44.187", "Id": "40896", "ParentId": "40888", "Score": "8" } } ]
{ "AcceptedAnswerId": "40894", "CommentCount": "1", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-02-04T20:43:32.837", "Id": "40888", "Score": "27", "Tags": [ "html", "css", "game", "community-challenge" ], "Title": "View for Ultimate Tic-Tac-Toe board" }
40888
<p>Can someone help me improve this code? I and trying to have a couple extension methods to convert strongly-typed lists to a <code>DataSet</code> and <code>DataTable</code> respectively.</p> <p>But... being so green to C#, I am not sure this is the most efficient way to do this.</p> <pre><code>using System; using System.Collections.Generic; using System.ComponentModel; using System.Data; using System.Reflection; namespace o7th.Class.Library.Data { /// &lt;summary&gt; /// List to DataTable Converter /// &lt;/summary&gt; public static class ListConverter { /// &lt;summary&gt; /// Convert our List to a DataTable /// &lt;/summary&gt; /// &lt;typeparam name="T"&gt;&lt;/typeparam&gt; /// &lt;param name="data"&gt;&lt;/param&gt; /// &lt;returns&gt;DataTable&lt;/returns&gt; public static DataTable ToDataTable&lt;T&gt;(this IList&lt;T&gt; data) { PropertyDescriptorCollection props = TypeDescriptor.GetProperties(typeof(T)); object[] values = new object[props.Count]; using (DataTable table = new DataTable()) { long _pCt = props.Count; for (int i = 0; i &lt; _pCt; ++i) { PropertyDescriptor prop = props[i]; table.Columns.Add(prop.Name, prop.PropertyType); } foreach (T item in data) { long _vCt = values.Length; for (int i = 0; i &lt; _vCt; ++i) { values[i] = props[i].GetValue(item); } table.Rows.Add(values); } return table; } } /// &lt;summary&gt; /// Convert our List to a DataSet /// &lt;/summary&gt; /// &lt;typeparam name="T"&gt;&lt;/typeparam&gt; /// &lt;param name="list"&gt;&lt;/param&gt; /// &lt;returns&gt;DataSet&lt;/returns&gt; public static DataSet ToDataSet&lt;T&gt;(this IList&lt;T&gt; list) { Type elementType = typeof(T); using (DataSet ds = new DataSet()) { using (DataTable t = new DataTable()) { ds.Tables.Add(t); //add a column to table for each public property on T PropertyInfo[] _props = elementType.GetProperties(); foreach (PropertyInfo propInfo in _props) { Type _pi = propInfo.PropertyType; Type ColType = Nullable.GetUnderlyingType(_pi) ?? _pi; t.Columns.Add(propInfo.Name, ColType); } //go through each property on T and add each value to the table foreach (T item in list) { DataRow row = t.NewRow(); foreach (PropertyInfo propInfo in _props) { row[propInfo.Name] = propInfo.GetValue(item, null) ?? DBNull.Value; } t.Rows.Add(row); } } return ds; } } } } </code></pre>
[ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-11-11T22:45:51.750", "Id": "126999", "Score": "0", "body": "Doesn't the using statement in the ToDataSet function call the Dispose method?" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-11-12T14:27:16.247", "Id": "127122", "Score": "0", "body": "Yes, however, since we are returning it, it would be pointless to include it." } ]
[ { "body": "<p>There are a few things I notice right off the bat.</p>\n\n<ol>\n<li><p>Your variable names while not bad, could be better. For instance <code>props</code> -> <code>properties</code>. Stuff like this makes the code easier to read.</p></li>\n<li><p>You have the properties, why not use a <code>foreach</code> loop to fill the datatable (you did it in ToDataSet)</p></li>\n<li><p>the <code>_</code> prefex should be used for class variables, not local variables.</p></li>\n<li><p>try using <code>var</code> when declaring obvious variable types <code>var row = t.NewRow()</code></p></li>\n<li><p>There is no error checking when you are filling the values in the data table. What happens if it is not a class (int, double, long)? You could force the generic to be a class by adding <code>where T : class</code>.</p></li>\n<li><p>Why don't you use the <code>ToDataTable</code> method to create the table in the <code>ToDataSet</code> method? This will eliminate duplicate code, and have 1 point of failure/modification as required. As an aside, I would use the code from <code>ToDataSet</code> to create your <code>DataTable</code>, as it is written better.</p></li>\n<li><p>While I applaud your use of it, I'm not sure the <code>using</code> syntax is appropriate here. I would move that to where these methods are being called <code>using (var dt = list.ToDataTable())</code> Having it here will more than likely cause unexpected things to happen in your code.</p></li>\n<li><p>I would make these extend <code>IEnumerable&lt;T&gt;</code> as that will make them way more useful by not limiting them to <code>IList&lt;T&gt;</code>.</p></li>\n</ol>\n\n<p>I do like your use of white space and indentation, so good job on that. The extra indentation will be removed when the <code>using</code> statements are removed. I also like the name of your methods, very clear and concise to their intent. </p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-02-04T22:04:36.087", "Id": "70049", "Score": "0", "body": "Thank you for the comments and suggestions. :) Couple questions/comments. #5 not worried about that just yet, but it will go in. #4. I've always been under the impression that it is more efficient to properly declare my variables, what would the benefit be of making it a variable type rather than a DataRow? (updated the q, with new code)" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-02-04T22:27:55.453", "Id": "70054", "Score": "2", "body": "[var actually is strongly typed in C#](http://msdn.microsoft.com/en-us/library/bb383973.aspx). It picks up the type you are assigning it. I like it because it cleans the code up a little more." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-02-19T00:43:16.143", "Id": "72413", "Score": "0", "body": "I never see you in the [chat room](http://chat.stackexchange.com/rooms/8595/the-2nd-monitor), even though you are an active user. You should join us sometime! :)" } ], "meta_data": { "CommentCount": "3", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-02-04T21:49:26.887", "Id": "40893", "ParentId": "40891", "Score": "8" } }, { "body": "<p>Using this below code, you can convert <code>List&lt;YourClassname&gt;</code> to <code>DataTable</code>:-</p>\n\n<pre><code>List&lt;YourClass&gt; objlist = alldata;\nstring json = Newtonsoft.Json.JsonConvert.SerializeObject(objlist);\nDataTable dt = Newtonsoft.Json.JsonConvert.DeserializeObject&lt;DataTable&gt;(json);\n</code></pre>\n\n<p>Here, I'm assuming that <code>alldata</code> contains <code>list&lt;YourClass&gt;</code> object and you can also do - <code>objlist.Add(objYourClass)</code>. Hope, these codes help you!!!</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-06-19T13:46:44.783", "Id": "430929", "Score": "1", "body": "Right, but that also assumes I will include Newtonsoft JSON object as a dependancy to all project using this.\n\nNo, this is definately not a viable solution to this 5yr old question" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-06-20T06:07:32.003", "Id": "430996", "Score": "0", "body": "It is working fine for me. I thing you are having trouble to understand my code. Or your working criteria could be differ from me." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-07-02T12:54:46.620", "Id": "432768", "Score": "0", "body": "I'm not having trouble understanding your code mate. You are utilizing a 3rd party reference to do what I have done without. I won't use Newtonsoft.Json's object to do this" } ], "meta_data": { "CommentCount": "3", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-05-31T07:51:46.800", "Id": "221393", "ParentId": "40891", "Score": "1" } } ]
{ "AcceptedAnswerId": "40893", "CommentCount": "2", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-02-04T21:04:19.510", "Id": "40891", "Score": "8", "Tags": [ "c#", "converting", "extension-methods", ".net-datatable" ], "Title": "Converting List to a DataTable and/or DataSet Extension Methods" }
40891
<p>I have a function that needs to evaluate some parameters to determine if they're valid or not. They all need to be evaluated individually, so I have some code like below.</p> <pre><code>#Configure widgets held in a layout def layoutConfigurer(name, widgetType, minW, minH, maxH, maxW, flat, focus, image, position=False): widgetType.setObjectName(_fromUtf8(name)) if minW or minH is not None: widgetType.setMinimumSize(QtCore.QSize(minW, minH)) if maxH or maxW is not None: widgetType.setMaximumSize(QtCore.QSize(maxH, maxW)) if flat: widgetType.setFlat(True) if focus: widgetType.setFocusPolicy(QtCore.Qt.NoFocus) if image: widgetType.setPixmap(QtGui.QPixmap(_fromUtf8(image))) if position: widgetType.setAlignment(QtCore.Qt.AlignCenter) </code></pre> <p>This code works, but is kind of ugly. I'm using the multiple <code>if</code> statements, because I need them all to be evaluated and not just the first true statements.</p> <p>I'm not sure if there is a better way of evaluating command line arguments or not, but I would like to make the above code seem prettier. At the moment, it seems a little inefficient</p>
[]
[ { "body": "<p>I don't see any simple way to generalize your <code>if</code> statements, since they result in very different actions. You might be able to push that complexity into the <code>widgetType</code> instead, if that code is under your control, but it won't reduce the total amount of code.</p>\n\n<p>What concerns me, though, is the length of the parameter list: 10 parameters, of which 9 are mandatory. The caller is certainly going to look ugly. A quick improvement might be to accept <a href=\"http://docs.python.org/2/tutorial/controlflow.html#keyword-arguments\">keyword arguments</a>. A deeper analysis might reveal that those parameters should belong in an object instead.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-02-05T00:31:33.527", "Id": "70067", "Score": "0", "body": "I have no control over the `widgetType` code since it gets set to a object from the QT librariers. I will admit that it's a little odd about the ammount of mandatory arguments, and I'll look into fixing that. The function itself takes parameters that are configurations of QT widgets, and then configures it, reducing what would be 6-7 lines of code to just one." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-02-05T00:56:18.437", "Id": "70070", "Score": "1", "body": "I'd definitely switch to kwargs and maybe provide defaults instead of requiring params - that way you can reduce conditionality and cut down on if tests" } ], "meta_data": { "CommentCount": "2", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-02-05T00:21:45.643", "Id": "40904", "ParentId": "40902", "Score": "6" } }, { "body": "<p>Fundamentally I agree that there is little to be done here; all you can really do is shove the complexity somewhere else. However there are some small things you can do try to reduce the branching that a reader of your code has to think through. I may not have translated these all correctly, but here's a couple ways to minimize the conditional code in the outer function:</p>\n\n<pre><code># If there's a reasonable default (perhaps 0,0), a helper can return it\nwidgetType.setMinimumSize(calcMinimumSize(minW, minH))\n\n# If there's no reasonable default, a helper can hide the conditional\n# (You should probably use only one of these first two approaches at a time.)\napplyMaximumSize(widgetType, maxH, maxW)\n\n# bool will constrain `flat` to True or False\nwidgetType.setFlat(bool(flat))\n\n# (x if C else y) lets you specify the default (I'm guessing `TabFocus`)\nwidgetType.setFocusPolicy(QtCore.Qt.NoFocus if focus else QtCore.Qt.TabFocus)\n</code></pre>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-02-05T14:10:40.470", "Id": "40957", "ParentId": "40902", "Score": "1" } } ]
{ "AcceptedAnswerId": "40904", "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-02-04T23:39:26.997", "Id": "40902", "Score": "4", "Tags": [ "python" ], "Title": "Alternative to multiple if statements" }
40902
<p>I want to get the shortest sequence to reach a number.</p> <p>Rules:</p> <ul> <li><code>A[0]</code> is always 1</li> <li>Either <code>A[i] = A[i-1]*2</code> or <code>A[i] = A[i-1]+1</code></li> </ul> <p>For example, if my input number is 17, my output should be 6, because</p> <pre><code>A[0]=1, A[1]=2, A[2]=4, A[3]=8, A[4]=16, A[5]=17 </code></pre> <p>The following code is not working properly for few inputs, such as 15.</p> <pre><code>public static int GetMinimumSequence(int n) { if (n == 1) return 1; int count = 1; int temp = 1; for (int i = 2; i &lt;= n; i++) { temp = temp * 2; if (temp &gt;= n) { temp = temp/2; temp = temp + 1; } count++; if(temp == n) break; } return count; } </code></pre>
[ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-02-05T06:53:12.843", "Id": "70111", "Score": "0", "body": "I believe I've interpreted \"minimum sequence\" correctly as \"shortest sequence\". If not, please revert my edit and let me know." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-02-05T12:24:32.110", "Id": "70171", "Score": "0", "body": "The answer which you accepted gives the wrong results IMO. People have posted new answers and edited old answers. I suggest you read the various answers again." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-02-05T12:35:15.067", "Id": "70175", "Score": "0", "body": "I think some clarity on the specification is in order. I misread it once, and now fear I may have misread it again. Is there a 'source' for this problem? perhaps you can just show us what you would consider to be the 'right' solution for `15`" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-02-05T12:59:47.353", "Id": "70178", "Score": "1", "body": "I have updated my ideone http://ideone.com/OxKfHW to compare my answer with the OP code. They disagree (but are 'close'). -1 vote applied to question because the specification is ambiguous, and the code produces the 'wrong' result for power-of-2 input values (4, 8, 16, ...)" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-02-05T15:17:32.137", "Id": "70211", "Score": "0", "body": "@MxR ... the shortest sequence may be, depending on how you interpret your 'Rule' `7 (A[0]=1, A[1]=2, A[2]=3, A[3]=6, A[4]=7, A[5]=14, A[6]=15)` in each case element `n+1` is either `[n] + 1` or `[n] * 2`" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-02-05T15:25:31.610", "Id": "70214", "Score": "0", "body": "My mistake; As per rule, it is either [n]+1 or [n]*2 so for 15, shortest sequence will be 7. My code and your code is also wrong as it is returning 11." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-02-05T15:27:23.450", "Id": "70216", "Score": "0", "body": "My answer depended on the way your code was written to 'understand' the problem (since you said it worked). Other answers have used the description to determine their algorithms... and have different answers. Hence the ambiguity." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-02-06T08:32:29.467", "Id": "70346", "Score": "0", "body": "My answer can confuse other users also. My answer is wrong and it is not giving correct result for few inputs." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-02-05T07:40:17.867", "Id": "70425", "Score": "0", "body": "This is the good old Hamming Weight Calculation. You will find dozens of different optimized implementations if you search for it on the net." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-02-06T18:10:04.630", "Id": "70454", "Score": "3", "body": "\"Below is my code but it is not working properly\" What's it doing on Code Review?" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-02-06T18:21:03.770", "Id": "70457", "Score": "1", "body": "@BenVoigt You are little late Ben. Yesterday I edited my post. Previously I thought it was a correct code and hence posted it here for better solution. But after few answers I found that my code was wrong for some scenarios. Hence I edited my post so that other users will not confused with my wrong code." } ]
[ { "body": "<p>My version of your code (other versions are a bit better; my version is more closely based on yours):</p>\n\n<pre><code>public static int GetMinimumSequence(int n)\n{\n if (n &lt;= 0)\n throw new ArgumentOutOfRangeException(); // or should return 0 when n == 0?\n\n if (n == 1)\n return 1;\n\n int a = 1; // you call this 'temp', I call it 'a' to match the problem description\n for (int i = 2; true; i++)\n {\n // can we afford to multiply by 2?\n if (a*2 &lt;= n)\n a *= 2; // yes so multiply by 2.\n else\n a += 1; // no so just add 1 instead\n // have we arrived at the correct result?\n if (a == n)\n return i;\n }\n}\n</code></pre>\n\n<p>A bug in your version is:</p>\n\n<ul>\n<li>Your <code>if (temp &gt;= n)</code> is wrong; you want <code>if (temp &gt; n)</code> instead (for example to get the right result when n is 16).</li>\n</ul>\n\n<p>You don't need (and shouldn't have) <code>i &lt;= n</code> as a condition in your for loop. The correct condition (the only condition in which you should return) is <code>if(temp == n)</code>.</p>\n\n<p>Instead of having a separate <code>count</code>, you can return <code>i</code> from inside the loop (as my example shows).</p>\n\n<hr>\n\n<p>200_success' answer points out that we're using the wrong algorithm. He shows a recursive solution which looks correct.</p>\n\n<p>I thought of a simpler algorithm as follows, which counts backwards.</p>\n\n<pre><code>public static int GetMinimumSequence(int n)\n{\n if (n &lt;= 0)\n throw new ArgumentOutOfRangeException();\n\n for (int i = 1; ; ++i)\n {\n if (n == 1)\n return i;\n if ((n % 2) == 0)\n n /= 2;\n else\n n -= 1;\n }\n}\n</code></pre>\n\n<p>Note:</p>\n\n<ul>\n<li>My algorithm is simpler than 200_success's</li>\n<li>200_success's is more obviously correct by inspection</li>\n<li>I therefore test my algorithm against 200_success to demonstrate whether mine is correct</li>\n<li>I also tested against ratchetfreak's answer and found two small off-by-one bugs in that implementation, which I correct in the version below.</li>\n</ul>\n\n<p>It's surprising how buggy most of the first implementations were. So <strong>another criticism of the code in the OP is that you didn't sufficiently test your implementation</strong>.</p>\n\n<pre><code>using System;\n\nnamespace GetMinimumSequence\n{\n class Program\n {\n static void Main(string[] args)\n {\n for (int i = 1; i &lt;= 100; ++i)\n {\n int a = test_ChrisW(i);\n int b = test_200_success(i);\n if (a != b)\n throw new ApplicationException(string.Format(\"Mismatch at {0}: {1} versus {2}\", i, a, b));\n }\n for (int i = 1; i &lt;= 100; ++i)\n {\n int a = test_ChrisW(i);\n int b = test_ratchetfreak(i);\n if (a != b)\n throw new ApplicationException(string.Format(\"Mismatch at {0}: {1} versus {2}\", i, a, b));\n }\n for (int i = 1; i &lt;= 100; ++i)\n {\n Console.Write(@\"Input \" + i + \" output \" + test_ChrisW(i) + \"\\n\");\n }\n }\n\n public static int test_ChrisW(int n)\n {\n if (n &lt;= 0)\n throw new ArgumentOutOfRangeException();\n\n for (int i = 1; ; ++i)\n {\n if (n == 1)\n return i;\n if ((n % 2) == 0)\n n /= 2;\n else\n n -= 1;\n }\n }\n\n public static int test_ratchetfreak(int n)\n {\n if (n &lt;= 0)\n throw new ArgumentOutOfRangeException();\n\n int count = 1; //not count == 0\n while (n &gt; 1) // not while (n &gt; 0)\n {\n if (n % 2 == 0) count++;\n else count += 2;\n n /= 2;\n }\n return count;\n }\n\n public static int test_200_success(int n)\n {\n if (n &lt;= 0)\n {\n throw new ArgumentOutOfRangeException();\n }\n else if (n == 1)\n {\n return 1;\n }\n else if ((n % 2) == 1)\n {\n return 1 + test_200_success(n - 1);\n }\n else\n {\n return 1 + Math.Min(test_200_success(n - 1),\n test_200_success(n / 2));\n }\n }\n }\n}\n</code></pre>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-02-05T02:28:00.540", "Id": "40912", "ParentId": "40910", "Score": "5" } }, { "body": "<p>This question, in general, has proven to be problematic. Depending on which reference was used to 'understand' what the basic requirement is, there are two possible solutions.</p>\n\n<p>In my first answer, I misread the spec. In my second version of the answer, I based the required logic on the actual code that MxR posted and claimed to 'work'.</p>\n\n<p>Subsequently, the post has been 'clarified' and the real requirements have been identified as being different to my original understanding, and different to the OP's original 'working' code.</p>\n\n<p>I have identified ways to solve this problem now in all three versions of the 'spec'.</p>\n\n<h2>Version 1: (my misread of the original spec)</h2>\n\n<p>.... no point in including it</p>\n\n<h2>Version 2:</h2>\n\n<p>This version is my second answer, based on the code example the OP included:</p>\n\n<blockquote>\n <p>Below is my code which is working fine.</p>\n\n<pre><code>public static int GetMinimumSequence(int n)\n {\n if (n == 1)\n return 1;\n\n int count = 1;\n int temp = 1;\n for (int i = 2; i &lt;= n; i++)\n {\n temp = temp * 2;\n if (temp &gt;= n)\n {\n temp = temp/2;\n temp = temp + 1;\n }\n count++;\n if(temp == n)\n break;\n }\n return count;\n }\n</code></pre>\n</blockquote>\n\n<p>The following answer is the one I proposed as a \"Better Way\".</p>\n\n<blockquote>\n <p>This is actually a simple (if you know logs) mathematical problem:</p>\n \n <p>What you want is the number of powers-of-two that are smaller than\n your input value, and then you want to 'step' forward until you get to\n your value.</p>\n \n <p>So, for example, with 17, the previous power-of-2 is <code>16</code> (which is\n 2<sup>4</sup>). You then step forward 1 to get to 17.</p>\n \n <p>The math for this is:</p>\n \n <ul>\n <li>calculate the previous power-of-2's exponent.</li>\n <li>calculate the difference between that power-of-2, and our input value.</li>\n <li>add them.</li>\n <li>add 1.</li>\n </ul>\n \n <p>The integer-part of the <em>Log<sub>2</sub></em> of the value is the exponent\n of the previous power of 2.</p>\n \n <p>This results in:</p>\n\n<pre><code>public static int GetMinimumSequence(int n)\n{\n int prevexponent = (int)Math.Log(n, 2);\n // ( 1 &lt;&lt; prevexponent) is same as (int)Math.Pow(2, prevexponent) but faster\n return 1 + prevexponent + n - (1 &lt;&lt; prevexponent);\n}\n</code></pre>\n</blockquote>\n\n<p>This answer was a decent answer, given the assumption it (incorrectly) made about the specification being provided by the 'working code'.</p>\n\n<h2>Version 3</h2>\n\n<p>A number of other answers have also been given that calculate the 'shortest distance' using the details of the OP's rules using the 'alternative' interpretation of the specification.</p>\n\n<blockquote>\n <ul>\n <li>A[0] is always 1</li>\n <li><p>Either A[i] = A[i-1]*2 or A[i] = A[i-1]+1</p>\n \n <p>what is the smallest number of steps (<code>i + 1</code>) that can get you to a target value?</p></li>\n </ul>\n</blockquote>\n\n<p>The answers presented so far use recursion:</p>\n\n<ul>\n<li><a href=\"https://codereview.stackexchange.com/a/40926/31503\">20_success has this proposal</a></li>\n</ul>\n\n<p>or some other loops:</p>\n\n<ul>\n<li><a href=\"https://codereview.stackexchange.com/a/40912/31503\">ChrisW uses a loop</a></li>\n<li><a href=\"https://codereview.stackexchange.com/a/40943/31503\">Ratchet Freak first code</a></li>\n</ul>\n\n<p>or an O(1) implementation</p>\n\n<ul>\n<li><a href=\"https://codereview.stackexchange.com/a/40943/31503\">Ratchet Freak log2/bitcount</a></li>\n</ul>\n\n<p>From what I can tell, the above answers are the only ones that produce the results according to this version of the spec.</p>\n\n<p>I dislike both ChrisW and 200_success's answers because:</p>\n\n<ul>\n<li>The recursive approach is speculative, and does too much work to get to the answer.</li>\n<li>The loop approach does not make the mathematical logic clear.</li>\n</ul>\n\n<p>A better approach is the following:</p>\n\n<pre><code>public static int GetMinimumSequenceRL(int n)\n{\n int cnt = 0;\n while (n &gt; 0) {\n cnt++;\n n = (n % 2 == 0) ? (n / 2) : (n - 1);\n }\n return cnt;\n}\n</code></pre>\n\n<p>This approach works backwards from the target. If the value is odd, it subtracts one, if it is even, it halves it.</p>\n\n<p>Each of these operations is a 'step', and it counts how many steps to get back to 0.</p>\n\n<p>Mathematically, this is guaranteed to bring you back on the shortest possible path, and it works without having to speculate down unused paths.</p>\n\n<p>ChrisW's solution is far better than the recursive approach, and it uses the same basic mathematical approach that I propose, but the <code>for (i....)</code> loop gives the code a misleading 'flavour', that it is looping through something finite... yet the code's only exit point is 'return' inside that loop.</p>\n\n<p><strong>BUT THE BEST</strong> solution is the <strong>one from Ratchet Freak</strong>, which is the most elegant.</p>\n\n<p>It does the bitcount (number of odd values) and the <code>log2</code> which is the number of doubles.</p>\n\n<p>Unfortunately, he does not make that logic very clear..... but, if it were me, I would accept that answer as the best solution.</p>\n\n<p>In java, by the way, this solution is a 1-liner:</p>\n\n<pre><code>public int getShortestSequence(int n) {\n return Integer.bitCount(n) + Integer.highestOneBit(n) - 1;\n}\n</code></pre>\n\n<hr>\n\n<h2>Conclusion</h2>\n\n<ul>\n<li>The best way to get the sequence is through the smart application of mathematics, not through a trial-and-error recursive approach</li>\n<li>When posting to CodeReview, it is always best to put full specifications in place</li>\n<li>When answering on CodeReview, it is best to clarify any ambiguity before you commit.</li>\n</ul>\n\n<p>I have <a href=\"http://ideone.com/YAHqaI\" rel=\"nofollow noreferrer\">updated the ideone to include</a> the OP solution, my version 2 solution, and then ChrisW's, 200_success, and my version 3.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-02-05T03:12:36.383", "Id": "70077", "Score": "0", "body": "I think this gives the correct result for n=16 and 17, but not for 18." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-02-05T03:19:45.867", "Id": "70078", "Score": "0", "body": "@ChrisW - included link to an ideone" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-02-05T03:22:09.343", "Id": "70079", "Score": "1", "body": "Yes; I still think it's wrong: to get to 18 you need to double a few times and then add 1 twice; or add 1 three times to get to 19. Math/Ceiling isn't enough except when the desired result is (2^n) or (2^n + 1)." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-02-05T03:22:57.080", "Id": "70080", "Score": "1", "body": "Ahhh.... I believe you are right .... let me fix that for me." } ], "meta_data": { "CommentCount": "4", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-02-05T03:04:12.593", "Id": "40913", "ParentId": "40910", "Score": "6" } }, { "body": "<p>This is not a solution, but is what I believe are the shortest paths for numbers up to 30. Each row contains n, the smallest number of steps from 0 to n and the associated path. I thought it might be useful to post this, first to have it checked by readers, then to help others check their code. I coded this in Ruby, which is why I've not posted a solution.</p>\n\n<pre><code> [[2, 2, [0, 1, 2]],\n [3, 3, [0, 1, 2, 3]],\n [4, 3, [0, 1, 2, 4]],\n [5, 4, [0, 1, 2, 4, 5]],\n [6, 4, [0, 1, 2, 3, 6]],\n [7, 5, [0, 1, 2, 3, 6, 7]],\n [8, 4, [0, 1, 2, 4, 8]],\n [9, 5, [0, 1, 2, 4, 8, 9]],\n [10, 5, [0, 1, 2, 4, 5, 10]],\n [11, 6, [0, 1, 2, 4, 5, 10, 11]],\n [12, 5, [0, 1, 2, 3, 6, 12]],\n [13, 6, [0, 1, 2, 3, 6, 12, 13]],\n [14, 6, [0, 1, 2, 3, 6, 7, 14]],\n [15, 7, [0, 1, 2, 3, 6, 7, 14, 15]],\n [16, 5, [0, 1, 2, 4, 8, 16]],\n [17, 6, [0, 1, 2, 4, 8, 16, 17]],\n [18, 6, [0, 1, 2, 4, 8, 9, 18]],\n [19, 7, [0, 1, 2, 4, 8, 9, 18, 19]],\n [20, 6, [0, 1, 2, 4, 5, 10, 20]],\n [21, 7, [0, 1, 2, 4, 5, 10, 20, 21]],\n [22, 7, [0, 1, 2, 4, 5, 10, 11, 22]],\n [23, 8, [0, 1, 2, 4, 5, 10, 11, 22, 23]],\n [24, 6, [0, 1, 2, 3, 6, 12, 24]],\n [25, 7, [0, 1, 2, 3, 6, 12, 24, 25]],\n [26, 7, [0, 1, 2, 3, 6, 12, 13, 26]],\n [27, 8, [0, 1, 2, 3, 6, 12, 13, 26, 27]],\n [28, 7, [0, 1, 2, 3, 6, 7, 14, 28]],\n [29, 8, [0, 1, 2, 3, 6, 7, 14, 28, 29]],\n [30, 8, [0, 1, 2, 3, 6, 7, 14, 15, 30]]] \n</code></pre>\n\n<p>Edit: I decided to post my Ruby code, just to show the approach I used. If you don't know Ruby, think of it as pseudo-code.</p>\n\n<pre><code>def min_seq(n)\n return [0, []] if n.zero?\n return [1, [0,1]] if n == 1\n seq = { 0 =&gt; {d: 0, p: nil}, 1 =&gt; {d: 1, p: 0} }\n (2..n).each do |i|\n j = i-1\n j = i/2 if ( i.even? &amp;&amp; (seq[i/2][:d] &lt; seq[i-1][:d]) )\n seq.merge! ( { i =&gt; { d: seq[j][:d]+1, p: j } } )\n end\n path = [n]\n loop do\n path &lt;&lt; (n = seq[n][:p])\n break if n.zero?\n end\n path.reverse!\n [path.size-1, path]\nend\n</code></pre>\n\n<p><code>n</code> is the given positive integer. For any <code>m &lt;= n</code>, the hash <code>seq</code> contains keys <code>0, 1,...,m</code>, where <code>seq[k] = { :d =&gt; x, :p =&gt; i }, 0 &lt;= k &lt;= m</code>, <code>x</code> being the minimum number of steps from <code>0</code> to <code>k</code> and <code>i</code> being the previous number on the shortest path. <code>seq</code> initially has keys <code>0 and 1</code>, then <code>2</code> is added, then <code>3</code>, and so on up to <code>n</code>, at which point the shortest path to <code>n</code> is available. The shortest path is determined in the code that precedes <code>path = [n]</code>; the remaining statements merely extract it from <code>seq</code>.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-02-05T07:42:33.493", "Id": "70120", "Score": "0", "body": "This is a lookup table for the array that he used to explain what he wants. But actually he wants to count the bits in an integer. Your hard drive would be full with such a list xD" } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-02-05T05:39:36.180", "Id": "40921", "ParentId": "40910", "Score": "3" } }, { "body": "<p>@CarySwoveland is on the right track. The original code and several other solutions so far get the wrong answer. For example, <code>GetMinimumSequence(12)</code> should not return 8, but rather 5, based on the optimal sequence 1, 2, 3, 6, 12.</p>\n\n<p>One straightforward solution uses recursion:</p>\n\n<pre><code>public static int GetMinimumSequence(int n) {\n if (n &lt;= 0) {\n throw new ArgumentOutOfRangeException();\n } else if (n == 1) {\n return 1;\n } else if ((n % 2) == 1) {\n return 1 + GetMinimumSequence(n - 1);\n } else {\n return 1 + Math.Min(GetMinimumSequence(n - 1),\n GetMinimumSequence(n / 2));\n }\n}\n</code></pre>\n\n<p>Add memoization to that for better performance with larger inputs. (I'll leave that to you as an exercise.) In technical terms, this solution uses dynamic programming, since the greedy algorithm leads you astray.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-02-05T11:05:30.877", "Id": "70149", "Score": "2", "body": "Why are you using `(n & 1) != 0` instead of `n % 2 == 1`, which I believe is more clear?" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-02-05T12:20:22.923", "Id": "70168", "Score": "0", "body": "+1 for finding bugs etc. Also I think I've corrected my answer with a solution that is more \"straightforward\" than yours is." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-02-06T09:47:14.273", "Id": "70365", "Score": "1", "body": "even best case with memoization will this be O(n) (going through the entire `n-1` path), whereas if you always went down the optimal path then it would be O(log n)" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-02-06T09:54:41.277", "Id": "70367", "Score": "0", "body": "@ratchetfreak Your solution is vastly superior in practice. As ChrisW notes, the main redeeming factor of this naïve solution is that it is obviously correct by inspection." } ], "meta_data": { "CommentCount": "4", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-02-05T06:42:29.160", "Id": "40926", "ParentId": "40910", "Score": "11" } }, { "body": "<p>1 point to remember:</p>\n\n<p>the subsequence <code>*2 +1 +1</code> can be simplified to <code>+1 *2</code> (because <code>n*2+2</code> is the same as <code>(n+1)*2</code>)</p>\n\n<p>this means you can work backwards, odd numbers need a <code>*2 +1</code> at the end of the sequence and even numbers get just a <code>*2</code></p>\n\n<pre><code>count=1;\nwhile(n&gt;1){\n if(n%2==0) count++;\n else count+=2;\n n/=2;//integer on positive number divide rounds down\n}\n</code></pre>\n\n<p>given the optimization there is a sequence of <code>+1 *2 (+1) *2 (+1) *2 (+1) *2 (+1) *2...</code> which happens to coincide exactly with the binary representation of the number (a +1 means a 1 on that place while no +1 means a 0 on that place)</p>\n\n<p>there are bit-hacking solutions to find both the number of bits set and the highest set bit, add them together and you will find the solution in constant time:</p>\n\n<pre><code>count = log2(n)+bitcount(n);\n</code></pre>\n\n<p>with log2 being:</p>\n\n<pre><code>int log2(int v){\n int r; // result of log2(v) will go here\n int shift;\n\n r = (v &gt; 0xFFFF)?1 &lt;&lt; 4:0; v &gt;&gt;= r;\n shift = (v &gt; 0xFF )?1 &lt;&lt; 3:0; v &gt;&gt;= shift; r |= shift;\n shift = (v &gt; 0xF )?1 &lt;&lt; 2:0; v &gt;&gt;= shift; r |= shift;\n shift = (v &gt; 0x3 )?1 &lt;&lt; 1:0; v &gt;&gt;= shift; r |= shift;\n r |= (v &gt;&gt; 1);\n return r;\n}\n</code></pre>\n\n<p>and bitcount being:</p>\n\n<pre><code>int bitcount(int v){\n int c; // store the total here\n\n c = v - ((v &gt;&gt; 1) &amp; 0x55555555);\n c = ((c &gt;&gt; 2) &amp; 0x33333333) + (c &amp; 0x33333333);\n c = ((c &gt;&gt; 4) + c) &amp; 0x0F0F0F0F;\n c = ((c &gt;&gt; 8) + c) &amp; 0x00FF00FF;\n c = ((c &gt;&gt; 16) + c) &amp; 0x0000FFFF;\n return c;\n}\n</code></pre>\n\n<p>source of <a href=\"http://graphics.stanford.edu/~seander/bithacks.html#IntegerLog\" rel=\"nofollow noreferrer\">log2</a> and <a href=\"https://stackoverflow.com/questions/3815165/how-to-implement-bitcount-using-only-bitwise-operators\">bitcount</a></p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-02-05T11:20:36.273", "Id": "40943", "ParentId": "40910", "Score": "10" } }, { "body": "<p>Improved the speed of the recursive solution. It stops now within a reasonable time for numbers larger than 1000.</p>\n\n<pre><code>static Dictionary&lt;int,int&gt; cache = new Dictionary&lt;int,int&gt;();\n\npublic static int GetMinimumSequence(int n) {\n if (n &lt;= 0) {\n throw new ArgumentOutOfRangeException();\n } else if (n == 1) {\n return 1;\n } else if (cache.ContainsKey(n)) {\n return cache[n];\n } \n\n int r;\n if ((n % 2) == 1) {\n r = 1 + GetMinimumSequence(n - 1);\n } else {\n r = 1 + Math.Min(GetMinimumSequence(n - 1),\n GetMinimumSequence(n / 2));\n }\n cache.Add(n, r);\n return r;\n}\n</code></pre>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-02-06T08:04:15.597", "Id": "41044", "ParentId": "40910", "Score": "2" } }, { "body": "<p>Basically my approach is </p>\n\n<ul>\n<li>Start from given number, add to holding array</li>\n<li>Check if it's an odd number, if so then add the number initially to holding variable (i.e array), subtract it with 1 and add it again to holding array. Otherwise just add them to the array</li>\n<li>Use a <code>while</code> loop to reduce the initial number by checking it again if its\nodd/even, until it reaches 1.</li>\n</ul>\n\n<p>In code it probably looks like this (Pardon the swift syntax):</p>\n\n<pre><code>var n = N;\n var temp = Array&lt;Int&gt;();\n\n temp.append(N);\n\n let isOdd = n % 2 != 0;\n\n if (isOdd) {\n temp.append(n - 1);\n }\n\n while n &gt; 1 {\n if (n%2 == 0) {\n var last = n/2;\n temp.append(last);\n n = last;\n } else {\n var newNumber = n-1;\n\n temp.append(newNumber);\n\n var last = (newNumber)/2;\n\n temp.append(last);\n\n n = last;\n }\n }\n\n return temp.count;\n</code></pre>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2017-11-14T20:08:43.790", "Id": "180434", "ParentId": "40910", "Score": "0" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "11", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-02-05T01:57:01.053", "Id": "40910", "Score": "8", "Tags": [ "c#", "algorithm", "pathfinding" ], "Title": "Getting the shortest sequence to reach a number" }
40910
<p>This is a very basic timer that can support multithreading with <code>std::thread</code> and <code>std::chrono</code>.</p> <p>The timer has the classic functions: <code>start()</code> and <code>stop()</code>.</p> <p>The <code>start()</code> method creates an independent thread (<em>if multithread support is enabled</em>), then sleep the thread for a given <code>Interval</code>, then execute <code>Timeout</code> function. This method sets the <code>running</code> flag to true.</p> <p>If <code>singleShot</code> flag is <strong><em>not</em></strong> enabled the <code>sleepThenTimeout</code> process is called while a <code>running</code> flag is <code>true</code>.</p> <p>If multithread support is not enabled, the <code>current</code> thread is sleep.</p> <p>The <code>stop()</code> method just sets the <code>running</code> flag to false and <code>join</code> the thread.</p> <p>My doubt is about threat-safety. I've just started to learn how multithreading works, so I'm not sure if I must use mutexes or something like that.</p> <p>Any other type of feedback are welcome!</p> <p><strong>Timer.h</strong></p> <pre><code>#ifndef TIMER_H #define TIMER_H #include &lt;thread&gt; #include &lt;chrono&gt; class Timer { public: typedef std::chrono::milliseconds Interval; typedef std::function&lt;void(void)&gt; Timeout; Timer(const Timeout &amp;timeout); Timer(const Timeout &amp;timeout, const Interval &amp;interval, bool singleShot = true); void start(bool multiThread = false); void stop(); bool running() const; void setSingleShot(bool singleShot); bool isSingleShot() const; void setInterval(const Interval &amp;interval); const Interval &amp;interval() const; void setTimeout(const Timeout &amp;timeout); const Timeout &amp;timeout() const; private: std::thread _thread; bool _running = false; bool _isSingleShot = true; Interval _interval = Interval(0); Timeout _timeout = nullptr; void _temporize(); void _sleepThenTimeout(); }; #endif // TIMER_H </code></pre> <p><strong>Timer.cpp</strong></p> <pre><code>#include "Timer.h" Timer::Timer(const Timeout &amp;timeout) : _timeout(timeout) { } Timer::Timer(const Timer::Timeout &amp;timeout, const Timer::Interval &amp;interval, bool singleShot) : _isSingleShot(singleShot), _interval(interval), _timeout(timeout) { } void Timer::start(bool multiThread) { if (this-&gt;running() == true) return; _running = true; if (multiThread == true) { _thread = std::thread( &amp;Timer::_temporize, this); } else{ this-&gt;_temporize(); } } void Timer::stop() { _running = false; _thread.join(); } bool Timer::running() const { return _running; } void Timer::setSingleShot(bool singleShot) { if (this-&gt;running() == true) return; _isSingleShot = singleShot; } bool Timer::isSingleShot() const { return _isSingleShot; } void Timer::setInterval(const Timer::Interval &amp;interval) { if (this-&gt;running() == true) return; _interval = interval; } const Timer::Interval &amp;Timer::interval() const { return _interval; } void Timer::setTimeout(const Timeout &amp;timeout) { if (this-&gt;running() == true) return; _timeout = timeout; } const Timer::Timeout &amp;Timer::timeout() const { return _timeout; } void Timer::_temporize() { if (_isSingleShot == true) { this-&gt;_sleepThenTimeout(); } else { while (this-&gt;running() == true) { this-&gt;_sleepThenTimeout(); } } } void Timer::_sleepThenTimeout() { std::this_thread::sleep_for(_interval); if (this-&gt;running() == true) this-&gt;timeout()(); } </code></pre> <p><strong>main.cpp</strong></p> <pre><code>#include &lt;iostream&gt; #include "Timer.h" using namespace std; int main(void) { Timer tHello([]() { cout &lt;&lt; "Hello!" &lt;&lt; endl; }); tHello.setSingleShot(false); tHello.setInterval(Timer::Interval(1000)); tHello.start(true); Timer tStop([&amp;]() { tHello.stop(); }); tStop.setSingleShot(true); tStop.setInterval(Timer::Interval(3000)); tStop.start(); return 0; } </code></pre>
[ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-02-05T05:00:14.400", "Id": "70098", "Score": "0", "body": "Why would you use up all the resources required for a thread when you can set SIGALARM?" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-02-06T03:20:52.353", "Id": "70306", "Score": "0", "body": "As far I know SIGALRM is not cross-plataform." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-02-06T05:34:26.497", "Id": "70326", "Score": "0", "body": "What platform are you thinking about that does not have sig alarm but does have a threading model?" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-02-09T03:55:23.367", "Id": "70810", "Score": "0", "body": "Sorry, my bad! I've chosen to use threads because I want to learn about threads. I've also could use Qt's Timer but that is not the way." } ]
[ { "body": "<p>Basically you are working with these class members inside the thread functions <code>_temporize</code> and <code>_sleepThenTimeout</code>.</p>\n\n<ul>\n<li><code>timeout</code>, <code>_isSingleShort</code> and <code>_interval</code>, these three cannot be changed after the <code>start</code> function is called, so it is safe to use them.</li>\n<li><code>_running</code> on the other hand can be read/write by both threads. In reality it might not cause any problem as assignment to <code>bool</code> is atomic (on most architectures), but to be 100% safe you can use <code>std::atomic&lt;bool&gt;</code>.</li>\n</ul>\n\n<p>Another important thing to keep in mind is that while timer class itself is thread safe, it is responsibility of the user of this class to make sure that the timer call back function (<code>_timeout</code>) is thread-safe by it self, as it will be executed in a separate thread.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-02-08T23:32:57.647", "Id": "70797", "Score": "0", "body": "What do you think about replace `if (this->running() == true) return;` with an assert?" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-02-09T08:08:33.487", "Id": "70821", "Score": "1", "body": "Yes, assert will be better suited here, as it is better to let the caller know of the problem, rather than failing silently. But `assert` or the `if` statement won't affect the thread safety." } ], "meta_data": { "CommentCount": "2", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-02-06T06:35:36.803", "Id": "41040", "ParentId": "40915", "Score": "3" } }, { "body": "<p>I changed the testing part in main to</p>\n\n<pre><code>int cntHello = 0;\nint cntStop = 0;\n\nTimer tHello([&amp;]()\n{\n cntHello++;\n});\n\ntHello.setSingleShot(false);\ntHello.setInterval(Timer::Interval(1000));\ntHello.start(true);\n\nTimer tStop([&amp;]()\n{\n ++cntStop;\n tHello.stop();\n});\n\ntStop.setSingleShot(true);\ntStop.setInterval(Timer::Interval(3001));\ntStop.start(true);\n\n// TODO why could join tHello at this point?\n// tHello.join();\ntStop.join();\ntHello.join();\n</code></pre>\n\n<p>First change is the during creating the Timer for tHello. I add '&amp;' between '[]' otherwise I cout not use cntHello inside the function. Why?\n(The counters are used later for checking how often the functions are called.)</p>\n\n<p>Second I use tStop allthough as multithread and wait after starting it until the threads have been finshed.(by using join) For that I wrote methods join() and joinable() for the class Timer with only the the methods for _thread. This works if I join for tStop first. If I join tHello first I got an exception. Can you explain why?</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2016-06-24T07:27:33.803", "Id": "132924", "ParentId": "40915", "Score": "2" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "4", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-02-05T04:09:03.850", "Id": "40915", "Score": "6", "Tags": [ "c++", "multithreading", "c++11", "timer" ], "Title": "Simple Multithread Timer" }
40915
<pre><code>public class diceGame { public static void main(String[] args) { int dice1; int dice2; int count = 0; int theSum = 0; int lowest = Integer.MAX_VALUE; int finalSum = 0; int diceSum; int totalSum=0; while (count &lt; Integer.parseInt(args[0])) { count = count + 1; diceSum=0; theSum=0; while (diceSum!=7) { diceSum = 0; dice1 = 1 + (int) ((Math.random() * (6 - 1)) + 1); dice2 = 1 + (int) ((Math.random() * (6 - 1)) + 1); diceSum = dice1 + dice2; if (diceSum != 7) { theSum = theSum + diceSum; } //System.out.println("the sum is "+theSum); } if (theSum &gt; finalSum) { finalSum = theSum; } if (theSum &lt; lowest) { lowest = theSum; } totalSum=totalSum+theSum; } double average=(double)totalSum/(Double.parseDouble(args[0])); System.out.println("After " + args[0] + " simulations: "); System.out.println("Biggest sum: " + finalSum); System.out.println("Smallest sum: " + lowest); System.out.println("The average is: "+average); } } </code></pre> <p>I would like to execute this with much less code and want to learn other/better ways to do some of things I did, such as a random <code>int</code>s.</p>
[ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-02-05T16:37:58.377", "Id": "70225", "Score": "0", "body": "as I commented on a previous question, `(6 - 1)) + 1) == 6`. To throw a dice, you want to use `new Random().nextInt(6) + 1`" } ]
[ { "body": "<ul>\n<li><p>As per Java naming convention, user-defined types should be capitalized. In this case, <code>diceGame</code> should be <code>DiceGame</code>.</p></li>\n<li><p>Prefer to have variables defined in the lowest scope possible. This is especially useful in not having to worry about whether or not a variable is still in use.</p>\n\n<p>Since <code>dice1</code> and <code>dice2</code> are only used within the loop, you can just initialize them in there:</p>\n\n<pre><code>// these can be removed\nint dice1;\nint dice2;\n\n// ...\n\nint dice1 = 1 + (int) ((Math.random() * (6 - 1)) + 1);\nint dice2 = 1 + (int) ((Math.random() * (6 - 1)) + 1);\n</code></pre></li>\n<li><p>These:</p>\n\n<pre><code>theSum = theSum + diceSum;\ntotalSum = totalSum + theSum;\n</code></pre>\n\n<p>can be rewritten as this:</p>\n\n<pre><code>theSum += diceSum;\ntotalSum += theSum;\n</code></pre>\n\n<p>This works in similar cases when you're accumulating a total with an arithmetic operator.</p></li>\n<li><p><code>theSum</code> is not a descriptive name. The sum of what? Based on the code alone, it's hard to tell exactly what it's used for, especially when you have <code>diceSum</code>, <code>finalSum</code>, and <code>totalSum</code>.</p></li>\n<li><p>I agree with @200_success' suggestion about creating a <code>Die</code> class. With that, you can create any number of <code>Die</code> objects instead of <code>int</code> variables. You can even have a data structure, such as an array, that holds these objects. You could have one array of <code>Die</code> objects instead of having to define multiple ones, especially if you end up needing as many as, say, 100 dice.</p></li>\n</ul>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-02-05T05:24:32.057", "Id": "40920", "ParentId": "40919", "Score": "13" } }, { "body": "<p>Your <code>main()</code> function desperately needs to be busted up, for multiple reasons:</p>\n\n<ul>\n<li>You use a <strong><em>lot</em> of variables</strong>, all of them declared at the top of <code>main()</code>. A human mind is only good at keeping track of about 7 things at a time, so this code is hard to follow.</li>\n<li>It violates the <strong>Single Responsibility Principle</strong>, by parsing the command line, throwing the dice, keeping the statistics, and printing the report. That's a lot of work for one function!</li>\n<li><strong>Object-oriented code is preferred</strong> in Java. A <code>static</code> function avoids object-oriented thinking.</li>\n<li>It's <strong>unclear what you're simulating</strong>: what constitutes a trial, and what you mean by biggest/smallest sum.</li>\n</ul>\n\n<hr>\n\n<p>A quick win in readability can be obtained by defining a <code>Die</code> class: <code>die.toss()</code> reads like English, whereas <code>1 + (int) ((Math.random() * (6 - 1)) + 1)</code> doesn't.</p>\n\n<pre><code>class Die {\n // Since \"throw\" is a Java keyword, we use \"toss\"\n int toss() {\n return 1 + (int)(6 * Math.random());\n }\n}\n</code></pre>\n\n<hr>\n\n<p>A good start to taming the variables would be to declare each of them in the tightest scope possible. For example, <code>theSum</code>, and <code>diceSum</code> are only relevant inside the loop. <code>count</code> is a loop counter, and it's much easier to recognize if you rewrite the loop as a for-loop. <code>dice1</code> and <code>dice2</code> are only relevant inside the inner loop, which is better expressed as a do-while loop.</p>\n\n<pre><code>for (int count = 0; count &lt; Integer.parseInt(args[0]); count++) {\n int theSum = 0, diceSum;\n do {\n int dice1 = 1 + (int) ((Math.random() * (6 - 1)) + 1);\n int dice2 = 1 + (int) ((Math.random() * (6 - 1)) + 1);\n diceSum = dice1 + dice2;\n if (diceSum != 7) {\n theSum = theSum + diceSum;\n }\n //System.out.println(\"the sum is \"+theSum);\n } while (diceSum != 7);\n …\n}\n</code></pre>\n\n<p>Now a picture is beginning to emerge. The inner loop is what you would call a <em>simulation trial</em>. Based on that, I would define a <code>DiceSimulation</code> class with a <code>runTrial()</code> method. Everything else just falls into place around that core function. ☺</p>\n\n<pre><code>public class DiceSimulation {\n private int trials = 0, // Formerly count\n min = Integer.MAX_VALUE, // Formerly lowest\n max = 0, // Formerly finalSum\n sum = 0; // Formerly totalSum\n\n private Die die1 = new Die(),\n die2 = new Die();\n\n /**\n * One trial consists of tossing a pair of dice until a sum of 7 is obtained.\n * The result of the trial is the sum of all tosses up to, but not including,\n * the toss that resulted in 7.\n */\n public int runTrial() {\n int trialSum = 0, pairSum; // Formerly theSum and diceSum\n while (7 != (pairSum = die1.toss() + die2.toss())) {\n trialSum += pairSum;\n }\n\n if (trialSum &gt; max) {\n max = trialSum;\n }\n if (trialSum &lt; min) {\n min = trialSum;\n }\n sum += trialSum;\n trials++;\n return trialSum;\n }\n\n public void report() {\n System.out.println(\"After \" + trials + \" simulations: \");\n System.out.println(\"Biggest sum: \" + max);\n System.out.println(\"Smallest sum: \" + min);\n System.out.println(\"The average is: \" + (double)sum / trials);\n }\n\n public static void main(String[] args) {\n int trials = Integer.parseInt(args[0]);\n\n DiceSimulation sim = new DiceSimulation();\n for (int count = 0; count &lt; trials; count++) {\n sim.runTrial();\n }\n sim.report();\n }\n}\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-02-06T08:14:32.933", "Id": "70343", "Score": "4", "body": "I prefed prefixing fields with `this.`. This makes it a lot more visible what is going on. For example the `sum+= trailSum;`.. `this.sum+= trailSum` makes obvious a field is getting updated" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-02-06T18:01:27.007", "Id": "70447", "Score": "0", "body": "I liked the idea of using Die.toss but you can use a single die object here.\n\nAnother thing, \n7 != (pairSum = die1.toss() + die2.toss()\nmakes code slightly more cryptic by having multiple responsibility together. Rather have a do while with \ndo \n{\npairSum = die1.toss() + die2.toss();\n...\n}while(pairSum!=7)" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-02-06T18:04:16.177", "Id": "70449", "Score": "0", "body": "I prematurely posted comment. Edited . see the the comment now." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-02-06T18:06:46.343", "Id": "70450", "Score": "0", "body": "@ArchitJain Note that `trialSum` should sum tosses before the 7, _excluding_ the 7." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-02-06T18:11:55.397", "Id": "70456", "Score": "1", "body": "umm.. corrrect..i missed that. On using a single die, pairSum = die.toss() + die.toss() Doesn't this works?" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-02-06T18:21:43.257", "Id": "70458", "Score": "0", "body": "@ArchitJain You are correct that tossing the \"same\" die twice _should_ yield the same statistics. It models the world less faithfully, though, and could lead to code maintenance bugs if the problem description ever changes." } ], "meta_data": { "CommentCount": "6", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-02-05T09:30:24.973", "Id": "40938", "ParentId": "40919", "Score": "23" } }, { "body": "<p>200_success has suggested that you change the readability of the line:</p>\n\n<pre><code>dice1 = 1 + (int) ((Math.random() * (6 - 1)) + 1);\n</code></pre>\n\n<p>to be:</p>\n\n<pre><code>1 + (int)(6 * Math.random());\n</code></pre>\n\n<p>(but then continues to use your version in his subsequent code)</p>\n\n<p>This is a good suggestion, but, more than that, you <strong>have</strong> to do that (or something similar) because your version of the dice-throw does not work.</p>\n\n<pre><code>Math.random() * (6 - 1)\n</code></pre>\n\n<p>will produce a value from <code>0.0</code> to <code>4.9999....</code></p>\n\n<p>Putting it back in the full context, you do:</p>\n\n<pre><code>1 + (int) ((Math.random() * (6 - 1)) + 1);\n</code></pre>\n\n<p>Which will produce the values 2 through 6 (but never 1).</p>\n\n<p>Using random numbers is surprisingly easy to get wrong... Part of the problem is that <code>Math.random()</code> works in the <code>double</code> domain from <code>0.0</code> to <code>0.9999....</code></p>\n\n<p>I strongly recommend using the <code>java.util.Random</code> class which has some easier methods to use which at least are closer to the domain of values you want, <code>int</code>.</p>\n\n<pre><code>Random randomsource = new Random();\n....\n dice1 = 1 + randomsource.nextInt(6);\n dice2 = 1 + randomsource.nextInt(6);\n</code></pre>\n\n<p>The above will create 1 of 6 different random integers (0 though 5), and will add 1 to the result. Much simpler.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-02-05T12:08:20.253", "Id": "40948", "ParentId": "40919", "Score": "11" } }, { "body": "<p>I would like to add one more thing, in while loop, the type conversion is happening on each iteration.</p>\n\n<pre><code>while (count &lt; Integer.parseInt(args[0])) {\n count = count + 1;\n</code></pre>\n\n<p>It should be done only once:</p>\n\n<pre><code>int rolls = Integer.parseInt(args[0]);\n\nwhile (count &lt; rolls) {\n count = count + 1;\n</code></pre>\n\n<p>Which would be better written as a <code>for</code> loop:</p>\n\n<pre><code>int rolls = Integer.parseInt(args[0]);\nfor (int count = 0; count &lt; rolls; count++) {\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-02-05T15:26:31.013", "Id": "70215", "Score": "1", "body": "As it depends on `Math.random()` I don't see how it could be done only once. The only way to avoid it is to use @rolfl's suggestion of using the `Random` class, which I highly recommend." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-02-05T15:28:54.330", "Id": "70217", "Score": "0", "body": "@SimonAndréForsberg You misunderstood this answer, see my edit" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-02-05T15:31:00.463", "Id": "70219", "Score": "1", "body": "Actually, [200_success already fixed this in his answer](http://codereview.stackexchange.com/a/40938/21609) without specially mentioning it." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-02-05T15:31:08.583", "Id": "70221", "Score": "0", "body": "@amon Good edit, now I see. +1." } ], "meta_data": { "CommentCount": "4", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-02-05T14:58:23.890", "Id": "40966", "ParentId": "40919", "Score": "11" } }, { "body": "<p>In addition to what others already have mentioned, I just have a few things to add:</p>\n\n<ul>\n<li><p>Magic numbers. Why 7? Where does that come from? Why 6? (There are 20-sided dice as well). Declare these numbers as constants, usually any number that's not 0 or 1 (and even those too sometimes, for when you don't have a good reason for using 0 or 1).</p>\n\n<pre><code>private static final int DIE_SIDES = 6;\nprivate static final int TARGET_NUMBER = 7;\n</code></pre>\n\n<p>Then instead of writing 6 or 7 in other places of your code, write <code>DIE_SIDES</code> or <code>TARGET_NUMBER</code> instead. Also, if you want to make it more flexible later (and more object oriented as @200_success suggests - which I agree on), you could make these <em>instance</em> variables instead of static variables by simply removing the <code>static</code> keyword.</p></li>\n<li><p>Consistent spacing. I find that it is harder to read:</p>\n\n<pre><code>totalSum=totalSum+theSum;\n</code></pre>\n\n<p>than to read</p>\n\n<pre><code>totalSum = totalSum + theSum;\n</code></pre>\n\n<p>You use good spacing in most of your code. Stick to that.</p></li>\n<li><p>Your use of division and the argument. On one place in the code, you parse <code>args[0]</code> as integer, but here you parse it as double: (also note the fixed spacing!)</p>\n\n<pre><code>double average = (double)totalSum / (Double.parseDouble(args[0]));\n</code></pre>\n\n<p>It seems to me quite clear that you always want to parse it as an integer, as it is the number of times to throw. And it doesn't make sense to throw 3.47 times, or 9.17 times, does it? I understand you wrote this line to avoid the resulting number becoming an integer, as <code>int / int == int</code> in Java. </p>\n\n<p>But as <code>double / int == double</code> and <code>int / double == double</code> you only need to typecast one of them to double, for simplicity, let's go with <code>totalSum</code>. And as @user36245 pointed out, you should only parse the number once and use it as a variable, this will also improve the readability of the line.</p>\n\n<pre><code>int numberOfThrows = Integer.parseInt(args[0]);\n...\ndouble average = (double)totalSum / numberOfThrows;\n</code></pre>\n\n<p>Now it is easier to tell what we are dividing :)</p></li>\n<li><p>Shorter addition. Instead of writing <code>totalSum = totalSum + theSum</code> you can write <code>totalSum += theSum</code>. Also, for cases when you just want to increase by one, as in <code>count = count + 1;</code> you can use <code>count++;</code></p></li>\n</ul>\n\n<p>I must say though, as I want to give a compliment also, that you're code is quite well formatted. You know where to put braces and parenthesis and you know how to indent your code properly, good! Keep on learning more things!</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-02-05T19:23:57.020", "Id": "40992", "ParentId": "40919", "Score": "8" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "1", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-02-05T05:09:25.717", "Id": "40919", "Score": "15", "Tags": [ "java", "beginner", "random", "simulation", "dice" ], "Title": "Basic Java dice game" }
40919
<p>I've created a linked list to use it in <a href="http://www.drdobbs.com/database/the-squarelist-data-structure/184405336" rel="nofollow">SquareList</a>. I've started to create a linked list based on just that. I want my class to follow the iterator pattern. How can it be improve to use vector iterator? </p> <pre><code>#ifndef LINKEDLIST_HPP #define LINKEDLIST_HPP #include &lt;stdlib.h&gt; template &lt;typename Object&gt; class Linkedlist { private: // The basic doubly linked Linkedlist node. // Nested inside of Linkedlist, can be public // because the Node is itself private struct Node { Object _data; Node *_prev; Node *_next; Node( const Object &amp; d = Object( ), Node * p = NULL, Node * n = NULL ) : _data( d ), _prev( p ), _next( n ) { } }; public: public: Linkedlist( ) { init( ); } ~Linkedlist( ) { clear( ); delete _head; delete _tail; } Linkedlist( const Linkedlist &amp; rhs ) { init( ); *this = rhs; } const Linkedlist &amp; operator= ( const Linkedlist &amp; rhs ) { if( this == &amp;rhs ) return *this; clear( ); for( const_iterator itr = rhs.begin( ); itr != rhs.end( ); ++itr ) push_back( *itr ); return *this; } // Return iterator representing beginning of Linkedlist. // Mutator version is first, then accessor version. iterator begin( ) { return iterator( _head-&gt;_next ); } const_iterator begin( ) const { return const_iterator( _head-&gt;_next ); } // Return iterator representing endmarker of Linkedlist. // Mutator version is first, then accessor version. iterator end( ) { return iterator( _tail ); } const_iterator end( ) const { return const_iterator( _tail ); } // Return number of elements currently in the Linkedlist. int size( ) const { return _size; } // Return true if the Linkedlist is empty, false otherwise. bool empty( ) const { return size( ) == 0; } void clear( ) { while( !empty( ) ) pop_front( ); } // front, back, push_front, push_back, pop_front, and pop_back // are the basic double-ended queue operations. Object &amp; front( ) { return *begin( ); } const Object &amp; front( ) const { return *begin( ); } Object &amp; back( ) { return *--end( ); } const Object &amp; back( ) const { return *--end( ); } void push_front( const Object &amp; x ) { insert( begin( ), x ); } void push_back( const Object &amp; x ) { insert( end( ), x ); } void pop_front( ) { erase( begin( ) ); } void pop_back( ) { erase( --end( ) ); } // Insert x before itr. iterator insert( iterator itr, const Object &amp; x ) { Node *p = itr.current; _size++; return iterator( p-&gt;_prev = p-&gt;_prev-&gt;_next = new Node( x, p-&gt;_prev, p ) ); } // Erase item at itr. iterator erase( iterator itr ) { Node *p = itr.current; iterator retVal( p-&gt;_next ); p-&gt;_prev-&gt;_next = p-&gt;_next; p-&gt;_next-&gt;_prev = p-&gt;_prev; delete p; _size--; return retVal; } iterator erase( iterator start, iterator end ) { for( iterator itr = start; itr != end; ) itr = erase( itr ); return end; } private: int _size; Node *_head; Node *_tail; void init( ) { _size = 0; _head = new Node; _tail = new Node; _head-&gt;_next = _tail; _tail-&gt;_prev = _head; } }; #endif </code></pre>
[]
[ { "body": "<p>You define the copy constructor in terms of the assignment operator</p>\n\n<pre><code>Linkedlist( const Linkedlist &amp; rhs )\n{\n init( );\n *this = rhs;\n}\n</code></pre>\n\n<p>It is more traditional to do it the other way around. Normally you define the assignment in terms of the copy constructor. The idiom is called \"Copy and Swap\"</p>\n\n<pre><code>Linkedlist(Linkedlist const&amp; rhs)\n{\n // Create a copy\n}\n\nLinkedlist&amp; operator=(Linkedlist rhs) // pass by value to get copy\n{\n rhs.swap(*this); // swap the copy with this.\n return *this; // As rhs leaves scope with the old values\n} // it is automatically deleted.\n</code></pre>\n\n<p>There are a couple of problems with doing it the other way around.</p>\n\n<p>You do not provide the strong exception guarantee. On an assignment you destroy the content of you list. Then start to populate it with new values. If at any point copying fails you are left with a half complete object and no way to roll back to the original object.</p>\n\n<p>Assignment should fall into three distinct phases.</p>\n\n<pre><code>A = B;\n</code></pre>\n\n<ol>\n<li><p>Create a copy of the object being assigned from <code>B</code> into a temporary object. This will be the new value that <code>A</code> holds once everything works. If this copy fails then the value of <code>A</code> should not be changed.</p></li>\n<li><p>Swap the internal state of <code>A</code> with the temporary object. Since a swap should never fail this has no danger. <code>A</code> will now hold a copy of <code>B</code> and the temporary object will hold the old value of <code>A</code>.</p></li>\n<li><p>Destroy the old object. If this fails it does not matter. As the state of <code>A</code> is now consistent.</p>\n\n<p>const Linkedlist &amp; operator= ( const Linkedlist &amp; rhs )\n{\n if( this == &amp;rhs )\n return *this;\n clear( );</p></li>\n</ol>\n\n<p>At this point <code>A</code> has been cleared. Thus if the folloping loop fails you have no way to recover the original value of <code>A</code>. This will leave your program in a funny state. You have provided <code>The Basic Exception Guarantee</code> in that the object is not invalid. But this is not usually acceptable.</p>\n\n<pre><code> for( const_iterator itr = rhs.begin( ); itr != rhs.end( ); ++itr )\n push_back( *itr );\n\n\n return *this;\n}\n</code></pre>\n\n<p>This seems a bit over-elaborate!</p>\n\n<pre><code>Object &amp; front( )\n { return *begin( ); }\n</code></pre>\n\n<p>You are creating an iterator just to de-reference it! Why not just</p>\n\n<pre><code>Object &amp; front( )\n { return head-&gt;next.data; }\n</code></pre>\n\n<p>You should also put a comment that it is undefined behavior when the list is empty. Best to document these things up front.x</p>\n\n<p>Not to sure you need to define two different classes for <code>iterator</code> and <code>const_iterator</code>. Seems like a lot of duplicated code.</p>\n\n<p>Also you iterator does not meet even the requirements to <code>trivial iterator</code> as you are missing <code>operator -&gt;</code>. See <a href=\"http://www.sgi.com/tech/stl/table_of_contents.html\" rel=\"nofollow noreferrer\">http://www.sgi.com/tech/stl/table_of_contents.html</a> specifically look at the iterator section. I presume you are actually trying to implement the concept of <code>Bi-Directional iterator</code> the definition can be found here <a href=\"http://www.sgi.com/tech/stl/BidirectionalIterator.html\" rel=\"nofollow noreferrer\">http://www.sgi.com/tech/stl/BidirectionalIterator.html</a></p>\n\n<p>In addition your container object is supposed to provide some specific types that allow the user of your class to obtain information about the content type. Requirements can be found here: <a href=\"http://www.sgi.com/tech/stl/Container.html\" rel=\"nofollow noreferrer\">http://www.sgi.com/tech/stl/Container.html</a></p>\n\n<p>See here for an example of an iterator: <a href=\"https://codereview.stackexchange.com/a/9399/507\">https://codereview.stackexchange.com/a/9399/507</a> (though I did not make the container as well as I could because I did not specify the types I should have).</p>\n\n<p>See here for an example of a linked list using a single sentinel.<br>\n<a href=\"https://codereview.stackexchange.com/a/126007/507\">https://codereview.stackexchange.com/a/126007/507</a></p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-02-06T06:29:43.510", "Id": "41039", "ParentId": "40922", "Score": "8" } }, { "body": "<p>There is small possibility to have memory leak here:</p>\n\n<pre><code> _head = new Node;\n _tail = new Node;\n</code></pre>\n\n<p>consider if after successfull allocaiton of first Node you get std::bad_alloc on second Node</p>\n\n<p>Class invariant is not preserved here:</p>\n\n<pre><code> _size++;\n return iterator( p-&gt;_prev = p-&gt;_prev-&gt;_next = new Node( x, p-&gt;_prev, p ) );\n</code></pre>\n\n<p>Again there is small posibility of std::bad_alloc when you create new Node but you have already increased _size</p>\n\n<p>By the way - I remember leading underscores are discouraged from usage in application code</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-02-06T17:25:01.217", "Id": "70435", "Score": "0", "body": "Forgot to mention the underscore things. http://stackoverflow.com/a/228797/14065" } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-02-06T10:21:36.360", "Id": "41054", "ParentId": "40922", "Score": "6" } } ]
{ "AcceptedAnswerId": "41039", "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-02-05T06:00:11.773", "Id": "40922", "Score": "3", "Tags": [ "c++", "design-patterns", "linked-list", "iterator" ], "Title": "Creating linked list data with iterator pattern" }
40922
<p>I'm mixing <a href="http://developer.chrome.com/extensions/i18n.html" rel="nofollow">chrome.i18n</a> into my templates as <code>templateHelpers</code> with <a href="https://github.com/marionettejs/backbone.marionette/blob/master/docs/marionette.view.md#viewtemplatehelpers" rel="nofollow">Backbone.Marionette</a>.</p> <pre><code>templateHelpers: function () { return { // Mix in chrome to reference internationalize. 'chrome.i18n': chrome.i18n, instant: this.instant }; } </code></pre> <p>and here's my template:</p> <pre><code>&lt;% if( instant ) { %&gt; &lt;img class="item-thumb" src="http://img.youtube.com/vi/&lt;%= video.get('id') %&gt;/default.jpg" /&gt; &lt;% } else { %&gt; &lt;img class="item-thumb" data-original="http://img.youtube.com/vi/&lt;%= video.get('id') %&gt;/default.jpg" /&gt; &lt;% } %&gt; &lt;span class="item-title" title="&lt;%= video.get('title') %&gt;"&gt;&lt;%= video.get('title') %&gt;&lt;/span&gt; &lt;span class="item-details"&gt; &lt;% if( video.get('highDefinition') ) { %&gt; &lt;%= chrome.i18n.getMessage('hd') %&gt; · &lt;% } %&gt; &lt;span class="item-duration"&gt; &lt;%= video.get('prettyDuration') %&gt; &lt;/span&gt; &lt;/span&gt; &lt;span class="hover-actions"&gt; &lt;button class="button-icon playInStream" title="&lt;%= chrome.i18n.getMessage('play') %&gt;"&gt; &lt;i class="fa fa-play"&gt;&lt;/i&gt; &lt;/button&gt; &lt;button class="button-icon addToStream" title="&lt;%= chrome.i18n.getMessage('enqueue') %&gt;"&gt; &lt;i class="fa fa-plus"&gt;&lt;/i&gt; &lt;/button&gt; &lt;button class="button-icon save" title="&lt;%= chrome.i18n.getMessage('save') %&gt;"&gt; &lt;i class="fa fa-save"&gt;&lt;/i&gt; &lt;/button&gt; &lt;/span&gt; </code></pre> <p>The number of templates being rendered could well be in the thousands. Would it be greatly more efficient to pass the strings themselves into the template, i.e. call <code>getMessage</code> inside of <code>templateHelpers</code>, or does it not make much of a difference at all? My thought is that since I don't use the rest of chrome.i18n, I shouldn't be serializing it, but I'm not sure if that's the case.</p>
[]
[ { "body": "<p>I doubt performance will take much of a hit by passing <code>chrome.i18n</code> into your templates, but I still don't think you should do it.</p>\n\n<p>Templates should be solely for visualising data where possible, sometimes this requires a small amount of logic, but you should keep it out whenever possible. I would much rather see this:</p>\n\n<pre><code>var i18n = chrome.i18n;\n\n...\n\ntemplateHelpers: function () {\n return {\n hdMessage: i18n.getMessage('hd'),\n instant: this.instant\n };\n}\n</code></pre>\n\n<p>-</p>\n\n<pre><code>&lt;% if( video.get('highDefinition') ) { %&gt;\n &lt;%= hdMessage %&gt; · \n&lt;% } %&gt;\n</code></pre>\n\n<p>In the long run this prevents your templates from being cluttered with internationalisation specific code, which will also be useful if you ever need to change the library.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-02-05T08:56:46.790", "Id": "40936", "ParentId": "40923", "Score": "1" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-02-05T06:01:01.120", "Id": "40923", "Score": "1", "Tags": [ "javascript", "template", "backbone.js", "i18n" ], "Title": "Mixing chrome.i18n (internationalization method) into templates" }
40923
<p>I've been making a bot for Reddit that finds reposts (based on image MD5 comparing) and posts a small comment on the thread (that part will be later, right now it downloads images and compares MD5). If the image is original content, it will add it to its list of hashes. The source code is <a href="https://bitbucket.org/ilan321/repostfinder" rel="nofollow noreferrer">here</a>. Any suggestions as to what I can improve? </p> <pre><code>public static bool DownloadImage(string url, bool isDirect) // returns if repost { // example url: http://imgur.com/UndN77d if (url.Contains('?')) { url = url.Split('?')[0]; // if it has a query at the end like ?1 } string filename = null; if (url.Contains("imgur")) { // is imgur, so use ImgurAPI class for it string imgurID = url.Split('/')[url.Split('/').Length - 1]; Console.WriteLine("Processing imgur id {0}", imgurID); if (!isDirect) { // the sole goal for this block is to get Vars.picToCompare string details = Imgur.GetImageDetails(imgurID); if (details == null) { return false; } Console.WriteLine("Got response: {0}", details); // json JObject imgur = JObject.Parse(details); if (imgur["success"].ToString() == "false") { // auth failed Console.WriteLine("Imgur processing failed.. Printing JSON contents: "); Console.WriteLine(details); Console.ReadKey(); return false; } else { Console.WriteLine("Imgur details recieved successfully!"); filename = imgur["data"]["link"].ToString(); url = filename; Console.WriteLine("Processed direct URL: " + filename); filename = filename.Split('/')[filename.Split('/').Length - 1]; Console.WriteLine("Processed image filename: " + filename); Vars.picToCompare = Path.Combine(Vars.picsFolder, filename); } } else { Vars.picToCompare = Path.Combine(Vars.picsFolder, url.Split('/')[url.Split('/').Length - 1]); // should be filename } } else { // for example mysite.com/blah.jpg Vars.picToCompare = Path.Combine(Vars.picsFolder, url.Split('/')[url.Split('/').Length - 1]); Console.WriteLine("Processing image url {0}", url); Console.WriteLine("Processed image {0}", Vars.picToCompare); } bool isRepost = false; using (WebClient client = new WebClient()) { if (File.Exists(Vars.picToCompare)) File.Delete(Vars.picToCompare); client.DownloadFile(url, Vars.picToCompare); Console.WriteLine("Successfully downloaded image {0}", Vars.picToCompare); } isRepost = Processing.CompareHash(url); if (isRepost) Console.WriteLine("This is a repost!"); else Console.WriteLine("This is OC. Adding to hashlist.."); //foreach (string hash in Vars.totalHashes) //{ // Console.WriteLine("Written hash to file: " + hash); //} return isRepost; } </code></pre>
[ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-02-05T08:07:57.140", "Id": "70124", "Score": "2", "body": "You are aware that images which have been loaded and saved one time can be different (when looked at at the byte level)?" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-02-05T08:44:09.467", "Id": "70130", "Score": "0", "body": "Usually they're fine, if I save the hashes file and rerun the same pictures (it redownloads them) it detects that they're reposts." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-02-05T08:47:39.967", "Id": "70131", "Score": "3", "body": "No, what I meant is that a jpeg *can* change (and also it's MD5 sum) if it is loaded and saved one time in an image processor. So don't be surprised if pictures look the same to you (your eye) but the MD5 sums turn out completely different." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-01-12T18:06:35.527", "Id": "408737", "Score": "0", "body": "late to the party, but rather than saving the image MD5 it's more robust to save the image's SIFT print, which doesn't care about resaving, or transforms like scale/rotation and if done right, (limited) cropping." } ]
[ { "body": "<pre><code>public static bool DownloadImage(string url, bool isDirect) // returns if repost\n</code></pre>\n\n<p>C# supports something called <a href=\"http://msdn.microsoft.com/en-us/library/b2s063f7.aspx\" rel=\"nofollow noreferrer\">XML Documentation Comments</a> which allow you to document your code directly while writing it in a processor (as in IDE) friendly way.</p>\n\n<hr>\n\n<pre><code>public static bool DownloadImage(string url, bool isDirect) // returns if repost\n</code></pre>\n\n<p>Liar! This does not download the image but does checking on the URL, downloads the image, creates a MD5 sum for that image and then returns if it is already in the list of hashes.</p>\n\n<p>You have one function that does <em>everything</em>, that's bad. Ideally you would split the responsibilities between multiple methods in one class, in some kind of such a structure (pseudo code):</p>\n\n<pre><code>class RepostChecker\n byte[] ComputeMD5(byte[] data)\n byte[] GetImage(string url)\n bool IsKnown(byte[] hash)\n</code></pre>\n\n<p>All of these methods can be static. So you can chain them like this:</p>\n\n<pre><code>IsKnown(ComputeMD5(GetImage(url)))\n</code></pre>\n\n<p>Or you can write a convenience method:</p>\n\n<pre><code>bool IsRepost(string url)\n</code></pre>\n\n<p>Which does the chaining for you. Then you define a class which does hold your hashes:</p>\n\n<pre><code>class Hashes\n static string HashToString(byte[] hash)\n\n void Add(string hash)\n bool Contains(string hash)\n void Load(whateverDatastoreYouUse)\n void Save(whateverDatastoreYouUse)\n</code></pre>\n\n<p>Internally this should <a href=\"https://stackoverflow.com/questions/16812751/which-collection-type-should-i-use-to-store-a-bunch-of-hashes\">use a <code>HashSet&lt;String&gt;</code>, not a normal <code>List&lt;String&gt;</code> like your implementation</a>.</p>\n\n<p>These changes would allow a more structured approach to the problem.</p>\n\n<hr>\n\n<pre><code>if (url.Contains('?'))\n{\n url = url.Split('?')[0]; // if it has a query at the end like ?1\n}\nstring filename = null;\nif (url.Contains(\"imgur\"))\n</code></pre>\n\n<p>You should use the <a href=\"http://msdn.microsoft.com/en-us/library/system.uri%28v=vs.110%29.aspx\" rel=\"nofollow noreferrer\">Uri class if you work with URLs</a>.</p>\n\n<pre><code>Uri uri = new Uri(url); // http://imgur.com/blabla?whatever\nuri.GetLeftPart(UriPartial.Path); // http://imgur.com/blabla\nuri.Host; // imgur.com\n</code></pre>\n\n<hr>\n\n<p>Ideally you would not have one <code>if {} else {}</code> construct to handle this situation, but an interface which implementations and a static factory:</p>\n\n<pre><code>interface ImageHosterInteractor // Notice that the name is not optimal\n byte[] GetImage(string url)\n</code></pre>\n\n<p>From this interface you can now derive implementations for imgur and/or any other site. The static factory would look like this:</p>\n\n<pre><code>public static class ImageHosterInteractorFactory\n{\n public static ImageHosterInteractor Create(Uri uri)\n {\n if (uri.PathAndQuery.EndsWith(\".png\")) // Or any other for that matter\n {\n // Implementation which simply loads the data from\n // the given Uri.\n return new ImageHosterInteractors.Plain();\n }\n\n // The uri does not end with an explicit ending,\n // so there's a good chance that we need to follow\n // redirections or perform some other magic.\n // So we use one of the explicit implementations.\n\n switch(uri.Host)\n {\n case \"imgur.com\":\n return new ImageHosterInteractors.Imgur();\n break;\n\n case \"whatever.com\":\n return new ImageHosterIntactors.Whatever();\n break; \n\n default:\n throw new NotImplementedException(\"There is no implementation assigned to handle: \" + uri.Host);\n\n }\n }\n}\n</code></pre>\n\n<p>That allows your code to simply process the URL, pass it into the factory and get <em>something</em> back that knows how to treat that site and you don't need to worry about it further down.</p>\n\n<pre><code>Uri uri = new Uri(fromwhatever);\nImagerHosterInteractor interactor = ImageHosterInteractorFactory.Create(uri);\nbyte[] image = interactor.GetImage(uri);\n</code></pre>\n\n<p>Also adding new sites to handle is as easy as implementing <code>ImageHosterInteractor</code> and adding it to the factory method.</p>\n\n<hr>\n\n<p>At the moment it looks like you're saving the images you download, is that necessary or is it enough to simply save the hashes?</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-02-05T09:05:59.857", "Id": "70134", "Score": "0", "body": "I am saving the images, since I'm running the programs and it's quite funny to see the random images I get. Also, this is one complicated piece of work you got there. I only started C# 2-3 months ago! :O" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-02-05T09:10:19.320", "Id": "70135", "Score": "1", "body": "In that case I'd like to suggest that you read a good book, start with something introductory into C# and OOP and [I'm sure the books from Jon Skeet](http://csharpindepth.com/) will be a very good read, too. I never even looked at one of these, [but I think they're good](http://stackoverflow.com/users/22656/jon-skeet). Even though it's Java, \"Effective Java\" is a very good read for general OOP principles." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-02-05T11:08:59.187", "Id": "70151", "Score": "0", "body": "Did you meant `HashSet<string>`? There is no such thing as `HashList`." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-02-05T11:37:22.307", "Id": "70159", "Score": "0", "body": "@svick: Yes, typo, sorry." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-02-05T16:44:56.447", "Id": "70227", "Score": "0", "body": "The book costs money, and I'm afraid I can't even afford the humble indie bundle, so no idea how to get it .-." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-02-07T08:04:23.647", "Id": "70580", "Score": "0", "body": "@Ilan321: Well, check your next library if they have some books or dig through [the free programming books list](https://github.com/vhf/free-programming-books)." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-02-07T17:31:59.350", "Id": "70636", "Score": "0", "body": "My library only has hebrew books (Israel sucks). Thanks for the link though! I'll be sure to read a bunch of them :)" } ], "meta_data": { "CommentCount": "7", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-02-05T08:44:53.500", "Id": "40934", "ParentId": "40927", "Score": "5" } } ]
{ "AcceptedAnswerId": "40934", "CommentCount": "4", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-02-05T06:56:21.310", "Id": "40927", "Score": "7", "Tags": [ "c#", "image", "http", "reddit" ], "Title": "Reddit RepostFinder Bot" }
40927
<p>In CodeIgniter, I have created function (helper) to populate, store and retrieve checkbox group. I just wonder if I have written code is in proper way and optimized or needs some more finishing?</p> <p><strong>Function</strong></p> <pre><code>if ( ! function_exists('checkbox_group') ) { function checkbox_group($checkboxes = array(), $name) { // setting hidden field for null, if no checkbox selected echo form_hidden($name.'[]', 'null'); // start checkbox loop foreach($checkboxes as $check =&gt; $label_text): $checked = FALSE; $selects = get_config_row($name); if(in_array($check, $selects)) $checked = TRUE; echo '&lt;div class="checkbox"&gt;'; echo form_label(form_checkbox($name.'[]', $check, $checked, 'id="'.$check.'" class="checkbox"') . $label_text, $check); echo '&lt;/div&gt;'; endforeach; } } </code></pre> <p><strong>Usage</strong></p> <pre><code>// checkbox items $checkboxes = array( 'noindex'=&gt;'No Index', 'nofollow'=&gt;'No Follow', 'noarchive'=&gt;'No Archive', 'nosnippet'=&gt;'No Snippet' ); // render checkboxes useing function checkbox_group($checkboxes, 'indexes'); </code></pre>
[ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-02-05T10:42:45.340", "Id": "70139", "Score": "1", "body": "Is this code is really optimized so there is no suggestion or feedback yet? :S" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-02-06T22:36:33.340", "Id": "70529", "Score": "0", "body": "It's probably because few people here have used Codeigniter. I did but it was a long time ago. PHP-wise I think your code is fine. I don't know why you use a config file to store information about potential checkbox items, but you seem good enough that you probably know what you're doing. Maybe someone better than me will come along with some patience." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-02-07T04:49:16.933", "Id": "70565", "Score": "0", "body": "@Pickett thanks for your feedback. I am storing config values in database and have separate admin section to manage those config settings. These checkboxes are for one of those settings. For instance these checkboxes allows or disallow robots to index, follow, archive, snippet etc.. will stored into db than the config.php will use that value" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-02-07T06:54:22.550", "Id": "70576", "Score": "1", "body": "Perhaps that works for you, but in general that is not recommended I think. A helper is supposed to be modular. You're supposed to be able to use it in any CI project. Now it's only valid for this particular project because it relies on how the database is constructed and another file, config.php. To keep it modular and MVC you should let it accept that data as a parameter instead, acquire the information through a model and then pass that information through the controller to the view and then as a parameter to your helper." } ]
[ { "body": "<p>I haven't worked with CodeIgniter before, so if I say something that argues their standards, please excuse me.</p>\n\n<p>It's such a basic piece of code that there isn't too much to be said. One things I notice right off the bat, your <code>checkbox_group()</code> function has a first parameter with a default value. I'm surprised you haven't done anything about this because it should be throwing you a warning.</p>\n\n<blockquote>\n <p>Note that when using default arguments, any defaults should be on the\n right side of any non-default arguments; otherwise, things will not\n work as expected.</p>\n</blockquote>\n\n<p>As per the <a href=\"http://www.php.net/manual/en/functions.arguments.php\" rel=\"nofollow\">PHP Functions page</a></p>\n\n<p>To better separate the function's business and the view, consider creating an output string and returning it to be <code>echo</code>ed. You'd then have:</p>\n\n<pre><code>$output = '';\n// setting hidden field for null, if no checkbox selected\n$output .= form_hidden($name . '[]', 'null');\n\n// start checkbox loop\nforeach ($checkboxes as $check =&gt; $label_text) :\n\n $checked = FALSE;\n $selects = get_config_row($name);\n if (in_array($check, $selects))\n $checked = TRUE;\n\n $output .= '&lt;div class=\"checkbox\"&gt;';\n $output .= form_label(form_checkbox($name . '[]', $check, $checked, 'id=\"' . $check . '\" class=\"checkbox\"') . $label_text, $check);\n $output .= '&lt;/div&gt;';\nendforeach;\nreturn $output;\n</code></pre>\n\n<p>Now you call:</p>\n\n<pre><code>// render checkboxes useing function\necho checkbox_group($checkboxes, 'indexes');\n</code></pre>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-05-25T16:32:23.280", "Id": "51701", "ParentId": "40932", "Score": "2" } }, { "body": "<p>Splitting the assignment like this is clumsy:</p>\n\n<pre><code>$checked = FALSE;\n…\nif (in_array($check, $selects))\n $checked = TRUE;\n</code></pre>\n\n<p><a href=\"http://php.net/in_array\" rel=\"nofollow\"><code>in_array()</code></a> returns a <code>bool</code>. Why not just say:</p>\n\n<pre><code>$checked = in_array($check, get_config_row($name));\n</code></pre>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-05-25T18:44:53.840", "Id": "51709", "ParentId": "40932", "Score": "1" } }, { "body": "<p>The HTML output would look like this (pretty-printed):</p>\n\n<pre><code>&lt;input type=\"hidden\" name=\"indexes[]\" value=\"null\" /&gt;\n&lt;div class=\"checkbox\"&gt;\n &lt;label for=\"noindex\"&gt;\n &lt;input type=\"checkbox\" name=\"indexes[]\" value=\"noindex\" id=\"noindex\" class=\"checkbox\" /&gt;No Index\n &lt;/label&gt;\n&lt;/div&gt;\n&lt;div class=\"checkbox\"&gt;\n &lt;label for=\"nofollow\"&gt;\n &lt;input type=\"checkbox\" name=\"indexes[]\" value=\"nofollow\" checked=\"checked\" id=\"nofollow\" class=\"checkbox\" /&gt;No Follow\n &lt;/label&gt;\n&lt;/div&gt;\n…\n</code></pre>\n\n<p>I think that is problematic in several ways:</p>\n\n<ul>\n<li><p>It will always submit a <code>indexes[]=null</code> value, even when some checkboxes are selected. What good does <code>indexes[]=null</code> do? Just omit that hidden field.</p></li>\n<li><p><code>&lt;div class=\"checkbox\"&gt;</code> is an unnecessary level of nesting. Just <code>&lt;label class=\"checkbox\"&gt;</code> would suffice. Then, in CSS, you can optionally style it with</p>\n\n<pre><code>label.checkbox {\n display: block;\n}\n</code></pre>\n\n<p>if you want it to be displayed as a block.</p></li>\n<li><p>Putting <code>class=\"checkbox\"</code> on an <code>&lt;input type=\"checkbox\"&gt;</code> is redundant. You could just use <code>input[type=\"checkbox\"]</code> as a CSS selector.</p></li>\n<li><p>Every <code>id</code> attribute in an HTML document must be unique. (If any other element also has <code>id=\"nofollow\"</code>, then the document is invalid.) Therefore, you should make a greater effort to avoid conflicting element IDs. For example, <code>id=\"indexes-nofollow\"</code> would be reasonable.</p></li>\n</ul>\n\n<p>In addition, your code seems to be <strong>vulnerable to HTML injection.</strong> Since <code>$label_text</code> should be considered to contain arbitrary text, not just sane identifiers, it needs to be escaped.</p>\n\n<p>Recommended rewrite:</p>\n\n<pre><code>echo form_label(\n form_checkbox($name.'[]', $check, $checked, \"id=\\\"$name-$check\\\"\") .\n htmlspecialchars($label_text),\n '',\n array('class' =&gt; 'checkbox')\n);\n</code></pre>\n\n<p>… which would produce output (pretty-printed):</p>\n\n<pre><code>&lt;label class=\"checkbox\"&gt;\n &lt;input type=\"checkbox\" name=\"indexes[]\" value=\"noindex\" id=\"indexes-noindex\" /&gt;No Index\n&lt;/label&gt;\n&lt;label class=\"checkbox\"&gt;\n &lt;input type=\"checkbox\" name=\"indexes[]\" value=\"nofollow\" checked=\"checked\" id=\"indexes-nofollow\" /&gt;No Follow\n&lt;/label&gt;\n…\n</code></pre>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-05-25T19:48:39.793", "Id": "51711", "ParentId": "40932", "Score": "1" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "4", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-02-05T07:51:37.377", "Id": "40932", "Score": "1", "Tags": [ "php", "codeigniter" ], "Title": "Checkbox Group Function and Usage" }
40932
<p>I am using jQuery to implement a basic quiz functionality. How can I improve this code snippet even more? Is there any better way of doing it?</p> <p>I am using jQuery 1.6.4.</p> <pre><code>/*jshint -W065 */ $(function () { var jQuiz = { answers: { q1: 'd', q2: 'd', q3: 'a', q4: 'c', q5: 'a' }, questionLenght: 5, checkAnswers: function () { var arr = this.answers; var ans = this.userAnswers; var resultArr = []; for (var p in ans) { var x = parseInt(p) + 1; var key = 'q' + x; var flag = false; if (ans[p] == 'q' + x + '-' + arr[key]) { flag = true; } else { flag = false; } resultArr.push(flag); } return resultArr; }, init: function () { $('.btnNext').click(function () { if ($('input[type=radio]:checked:visible').length === 0) { return false; } $(this).parents('.questionContainer').fadeOut(500, function () { $(this).next().fadeIn(500); }); var el = $('#progress'); el.width(el.width() + 120 + 'px'); }); $('.btnPrev').click(function () { $(this).parents('.questionContainer').fadeOut(500, function () { $(this).prev().fadeIn(500); }); var el = $('#progress'); el.width(el.width() - 120 + 'px'); }); $('.btnShowResult').click(function () { var arr = $('input[type=radio]:checked'); var ans = jQuiz.userAnswers = []; for (var i = 0, ii = arr.length; i &lt; ii; i++) { ans.push(arr[i].getAttribute('id')); } $('#progress').width(300); $('#progressKeeper').hide(); var results = jQuiz.checkAnswers(); var resultSet = ''; var trueCount = 0; for (var i = 0, ii = results.length; i &lt; ii; i++) { if (results[i] === true) trueCount++; resultSet += '&lt;div&gt; Question ' + (i + 1) + ' is ' + results[i] + '&lt;/div&gt;'; } resultSet += '&lt;div class="totalScore"&gt;Your total score is ' + trueCount * 20 + ' / 100&lt;/div&gt;'; $('#resultKeeper').html(resultSet).show(); }); } }; jQuiz.init(); }); </code></pre>
[ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-02-05T10:42:47.767", "Id": "70140", "Score": "0", "body": "Why are you binding two different functions to `$('.btnShowResult').click`" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-02-05T11:12:54.510", "Id": "70152", "Score": "0", "body": "You answered with \"what\" you are binding. I asked \"why\". Since they are using the same selector, you _could_ chain the method calls, but you could just as easily put them in the same click handler. If you are worried about readability, factor some code out into well named methods." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-02-05T11:19:06.063", "Id": "70153", "Score": "0", "body": "As a starting point, http://www.jslint.com/ put a comment `/*global $ */` at the top of your code, and follow the advice it gives you." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-02-05T11:35:49.567", "Id": "70158", "Score": "1", "body": "Is your quiz trolling me? Some of the answers are incorrect." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-02-05T11:41:29.187", "Id": "70160", "Score": "0", "body": "And yes of course I could chain the method calls, my mistake. I have updated the code. And yes I have updated the answers too.. :)" } ]
[ { "body": "<p>Some suggestions</p>\n\n<ul>\n<li><p>If you ignore the <code>q</code> your questions object is a list of sequential integers so might as well be an array. This will simplify the logic later on.</p>\n\n<pre><code>answers: [\n 'd',\n 'd',\n 'a',\n 'c',\n 'a'\n]\n</code></pre></li>\n<li><p>If you use an array as suggested above, then we can simplify this block quite a lot (also, use <a href=\"https://developer.mozilla.org/en/Core_JavaScript_1.5_Reference/Operators/Comparison_Operators\" rel=\"nofollow\">strict comparators</a>!): </p>\n\n<blockquote>\n<pre><code>var resultArr = [];\n for (var p in ans) {\n var x = parseInt(p) + 1;\n var key = 'q' + x;\n var flag = false;\n if (ans[p] == 'q' + x + '-' + arr[key]) {\n flag = true;\n } else {\n flag = false;\n }\n resultArr.push(flag);\n }\n</code></pre>\n</blockquote>\n\n<pre><code> var results = [];\n for ( var i = 0; = &lt; ans.length; i++ ) {\n var flag = (ans[p] === arr[i]);\n result.push(flag);\n }\n</code></pre></li>\n<li><p>This is daft unless you want to make <strong>certain</strong> it's not something other than a boolean;</p>\n\n<blockquote>\n<pre><code>if (results[i] === true) {}\n</code></pre>\n</blockquote>\n\n<pre><code>if (results[i]) {}\n</code></pre></li>\n<li><p>It's much nicer to build HTML using jQuery than with Strings. And your <code>for</code> loop seems to have an unnecessary variable.</p>\n\n<pre><code> var resultSet = $('&lt;div&gt;');\n var trueCount = 0;\n for (var i = 0; i &lt; results.length; i++) {\n if (results[i] === true) trueCount++;\n resultSet.text('Question ' + (i + 1) + ' is ' + results[i] + ');\n }\n</code></pre></li>\n<li><p>If you're declaring multiple variables you can separate them with a comma.</p>\n\n<pre><code>var results = jQuiz.checkAnswers(),\n resultSet = $('&lt;div&gt;'),\n trueCount = 0;\n</code></pre></li>\n</ul>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-02-05T22:54:53.420", "Id": "41015", "ParentId": "40939", "Score": "2" } } ]
{ "AcceptedAnswerId": "41015", "CommentCount": "5", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-02-05T09:54:30.890", "Id": "40939", "Score": "2", "Tags": [ "javascript", "jquery", "game" ], "Title": "Basic quiz in jQuery" }
40939
<p>I have written the following function that takes an <code>address</code> object and builds a string using the object properties. It will later be used to display a tooltip</p> <pre><code>var getAddressTooltip = function (address) { var tooltip = ''; if (address.MasterAddress !== undefined &amp;&amp; address.MasterAddress !== null &amp;&amp; address.MasterAddress.Id !== undefined &amp;&amp; address.MasterAddress.Id !== null) { tooltip += '[' + address.MasterAddress.Id + '] '; } if (address.PurchasingContact !== null &amp;&amp; address.PurchasingContact !== undefined &amp;&amp; address.PurchasingContact.Name !== null &amp;&amp; address.PurchasingContact.Name !== undefined &amp;&amp; address.PurchasingContact.Name.length &gt; 0) { tooltip += $.trim(address.PurchasingContact.Name) + ',\n'; } if (address.ShipTo !== null &amp;&amp; address.ShipTo !== undefined &amp;&amp; address.ShipTo.length &gt; 0) { tooltip += $.trim(address.ShipTo) + ',\n'; } if (address.Line1 !== null &amp;&amp; address.Line1 !== undefined &amp;&amp; address.Line1.length &gt; 0) { tooltip += $.trim(address.Line1) + ',\n'; } if (address.Line2 !== null &amp;&amp; address.Line2 !== undefined &amp;&amp; address.Line2.length &gt; 0) { tooltip += $.trim(address.Line2) + ',\n'; } if (address.City !== null &amp;&amp; address.City !== undefined &amp;&amp; address.City.length &gt; 0) { tooltip += $.trim(address.City) + ',\n'; } if (address.State !== null &amp;&amp; address.State !== undefined &amp;&amp; address.State.Name !== null &amp;&amp; address.State.Name !== undefined &amp;&amp; address.State.Name.length &gt; 0) { tooltip += $.trim(address.State.Name) + ',\n'; } if (address.ZIP !== null &amp;&amp; address.ZIP !== undefined &amp;&amp; address.ZIP.length &gt; 0) { tooltip += $.trim(address.ZIP) + ',\n'; } //replace trailing comma / line break if (tooltip.substr(tooltip.length - 2, 2) === ',\n') { tooltip = tooltip.substr(0, tooltip.length - 2); } return tooltip; }; </code></pre> <p>As you can probably tell, I'm rather fastidious about ensuring the values are there before concatenating them, as we have had problems in the past with properties coming back as <code>undefined</code> and bringing the whole application crashing to a halt. </p> <p>However, the cyclomatic complexity of this function is through the roof because of all the <code>null</code> / <code>undefined</code> / <code>length &gt; 0</code> checks that I'm doing. It is entirely possible that I'm taking things too far.</p> <p>What I'm wondering is if anybody knows a faster, smarter and tidier way of doing the same thing? Do I really need all these checks? It appears that if I want valid, safe and linted JavaScript, all of them are necessary.</p>
[ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-02-05T14:15:54.130", "Id": "70193", "Score": "0", "body": "You're not taking things too far - you always need to validate your input. What you've done is copy/pasted the same checks on many different attributes. If you extract those into a method you can call, you'll get your complexity down to where it belongs." } ]
[ { "body": "<p>What about this:</p>\n\n<pre><code>var getAddressTooltip = function (address) {\n\n var tooltip = '';\n\n if (address.MasterAddress &amp;&amp;\n address.MasterAddress.Id) {\n tooltip += '[' + address.MasterAddress.Id + '] ';\n }\n if (address.PurchasingContact &amp;&amp;\n address.PurchasingContact.Name) {\n tooltip += $.trim(address.PurchasingContact.Name) + ',\\n';\n }\n if (address.ShipTo) {\n tooltip += $.trim(address.ShipTo) + ',\\n';\n }\n if (address.Line1) {\n tooltip += $.trim(address.Line1) + ',\\n';\n }\n if (address.Line2) {\n tooltip += $.trim(address.Line2) + ',\\n';\n }\n if (address.City) {\n tooltip += $.trim(address.City) + ',\\n';\n }\n if (address.State &amp;&amp;\n address.State.Name) {\n tooltip += $.trim(address.State.Name) + ',\\n';\n }\n if (address.ZIP) {\n tooltip += $.trim(address.ZIP) + ',\\n';\n }\n\n //replace trailing comma / line break\n if (tooltip.substr(tooltip.length - 2, 2) === ',\\n') {\n tooltip = tooltip.substr(0, tooltip.length - 2);\n }\n\nreturn tooltip; };\n</code></pre>\n\n<p>Since JavaScript considers null, undefined, and the empty string to be falsy, the value of the variable itself can be used to substitute for all the tests. Further, as any object is automatically truthy, the tests like <code>address.PurchasingContract</code> will be true if the object is there.</p>\n\n<p><strong>References:</strong></p>\n\n<p><a href=\"https://developer.mozilla.org/en-US/docs/Web/JavaScript/A_re-introduction_to_JavaScript#Other_types\" rel=\"nofollow\">MDN: A Reintroduction to JavaScript</a> (just the first thing I came across)</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-02-05T12:30:51.307", "Id": "70173", "Score": "0", "body": "It's good, it's fast and it's tidy :) The only problem I'd have is if a property on `address` happens to evaluate to falsy, (say, `0`) it would not be concatenated. But I'll admit it's unlikely!" } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-02-05T11:59:22.950", "Id": "40946", "ParentId": "40941", "Score": "3" } }, { "body": "<p>Function-extraction time!</p>\n\n<pre><code>var tipTrick = function (input) {\n if (input) {\n return $.trim(input) + ',\\n';\n }\n return '';\n}\n</code></pre>\n\n<p>Then use it to your heart's content as:</p>\n\n<pre><code>tooltip += tipTrick(address.ShipTo);\n.....\n</code></pre>\n\n<p>You can actually do something similar (though more complicated) for the initial two conditions as well.... (<code>MasterAddress</code> and <code>PurchasingContact</code>) but for just those two cases, it may be simpler to leave as-is.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-02-05T13:26:38.260", "Id": "70185", "Score": "0", "body": "I would not use `address.PurchasingContact.Name` as an example, given your last paragraph." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-02-05T14:13:53.227", "Id": "70191", "Score": "0", "body": "I would also extract a function to check for undefined, null, and length 0, then reuse that. The code appears to have a lot of copy/paste, which is why it's so complex." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-02-05T14:27:23.007", "Id": "70197", "Score": "0", "body": "Yep, it's more maintainable too!" } ], "meta_data": { "CommentCount": "3", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-02-05T13:15:20.203", "Id": "40953", "ParentId": "40941", "Score": "3" } } ]
{ "AcceptedAnswerId": "40953", "CommentCount": "1", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-02-05T11:03:45.553", "Id": "40941", "Score": "1", "Tags": [ "javascript", "strings", "cyclomatic-complexity", "null" ], "Title": "Reducing cyclomatic complexity in a simple string concatenation" }
40941
<p>I am sorting 2 arrays of object like this, but I know this is very bad. Any good approach, like using each method like so? ( I tried, but using each, I am unable to return the object )</p> <pre><code>var O1 = [{'name':'one'}, {'name':'two'}, {'name':'three'}, {'name':'four'}, {'name':'five'}, {'name':'six'}]; var O2 = [{'name':'rat'}, {'name':'cat'}, {'name':'lion'}, {'name':'tiger'}, {'name':'dog'}, {'name':'horse'}]; var sorted1 = _.sortBy(O1, function(item){ return item.name; }) var sorted2 = _.sortBy(O2, function(item){ return item.name; }) console.log(sorted1, sorted2); </code></pre> <p><a href="http://jsfiddle.net/3gwebtrain/Qtskg/" rel="nofollow">Demo</a></p>
[]
[ { "body": "<p>There is nothing much inherently wrong with your code besides that you would want to extract that function so that you do not need to declare it twice:</p>\n\n<pre><code>function itemName( item ){\n return item.name;\n}\n\nvar sorted1 = _.sortBy(O1, itemName);\nvar sorted2 = _.sortBy(O2, itemName);\n\nconsole.log(sorted1, sorted2);\n</code></pre>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-02-05T14:19:33.550", "Id": "40958", "ParentId": "40942", "Score": "1" } }, { "body": "<p>Or you can do it without a function at all:</p>\n<blockquote>\n<p><a href=\"http://underscorejs.org/#sortBy\" rel=\"nofollow noreferrer\"><strong>sortBy</strong></a> _.sortBy(list, iterator, [context])</p>\n<p>Returns a (stably) sorted copy of list, ranked in ascending order by the results of running each value through iterator. <strong>Iterator may also be the string name of the property to sort by (eg. <code>length</code>).</strong></p>\n</blockquote>\n<pre><code>var sorted1 = _.sortBy(O1, 'name'),\n sorted2 = _.sortBy(O2, 'name');\n</code></pre>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-02-05T20:52:36.287", "Id": "41000", "ParentId": "40942", "Score": "2" } } ]
{ "AcceptedAnswerId": "41000", "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-02-05T11:12:52.190", "Id": "40942", "Score": "2", "Tags": [ "javascript", "sorting", "underscore.js" ], "Title": "How to sort two array of objects using Underscore.js?" }
40942
<p>I have a function which verifies the "Password" field and suggests the user to enter a <em>strong password</em>. I also have a label named "Password Strength", referring to the strength of a password (<em>very weak, weak, medium</em>, etc).</p> <p>I'm just wondering if there is a better way to re-write this code.</p> <p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false"> <div class="snippet-code"> <pre class="snippet-code-js lang-js prettyprint-override"><code>function chkPasswordStrength(txtpass,strenghtMsg,errorMsg) { var desc = new Array(); desc[0] = "Very Weak"; desc[1] = "Weak"; desc[2] = "Better"; desc[3] = "Medium"; desc[4] = "Strong"; desc[5] = "Strongest"; errorMsg.innerHTML = '' var score = 0; //if txtpass bigger than 6 give 1 point if (txtpass.length &gt; 6) score++; //if txtpass has both lower and uppercase characters give 1 point if ( ( txtpass.match(/[a-z]/) ) &amp;&amp; ( txtpass.match(/[A-Z]/) ) ) score++; //if txtpass has at least one number give 1 point if (txtpass.match(/\d+/)) score++; //if txtpass has at least one special caracther give 1 point if ( txtpass.match(/.[!,@,#,$,%,^,&amp;,*,?,_,~,-,(,)]/) ) score++; //if txtpass bigger than 12 give another 1 point if (txtpass.length &gt; 12) score++; strenghtMsg.innerHTML = desc[score]; strenghtMsg.className = "strength" + score; if (txtpass.length &lt; 6) { errorMsg.innerHTML = "Password Should be Minimum 6 Characters" errorMsg.className = "errorclass" } }</code></pre> <pre class="snippet-code-css lang-css prettyprint-override"><code>&lt;style type="text/css"&gt; .strength0 { width:200px; background:#B20E37; text-align: center; font-weight: bold; } .strength1 { width:200px; background:#D32847; text-align: center; font-weight: bold; } .strength2 { width:200px; background:#ff5f5f; text-align: center; font-weight: bold; } .strength3 { width:200px; background:#83D680; text-align: center; font-weight: bold; } .strength4 { background:#4dcd00; width:200px; text-align: center; font-weight: bold; } .strength5 { background:#399800; width:200px; text-align: center; font-weight: bold; } .errorclass { font-weight:bold; font-size: 10px; color: #4F080B; font-family: Arial, } &lt;/style&gt;</code></pre> <pre class="snippet-code-html lang-html prettyprint-override"><code>&lt;tr&gt; &lt;%= label "Password",:mandatory=&gt;true %&gt; &lt;td&gt; &lt;input id="user_password" type="password" size="30" name="user[password]" onkeyup="chkPasswordStrength(this.value,document.getElementById('strendth'),document.getElementById('error'))"&gt; &lt;/td&gt; &lt;td id="strendth" class="strength5"&gt;&lt;b&gt;Password Strength&lt;/td&gt; &lt;/tr&gt; &lt;tr&gt;&lt;td&gt;&lt;/td&gt;</code></pre> </div> </div> </p>
[ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-02-05T11:48:50.867", "Id": "70161", "Score": "0", "body": "binding using `onkeyup=` the way you are is the same as using `eval`." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-02-05T11:50:16.577", "Id": "70162", "Score": "9", "body": "Your logic is a little bit flawed. [The strength of a password is not necessarily defined by the character set it uses](http://security.stackexchange.com/questions/6095/xkcd-936-short-complex-password-or-long-dictionary-passphrase). So the password \"abcdE1$\" would yield a score of \"Strong\", while the password \"thisisaverylongpasswordbecause\" would only get a score of \"Better\", despite being *much* harder to bruteforce (and maybe also harder to acquire by \"looking over someones shoulder\")." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-02-05T12:02:09.610", "Id": "70164", "Score": "0", "body": "@Bobby Is there a way to combine all those characters(alphabets,special characters,numbers) into Regular Expression" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-02-06T05:27:45.020", "Id": "70324", "Score": "5", "body": "Obligatory: https://xkcd.com/936/" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-02-06T19:47:34.953", "Id": "70489", "Score": "0", "body": "Hi, I have removed the [tag:code-challenge] tag. That one is reserved for [specific posts](http://meta.codereview.stackexchange.com/a/1472/23788) (feel free to participate!)." } ]
[ { "body": "<blockquote>\n <p><strong><em>Dislcaimer:</strong> I'm not a security researcher and the following answer is compiled from my own, humble knowledge. The math is very basic and there are many things to consider, if in doubt, <a href=\"https://security.stackexchange.com/\">pay Security a visit</a>. Also there are many factors that can kill password security completely, for example the user themselves or social engineering.</em></p>\n</blockquote>\n\n<p>In this case I'm not reviewing the code, but I'm reviewing your program logic.</p>\n\n<h2>A short talk about password security</h2>\n\n<p>Let's first define the rules you use (the term \"special chars\" here for further on refers to the set <code>!@#$%^&amp;*?_~-()</code>):</p>\n\n<ul>\n<li>Password length > 6: 1 Point</li>\n<li>Password length > 12: 1 Point</li>\n<li>Password contains at least one lower and one upper case letter: 1 Point</li>\n<li>Password contains at least one digit: 1 Point</li>\n<li>Password contains at least one of the special chars: 1 Point</li>\n</ul>\n\n<p>Your scale goes from 0 (Very Weak) to 5 (Strongest). That means a password based on length can never go beyond 2 (Better), but a short password can be 4 (Strong). <a href=\"https://security.stackexchange.com/questions/6095/xkcd-936-short-complex-password-or-long-dictionary-passphrase\">This is bad if we keep in mind that strong passwords do not necessarily use a broad character set</a>.</p>\n\n<p>The following passwords are considered Strong by your algorithm:</p>\n\n<ul>\n<li>abcdE$1</li>\n<li>qwert!1</li>\n<li>1111Aa@</li>\n</ul>\n\n<p>Now these do not look like strong ones to me, let's have a look at how many possible combinations such a password has. The total character set for these passwords is 26 (lower) + 26 (upper) + 10 (digits) + 14 (special) = 76.</p>\n\n<blockquote>\n <p>76^7 = ~1.4 * 10^13 = ~14 trillion</p>\n</blockquote>\n\n<p>So an attacker which knows the character set and the length of the password, has to search roughly 14 trillion combinations until they find the password. Though, that is the worst case scenario, could be that they find it on the third try, but could be that it is the next to the last. Todays computers can do more then 500 million guesses per second, that's roughly 8 hours...this can not be considered secure in any way.</p>\n\n<p>Let's have a look at the other side of the spectrum, the following password is only considered Better:</p>\n\n<blockquote>\n <p>thisisaverylongpasswordbecause (This is a very long password because)</p>\n</blockquote>\n\n<p>It only has a character set of 26 and a length of 30 (the maximum for your system if I've seen this correctly).</p>\n\n<blockquote>\n <p>26^30 = ~ 2.8 * 10^42 = ~2.8 tredecillion</p>\n</blockquote>\n\n<p>I have <em>no</em> idea what that number is supposed to mean, <a href=\"http://www.wolframalpha.com/input/?i=2813198901284745919258621029615971520741376&amp;lk=1&amp;a=ClashPrefs_*Math-\" rel=\"noreferrer\">so let's compare it</a>. Okay, that doesn't help either...maybe if we put it into a timeframe, 500 million guesses per second again:</p>\n\n<blockquote>\n <p>~1.8 * 10^26 <strong>years</strong></p>\n</blockquote>\n\n<p>That's actually good news! That's well before the heat death of the universe.</p>\n\n<p>So, less nonsense, more talk: What's going on here?</p>\n\n<p>The strength of a password can not reliable be defined. But we know two things:</p>\n\n<ol>\n<li>The longer it is, the more combinations you have to go through.</li>\n<li>The more different characters it uses, the more combinations you have to go through.</li>\n</ol>\n\n<p>The difference is that one adds to the <em>base</em>, and the other to the <em>exponent</em>. A higher exponent weighs in heavier than a higher base and yields more total combinations. So whenever possible <a href=\"http://en.wikipedia.org/wiki/Passphrase\" rel=\"noreferrer\">use a passphrase instead of a password</a>.</p>\n\n<p>Despite being, seemingly, vulnerable to dictionary attacks, the <a href=\"http://en.wikipedia.org/wiki/Oxford_dictionary\" rel=\"noreferrer\">Oxford Dicitonary</a> holds 300 thousand main entries, so if we have a passphrase of 4 words, that's:</p>\n\n<blockquote>\n <p>300000^4 = 8.1 * 10^21</p>\n</blockquote>\n\n<p>And that does not take into account possible misspellings, if the words start uppercase, lowercase or mixed and different languages.</p>\n\n<p>Make the users favor passphrases and long, easier to remember passwords then complicated short ones.</p>\n\n<h2>Sell it as a feature!</h2>\n\n<p>This will make your marketing department happy, you just implemented support for the more secure passphrases into your software! Let your users know about it by simply adding a short information to the password box:</p>\n\n<blockquote>\n <p>We support passphrases up to a length of XX characters!</p>\n \n <p>Passphrases are more secure and easier to remember than ordinary passwords.</p>\n</blockquote>\n\n<p>And some short information about how to \"create\" one, and drop any indicator if the password is secure or not.</p>\n\n<h2>Who you can and can't help</h2>\n\n<p>There are quite many user groups out there, the question is who you want to reach with this help. Let's define three groups:</p>\n\n<ul>\n<li>The \"average user\", which does not understand why they need to press a button labeled \"Delete\" to delete something.</li>\n<li>The normal user, always ready to learn and looks beyond their own nose.</li>\n<li>The technical user, already uses a password manager and/or passphrases.</li>\n</ul>\n\n<p>No matter how hard you try, you will not be able to help the \"average user\". If you tell them to use a password of minimum length 6, they will use \"123456\" or \"asdfgh\". If you tell them to use a password of minimum length 12, they will use \"asdfghjkzxcvbn\" or \"000000000001\". They are beyond hope and will <em>actively</em> workaround security measures you implement. Just let 'em be.</p>\n\n<p>The \"normal user\" on the other hand is ready to learn something new, telling them about passphrases and that you support them will make them want to use passphrases. If your small help text and the rest of the system in that moment is helpful, they will use a passphrase which is not something absolutely stupid.</p>\n\n<p>The \"technical user\" will be pleased that you support a XX length password and passphrases. They most likely already use a strong and random password and a password manager or passphrases, but that you don't limit them in any way will make them happy.</p>\n\n<h2>Secure passwords stored insecure are insecure</h2>\n\n<p>It doesn't matter how good the password or passphrase is, if <em>you</em> fail to store in a secure manner, they are insecure.</p>\n\n<p>We will completely leave out social engineering or \"harmful\" users (there are people after all who have their creditcard PIN on a note in the same wallet), we can't help them.</p>\n\n<p>But what is important that if somebody manages to break into your server and manage to copy the user database, they must <em>not</em> have access to all accounts. This is achieved by <a href=\"https://security.stackexchange.com/questions/211/how-to-securely-hash-passwords\">simply hashing the passwords with an appropriate method</a>. Even if the attacker now has all the usernames and e-mail addresses, the passwords are still safe.</p>\n\n<p>It will also make the marketing department happy that, despite you've been hacked, they can tell the users that their accounts are still safe (password change advised, obviously).</p>\n\n<p>The great news is, if you hash the passwords there's absolutely no reason to limit password length at all! They will all end up as the same length hash in your database, so you can let me use that sentence from that book as a passphrase.</p>\n\n<h2>Ask the right people the right questions</h2>\n\n<p>Last but not least, defining what is a strong password depends on many things. If in doubt, pay the people <a href=\"https://security.stackexchange.com/\">over at Security a visit</a>, that's what they're there for.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-02-05T15:13:40.233", "Id": "70209", "Score": "3", "body": "It should be noted that the special character check is poor. There are many *many* more types of special characters out there than what's available on a typical western keyboard. It would be better to check that there are alphanumeric characters, rather than check for specific non-alphanumeric characters." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-02-05T21:04:52.797", "Id": "70262", "Score": "2", "body": "shouldn't length be mostly what matters for password security? i don't see how special characters/case makes passwords more robust vs brute force/etc... (queue reference to the relevant XKCD everyone has seen)." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-02-06T04:42:49.080", "Id": "70317", "Score": "0", "body": "@Bobby Thank you for your great logical answer.I'd love to see your logic in to a code!" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-02-06T08:11:55.093", "Id": "70342", "Score": "0", "body": "@HC_: I tried to get exactly that across, did I fail at that?" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-02-06T09:20:15.513", "Id": "70356", "Score": "1", "body": "@Pavan: Getting this into code is *hard*. [There are many](http://security.stackexchange.com/questions/6499/best-password-strength-checker) [question on Securiy](http://security.stackexchange.com/questions/2687/how-reliable-is-a-password-strength-checker) [about this](http://security.stackexchange.com/questions/26748/does-the-password-you-use-to-sign-into-a-vpn-determine-the-strength) [very topic](http://security.stackexchange.com/questions/4630/how-can-we-accurately-measure-a-password-entropy-range)." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-02-06T09:33:06.783", "Id": "70361", "Score": "0", "body": "@Pavan: Long story short: It's complicated. If I'd be in your shoes I'd include a descriptive paragraph about why the user should use passphrases and move on. You can't reliable check the strength of a password and there *will* be users which will actively work around your measures (\"oh, it wants a long password, 1234567890 will do!\")." } ], "meta_data": { "CommentCount": "6", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-02-05T12:29:45.963", "Id": "40950", "ParentId": "40944", "Score": "53" } }, { "body": "<p>As mentioned by Tim Seguine do not use <code>onkeyup</code>, instead use <code>addEventListener</code> and <code>attachEvent</code> if you need to support older IE versions.</p>\n\n<p>Furthermore : <code>chkPasswordStrength(txtpass,strenghtMsg,errorMsg)</code> is unfortunately named, you disemvoweled <code>check</code> for no good reason, <code>txtpass</code> could simply be <code>password</code> and your 2 <code>Msg</code> parameters are not messages as one might think, but DOM elements instead..</p>\n\n<p>You are initially clearing <code>errorMsg.innerHTML</code>, but you are not resetting the <code>className</code>, I would:</p>\n\n<pre><code> if (txtpass.length &lt; 6)\n {\n errorMsg.innerHTML = \"Password Should be Minimum 6 Characters\";\n errorMsg.className = \"errorclass\";\n }\n else\n {\n errorMsg.innerHTML = \"\";\n errorMsg.className = \"\";\n }\n</code></pre>\n\n<p>Also, I would write</p>\n\n<pre><code> var desc = new Array();\n desc[0] = \"Very Weak\";\n desc[1] = \"Weak\";\n desc[2] = \"Better\";\n desc[3] = \"Medium\";\n desc[4] = \"Strong\";\n desc[5] = \"Strongest\";\n</code></pre>\n\n<p>as </p>\n\n<pre><code>var strengths = ['Very weak','Weak','Better','Medium','Strong','Strongest'];\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-02-05T15:10:52.330", "Id": "70206", "Score": "0", "body": "I disagree with the last, though, why not simply `var desc = new Array(\"Very Weak\", \"Weak\", ...);`. That is easier to read as you do not need to read to the end of the line to know that `desc` is now an array...which is an unfortunate name, too." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-02-05T15:13:11.993", "Id": "70208", "Score": "3", "body": "So true on the name!@! Though to even go further, I guess with only 6 entries I could go for `['','']`" } ], "meta_data": { "CommentCount": "2", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-02-05T15:04:44.400", "Id": "40967", "ParentId": "40944", "Score": "15" } }, { "body": "<p>You're repeating a lot of CSS. Let's fix that by using your <code>#strength</code> ID.</p>\n\n<pre><code>&lt;style type=\"text/css\"&gt;\n#strength {\n width: 200px;\n text-align: center;\n font-weight: bold;\n}\n\n.strength0 {\n background-color: #B20E37;\n}\n\n.strength1 {\n background-color: #D32847;\n}\n\n.strength2 {\n background-color: #ff5f5f;\n}\n\n.strength3 {\n background-color: #83D680;\n}\n\n.strength4 {\n background-color: #4dcd00;\n}\n\n.strength5 {\n background-color: #399800;\n}\n\n.errorclass {\n font-size: 10px;\n font-family: Arial;\n font-weight: bold;\n color: #4F080B;\n}\n&lt;/style&gt;\n</code></pre>\n\n<p><strong>Notes:</strong></p>\n\n<ul>\n<li>Please check your rule for <code>.errorclass</code> again. Your <code>font-family</code> declaration ends with a <code>,</code> instead of a <code>;</code>.</li>\n<li>In my opinion, one should always leave a space between <code>:</code> value and property declarations. It simply improves readability. </li>\n<li>Be aware when using the shorthand of a property. An example of what could happen: If you write <code>background: red;</code>, this doesn't only set the <code>background-color</code> to red. It also applys the default values for the other properties available in the shorthand syntax (<code>background-image</code>, <code>background-repeat</code>, ...)</li>\n</ul>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-02-05T17:45:03.413", "Id": "70237", "Score": "0", "body": "\"you would also overwrite any background-image declarations you made earlier and so on\" Ignoring the fact that the OP is not using images, what if that's the point? Using shorthand, even if it is for a single value, is shorter than using the longhand. \"It's a good practise to always leave a space between : and value und property declarations\" this is nonsense, it is valid either way." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-02-05T19:30:47.700", "Id": "70250", "Score": "0", "body": "@cimmanon I edited my answer to word these things better. Better?" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-02-06T03:42:20.677", "Id": "70310", "Score": "1", "body": "@cimmanon Prudent whitespace makes for a happy space." } ], "meta_data": { "CommentCount": "3", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-02-05T16:57:46.633", "Id": "40980", "ParentId": "40944", "Score": "14" } }, { "body": "<p>You have 1 check (less than 6 characters) which gives an error, but you execute it AFTER all the non-error checks. This means that if I make a password 12345, it's going to give me 1 point even though it's completely invalid for this purpose.</p>\n\n<p>You should move that check before all the rest and return if it fails, because right now you're just wasting valuable processor speed if the password is less than 6 characters.</p>\n\n<p>apart from that, you give 1 point if it's above 6 characters, but you give an error if it's below that. so either they have a point or they get an error. so you can't have 0 points. why then have a category for 0?</p>\n\n<p>Finally, you're embedding DOM element retrievals into your function call in the HTML, which should be avoided. I would just pass the name of the elements and do the DOM retrieval in the function itself.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-02-06T13:10:00.337", "Id": "70382", "Score": "0", "body": "No, it's not \"valuable processor speed\" until you have proven than it is. It simply makes more sense to make the check early: it's one mental check that you don't have to do when reading the rest of the code." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-02-06T13:28:05.390", "Id": "70384", "Score": "0", "body": "It might not be valuable, but you're still wasting processor time for doing those checks if they're not needed. You should always have your checks that break or prevent functionality first so the code can continue right on if the checks return false. If you're first processing it all and then checking \"oh, I need to fail if X\", you're spending processing time on obsolete processes. If you got a bunch of those, the program appears to respond marginally slower, which detracts from user experience." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-02-06T13:49:57.050", "Id": "70387", "Score": "0", "body": "I also agree that you should do those checks first, but for readability reasons. Micro optimizations are often worthless, measure the gain before saying \"it's faster\". There's no way for a user to notice any difference between those two versions of `chkPasswordStrength`." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-02-06T14:19:01.997", "Id": "70397", "Score": "1", "body": "Yes, the performance gain is unnoticable. maybe I shouldn't have mentioned that. but still, even if you wouldn't do it for the performance gain, you should still do it for non-readability reasons, even if that reason is just getting familiar with best practices. While there are no severely delaying checks in this code, other code might have those (like database or service calls). Being familiar with the concept of optimal path in trivial cases means you're used to it in non-trivial cases as well, and are more likely to use it." } ], "meta_data": { "CommentCount": "4", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-02-06T09:27:51.763", "Id": "41049", "ParentId": "40944", "Score": "6" } }, { "body": "\n\n<p>Bobby delivered an excellent answer about password strength, so I will focus on the code.</p>\n\n<h3>Reg ex</h3>\n\n<p>You have the following regular expression:</p>\n\n<pre class=\"lang-js prettyprint-override\"><code>/.[!,@,#,$,%,^,&amp;,*,?,_,~,-,(,)]/\n</code></pre>\n\n<p>It matches one non-line-break character followed by any of the following characters <code>!,@,#,$,%,^,&amp;,*,?,_,~</code>, or a character in the range comma to comma, or any of the following <code>(,)</code>. You repeat comma as if it were a separator. A character class need no separators, so putting a comma in a character class simply means that it will match comma. A dash on the other hand has a special meaning in a character class, so you will need to escape it if you want a character class to contain a dash.</p>\n\n<p>In general I would recommend escaping all special characters in regular expressions if you want to use their literal value, it helps you to avoid mistakes like this dash, and makes the intention clearer.</p>\n\n<p>In the context it seems strange that you include so few characters in a special character class. For this feature it seems logical to simply define special characters as anything not in the other character classes:</p>\n\n<pre class=\"lang-js prettyprint-override\"><code>/[^A-Za-z0-9]/\n</code></pre>\n\n<p>Alternately if you for some reason want only <a href=\"http://en.wikipedia.org/wiki/ASCII#ASCII_printable_characters\">the basic printable ASCII special characters</a> you can easily include them all using ranges (use a character map to find such ranges):</p>\n\n<pre class=\"lang-js prettyprint-override\"><code>/[\\ -\\/\\:-\\@\\[-\\`\\{-\\~]/\n</code></pre>\n\n<p>Here's a short explanation on how this works:</p>\n\n<pre class=\"lang-js prettyprint-override\"><code>/[ // start of the expression/range\n \\ -\\/ // All characters from \" \" to \"/\"\n \\:-\\@ // All characters from \":\" to \"@\"\n \\[-\\` // All characters from \"[\" to \"`\"\n \\{-\\~ // All characters from \"{\" to \"~\"\n]/ // end the range/expression\n</code></pre>\n\n<h3>Function call</h3>\n\n<p>You have the following in your HTML:</p>\n\n<pre class=\"lang-js prettyprint-override\"><code>&lt;input id=\"user_password\" type=\"password\" size=\"30\" name=\"user[password]\" onkeyup=\"chkPasswordStrength(this.value,document.getElementById('strendth'),document.getElementById('error'))\"&gt;\n</code></pre>\n\n<p>Some people would like to avoid such inline code altogether, personally I don't think it is a big deal whether or not to inline a simple function call, but including all those parameters is a bit of an eyesore, and there is really no reason to have them, your function could easily fetch the same info itself.</p>\n\n<p>Another thing to consider is that there is no guarantee that the <code>keyup</code> event will fire just because something was entered into the field. That would for instance not be the case if something was mouse-pasted into the field, and I'm not sure that you can rely on <code>keyup</code> to fire on all devices that use screen keyboards. In any case I'd double-guard a live field validation function by also having it fire on the <code>change</code> event.</p>\n\n<h3>Clean tables</h3>\n\n<p>I'm not sure exactly what that Rails label does, but if anything is rendered in its place the result is most likely illegal HTML, and therefore possibly inconsistent browser behaviour. You can enclose a complete table in another element, or you can put an element inside a single <code>td</code> or <code>th</code> element. Anything in-between is generally not allowed.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-02-06T12:24:47.113", "Id": "41061", "ParentId": "40944", "Score": "11" } } ]
{ "AcceptedAnswerId": "40950", "CommentCount": "5", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-02-05T11:33:19.137", "Id": "40944", "Score": "54", "Tags": [ "javascript", "css", "validation" ], "Title": "Verifying password strength using JavaScript" }
40944
<p>Recently I set about to writing conversion functions in Haskell between decimal and <a href="http://en.wikipedia.org/wiki/Negabinary" rel="nofollow">negabinary</a>. I tried to write them in as much functional a style as possible, also aiming at brevity. Below I present my take at the task. I'd be interested in your refinements of the method I employ or any comments whatsoever.</p> <p>These are my two functions for converting back and forth:</p> <pre><code>type NegaBinary = String dec2negbin :: Int -&gt; NegaBinary dec2negbin = reverse . map intToDigit . unfoldr (\x -&gt; if x==0 then Nothing else Just(abs(xrem x (-2)), xdiv x (-2))) where xrem a b = if b &gt; 0 then rem a b else (-(rem a (-b))) xdiv a b = if b &gt; 0 then div a b else (-(div a (-b))) negbin2dec :: NegaBinary -&gt; Int negbin2dec = sum . map (\x -&gt; (snd x)*(-2)^(fst x)) . zip [0..] . reverse . map digitToInt </code></pre> <p>I defined the <code>NegaBinary</code> type just for clarity. The <code>dec2negbin</code> employs the <code>unfoldr</code> function for sequential divisions and remainder calculations. I also used two local functions: <code>xrem</code> and <code>xdiv</code>, because the standard functions (<code>rem</code> and <code>div</code>) had the undesirable behavior of always approaching the dividend from below (meaning that in <code>div a b =&gt; c</code> <code>b*c</code> is always lower than <code>a</code>). What I wanted is for it to approach in the direction <em>from</em> zero, so the behavior is different for positive and negative dividends. I know the definition of <code>dec2negbin</code> is a bit bulky, so improvements are welcome.</p>
[]
[ { "body": "<p>A couple of things I noticed:</p>\n\n<p>xrem and xdiv are exactly the same except they use a different division function. You could therefore replace them with a single function that takes the type of division as a parameter:</p>\n\n<pre><code>dec2negbin :: Int -&gt; NegaBinary\ndec2negbin = reverse .\n map intToDigit .\n unfoldr (\\x -&gt; if x==0 then Nothing else Just(abs(doDiv rem x (-2)), doDiv div x (-2)))\n where\n doDiv division a b = if b &gt; 0 then division a b else (-(division a (-b)))\n</code></pre>\n\n<p>In your second function you could use <a href=\"http://hackage.haskell.org/package/base-4.6.0.1/docs/Prelude.html#v%3azipWith\" rel=\"nofollow\">zipWith</a> which applies a given function whilst zipping instead of doing a zip then a map:</p>\n\n<pre><code>negbin2dec :: NegaBinary -&gt; Int\nnegbin2dec = sum . zipWith raise [0..] . reverse . map digitToInt\n where\n raise e x = x * (-2) ^ e\n</code></pre>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-02-21T18:48:08.147", "Id": "42452", "ParentId": "40949", "Score": "1" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-02-05T12:11:32.597", "Id": "40949", "Score": "5", "Tags": [ "haskell", "functional-programming", "converting", "integer" ], "Title": "Conversion from decimal to negabinary and vice versa in Haskell" }
40949
<p>Aim: Import Excel to SQL</p> <p>Potential Issue: </p> <p>Wrong file type - this is handled in the 'upload' button by not allowing anything but *.xlsx files. The wrong type of Excel file (i.e. not 2003 onwards) would be good to be able to handle this as well.</p> <p>Notes:</p> <p>The below code does work. What I am always looking for it improvements. I have not put in any character checking to the below code but it would be there as required.</p> <pre class="lang-vbs prettyprint-override"><code>Dim oleda As New OleDbDataAdapter() Dim ds As New DataSet() Dim cmd As New OleDbCommand() Dim strServerConnection As [String] = ConfigurationManager.ConnectionStrings("SQLLocal").ConnectionString Dim vFileName As String = FileUpload1.PostedFile.FileName Dim uploadFolder As String = "C:\sites\Examples\CSVUpload\File\" &amp; vFileName FileUpload1.SaveAs(Server.MapPath(Convert.ToString("~/UploadedExcel/") &amp; vFileName)) Dim excelConnectionString As String = (Convert.ToString("Provider=Microsoft.ACE.OLEDB.12.0; Data Source=") &amp; uploadFolder) + "; Extended Properties='Excel 12.0;HDR=YES;IMEX=1;';" Dim excelConnection As New OleDbConnection(excelConnectionString) cmd.CommandText = "Select [name],[address],[phone] from [Sheet1$]" cmd.CommandType = CommandType.Text cmd.Connection = excelConnection excelConnection.Open() oleda = New OleDbDataAdapter(cmd) oleda.Fill(ds, "dataExcel") If ds.Tables("dataExcel").Rows.Count &gt; 0 Then For i As Integer = 0 To ds.Tables("dataExcel").Rows.Count - 1 ds.Tables("dataExcel").Rows(i)("name") = ds.Tables("dataExcel").Rows(i)("Name") ds.Tables("dataExcel").Rows(i)("address") = ds.Tables("dataExcel").Rows(i)("Address").ToString().ToLower().Trim() 'Check characters here with App_code and variable ds.Tables("dataExcel").Rows(i)("phone") = ds.Tables("dataExcel").Rows(i)("Phone").ToString().ToLower().Trim() Next End If Dim sqlBulk As New SqlBulkCopy(strServerConnection) sqlBulk.BatchSize = 150 sqlBulk.BulkCopyTimeout = 600 'Give your Destination table name sqlBulk.DestinationTableName = "dbo.PersonRecord" 'map the columns.... sqlBulk.ColumnMappings.Clear() sqlBulk.ColumnMappings.Add("Name", "Name") sqlBulk.ColumnMappings.Add("Address", "Address") sqlBulk.ColumnMappings.Add("Phone", "Phone") 'write to db sqlBulk.WriteToServer(ds.Tables("dataExcel")) End Sub </code></pre>
[]
[ { "body": "<p>I'd suggest modularizing it, breaking it up into a few smaller functions that each do a small piece of the task. You might have one routine to open the file, one routine to establish the Excel connection, one to \"canonicalize\" the data (where you're fixing the Excel data), and one to write the data into the SQL database.</p>\n\n<p>If you break it into smaller functions, each function can then take on appropriate responsibilities, particularly around error handling. Your OpenUserSpreadsheet() function could do checking on the file name, making sure the user's file is of the right type, version, etc. Your OpenExcelConnection() would make sure that the dataset is correct, your NormalizeUserData() function would convert the case of the data and do the string trimming, and so on. </p>\n\n<p>Once you have the code in smaller modules, you'll find its easier to think about the appropriate tasks related to each. You might look at your new WriteToSQL() and say \"oh, I wonder what if the column name is wrong? What if the table name is not found? What if I can't log on?\" A smaller module dedicated to SQL makes you focus only on SQL problems. You can then do this across all your code making small, specific improvements without the distraction of \"what do I need to do with all the things in all of this code?\"</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-02-05T14:06:34.347", "Id": "40956", "ParentId": "40952", "Score": "1" } } ]
{ "AcceptedAnswerId": "40956", "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-02-05T13:12:15.683", "Id": "40952", "Score": "1", "Tags": [ "sql", "asp.net", "excel" ], "Title": "Excel to SQL Upload" }
40952
<p>I wrote a function <code>split-seq-by-n</code> which accepts a sequence and a number and splits the sequence into subsequences of length n (the last subsequence getting the remaining elements). It works on all subclasses of <code>'sequence</code>, among others <code>'string</code>, <code>'cons</code>, <code>'vector</code> etc.</p> <pre><code>;; Splits sequence into subsequences of length n (defun split-seq-by-n (seq n) (labels ((seq-split (seq n &amp;optional acc orig-n) (cond ((zerop (length seq)) (nreverse acc)) ((zerop n) (seq-split seq orig-n (cons (subseq seq 0 0) acc) orig-n)) (t (seq-split (subseq seq 1) (1- n) (cons (concatenate (class-of seq) (if acc (car acc) (subseq seq 0 0)) (list (elt seq 0))) (cdr acc)) orig-n))))) (seq-split seq n nil n))) </code></pre> <p>Any comments, improvements, critiques welcome.</p>
[]
[ { "body": "<p>It looks okay for a recursion exercise, but it's naive code. Not usable in 'production'.</p>\n\n<ul>\n<li>it conses like mad. It creates a lot of intermediate garbage. Splitting a string involves making lots of smaller strings.</li>\n<li>for lists it is not efficient, too</li>\n<li>CONCATENATE in loops or recursive functions is a code smell</li>\n<li>the recursive implementation with the subroutine is good style in a functional language, but makes it hard to debug in the real world. For example, how do you TRACE the internal function?</li>\n<li>Common Lisp does not guarantee tail call optimization (TCO). Individual implementations do support it. Still, for general portable code it might be preferable to code loop.</li>\n</ul>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-02-10T13:06:09.347", "Id": "41330", "ParentId": "40954", "Score": "4" } }, { "body": "<p>When writing functions for manipulating sequences, it's typically easier to write a version that handles the list case specially, and then uses the generic sequence functions for everything else (since they'll probably be fine for vectors). Taking that approach, I'd write the following code. The main interface, <code>split-seq-by-n</code> takes the sequence and the <code>n</code>, and calls either <code>split-list-by-n</code> (optimized for lists) or <code>split-sequence-by-n</code> (which works for generic sequences, and so is probably efficient for vectors):</p>\n\n<pre><code>(defun split-seq-by-n (sequence n)\n (if (listp sequence) \n (split-list-by-n sequence n)\n (split-sequence-by-n sequence n)))\n\n(defun split-sequence-by-n (sequence n)\n (loop \n :with length := (length sequence)\n :for start :from 0 :by n :below length\n :collecting (subseq sequence start (min length (+ start n)))))\n\n(defun split-list-by-n (list n)\n (do ((nn (1- n) (1- nn))\n (part '())\n (parts '()))\n ((endp list) \n (nreverse (if (endp part) parts\n (list* (nreverse part) parts))))\n (push (pop list) part)\n (when (zerop nn)\n (push (nreverse part) parts)\n (setf part '()\n nn n))))\n</code></pre>\n\n<p>Since the generic sequence functions should be fine for sequences that support random indexing, <code>split-sequence-by-n</code> is pretty straightforward. The only bit that's a little complex it caching the length at first so that we have a maximum value for the <code>end</code> value in <code>subseq</code>. <code>split-list-by-n</code> is a bit more complex. It iterates over the list just once, allocating only as much new structure as is strictly necessary. </p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-03-11T23:37:39.867", "Id": "76385", "Score": "0", "body": "that's nice. I particularly like your use of `list*` instead of `cons`." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-03-11T23:55:38.853", "Id": "76388", "Score": "0", "body": "@WojciechGac When I'm working with conses as lists, I use `first`, `rest`, and `list*`. When I'm working with them as trees, I use `car`, `cdr`, and `cons`." } ], "meta_data": { "CommentCount": "2", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-03-11T22:19:19.813", "Id": "44108", "ParentId": "40954", "Score": "3" } }, { "body": "<p>Your code works but has some efficieny problems, as already <a href=\"https://codereview.stackexchange.com/a/41330/37033\">pointed out by Rainer Joswig</a> (\"it conses like mad\"). Now that you posted a modified version I added some details at the end of the answer. </p>\n\n<h3>Alternative approach</h3>\n\n<p>I like <a href=\"https://codereview.stackexchange.com/a/44108/37033\">Joshua Taylor's answer</a> because it is both efficient and simple.\nHowever, I'd like to take another approach and define <code>split-n</code> efficiently (by, e.g. avoiding whenever possible needless memory allocation) while providing <strong>more control</strong> to the programmer over the function's behavior (like standard functions and macros in Common Lisp generally do; e.g. <code>eof-error-p</code> in <code>read-line</code>, <code>:test</code>, <code>:key</code> and <code>:from-end</code> arguments, etc.).</p>\n\n<p><a href=\"http://pastebin.com/ubtgUsd4\" rel=\"nofollow noreferrer\">All the following code can be found here.</a></p>\n\n<h3>Design</h3>\n\n<p>This was unexpected:</p>\n\n<blockquote>\n <p>the last subsequence getting the remaining elements</p>\n</blockquote>\n\n<p>I agree that this behavior might be desirable, but I think the expected property of the split function would be to return sequences <em>having no more than <code>n</code> elements</em>. We can see that this is the behavior of <a href=\"https://github.com/TBRSS/serapeum/blob/master/reference.md#batches-seq-n-key-start-end\" rel=\"nofollow noreferrer\"><code>serapeum:batches</code></a>, which is another interesting implementation to read.</p>\n\n<p><strong>I'd rather have <code>split-n</code> let me choose what to do with the remaining parts. That's why I add a <code>:last</code> argument which may take the following values</strong>:</p>\n\n<ul>\n<li><code>:undersized</code>: have a last group with fewer elements</li>\n<li><code>:oversized</code>: join the remaining elements with the preceding group (what you want)</li>\n<li><code>:truncated</code>: discard the remaining elements and return them as another value</li>\n</ul>\n\n<p>The default value when no argument is given, or when <code>T</code> or <code>NIL</code> are given, would be what I consider the least suprising option, namely <code>:undersized</code>. I think <code>:truncate</code> should be asked for explicitely because it changes the expected return values.</p>\n\n<p><strong>Moreover, the function can be used in more circumstances if we have a way to allow (resp. disallow) the resulting parts from sharing data with the original sequence</strong>. This can be controlled by a boolean <code>:sharedp</code> argument (see e.g. <a href=\"http://weitz.de/cl-ppcre/\" rel=\"nofollow noreferrer\"><code>CL-PPCRE</code></a>). </p>\n\n<p>For example, splitting an array into sub-arrays of <code>n</code> elements could possibly return displaced arrays: any modification to the original element would be visible in the corresponding sub-array, and inversely.</p>\n\n<p>Likewise, it may be desirable that an original list and the splitted lists share a common tail: imagine a queue where a producer adds elements to the end of the queue, and a consumer function extracts elements by batches of <code>n</code> elements; the following call:</p>\n\n<pre><code>(split-n queue n :last :truncated :sharedp t)\n</code></pre>\n\n<p>... would grab a lists of sequences of size <code>n</code>, and the remaining elements returned as a second value would be the new head of the queue, the tail being left untouched.</p>\n\n<p><strong>Finally, we may want to control the type of the output sequence, as suggested in comments</strong>. For now, the accepted result type is either <code>list</code> or <code>vector</code>. We could also pass a function designator so that we can feed directly a consumer with the subsequences instead of collecting them first (see <code>do-batches</code> <a href=\"http://pastebin.com/raw.php?i=ubtgUsd4\" rel=\"nofollow noreferrer\">in the pasted code</a>).</p>\n\n<h3>Return values</h3>\n\n<p><code>split-n</code> returns 2 values:</p>\n\n<ol>\n<li><p>a list of non-empty subsequences of sequence</p>\n\n<ul>\n<li>if <code>:last</code> is <code>:undersized</code>, the only subsequence that may not have exactly <code>n</code> elements is the last subsequence; if so, it contains 1 or more elements but less than <code>n</code>.</li>\n<li>if <code>:last</code> is <code>:oversized</code>, all subsequences but the last have exactly <code>n</code> elements; the last subsequence can contain <em>fewer</em> or <em>more</em> than <code>n</code> elements (fewer if <code>n</code> is larger than the size of the original sequence; more if the size is larger but not exactly divisible by <code>n</code>).</li>\n<li>if <code>:last</code> is <code>:truncated</code>, all returned subsequences have exactly <code>n</code> elements</li>\n</ul></li>\n<li><p>A generalized boolean which indicates whether there were remaining elements:</p>\n\n<ul>\n<li>if <code>NIL</code>, the original sequence was evenly split.</li>\n<li><p>otherwise, the value depends on the <code>:last</code> argument:</p>\n\n<ul>\n<li>if <code>:truncated</code>, the secondary value is a list of at most <code>n-1</code> elements not included in the primary list.</li>\n<li>otherwise, the secondary value is the size of the last element in the primary sequence: it is necessarly lower than <code>n</code> when <code>:last</code> is <code>:undersized</code>, and different than <code>n</code> when <code>:last</code> is <code>:oversized</code>.</li>\n</ul></li>\n</ul></li>\n</ol>\n\n<h3>Remarks</h3>\n\n<p>In a previous version, I used <a href=\"https://github.com/TBRSS/serapeum/blob/master/reference.md#collecting-body-body\" rel=\"nofollow noreferrer\"><code>serapeum:collecting</code></a> but since we are interested in having different possible return types (list or vectors), I wrote little helper functions to collect elements. </p>\n\n<pre><code>(defparameter *pouch* nil)\n\n(defun queue-collector ()\n (let ((q (serapeum:queue)))\n (cons\n (lambda (x) (serapeum:enq x q))\n (lambda () (serapeum:qlist q)))))\n\n(defun vector-collector (size)\n (let ((v (make-array size :fill-pointer 0 :adjustable nil)))\n (cons\n (lambda (x) (vector-push x v))\n (lambda () v))))\n\n(defun take (value &amp;optional (cons *pouch*))\n (funcall (car cons) value))\n\n(defun loot (&amp;optional (cons *pouch*))\n (funcall (cdr cons)))\n\n(defun call-while-hoarding (function &amp;key (result-type 'list) size)\n (let ((*pouch* (ecase result-type\n (list (queue-collector))\n (vector (if size\n (vector-collector size)\n (unbounded-vector-collector))))))\n (funcall function)))\n\n(defmacro hoarding ((&amp;rest args) &amp;body body)\n ;; parse: name is optional\n (let* ((name-p (not (keywordp (first args))))\n (args (if name-p (cdr args) args))\n (name (when name-p (car args))))\n `(funcall #'call-while-hoarding\n (lambda ()\n ,@(if name\n `((let ((,name *pouch*)) ,@body))\n body))\n ,@args)))\n</code></pre>\n\n<p>The <code>hoarding</code> macro binds a new collector in the special variable <code>*pouch*</code>, which is a <code>cons</code> of two closures: one to collect elements, the other to retrieve all collected elements. Those closures are respectively called by helper functions, <code>take</code> and <code>loot</code>. </p>\n\n<p>Contrary to <code>serapeum:collecting</code>, collectors can be named and specialized on the return type. Unfortunately, the <code>return-type</code> option is not as smart as the one for <a href=\"http://www.lispworks.com/documentation/HyperSpec/Body/f_mapc_.htm\" rel=\"nofollow noreferrer\"><code>map</code></a> which accepts type specifier with element types and sizes. Here, the expected size can be specified too, but no check is done to ensure that <code>(loot)</code> returns a collection of the expected size (we can call <code>(loot)</code> multiple times, after all).</p>\n\n<h3>Main function</h3>\n\n<pre><code>(defun split-n (sequence n\n &amp;key last sharedp (result-type 'list)\n &amp;aux (size (length sequence)))\n (check-type sequence sequence)\n (check-type n (integer 1 *))\n ;; let the value be checked by \"hoarding\"\n ;; (check-type result-type (member list vector))\n (ecase last\n ((nil t) (setf last :undersized))\n ((:truncated :oversized :undersized) last))\n (let ((slice\n (etypecase sequence\n (vector\n (let* ((type (array-element-type sequence))\n (beg 0)\n (end n)\n (copy (if sharedp\n (lambda (b e)\n (make-array (- e b)\n :displaced-to sequence\n :displaced-index-offset b\n :element-type type))\n (lambda (b e)\n (subseq sequence b e)))))\n (lambda (&amp;optional tail)\n (if tail\n (when (&lt; beg size)\n (funcall copy beg size))\n (prog1 (funcall copy beg end)\n (setf beg end\n end (+ n end)))))))\n (list\n (let ((copy\n (if sharedp #'identity #'copy-list))\n (current sequence))\n (lambda (&amp;optional tail)\n (when current\n (if tail\n (funcall copy current)\n (prog1 (subseq current 0 n)\n (setf current (nthcdr n current)))))))))))\n (multiple-value-bind (count remainder) (truncate size n)\n (hoarding (:result-type result-type\n :size (ecase last\n (:undersized (+ count (signum remainder)))\n (:oversized count)\n (:truncated count)))\n (dotimes (_ (ecase last\n (:undersized count)\n (:oversized (1- count))\n (:truncated count)))\n (take (funcall slice)))\n (let ((residual (funcall slice t)))\n (case last\n ((:undersized :oversized)\n (when residual (take residual))\n (values (loot)\n (cond\n ((zerop remainder) nil)\n ((eq last :undersized) remainder)\n (t (min size (+ remainder n))))))\n (:truncated (values (loot)\n residual))))))))\n</code></pre>\n\n<h3>Tests</h3>\n\n<p><em>Edit: I ran exhaustive tests and fixed a lot of corner cases. Also, you can see that I factorized lists and arrays in a single method. Test results have been updated.</em></p>\n\n<p>Firt, enable tracing:</p>\n\n<pre><code>(trace split-n)\n</code></pre>\n\n<p>Then, we run it for some combinations of inputs:</p>\n\n<pre><code>(with-open-file (*trace-output*\n #P\"/tmp/pastebin\" :direction :output :if-exists :supersede)\n (dolist (last '(:undersized :oversized :truncated))\n (dolist (shared '(nil t))\n (dolist (type '(vector list))\n (dolist (input (list #() '()\n #(1) '(1)\n '(a b c) #(a b c)\n '(1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16)\n #(1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16)\n \"something in a string\"))\n (dolist (n '(1 2 3 4 5 6 7 8))\n (split-n input n :last last :sharedp shared :result-type type)\n (terpri *trace-output*)))))))\n</code></pre>\n\n<p><a href=\"http://pastebin.com/raw.php?i=C5aXFX5A\" rel=\"nofollow noreferrer\">Results are available on pastebin</a>.</p>\n\n<h3>(edit) Back to your code</h3>\n\n<p>I go back to your original question as well as <a href=\"https://codereview.stackexchange.com/a/99279/37033\">your answer</a>. Even though the code is readable and well organized, you are doing some nasty things maybe without realizing it:</p>\n\n<ul>\n<li><p><a href=\"http://clhs.lisp.se/Body/f_subseq.htm\" rel=\"nofollow noreferrer\">SUBSEQ</a> always create a copy of the input sequence. You create copies for the head and the tail in <code>partition</code>, for example. Imagine a sequence of thousand elements splitted by groups of 10: it might be inevitable to allocate 100 subsequences, but this is not what happens because you needlessly copy many more sequences at each step:</p>\n\n<ol>\n<li>partition into a head, a sequence of 10 elements, and a tail, a sequence of 990 elements.</li>\n<li>parition that copy into a head, and the next tail, a sequence of 980 elements.</li>\n<li>.... repeat the process: how many times are elements being copied? Half a million times? You accidentally wrote code with <a href=\"http://accidentallyquadratic.tumblr.com/\" rel=\"nofollow noreferrer\">quadratic complexity</a> impacting both time and memory.</li>\n</ol></li>\n<li><p>In the <code>:oversized</code> case, you still <code>partition</code> and <code>append</code> lists; here, you could use <code>nconc</code> instead of <code>append</code>. Since you just created the list and nobody else has a reference to it, why not mutate it?</p></li>\n<li><p>In the same place, you write:</p>\n\n<pre><code> (apply #'(lambda (x y) (concatenate result-type x y)) oversized)\n</code></pre>\n\n<p>IMHO the lambda is not really useful and the thing could be written:</p>\n\n<pre><code> (concatenate result-type (first oversized) (second oversized))\n</code></pre>\n\n<p>But still, you took a sequence, split it in parts, then extract the last two elements and join them, which is quite some work. This is not catastrophic eiter, but since <code>truncate</code> can give you the size in advance you can avoid doing unnecessary work.</p></li>\n<li><p>By the way, you remove 2 from <code>n</code> in order to get the last two subsequences: did you check what happens when splitting <code>\"abcd\"</code> by 10 using the <code>:oversized</code> mode? </p></li>\n</ul>\n\n<p>Your code is readable and the major efficiency hit comes from repeatedly calling <code>subseq</code>. I'd suggest trying to write the most over-engineered, gold-plated solution you can do, just as an exercise. This will force you to consider all possible corner cases and see if you can refactor things a little more. Good luck!</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2015-08-06T11:06:29.697", "Id": "181837", "Score": "1", "body": "Great writeup! The only thing I was missing is perhaps to also add a `result-type` parameter like with standard `map` to control the type of the returned sequence." } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2015-08-05T15:12:15.017", "Id": "99115", "ParentId": "40954", "Score": "1" } }, { "body": "<p>@coredump, here's a slightly simplified version of the splitter. It does more or less the same things as your version, except for the <code>:sharedp</code> keyword:</p>\n\n<pre><code>(defun emptyp (sequence)\n (typecase sequence\n (null t)\n (array (zerop (length sequence)))\n (otherwise nil)))\n\n(defun partition (sequence n)\n (let* ((tail (subseq sequence n))\n (head (if (emptyp tail)\n sequence\n (subseq sequence 0 n))))\n (values head tail)))\n\n(defun split (sequence n &amp;key (last :undersized) (result-type 'list))\n (let ((raw-seq (mapcar (lambda (x) (coerce x result-type)) \n (loop\n with head\n until (emptyp sequence)\n do\n (multiple-value-setq (head sequence)\n (partition sequence n))\n collect head))))\n (if (&lt; (length (car (last raw-seq))) n)\n (ecase last\n (:undersized\n raw-seq)\n (:oversized\n (multiple-value-bind (regular oversized)\n (partition raw-seq (- (length raw-seq) 2))\n (append regular \n (list (apply #'(lambda (x y) \n (concatenate result-type x y)) oversized)))))\n (:truncated\n (multiple-value-bind (regular oversized)\n (partition raw-seq (1- (length raw-seq)))\n (values regular (coerce (car oversized) result-type)))))\n raw-seq)))\n</code></pre>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2015-08-07T15:49:38.847", "Id": "99279", "ParentId": "40954", "Score": "1" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-02-05T13:21:02.553", "Id": "40954", "Score": "4", "Tags": [ "recursion", "lisp", "common-lisp" ], "Title": "Generic sequence splitter in Common Lisp" }
40954
<p>The main impetus for this review is to determine if my ASP.NET Web API controller has too many dependencies. I'm of the opinion that 3-4 is okay, but 6 seems like too many. I have many controllers with similar layout. I've considered extracting all of the "PostPrimary" operations into a single wrapping dependency, but not sure if that's overkill. If I did create a wrapper, I'm not sure whether I'd create some <code>IManipulator</code> interface and the wrapper could just hold its own <code>IEnumerable&lt;IManipulator&gt;</code> that it could iterate through and execute each, or whether It would just explicitly hold one of each dependency.</p> <p>Some other things to note:</p> <ul> <li>This particular controller only has one "PrePrimary" manipulator, though similar controllers have more, so a PrePrimary wrapper would also be a possibility.</li> <li>I'd prefer to use some ORM instead of the repository pattern, but this legacy database is so messed up, NHibernate struggled to navigate my last project through the swamp of SQL, but the going was slow and they got bogged down many times.</li> <li>I understand that my repository's method contains waaay too many parameters, but I feel like a repository should be fairly open and honest about what constraints its going to use in its SQL, so I use a 1:1 relationship between repository parameters and SQL parameters that go into the <code>WHERE</code> clause. Is this reasonable?</li> <li>The verbosity of my identifiers is not open for discussion :P</li> </ul> <p>So with that,</p> <pre><code>using System.Web.Http; using MyProject.Models; using MyProject.Models.DtoV1; using MyProject.Models.Repo; namespace MyProject.Controllers.Version1 { public class PropertyDimensionController : ApiController { private readonly IPropcodeVetter propcodeVetter; private readonly IPropertyDimensionRepository propertyDimensionRepository; private readonly IPropertyDimensionAllPropsManager propertyDimensionAllPropsManager; private readonly IComparisonRundateVsPopulator comparisonRundateVsPopulator; private readonly IMetricBenchRatePopulator metricBenchRatePopulator; private readonly IDecimalRounder decimalRounder; public PropertyDimensionController(IPropertyDimensionRepository propertyDimensionRepository, IPropcodeVetter propcodeVetter, IPropertyDimensionAllPropsManager propertyDimensionAllPropsManager, IMetricBenchRatePopulator metricBenchRatePopulator, IComparisonRundateVsPopulator comparisonRundateVsPopulator, IDecimalRounder decimalRounder) { this.propertyDimensionRepository = propertyDimensionRepository; this.propcodeVetter = propcodeVetter; this.propertyDimensionAllPropsManager = propertyDimensionAllPropsManager; this.metricBenchRatePopulator = metricBenchRatePopulator; this.comparisonRundateVsPopulator = comparisonRundateVsPopulator; this.decimalRounder = decimalRounder; } public PropertyDimensionResponse Post(PropertyDimensionRequest propertyDimensionRequest) { // PropertyDimension's PrePrimary Manipulations var vettedPropcodes = propcodeVetter.GetVettedPropcodes(propertyDimensionRequest); // PropertyDimension's Primary Operation var propertyDimensionResponse = propertyDimensionRepository.Read(propertyDimensionRequest.Clientcode, propertyDimensionRequest.Projectcode, vettedPropcodes, propertyDimensionRequest.Rundate, propertyDimensionRequest.ComparisonRundate, propertyDimensionRequest.DemographicResponse, propertyDimensionRequest.Metric, propertyDimensionRequest.MetricOnly); // PropertyDimension's PostPrimary Manipulations propertyDimensionResponse = propertyDimensionAllPropsManager.EnsureAllProperties(propertyDimensionResponse, propertyDimensionRequest); propertyDimensionResponse = comparisonRundateVsPopulator.Populate(propertyDimensionResponse); propertyDimensionResponse = metricBenchRatePopulator.Populate(propertyDimensionResponse); propertyDimensionResponse = decimalRounder.RoundAllValues(propertyDimensionResponse); return propertyDimensionResponse; } } } </code></pre>
[]
[ { "body": "<p>I would consider inheritance when dealing with \"I have many controllers with similar layout\".</p>\n\n<p>When dealing with constructor overinjection, you could consider refactoring to aggregate services.</p>\n\n<p>I have also seen solutions where people use partial classes when dealing with constructor overinjection, wich I strongly wouldn't recommend in cases when you dont have automatic genaration of code.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-02-05T20:42:45.803", "Id": "70260", "Score": "0", "body": "The inheritance idea is interesting, but I feel the duplicated logic is *so* minute that it probably wouldn't be worth the overhead." } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-02-05T14:58:09.517", "Id": "40965", "ParentId": "40960", "Score": "1" } }, { "body": "<p>I'm going to make some high-level suggestions about the design. Generally, what I find helpful is to clarify what each class's responsibility is. From what I understand of your code, you have 3 types of objects:</p>\n\n<ul>\n<li><p><code>PropertyDimensionRequest</code>: a data container which I assume contains the data of the web request.</p></li>\n<li><p><code>PropertyDimensionController</code>: this does 2 things - loads data from database, and then does an \"assembly-line\" kind of processing on the request and response to populate the response.</p></li>\n<li><p><code>IPropertyDimensionAllPropsManager,IComparisonRundateVsPopulator</code>, etc: which all populate parts of the web response.</p></li>\n</ul>\n\n<p>Assuming I understood the function of these objects, I would make the following changes:</p>\n\n<ol>\n<li><p>Modify <code>PropertyDimensionRequest</code> to retrieve the data and return the response. I think this better encapsulates the database parameters needed. (Why does PropertyDimensionController care what parameters are needed?) This allows gives you flexibilty to change the Data Access method, without affecting the Controller code at all.</p></li>\n<li><p>Refactor the <code>IPropertyDimensionAllPropsManager,IComparisonRundateVsPopulator</code>, etc. to have a common interface, (maybe something called <code>IResponsePopulator</code>?), and add them to a list in the PropertyDimensionController class, or if they are reusable, and thread-safe, register them into some Singleton data structure. </p></li>\n</ol>\n\n<p>The final code would look something like this:</p>\n\n<pre><code> public PropertyDimensionResponse Post(PropertyDimensionRequest propertyDimensionRequest)\n {\n // not sure what I would do about this\n var vettedPropcodes = propcodeVetter.GetVettedPropcodes(propertyDimensionRequest);\n\n // Let PropertyDimensionRequest read from database, since it contains\n // all the parameters. Just pass it objects it doesn't have access to\n var propertyDimensionResponse = propertyDimensionRequest.Read(propertyDimensionRepository, vettedPropcodes);\n\n // this replaces all the code where the response was being\n // processed by various objects. If refactored to a common interface\n // you just load (or inject) them into a list, and then iteratively\n // process the response\n ResponsePopulators.ForEach( i =&gt; i.Populate(propertyDimensionResponse));\n\n return propertyDimensionResponse;\n }\n}\n</code></pre>\n\n<p>(My C# coding is a little rusty, so please forgive any syntax errors).</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-02-05T20:40:19.090", "Id": "70259", "Score": "0", "body": "Interesting. The PropertyDimensionRequest is just a DTO, so I felt compelled to keep it logic-free and as simple as possible. Of course Read() could be an extension method on it, but then I don't get to easily mock it, so I'd use a repository method, and then we're back where we started, although I'd just pass the entire request into the repository and get back the skeleton of the response. The rest of your thoughts on the collection of populators is kind of what I was thinking with regards to my manipulator wrapper, except you're suggesting forgoing the wrapping." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-02-06T17:45:56.320", "Id": "70442", "Score": "0", "body": "@mo.: [I did a little reading on the Repository pattern](http://www.remondo.net/repository-pattern-example-csharp/). One point to take from this article, is that you could remove the dependencies between the Controller and the specific `PropertyDimensionRequest` properties used for the data query, by adding an \"Entity specific\" look up method. (See the `HotelRepository.FindHotelsByCity()` method in the article). Adding the specific lookup function to your Repository provides a better [separation of concerns](http://en.wikipedia.org/wiki/Separation_of_concerns), than leaving it in controller." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-02-18T14:48:04.813", "Id": "72293", "Score": "0", "body": "Note that this specific code wouldn't work, because all the `Populate()` methods *return* the changed response. But that's trivial to fix: `foreach (var populator in ResponsePopulators) propertyDimensionResponse = populator.Populate(propertyDimensionResponse);`." } ], "meta_data": { "CommentCount": "3", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-02-05T19:23:30.770", "Id": "40991", "ParentId": "40960", "Score": "3" } }, { "body": "<p>Well Firstly that constructor is a bit of a worry. </p>\n\n<p>Anything more than 3 (at most!) arguments is normally a bad idea.</p>\n\n<p>Now that you have so many it would be a good idea to make yourself a :</p>\n\n<pre><code> public interface PropertyDimensionControllerParameters : ApiControllerParameters\n {\n IPropcodeVetter vetter;\n IPropertyDimensionRepository repository;\n IPropertyDimensionAllPropsManager propsManager;\n IComparisonRundateVsPopulator comparisonRundateVsPopulator;\n IMetricBenchRatePopulator metricBenchRatePopulator;\n IDecimalRounder decimalRounder;\n }\n</code></pre>\n\n<p>which will clean up your constructor call and allow a much easier one-stop-shop functionality change. So now your constructor goes:</p>\n\n<pre><code> public PropertyDimensionController(PropertyDimensionControllerParameters parameters)\n {\n if(parameters == null) throw new ArgumentNullException(\"parameters\");\n _parameters = parameters;\n }\n</code></pre>\n\n<p>And you can do that across the board. Any where a method overload is super hard to read, encapsulate it in an object that makes sense. </p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-02-06T15:08:55.187", "Id": "70408", "Score": "0", "body": "I've heard of making parameter classes for certain things, but never for a constructor. Wouldn't using aggregate services (as named by Dzenan and originally hinted at by myself) make a lot more sense in this case?" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-02-06T15:16:13.197", "Id": "70409", "Score": "0", "body": "Was trying to edit, but took so long my time limit expired :O - It seems like your suggestion would be sweeping the too-many-concerns problem of the controller under the rug." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-02-06T15:18:42.500", "Id": "70410", "Score": "0", "body": "Well I am a major proponent of Dependency Inversion. All of my services are written as interfaces and passed into things via constructors. that way regardless of what implementation method you choose, one that requires 4 items or 40 the function calls remain the same and no code needs recompiling. \n\nI don't hold constructors as sacred as most do. I tend to build things via factories so they don't matter, the implementation classes are never exposed. all my implementations are internal while interfaces are public. In short it doesn't matter which way you go, as long as you code to a contract" } ], "meta_data": { "CommentCount": "3", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-02-06T10:01:23.930", "Id": "41051", "ParentId": "40960", "Score": "2" } } ]
{ "AcceptedAnswerId": "40991", "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-02-05T14:23:00.413", "Id": "40960", "Score": "3", "Tags": [ "c#", "dependency-injection", "controller" ], "Title": "Controller with too many dependencies?" }
40960