body
stringlengths
25
86.7k
comments
list
answers
list
meta_data
dict
question_id
stringlengths
1
6
<p>Over the past week, we tried to make our AngularJS model layer more powerful and reduce complexity in our controllers and template by using the object-oriented programming pattern and the CoffeeScript class keyword. You can see the result here: <a href="http://plnkr.co/edit/c1uxN6ZorQzOVizlzU5Y?p=preview" rel="nofollow">http://plnkr.co/edit/c1uxN6ZorQzOVizlzU5Y?p=preview</a></p> <p>This is our Base class that handles most of that complexity:</p> <pre class="lang-coffee prettyprint-override"><code>'use strict' angular.module('myApp') .factory 'Base', ($q, $http) -&gt; class Base ### A list of all the properties that an object of this class can have ### @properties: -&gt; p = {} p.id = null p.name = null p.description = null p.errors = [] p ### The base API path used to call REST APIs for the current class This is to be overridden by child classes ### @baseApiPath: ":apiPath/organizations/:organizationId" ### Extra fields, not part of the default API response format, that we want included ### @requestedFields: [] ### Get data and instantiate new objects for existing records from a REST API ### @find: (params = {}) -&gt; params.fields = if Array.isArray(params.fields) then params.fields.concat(@requestedFields) else @requestedFields deferred = $q.defer() $http.get(@baseApiPath, {params: params}) .success (data, status, headers, config) =&gt; # create a new object of the current class (or an array of them) and return it (or them) if Array.isArray data.data response = for result in data.data then new @(result, true) # add "delete" method to results object to quickly delete objects and remove them from the results array response.delete = (object) -&gt; object.delete().then -&gt; response.splice response.indexOf(object), 1 else response = new @(data.data, true) deferred.resolve response .error (data, status, headers, config) =&gt; deferred.reject data.errors deferred.promise constructor: (propValues, convertKeys = false) -&gt; # Prevent the Base class itself from being instantiated if @constructor.name is "Base" throw "The Base class cannot be instantiated and is only meant to be extended by other classes." @assignProperties propValues, convertKeys ### Persist the current object's data by passing it to a REST API Dynamically switch between POST and PUT verbs if the current object has a populated id property ### save: (data = @getDataForApi(), params = {}) -&gt; deferred = $q.defer() if @validate() params.fields = if Array.isArray(params.fields) then params.fields.concat(@requestedFields) else @requestedFields if @id? promise = $http.put "#{@constructor.baseApiPath}/#{@id}", data, {params: params} else promise = $http.post @constructor.baseApiPath, data, {params: params} promise .success (data, status, headers, config) =&gt; deferred.resolve @successCallback(data, status, headers, config) .error (data, status, headers, config) =&gt; deferred.reject @failureCallback(data, status, headers, config) else deferred.reject() deferred.promise ### Validate that the current object is valid and ready to be saved Child classes should override this method and provide their own validation rules ### validate: -&gt; true ### Delete the current object ### delete: (params = {}) -&gt; deferred = $q.defer() $http.delete("#{@constructor.baseApiPath}/#{@id}", {params: params}) .success (data, status, headers, config) =&gt; deferred.resolve @successCallback(data, status, headers, config) .error (data, status, headers, config) =&gt; deferred.reject @failureCallback(data, status, headers, config) deferred.promise ### Assigns incoming data values to the current object's properties e.g. we might receive data such as {"id": 1, "full_name": "foobar"}; this will get assigned to the current object's id and fullName properties This method is useful for parsing API responses and updating an object's properties after a GET, POST or PUT ### assignProperties: (data = {}, convertKeys = false) -&gt; # let's loop over all properties that an object can have and assign the corresponding values that we received, one by one for name, property of @constructor.properties() # sometimes, the incoming data use a different case for their keys dataKey = if convertKeys then Base.toUnderScore name else name @[name] = # if a value exists in the incoming data if data[dataKey] isnt undefined # if property is a constructor, instantiate a new object or an array of objects if property? and typeof property is "function" if Array.isArray data[dataKey] for nestedValues in data[dataKey] new property(nestedValues, convertKeys) else new property(data[dataKey], convertKeys) # otherwise, just use the data value as it is else data[dataKey] # if there is no incoming value for this property, assign the default value else property # return the incoming data in case some other function wants to play with it next return data ### Extract data from current object and format it to be sent along with a persist API request Collect values of all properties of current object, and potential nested objects ### getDataForApi: (object = @) -&gt; data = {} # let's loop over all properties that an object can have for name, property of @constructor.properties() # see if the current object has a value for this property if object[name]? data[Base.toUnderScore(name)] = # if the current property is a constructor, dig into the nested object if typeof property is "function" if Array.isArray object[name] for nestedObject in object[name] then prepareData nestedObject else @getDataForApi object[name] # otherwise, get the value as it is else object[name] return data ### Callbacks for $http response promise ### successCallback: (data, status, headers, config) =&gt; @assignProperties data.data, true failureCallback: (data, status, headers, config) =&gt; @assignErrors data.errors assignErrors: (errorData) -&gt; @errors = errorData ### Convert string case from "user_score" to "camelCase" format ### @toCamelCase: (string) -&gt; string.replace /_([a-z])/g, (g) -&gt; g[1].toUpperCase() ### Convert string case from "camelCase" to "under_score" format ### @toUnderScore: (string) -&gt; string.replace /([a-z][A-Z])/g, (g) -&gt; g[0] + '_' + g[1].toLowerCase() </code></pre> <p>Then it's really easy to extend it in a useful child class:</p> <pre class="lang-coffee prettyprint-override"><code>angular.module('myApp') .factory 'Animal', (Base, $q) -&gt; class Animal extends Base @properties: -&gt; p = Base.properties() p.color = null p.fooBar = null p @baseApiPath: "#{Base.baseApiPath}/animals" validate: -&gt; if not @color? or @color is "" @errors.push {message: "The field cannot be empty"} return false super save: -&gt; if @validate() super color: @color foo_bar: @fooBar </code></pre> <p>This child class can now be used in a controller this way:</p> <pre class="lang-coffee prettyprint-override"><code>angular.module('myApp') .controller 'IndexCtrl', ($scope, Animal) -&gt; Animal.find().then (response) -&gt; $scope.animals = response </code></pre> <p>It is then really easy to, for instance, loop over those items and have action buttons on them, like this:</p> <pre class="lang-html prettyprint-override"><code>&lt;div ng-controller="IndexCtrl"&gt; &lt;table&gt; &lt;thead&gt; &lt;tr&gt; &lt;th&gt;Id&lt;/th&gt; &lt;th&gt;Name&lt;/th&gt; &lt;th&gt;Color&lt;/th&gt; &lt;th&gt;Foo Bar&lt;/th&gt; &lt;/tr&gt; &lt;/thead&gt; &lt;tbody&gt; &lt;tr ng-repeat="animal in animals"&gt; &lt;td&gt;{{animal.id}}&lt;/td&gt; &lt;td&gt;{{animal.name}}&lt;/td&gt; &lt;td&gt;{{animal.color}}&lt;/td&gt; &lt;td&gt;{{animal.fooBar}}&lt;/td&gt; &lt;td&gt;&lt;button ng-click="animal.save()"&gt;Save&lt;/button&gt;&lt;/td&gt; &lt;td&gt;&lt;button ng-click="animal.delete()"&gt;Delete&lt;/button&gt;&lt;/td&gt; &lt;/tr&gt; &lt;/tbody&gt; &lt;/table&gt; &lt;/div&gt; </code></pre> <p>And finally, this is the kind of format that is used for our incoming data:</p> <pre class="lang-json prettyprint-override"><code>{ "data": [ { "id": 1, "name": "Tiger", "color": "yellow", "foo_bar": "foo" }, { "id": 2, "name": "Dog", "color": "brown", "foo_bar": "blah" } ], "errors": [] } </code></pre> <p>As you can see, it's using "under_score" format, but JavaScript convention is to use camelCase variable names, so we just convert those names on the fly when receiving the data.</p> <p>We're going to continue making progress on this pattern next week but I was wondering if anyone sees any big pitfall that we should avoid, or any good optimization we could do here.</p> <p>I tried to put all the complexity in the Base class so that child classes are kept very small and easy to create.</p>
[ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-05-07T21:29:16.903", "Id": "86458", "Score": "0", "body": "It's been a few days. We've improved this class a lot. The current code is missing a lot of functionalities still. I should be able to post an updated version soon." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-05-22T22:07:34.210", "Id": "88882", "Score": "0", "body": "I expect this question will get answered if you update your code. Do you still want that code reviewed?" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-05-24T18:23:45.680", "Id": "89218", "Score": "0", "body": "Thanks for the reminder. Sorry about the delay. I just updated the code, both in the post and in the plunkr. We added automatic \"serializing\" of objects (loop over object properties and save to a simpler objects with \"under_score\" format property names) to post to APIs and a proper delete method in the Base class. If anyone wants to give their opinion on our code, it would be greatly appreciated." } ]
[]
{ "AcceptedAnswerId": null, "CommentCount": "3", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-05-05T03:04:23.610", "Id": "48954", "Score": "4", "Tags": [ "object-oriented", "coffeescript", "angular.js" ], "Title": "An Object-Oriented Programming pattern for AngularJS models using CoffeeScript classes" }
48954
<p>I'm writing a program which determines how many bits are in a floating point value (this will be run on Unix).</p> <pre><code>#include &lt;stdio.h&gt; #include &lt;stdlib.h&gt; void countbits(int k); int main(){ int input; // int a = (int) malloc(sizeof(int)); printf("Please enter a number: "); scanf("%d",&amp;input); // a = input; countbits(input); } void countbits(int k){ int j,count; count = 0; for(j = 0; j &lt; 31; j++){ if(k &amp; 0x000001 == 1){ count++; } k &gt;&gt;= 1; } printf("%d has %d bits set\n",k,count); // count = 0; } </code></pre> <p>Output example:</p> <blockquote> <p>2 has 1 bits set<br> 6 has 2 bits set<br> 32 has 1 bits set </p> </blockquote> <p>I'll really appreciate any feedback or correction or if there is something I can do better.</p>
[ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-05-05T09:49:28.670", "Id": "85976", "Score": "0", "body": "I don't see how this code has anything to do with [tag:floating-point]. Please explain? I'm putting the question back on hold in the meantime." } ]
[ { "body": "<p>You should do the output in <code>main()</code>, not in <code>countbits()</code>. Functions should have only one primary purpose, according to the <a href=\"http://en.wikipedia.org/wiki/Single_responsibility_principle\" rel=\"nofollow noreferrer\">Single Responsibility Principle (SRP)</a>. In this case, <code>countbits()</code> should just perform the calculations and return the result. Thus, its return type should now be of type <code>int</code>.</p>\n\n<p>Inside of <code>countbits()</code>, you could just loop while <code>k</code> is not <code>0</code> instead of looping 32 times. Once all the bits in <code>k</code> shift away and <code>k</code> becomes <code>0</code>, there's no point in continuing. This will also give you a result of <code>0</code> right away if the input is <code>0</code>; calculating this will be a waste of time.</p>\n\n<pre><code>int main(void) {\n int input;\n\n // get the input...\n\n int count = countbits(input);\n\n printf(\"%d has %d bits set\\n\", input, count);\n}\n\nint countbits(int k) {\n int count = 0;\n\n while (k != 0) {\n // perform calculations...\n }\n\n return count;\n}\n</code></pre>\n\n<p>Some notes about this and other things:</p>\n\n<ul>\n<li><code>main()</code> should have a <code>void</code> parameter since it isn't taking any command line arguments.</li>\n<li>The first (unformatted) output in <code>main()</code> should use <a href=\"https://stackoverflow.com/questions/2454474/what-is-the-difference-between-printf-and-puts-in-c\"><code>puts()</code> instead of <code>printf()</code></a>.</li>\n<li><code>count</code> doesn't need to be declared and then assigned to <code>0</code>. Just initialize it to <code>0</code>.</li>\n<li><code>j</code> should be initialized inside the <code>for</code> loop statement (if you have C99). If you don't, then declare it <em>right</em> before the loop. Variables should be used as close in scope as possible.</li>\n</ul>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-05-05T04:31:26.153", "Id": "85939", "Score": "0", "body": "Thanks Jamal! Can you talk little bit about my method in countbits. I'm not so sure about it if its correct." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-05-05T04:34:50.470", "Id": "85940", "Score": "0", "body": "Professor gave us example what our program should output he has 4 prints 2. 32 prints 2. 16 prints 3. 2 prints 1. However my 32, 4, 16, 2 all prints 1." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-05-05T04:43:52.510", "Id": "85941", "Score": "0", "body": "@user3478869: Since this isn't working as it should, I will have to place the question on hold until it works. We only review working code (and I had assumed it was tested for correctness first). You can ask Stack Overflow on how to fix this. After it works, edit in the changes (but do *not* apply my changes), and the hold can be removed." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-05-05T04:53:22.090", "Id": "85942", "Score": "0", "body": "It has been confirmed that it is working correctly." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-05-05T04:59:52.573", "Id": "85944", "Score": "0", "body": "@user3478869: With the current code, or with some changes? My test code is also showing different results from the expected output." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-05-05T05:01:17.613", "Id": "85945", "Score": "0", "body": "I figured that his expected output is wrong. He just have a dummy example to give an idea what program should output." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-05-05T05:02:36.330", "Id": "85946", "Score": "0", "body": "@user3478869: If so, then update the question with the expected output, if you're sure (worked it out and everything)." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-05-05T05:11:03.770", "Id": "85947", "Score": "0", "body": "Wait, scratch that. Your current output is correct, which is what I'm getting as well. I'm not sure why your professor has given you those values." } ], "meta_data": { "CommentCount": "8", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-05-05T04:17:53.993", "Id": "48957", "ParentId": "48956", "Score": "2" } } ]
{ "AcceptedAnswerId": "48957", "CommentCount": "1", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-05-05T03:49:38.220", "Id": "48956", "Score": "1", "Tags": [ "c", "homework", "floating-point" ], "Title": "Determine how many bits are in a floating point value" }
48956
<p>This is my first attempt at a login system! I've only had roughly 2 days of experience with MySQL and PHP so far and this is what I came up with:</p> <pre><code>&lt;?php session_start(); //Start Database $IP = ""; $user = ""; $pass = ""; $db = ""; $con = mysqli_connect($IP, $user, $pass, $db); // Check connection if ( mysqli_connect_errno() ) { echo "&lt;div&gt;"; echo "Failed to connect to MySQL: " . mysqli_connect_error(); echo "&lt;/div&gt;"; } // Pretty much kicks out a user once they revisit this page and is logged in if( $_SESSION["name"] ) { echo "You are already logged in, ".$_SESSION['name']."! &lt;br&gt; I'm Loggin you out M.R .."; unset( $_SESSION ); session_destroy(); exit(""); } $loggedIn = false; $userName = $_POST["name"] or ""; $userPass = $_POST["pass"] or ""; if ($userName &amp;&amp; $userPass ) { // User Entered fields $query = "SELECT name FROM Clients WHERE name = '$userName' AND password = '$userPass'";// AND password = $userPass"; $result = mysqli_query( $con, $query); $row = mysqli_fetch_array($result); if(!$row){ echo "&lt;div&gt;"; echo "No existing user or wrong password."; echo "&lt;/div&gt;"; } else $loggedIn = true; } if ( !$loggedIn ) { echo " &lt;form action='logmein.php' method='post'&gt; Name: &lt;input type='text' name='name' value='$userName'&gt;&lt;br&gt; Password: &lt;input type='password' name='pass' value='$userPass'&gt;&lt;br&gt; &lt;input type='submit' value='log in'&gt; &lt;/form&gt; "; } else{ echo "&lt;div&gt;"; echo "You have been logged in as $userName!"; echo "&lt;/div&gt;"; $_SESSION["name"] = $userName; } ?&gt; </code></pre>
[ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2015-04-28T14:48:13.273", "Id": "159675", "Score": "0", "body": "It is my general opinion that new programmers should not be authoring login systems. A modern login system should have two-factor authentication, anti-phishing support, and a host of other features along with application and database security defenses. These are topics not suited to new developers but are essential. Barebones SSO (http://barebonescms.com/documentation/sso/) is a great starting point for someone who wants to get up and running with a properly hardened and vetted login system." } ]
[ { "body": "<p>At a quick look:</p>\n\n<ul>\n<li><p>Your code is <strong>vulnerable to SQL Injection</strong>: assume the user wants to hurt you, so always parse superglobals <code>$_GET</code> and <code>$_POST</code></p>\n\n<p><a href=\"https://stackoverflow.com/questions/60174/how-can-i-prevent-sql-injection-in-php\">https://stackoverflow.com/questions/60174/how-can-i-prevent-sql-injection-in-php</a></p></li>\n<li><p>To check if variable have values:</p>\n\n<pre><code>// good practice\nif (isset($userName, $userPass))\n// bad practice\nif ($userName &amp;&amp; $userPass )\n</code></pre></li>\n<li><p>More important:</p>\n\n<blockquote>\n <p>Don't reinvent the wheel unless you plan on learning more about wheels.</p>\n</blockquote>\n\n<p>A simple search on google for <code>PHP login system</code> will give you a limitless number of examples from where you can learn how to build a proper system: </p></li>\n</ul>\n\n<p><a href=\"http://www.phpeasystep.com/workshopview.php?id=6\" rel=\"nofollow noreferrer\">http://www.phpeasystep.com/workshopview.php?id=6</a></p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-05-05T06:12:06.613", "Id": "85948", "Score": "2", "body": "I disagree with your \"connection phase and call die\" recommendation. What the OP is doing is good practice. Why are you suggesting they use the deprecated mysql_ extension instead of mysqli_ ?" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-05-05T06:12:17.693", "Id": "85949", "Score": "0", "body": "Thanks! Very good suggestions. I did not know that it was bad to just check `($userName && $userPass )` and I didn't know including the data-base in the mysql connect would be bad. Also, this was just a way for me to learn more about php and mysql .. Like stated in the beginning, I only have roughly 2 days of experience with php and mysql." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-05-05T06:13:45.577", "Id": "85950", "Score": "0", "body": "@bumperbox good catches. I didn't even noticed they were the deprecated mysql functions. And connection and die is bad?" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-05-05T06:15:50.250", "Id": "85951", "Score": "0", "body": "Using mysql_ extension is bad, if you are already using mysqli_ extension. Connect or die is not bad, but just grouped under the same heading in the answer. Have a look at php manual for reference guidelines on checking a connection error. http://nz1.php.net/manual/en/mysqli.connect-error.php" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-05-05T06:22:18.070", "Id": "85953", "Score": "0", "body": "The sql injection is a valid point, and something you need to deal with, mysqli_ extension makes this easy" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-05-05T06:23:30.717", "Id": "85954", "Score": "0", "body": "Good call! i edited the sql connection statement." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-05-05T06:27:43.830", "Id": "85955", "Score": "4", "body": "The `isset` recommendation nonsense, those two variables are guaranteed to be *set*, no need to check them. What you do need to check are the `$_POST` variables/indices." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-05-05T06:31:42.700", "Id": "85956", "Score": "1", "body": "@Lemony Better read http://kunststube.net/isset" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-05-05T12:17:15.267", "Id": "85990", "Score": "4", "body": "The provided phpeasystep example is even worse! don't use it" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-05-05T15:19:01.803", "Id": "86017", "Score": "0", "body": "@bumperbox Why is he calling `mysqli` rather than using the `PDO` extensions?" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-05-05T15:48:48.197", "Id": "86019", "Score": "0", "body": "@Shadur, while I personally prefer PDO, I was under the impression that mysqli_* and PDO were equivalent in terms of safety? PDO is simply the object-oriented approach." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-05-05T18:18:34.637", "Id": "86047", "Score": "0", "body": "The OO approach does make things a little safer. And either way, I'd -1 this for the fact that he still isn't using `prepare()` and `execute()`." } ], "meta_data": { "CommentCount": "12", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-05-05T05:50:41.250", "Id": "48959", "ParentId": "48958", "Score": "8" } }, { "body": "<p>First up, that's a pretty good effort for a couple days of experience, you have obviously done some reading yourself.</p>\n\n<p>To be honest it is, what I call spaghetti code, echo html statements in between logic. While it works fine (and is how most people learn), it becomes a pain to maintain in the long term. </p>\n\n<p>Rather then straighten out the spaghetti, I have made some minor comments, so that your code it still recognizable, and you can see the changes. </p>\n\n<p>I have put some inline comments describing the changes.</p>\n\n<pre><code>&lt;?php\n // turn error reporting on, it makes life easier if you make typo in a variable name etc\n error_reporting(E_ALL);\n\n session_start();\n\n //Start Database\n $IP = \"\";\n $user = \"\";\n $pass = \"\";\n $db = \"\";\n $con = mysqli_connect($IP, $user, $pass, $db);\n\n // Check connection\n if (!$con) {\n echo \"&lt;div&gt;\";\n echo \"Failed to connect to MySQL: \" . mysqli_connect_error();\n echo \"&lt;/div&gt;\";\n\n // *** what happens here, you let the script continue regardless of the error?\n }\n\n // Pretty much kicks out a user once they revisit this age and is logged in\n\n // *** It is best to test isset($_SESSION[\"name\"]), otherwise php will generate a warning if 'name' index is not set.\n // you can also test for !empty($_SESSION[\"name\"]), as empty detects if a value is not set, but it will also detect 0 as empty, so use with caution\n // if( $_SESSION[\"name\"] )\n if( isset($_SESSION[\"name\"]) &amp;&amp; $_SESSION[\"name\"] )\n {\n echo \"You are already logged in, \".$_SESSION['name'].\"! &lt;br&gt; I'm Loggin you out M.R ..\";\n unset( $_SESSION );\n session_destroy();\n\n // *** The empty quotes do nothing\n // exit(\"\");\n exit;\n }\n\n $loggedIn = false;\n\n // *** While or is nice solution, it doesn't take into account when the 'name' index is not set, which generates a php warning\n // $userName = $_POST[\"name\"] or \"\";\n $userName = isset($_POST[\"name\"]) ? $_POST[\"name\"] : null;\n\n // *** same change as above\n // $userPass = $_POST[\"pass\"] or \"\";\n $userPass = isset($_POST[\"pass\"]) ? $_POST[\"pass\"] : null;\n\n // *** This test really comes down to, what if username or password is evaluated to false.\n // have a good think about what it is you are actually testing\n // php casts strings and numeric values to boolean, so something that you don't think is false could be cast as false, eg a string containing \"0\"\n if ($userName &amp;&amp; $userPass )\n {\n // User Entered fields\n // *** This is dangerous, it is subject to sql injection, given you wrote this code in 2 days, i am sure you can find\n // plenty of info on sql injection and mysqli and improve it\n $query = \"SELECT name FROM Clients WHERE name = '$userName' AND password = '$userPass'\";// AND password = $userPass\";\n\n $result = mysqli_query( $con, $query);\n\n // *** Error checking, what if !$result? eg query is broken\n\n $row = mysqli_fetch_array($result);\n\n if(!$row){\n echo \"&lt;div&gt;\";\n echo \"No existing user or wrong password.\";\n echo \"&lt;/div&gt;\";\n }\n else {\n // *** My PERSONAL preference is to use {} every where, it just makes it easier if you add \n // code into the condition later\n $loggedIn = true;\n }\n }\n\n if ( !$loggedIn )\n {\n echo \"\n &lt;form action='logmein.php' method='post'&gt;\n Name: &lt;input type='text' name='name' value='$userName'&gt;&lt;br&gt;\n Password: &lt;input type='password' name='pass' value='$userPass'&gt;&lt;br&gt;\n &lt;input type='submit' value='log in'&gt;\n &lt;/form&gt;\n \";\n }\n else{\n echo \"&lt;div&gt;\";\n echo \"You have been logged in as $userName!\";\n echo \"&lt;/div&gt;\";\n $_SESSION[\"name\"] = $userName;\n }\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-05-05T13:15:49.373", "Id": "85996", "Score": "1", "body": "I could not have asked for anything more! I'm going to take to the time to really take this in and study it. By the way, the only reason I had `exit(\"\")` was because I was getting errors with just `exit()`.. Also I completely forgot about the `?` operator; now I can put it to some use! Time to learn about sql injection, this is something I was avoiding till the last part. On a side note, Is there a better way to approach(ehoing) my way of taking away the login form if the user is logged in? Should I just use css to remove it?" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-05-05T14:56:40.200", "Id": "86011", "Score": "2", "body": "it also looks like the password is stored in plain text. one should never do this. use something like blowfish to hash it and compare it with the hashed password taken from `$_POST`" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-05-05T17:28:43.300", "Id": "86040", "Score": "0", "body": "@Lemony-Andrew Do some work on your code. Improve the parts that are not so good, then post it again (in another question), and we will review it again." } ], "meta_data": { "CommentCount": "3", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-05-05T06:33:17.827", "Id": "48962", "ParentId": "48958", "Score": "8" } }, { "body": "<ul>\n<li><p><code>$userName = $_POST['name'] or \"\";</code> doesn't do what it looks like it does.</p>\n\n<p><code>or</code> has a lower precedence than just about any other operator in PHP, including <code>=</code>. So that line is equivalent to <code>($userName = $_POST['name']) or \"\";</code>. Basically, the <code>or \"\"</code> part has no effect. <code>$userName</code> will be whatever is in <code>$_POST['name']</code>, or <code>null</code> if nothing was there.</p>\n\n<p>You can't just fix it with parentheses either. <code>or</code> is a boolean operator, and the result will be either <code>true</code> or <code>false</code>. And in any case, you're still getting a variable that might be undefined, and will trigger notices in that case.</p>\n\n<p>Unfortunately, there's no good shorthand way to access a maybe-undefined variable without potentially triggering notices (there's <code>@</code>, but it's advised against for several reasons, a couple of which i agree with). You need to be a bit wordier.</p>\n\n<pre><code>$userName = isset($_POST['name']) ? $_POST['name'] : \"\";\n</code></pre></li>\n<li><p>Try to make your conditions positive. For example,</p>\n\n<pre><code>if(!$row){\n echo \"&lt;div&gt;\";\n echo \"No existing user or wrong password.\";\n echo \"&lt;/div&gt;\";\n}\nelse \n $loggedIn = true;\n</code></pre>\n\n<p>is often less confusing as</p>\n\n<pre><code>if($row)\n $loggedIn = true;\nelse {\n echo \"&lt;div&gt;\";\n echo \"No existing user or wrong password.\";\n echo \"&lt;/div&gt;\";\n}\n</code></pre>\n\n<p>(By the way, bumperbox has a bit of a point about braces. I'm not as adamant about them, but i would suggest including them if the code will span multiple lines. If the code fits on the same line as the <code>if</code>, like this:</p>\n\n<pre><code>if ($row) $loggedIn = true;\nelse {\n echo \"&lt;div&gt;\";\n echo \"No existing user or wrong password.\";\n echo \"&lt;/div&gt;\";\n}\n</code></pre>\n\n<p>the intent is clear, and someone adding code should already know to add the braces as well. With the code indented on the next line the way you have it, it's easy to miss that there are no braces.)</p></li>\n</ul>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-05-05T13:17:45.403", "Id": "85998", "Score": "0", "body": "I agree that it's better to just keep conditions the way they are and not reverse them with the `!` operator. And I completely forgot that what I wrote `$userName = $_POST['name'] or \"\";` was completely redundant." } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-05-05T12:12:38.813", "Id": "48973", "ParentId": "48958", "Score": "2" } } ]
{ "AcceptedAnswerId": "48962", "CommentCount": "1", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-05-05T04:43:19.110", "Id": "48958", "Score": "9", "Tags": [ "php", "mysqli", "session", "authentication" ], "Title": "First PHP login system" }
48958
<p>Below is the code that I've written for matrix multiplication:</p> <pre><code>import java.text.DecimalFormat; import java.util.InputMismatchException; import java.util.Scanner; public class MatrixMultiplication { private static final String TERMINATED_MESSAGE = "Terminated" + "," + " "; private static final String INVALID_MATRIX_DIMENSION_ERROR_MESSAGE = TERMINATED_MESSAGE + "Invalid matrix dimension!"; private static final String MATRIX_MISMATCH_ERROR_MESSAGE = TERMINATED_MESSAGE + "First matrix column and second matrix row must be same!"; private static final String INVALID_INPUT_ERROR_MESSAGE = TERMINATED_MESSAGE + "Invalid Input!"; private static Scanner scanner; private static DecimalFormat decimalFormat; private static int firstMatrixRows; private static int firstMatrixcolumns; private static int secondMatrixRows; private static int secondMatrixColumns; private static double firstMatrix[][]; private static double secondMatrix[][]; private static double resultMatrix[][]; private static boolean errorFlag; public static void main(String[] args) { initialize(); if (!errorFlag) getInput(); if (!errorFlag) calculateProduct(); if (!errorFlag) displayResult(); } private static void initialize() { scanner = new Scanner(System.in); decimalFormat = new DecimalFormat("#.##"); errorFlag = false; try { System.out.print("Number of Rows in First Matrix: "); firstMatrixRows = scanner.nextInt(); System.out.print("Number of Columns in First Matrix: "); firstMatrixcolumns = scanner.nextInt(); System.out.print("Number of Rows in Second Matrix: "); secondMatrixRows = scanner.nextInt(); System.out.print("Number of Columns in Second Matrix: "); secondMatrixColumns = scanner.nextInt(); } catch (InputMismatchException ime) { System.out.println(INVALID_INPUT_ERROR_MESSAGE); errorFlag = true; return; } firstMatrix = new double[firstMatrixRows][firstMatrixcolumns]; secondMatrix = new double[secondMatrixRows][secondMatrixColumns]; if (firstMatrixRows == 0 || firstMatrixcolumns == 0 || secondMatrixRows == 0 || secondMatrixColumns == 0) { System.out.println(INVALID_MATRIX_DIMENSION_ERROR_MESSAGE); errorFlag = true; return; } else if (firstMatrixcolumns != secondMatrixRows) { System.out.println(MATRIX_MISMATCH_ERROR_MESSAGE); errorFlag = true; return; } resultMatrix = new double[firstMatrixRows][secondMatrixColumns]; } private static void getInput() { System.out.println("Enter the first matrix (" + firstMatrixRows + " x " + firstMatrixcolumns + ") :"); readValues(firstMatrix); System.out.println("Enter the second matrix (" + secondMatrixRows + " x " + secondMatrixColumns + ") :"); readValues(secondMatrix); } private static void readValues(double matrix[][]) { for (int i = 0; i &lt; matrix.length; i++) { for (int j = 0; j &lt; matrix[0].length; j++) { try { matrix[i][j] = scanner.nextDouble(); } catch (InputMismatchException ime) { System.out.println(INVALID_INPUT_ERROR_MESSAGE); errorFlag = true; return; } } } } private static void calculateProduct() { for (int i = 0; i &lt; firstMatrixRows; i++) { for (int j = 0; j &lt; secondMatrixColumns; j++) { for (int k = 0; k &lt; secondMatrixRows; k++) { resultMatrix[i][j] = resultMatrix[i][j] + (firstMatrix[i][k] * secondMatrix[k][j]); } } } } private static void displayResult() { System.out.println("First Matrix:"); printMatrix(firstMatrix); System.out.println("Second Matrix:"); printMatrix(secondMatrix); System.out.println("Result Matrix (Product):"); printMatrix(resultMatrix); } private static void printMatrix(double matrix[][]) { for (int i = 0; i &lt; matrix.length; i++) { for (int j = 0; j &lt; matrix[0].length; j++) { System.out.print(decimalFormat.format(matrix[i][j]) + "\t\t"); } System.out.println(); } System.out.println(); } } </code></pre> <p>What are your thoughts on this? Can this code be optimized or done using any other simpler logic? Any suggestions and thoughts are welcome.</p>
[ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-05-05T12:52:34.170", "Id": "85993", "Score": "1", "body": "I can't say much of the code, but all the input that you require for a simple multiplication seems to make this very uncomfortable to use (you even request the 'middle' dimension twice). Perhaps you could be inspired by the MATLAB notation, where multiplying 2 matrices is as simple as: `[1 2; 3 4]*[1 0; 0 1]`, or when you are in a verbose mood: `mtimes([1 2; 3 4],[1 0; 0 1])`." } ]
[ { "body": "<h1>Static and void</h1>\n\n<p><strong>All</strong> your variables are static. <strong>All</strong> your methods return <code>void</code>. This is not good.</p>\n\n<p>Java is an object-oriented language. You're not using it that way. You're using it more as a procedural language by having everything as static and using only <code>void</code> methods. Although this works (apparently), you're losing flexibility.</p>\n\n<p>I have a mission for you:</p>\n\n<p>Remove all the below lines from your program and use them as <strong>local variables</strong> rather than static fields.</p>\n\n<pre><code>private static Scanner scanner;\nprivate static DecimalFormat decimalFormat; \n\nprivate static int firstMatrixRows;\nprivate static int firstMatrixcolumns;\nprivate static int secondMatrixRows;\nprivate static int secondMatrixColumns;\n\nprivate static double firstMatrix[][];\nprivate static double secondMatrix[][];\nprivate static double resultMatrix[][];\n\nprivate static boolean errorFlag;\n</code></pre>\n\n<p>To get you started I have some few suggestions:</p>\n\n<ul>\n<li><code>displayResult</code> method can take three parameters: <code>firstMatrix</code>, <code>secondMatrix</code>, and, you guessed it: <code>resultMatrix</code>.</li>\n<li><code>calculateProduct</code> can take two parameters: <code>firstMatrix</code>, <code>secondMatrix</code>, and <strong>return</strong> the result matrix.</li>\n<li><code>getInput</code> can be modified into only reading one matrix, then you can use <code>getInput(\"Enter the first matrix\", firstMatrix);</code></li>\n<li>Use <code>firstMatrix.length</code> and <code>firstMatrix[0].length</code> to determine the width and height of a matrix.</li>\n</ul>\n\n<h3>Your own Matrix class</h3>\n\n<p>And finally, this is a major suggestion that partially goes against the above suggestions:</p>\n\n<p>Replace <code>double[][]</code> with <code>MyMatrix</code> that you <a href=\"http://docs.oracle.com/javase/tutorial/java/javaOO/\" rel=\"nofollow noreferrer\">create as your own class</a>.</p>\n\n<ul>\n<li>The <code>MyMatrix</code> class itself can contain the <code>getInput</code> method and a <code>public MyMatrix multiply(MyMatrix otherMatrix)</code> method.</li>\n<li>It can also contain <code>double[][] matrixData</code></li>\n<li>The class can contain an <code>output</code> method for outputting it's internal <code>matrixData</code>.</li>\n<li>It can also contain, if you want, <code>private final int columns;</code> and <code>private final int rows;</code></li>\n</ul>\n\n<p>This is what I would ultimately recommend, as it will allow you to add an <code>add</code> method, and a whole lot of other matrix-specific methods such as <code>calculateInverseMatrix</code>.</p>\n\n<h1>Constants</h1>\n\n<p>The only variables I can accept being <code>static</code> are the ones marked <code>final</code> (the constants). I would however make a minor change to one of them, as there's no meaning to use string concatenation here: <code>\"Terminated\" + \",\" + \" \"</code>.</p>\n\n<pre><code>private static final String TERMINATED_MESSAGE = \"Terminated, \";\n</code></pre>\n\n<h1>Use exceptions rather than <code>errorFlag</code></h1>\n\n<pre><code> if (firstMatrixRows == 0 || firstMatrixcolumns == 0 || secondMatrixRows == 0 || secondMatrixColumns == 0) {\n throw new IllegalStateException(INVALID_MATRIX_DIMENSION_ERROR_MESSAGE);\n } else if (firstMatrixcolumns != secondMatrixRows) {\n throw new IllegalStateException(MATRIX_MISMATCH_ERROR_MESSAGE);\n }\n</code></pre>\n\n<p>Throwing an exception is to be used for exceptional cases. You should perhaps consider <a href=\"https://stackoverflow.com/questions/8423700/how-to-create-a-custom-exception-type-in-java\">creating your own Exception class</a>, and ask yourself if you want it to be a <a href=\"http://www.javapractices.com/topic/TopicAction.do?Id=129\" rel=\"nofollow noreferrer\">checked or unchecked exception</a>.</p>\n\n<p>Once you have created your own <code>MyMatrix</code> class and restructured your program a bit to use more object orientation (remember my challenge, get rid of all those static variables!) I hope that you will write a follow-up question and that I will say \"Well done! You did it!\".</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-05-05T12:09:59.217", "Id": "48972", "ParentId": "48969", "Score": "17" } } ]
{ "AcceptedAnswerId": "48972", "CommentCount": "1", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-05-05T11:36:19.840", "Id": "48969", "Score": "10", "Tags": [ "java", "optimization", "algorithm", "matrix" ], "Title": "Matrix multiplication" }
48969
<p>This question is a followup from my previous question <a href="https://codereview.stackexchange.com/questions/48869/my-eventbus-system">My EventBus system</a>, and incorporates most points from <a href="https://codereview.stackexchange.com/a/48889/32231">@rolfl's answer</a>.</p> <p>It includes, but is not limited to:</p> <ul> <li>Usage of <code>Collections.synchronizedSet</code> over manual <code>synchronized { }</code> on trivial methods.</li> <li>Minimal locking</li> <li>High performance code, but <strong>not</strong> going into micro-optimizations if it harms the readability of the code.</li> </ul> <p>The code:</p> <pre><code>@Retention(RetentionPolicy.RUNTIME) @Target(ElementType.METHOD) public @interface Event { } </code></pre> <hr> <pre><code>public interface EventBus { void registerListenersOfObject(final Object callbackObject); &lt;T&gt; void registerListener(final Class&lt;T&gt; eventClass, final Consumer&lt;? extends T&gt; eventListener); void executeEvent(final Object event); void removeListenersOfObject(final Object callbackObject); &lt;T&gt; void removeListener(final Class&lt;T&gt; eventClass, final Consumer&lt;? extends T&gt; eventListener); void removeAllListenersOfEvent(final Class&lt;?&gt; eventClass); void removeAllListeners(); } </code></pre> <hr> <pre><code>public class SimpleEventBus implements EventBus { private final static Set&lt;EventHandler&gt; EMPTY_SET = new HashSet&lt;&gt;(); private final static EventHandler[] EMPTY_ARRAY = new EventHandler[0]; private final ConcurrentMap&lt;Class&lt;?&gt;, Set&lt;EventHandler&gt;&gt; eventMapping = new ConcurrentHashMap&lt;&gt;(); private final Class&lt;?&gt; eventClassConstraint; public SimpleEventBus() { this(Object.class); } public SimpleEventBus(final Class&lt;?&gt; eventClassConstraint) { this.eventClassConstraint = Objects.requireNonNull(eventClassConstraint); } @Override public void registerListenersOfObject(final Object callbackObject) { Arrays.stream(callbackObject.getClass().getMethods()) .filter(this::isEligibleMethod) .forEach(method -&gt; { Class&lt;?&gt; eventClass = method.getParameterTypes()[0]; addEventHandler(eventClass, new MethodEventHandler(method, callbackObject, eventClass)); }); } @Override @SuppressWarnings("unchecked") public &lt;T&gt; void registerListener(final Class&lt;T&gt; eventClass, final Consumer&lt;? extends T&gt; eventListener) { Objects.requireNonNull(eventClass); Objects.requireNonNull(eventListener); if (eventClassConstraint.isAssignableFrom(eventClass)) { addEventHandler(eventClass, new ConsumerEventHandler((Consumer&lt;Object&gt;)eventListener)); } } @Override public void executeEvent(final Object event) { if (eventClassConstraint.isAssignableFrom(event.getClass())) { getCopyOfEventHandlers(event.getClass()).forEach(eventHandler -&gt; eventHandler.invoke(event)); } } @Override public void removeListenersOfObject(final Object callbackObject) { Arrays.stream(callbackObject.getClass().getMethods()) .filter(this::isEligibleMethod) .forEach(method -&gt; { Class&lt;?&gt; eventClass = method.getParameterTypes()[0]; removeEventHandler(eventClass, new MethodEventHandler(method, callbackObject, eventClass)); }); } @Override @SuppressWarnings("unchecked") public &lt;T&gt; void removeListener(final Class&lt;T&gt; eventClass, final Consumer&lt;? extends T&gt; eventListener) { Objects.requireNonNull(eventClass); Objects.requireNonNull(eventListener); if (eventClassConstraint.isAssignableFrom(eventClass)) { removeEventHandler(eventClass, new ConsumerEventHandler((Consumer&lt;Object&gt;)eventListener)); } } @Override public void removeAllListenersOfEvent(final Class&lt;?&gt; eventClass) { eventMapping.remove(Objects.requireNonNull(eventClass)); } @Override public void removeAllListeners() { eventMapping.clear(); } private boolean isEligibleMethod(final Method method) { return (method.getAnnotation(Event.class) != null &amp;&amp; method.getReturnType().equals(void.class) &amp;&amp; method.getParameterCount() == 1 &amp;&amp; eventClassConstraint.isAssignableFrom(method.getParameterTypes()[0])); } private void addEventHandler(final Class&lt;?&gt; eventClass, final EventHandler eventHandler) { Objects.requireNonNull(eventClass); Objects.requireNonNull(eventHandler); eventMapping.putIfAbsent(eventClass, Collections.synchronizedSet(new HashSet&lt;&gt;())); eventMapping.get(eventClass).add(eventHandler); } private void removeEventHandler(final Class&lt;?&gt; eventClass, final EventHandler eventHandler) { Objects.requireNonNull(eventClass); Objects.requireNonNull(eventHandler); eventMapping.getOrDefault(eventClass, EMPTY_SET).remove(eventHandler); } private Stream&lt;EventHandler&gt; getCopyOfEventHandlers(final Class&lt;?&gt; eventClass) { Set&lt;EventHandler&gt; eventHandlers = eventMapping.get(Objects.requireNonNull(eventClass)); return (eventHandlers == null) ? Stream.empty() : Arrays.stream(eventHandlers.toArray(EMPTY_ARRAY)); } private static interface EventHandler { void invoke(final Object event); } private static class MethodEventHandler implements EventHandler { private final Method method; private final Object callbackObject; private final Class&lt;?&gt; eventClass; public MethodEventHandler(final Method method, final Object object, final Class&lt;?&gt; eventClass) { this.method = Objects.requireNonNull(method); this.callbackObject = Objects.requireNonNull(object); this.eventClass = Objects.requireNonNull(eventClass); } @Override public void invoke(final Object event) { try { method.setAccessible(true); method.invoke(callbackObject, Objects.requireNonNull(event)); } catch (IllegalAccessException | IllegalArgumentException | InvocationTargetException ex) { throw new RuntimeException(ex); } } @Override public int hashCode() { int hash = 7; hash = 71 * hash + Objects.hashCode(this.method); hash = 71 * hash + Objects.hashCode(this.callbackObject); hash = 71 * hash + Objects.hashCode(this.eventClass); return hash; } @Override public boolean equals(final Object obj) { if (obj == null) { return false; } if (getClass() != obj.getClass()) { return false; } final MethodEventHandler other = (MethodEventHandler)obj; if (!Objects.equals(this.method, other.method)) { return false; } if (!Objects.equals(this.callbackObject, other.callbackObject)) { return false; } if (!Objects.equals(this.eventClass, other.eventClass)) { return false; } return true; } } private static class ConsumerEventHandler implements EventHandler { private final Consumer&lt;Object&gt; eventListener; public ConsumerEventHandler(final Consumer&lt;Object&gt; consumer) { this.eventListener = Objects.requireNonNull(consumer); } @Override public void invoke(final Object event) { eventListener.accept(Objects.requireNonNull(event)); } @Override public int hashCode() { int hash = 5; hash = 19 * hash + Objects.hashCode(this.eventListener); return hash; } @Override public boolean equals(final Object obj) { if (obj == null) { return false; } if (getClass() != obj.getClass()) { return false; } final ConsumerEventHandler other = (ConsumerEventHandler)obj; if (!Objects.equals(this.eventListener, other.eventListener)) { return false; } return true; } } } </code></pre> <p>The unit tests of the old version are still valid and also still pass.</p>
[]
[ { "body": "<p>While synchronization is correct now, <code>Collections.synchronizedSet(new HashSet&lt;&gt;()))</code> is still a fairly coarse grained way to synchronize. You can replace this with <code>Collections.newSetFromMap(new ConcurrentHashMap&lt;&gt;())</code> to benefit from the better locking strategy of <code>ConcurrentHashMap</code>.</p>\n\n<p>Getting a value from a Map, or entering one if absent is made easier using lambdas in Java 8 using <code>Map.computeIfAbsent()</code> you can substitute :</p>\n\n<pre><code>eventMapping.putIfAbsent(eventClass, Collections.newSetFromMap(new ConcurrentHashMap&lt;&gt;()));\neventMapping.get(eventClass).add(eventHandler);\n</code></pre>\n\n<p>by</p>\n\n<pre><code>eventMapping.computeIfAbsent(eventClass, k -&gt; Collections.newSetFromMap(new ConcurrentHashMap&lt;&gt;())).add(eventHandler);\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-05-07T08:44:09.647", "Id": "86299", "Score": "0", "body": "Thanks a lot! This greatly clarified my code. There really should have been more focus on `computeIfAbsent` (in the docs/tutorials/highlights) as this makes using multimaps a lot easier. Also I decided to obtain a set as the following: `private final static Supplier<Set<EventHandler>> CONCURRENT_SET_SUPPLIER = () -> Collections.newSetFromMap(new ConcurrentHashMap<>());`" } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-05-05T22:29:50.297", "Id": "49023", "ParentId": "48970", "Score": "4" } }, { "body": "<p>There are two bugs related to type system:</p>\n\n<p>Currently if all three parameter types, <code>registerListener</code>'s first, and registered <code>Consumer</code>'s and <code>executeEvent</code>'s, it works as expected.</p>\n\n<pre><code>@Test\npublic void worksAsExpected() {\n String expected = \"WORKS\";\n AtomicReference&lt;String&gt; actual = new AtomicReference&lt;&gt;(null);\n EventBus bus = new SimpleEventBus(String.class);\n bus.registerListener(String.class, (String s)-&gt; {actual.set(s);});\n bus.executeEvent(expected);\n assertEquals(expected, actual.get());\n}\n</code></pre>\n\n<p>In the below case I register a listener for events of type <code>Number</code> and execute and event of type <code>Number</code> but it fails to execute the handler:</p>\n\n<pre><code>@Test\npublic void shouldHaveWorkedButDoesNot() {\n Number expected = 1;\n AtomicReference&lt;Number&gt; actual = new AtomicReference&lt;&gt;(null);\n EventBus bus = new SimpleEventBus(Number.class);\n bus.registerListener(Number.class, (Number n)-&gt; {actual.set(n);});\n bus.executeEvent(expected);\n assertEquals(expected, actual.get());\n}\n</code></pre>\n\n<p>This happens because in the <code>getCopyOfEventHandlers</code> only gets the handlers registered for runtime type of the executed <code>event</code>. It should get handlers registered for the runtime type <em>or any super-type thereof</em>.</p>\n\n<p>To fix this; <code>getCopyOfEventHandlers</code> should be something like:</p>\n\n<pre><code>private Set&lt;EventHandler&gt; getEventHandlersFor(final Class&lt;?&gt; eventClass) {\n return eventMapping.entrySet().stream()\n .filter(entry -&gt; entry.getKey().isAssignableFrom(eventClass))\n .flatMap(entry -&gt; entry.getValue().stream())\n .collect(Collectors.toSet());\n}\n</code></pre>\n\n<p>The second type problem is this:</p>\n\n<p>When I register a handler for <code>Number</code>s and it will run for any <code>Number</code>s. Some might be <code>Float</code>s, others might be <code>AtomicLong</code>s. If I register a <code>Consumer&lt;AtomicInteger&gt;</code> to handle <code>Number</code>s and pass in a <code>Float</code>, which is a <code>Number</code>, I will get a runtime exception.</p>\n\n<pre><code>@Test\npublic void shouldNotCompileButDoes() {\n EventBus bus = new SimpleEventBus(Number.class);\n // Not all Numbers are AtomicIntegers so this is a type error\n bus.registerListener(Number.class, \n (AtomicInteger n)-&gt; {System.out.println(n.get());});\n Number someNumber = 4f;\n bus.executeEvent(someNumber); // e.g. Float does not have .get()\n}\n</code></pre>\n\n<p>Conversely if I register a <code>Consumer&lt;Object&gt;</code> to handle <code>Number</code>s and pass in any <code>Float</code>, I will always run. In fact obviously a <code>Consumer&lt;Object&gt;</code> can <code>accept</code> any object.</p>\n\n<pre><code>@Test\npublic void shouldCompileButDoesNot() {\n EventBus bus = new SimpleEventBus(Number.class);\n // All Numbers are Objects this would work\n// bus.registerListener(Number.class, \n// (Object o)-&gt; {System.out.println(o);});\n Number someNumber = 4f;\n bus.executeEvent(someNumber);\n}\n</code></pre>\n\n<p>To fix this; you should replace <code>Consumer&lt;? extends T&gt; eventListener</code> in <code>registerListener</code>s signature with <code>Consumer&lt;? super T&gt;</code>. In fact because the <code>T</code> only appears a parameter type in <code>Consumer&lt;T&gt;</code> declaration, a parameter of type <code>Consumer&lt;? extends T&gt;</code> should either be a type error or could be replaced by just <code>Consumer&lt;?&gt;</code>. I suspect latter might be the case for <code>removeListener</code>.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-05-06T09:49:08.350", "Id": "49053", "ParentId": "48970", "Score": "5" } } ]
{ "AcceptedAnswerId": "49053", "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-05-05T11:37:25.680", "Id": "48970", "Score": "6", "Tags": [ "java", "thread-safety", "reflection", "event-handling" ], "Title": "My EventBus system followup" }
48970
<p>I have requirement to apply multiple filters on database. I will have multiple conditions in the front end where the user can select the conditions he wants to filter with and then see the output. This is similar to the filter that Freshdesk has or for instance similar to many ecommerece sites.</p> <p>This is my CoffeeScript file:</p> <pre><code>read = -&gt; $("#payment_status_filter :checkbox").click -&gt; collect_data() $("#status_filter :checkbox").click -&gt; collect_data() collect_data = -&gt; status_array = [] if $("#status_filter :checkbox").is(":checked") console.log("####*******status filter##########@@@@@@") $("#status_filter :checked").each -&gt; status_array.push $(this).val() console.log(status_array) payment_status_array = [] if $("#payment_status_filter :checkbox").is(":checked") $("#payment_status_filter :checked").each -&gt; console.log("*****PAYMENT STATUS**********") payment_status_array.push $(this).val() console.log(payment_status_array) ajax_call(payment_status_array,status_array) ajax_call= (payment_status,status) -&gt; $.ajax( type: "GET" url: "/admin/filter_request" format: 'js' dataType: "script" data: payment_status: payment_status status: status ).done (data) -&gt; console.log data $(".request_table_span").html data return $(document).ready read $(document).on "page:load", read </code></pre> <p>What I am doing above is that when the user clicks a checkbox for a <code>payment_status</code> conditions say "Paid" or "Unpaid" then it will fire a ajax request to a controller which will respond with a result. I have written such that when the requisite condition is clicked all the conditions in the whole page will be collected and sent along because more than one filter can be applied at the same time.</p> <p>The following is my controller code:</p> <pre><code>def filter_request Rails.logger.info params @requests = Request.all @requests = @requests.where(payment_status: params[:payment_status]) if params[:payment_status] @requests = @requests.where(status: params[:status]) if params[:status] respond_to do |format| format.js end end </code></pre> <p>The above approach seems not very good when the requirement has many filters, especially the controller part. How do I go about this? Any better approaches?</p>
[]
[ { "body": "<p>I would advise you to implement search in Index action. If there are no search filters passed, then simply return everything (both for HTML and JSON).</p>\n\n<p>You should rebuild a bit of the form so search params are nested, and you won't have to filter them.</p>\n\n<p>Finally, you can move the search logic to model:</p>\n\n<pre><code>class Request\n def self.search(opts={})\n #reject empty filters\n filters = opts.reject(&amp;:blank?)\n where(filters)\n end\nend\n\nclass RequestsController\n def index\n @requests = Request.search(params[:search])\n end\nend\n</code></pre>\n\n<p>Now you need to worry only about passing correct params (form fields should match db columns). Some transformations may be necessary depending on how you expect to build the query.</p>\n\n<p>Be sure to fully test the form with integration spec; you are relying on view a lot.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-06-12T12:23:28.953", "Id": "54061", "ParentId": "48971", "Score": "1" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-05-05T11:59:32.133", "Id": "48971", "Score": "2", "Tags": [ "performance", "ruby-on-rails", "search", "coffeescript", "active-record" ], "Title": "Multiple search filter like the one in freshdesk" }
48971
<p>I wrote a short program for my exercise routine. It takes a JSON array of exercise names and duration (seconds) and puts it on the screen. The JSON looks like this:</p> <pre><code>var exerciseArray = [ { "desc": "Pushup/Pullup", "countdown": 30 }, { "desc": "Squat punch", "countdown": 45 }, { "desc": "Jumping jacks", "countdown": 60 } ]; </code></pre> <p>The function works, but it seems to be to be kind of a kludge. My problem was that I couldn't figure out how work with <code>setInterval</code> to iterate through the list of exercises (<code>exerciseArray</code>). What I did in the end is just decrement the <code>countdown</code> value, and when it's zero, move to the next item in <code>exerciseArray</code> (<code>i++;</code>). When I hit the end of the array — as measured by <code>i</code> and <code>exerciseArray.length</code> — I just run <code>clearInterval</code> and I'm done. Code below (I removed some of the extraneous stuff that just updates the HTML with the number of seconds, you can see the full thing on <a href="http://github.com/eykanal/exerciseTimer" rel="nofollow">github</a>):</p> <pre><code>function exerciseTimer(exerciseArray) { var i = 0; var exerciseObject = exerciseArray[i]; // do stuff var tt = setInterval(function() { var exerciseObject = exerciseArray[i]; // write html to the page exerciseObject.countdown = exerciseObject.countdown - 1; if (exerciseObject.countdown &lt;= 0) { if(i &lt; (exerciseArray.length - 1)) { i++; } else { clearInterval(tt); } } }, 100); } </code></pre> <p>My question is, what is the appropriate way to iterate while using <code>setInterval</code>? Is there a cleaner way? This feels very ugly to me.</p>
[ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-05-05T14:07:47.857", "Id": "86002", "Score": "0", "body": "Is your intent to have the code write some HTML, wait until that exercise timeout, and then write some different HTML and then wait for the next timeout, or are you doing updates or executing other code **during** the period of each exercise?" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-05-05T19:00:55.353", "Id": "86056", "Score": "0", "body": "@Edward - There are updates during the exercise; namely, the timer counts down." } ]
[ { "body": "<p>If you only need the entries once, you could simply keep using <code>shift</code> until there are no more entries:</p>\n\n<pre><code>var exercises = [\n {\n \"desc\": \"Pushup/Pullup\",\n \"countdown\": 30\n }, {\n \"desc\": \"Squat punch\",\n \"countdown\": 45\n }, {\n \"desc\": \"Jumping jacks\",\n \"countdown\": 60\n }\n];\n\nfunction exerciseTimer(exercises) {\n // do stuff\n var exercise = exercises.shift(),\n tt = setInterval(function() {\n // write html to the page\n exercise.countdown = exercise.countdown - 1;\n //Does it work ?\n console.log( exercise );\n if (exercise.countdown &lt;= 0) { \n exercise = exercises.shift(); \n if(!exercise) {\n clearInterval(tt);\n }\n }\n }, 100);\n };\n\nexerciseTimer( exercises );\n</code></pre>\n\n<p>I would also suggest to not make the type of the variable part of the variable name. <code>exercise</code> and <code>exercises</code> are much easier to read than <code>exerciseArray</code> and <code>exerciseObject</code>. </p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-05-05T14:17:53.213", "Id": "48984", "ParentId": "48978", "Score": "4" } }, { "body": "<p>Assuming that what you want is to iterate through each exercise, display something static and wait for the timeout to expire before moving on to the next, I might do it like this:</p>\n\n<pre><code>&lt;h1 id=\"exercisename\"&gt;Get Ready&lt;/h1&gt;\n&lt;h2 id=\"seconds\"&gt;0&lt;/h2&gt;\n&lt;p&gt;Click the button to start the exercises.&lt;/p&gt;\n&lt;button onclick=\"nextExercise()\"&gt;Begin&lt;/button&gt; \n&lt;script&gt;\nvar exercises = [\n {\n \"desc\": \"Pushup/Pullup\",\n \"countdown\": 3\n }, {\n \"desc\": \"Squat punch\",\n \"countdown\": 4\n }, {\n \"desc\": \"Jumping jacks\",\n \"countdown\": 6\n }\n];\nvar excount = 0;\nvar timeleft = 0;\nvar secondsTimer;\nfunction setSeconds(s)\n{\n var sec = document.getElementById('seconds');\n sec.textContent = timeleft;\n}\nfunction tick()\n{\n setSeconds(timeleft--);\n if (timeleft &lt;= 0){\n clearInterval(secondsTimer);\n }\n}\nfunction nextExercise()\n{\n var ex = exercises[excount++];\n var name = document.getElementById('exercisename');\n if (typeof ex == 'undefined') {\n name.textContent = \"Done\";\n excount = 0;\n } else {\n name.textContent = ex.desc+\" for \"+ex.countdown+\" seconds\";\n timeleft = ex.countdown;\n setSeconds(timeleft);\n secondsTimer = setInterval(tick, 1000);\n setTimeout(nextExercise,ex.countdown*1000);\n }\n}\n&lt;/script&gt;\n</code></pre>\n\n<p>Obviously for a real workout, you'd probably want to increase the times a bit. :)</p>\n\n<h2>Update:</h2>\n\n<p>Based on a comment, I've also added a countdown timer. Note that the countdown is handled as using <code>setInterval</code> while the exercise timers use a separate and independent <code>setTimeout</code>.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-05-05T15:52:01.327", "Id": "86020", "Score": "0", "body": "The way this works now, I have it counting down for me. I use the `setIterator` to change the displayed second as time progresses. This is a minor decrease in functionality." } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-05-05T14:58:21.623", "Id": "48989", "ParentId": "48978", "Score": "4" } } ]
{ "AcceptedAnswerId": "48984", "CommentCount": "2", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-05-05T13:13:12.113", "Id": "48978", "Score": "4", "Tags": [ "javascript", "timer", "iteration" ], "Title": "Iterate through series of timers" }
48978
<p>I was tasked with making a program that uploads a .csv to a NoSQL cluster. The files are larger (typically 2-17GB). My program works in batch mode and can process a 17GB file in 6 hours.</p> <p>I decided to make a consumer-producer multithreading structure. This caused it to be significantly slower. I want to know why the producer-consumer construct was slower than a batch produce, batch consume method.</p> <p>The batch looks like this:</p> <pre><code>int count = 0; // Row r; while ((r = rm.getNextRow()) != null) { RowQueue.Enqueue(r); while (RowQueue.Count &lt;= ROWMAX) { if ((r = rm.getNextRow()) != null) RowQueue.Enqueue(r); else break; } // int uniqueIdentifer = -1; if (count &gt; 1000) { PrintAndSavePosition(count, rm, positionQueue, true); count = 0; } //give it some extra room to be safe while (RowQueue.Count != 0) { r = RowQueue.Dequeue(); while (uniqueIdentifer == -1) { uniqueIdentifer = nsqw.tryPut(r); if (uniqueIdentifer == -1) Thread.Sleep(1); } count++; } positionQueue.Add(new Tuple&lt;int, long&gt;(uniqueIdentifer, rm.Position)); } </code></pre> <p>As compared to</p> <pre><code>public void produceLoop(){ while (true) { while (RowQueue.Count &lt;= ROWMAX &amp;&amp; (r = rm.getNextRow()) != null){ RowQueue.Enqueue(r); } } } public void consumeLoop(){ while(true){ while (RowQueue.Count != 0) { RowQueue.TryDequeue(out r); while (uniqueIdentifer == -1) { uniqueIdentifer = nsqw.tryPut(r); if (uniqueIdentifer == -1) Thread.Sleep(1); } count++; } positionQueue.Add(new Tuple&lt;int, long&gt;(uniqueIdentifer, rm.Position)); } } } </code></pre> <p>The bottom half are infinite loops for a speed test.</p>
[]
[ { "body": "<p>I'm not an expert in cluster operations, so I'll review the parts I do know.</p>\n\n<p><strong>Single-letter variable names</strong></p>\n\n<p>These are a big no-no unless the only thing you're worried about is not being fireable. Any maintenance programmer looking in the middle of a chunk of code is not going to be happy jumping back and forwards to definitions to work out what on earth <code>r</code> is when you could just as easily have written <code>row</code>.</p>\n\n<p><strong>var</strong></p>\n\n<p>You should use <code>var</code> when the right hand side of an assignment makes the type obvious. e.g.</p>\n\n<p><code>int uniqueIdentifier = 1;</code></p>\n\n<p>should be</p>\n\n<p><code>var uniqueIdentifier = 1;</code></p>\n\n<p>This is recommended because if you decide to change the type (e.g. to a GUID), you only have to change it in one place.</p>\n\n<p><strong>Style</strong></p>\n\n<p>In C# the general naming guideline for methods is to use PascalCase. This is, of course, optional (as with any point on style), but recommended to make code easier to read for another programmer.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-10-30T11:00:17.143", "Id": "68371", "ParentId": "48981", "Score": "2" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-05-05T13:53:18.517", "Id": "48981", "Score": "1", "Tags": [ "c#", "multithreading" ], "Title": "Uploading a .csv to a NoSQL cluster - batch faster than consumer/producer" }
48981
<p>As an exercise, I decided to create a simple Tic-Tac-Toe game. It is Ruby on Rails based, but as for now I'm not using the server side for anything (I intend to build up on it in the future, though).</p> <p>As I'm rather new with JavaScript, HTML5 and CSS, I'd like some feedback regarding what did I do wrong or what could be done better.</p> <p>index.html.erb</p> <pre><code>&lt;!DOCTYPE html&gt; &lt;div id="container"&gt; &lt;div class="row"&gt; &lt;canvas class="field" id="f11" width="150" height="150" token="None"&gt;&lt;/canvas&gt; &lt;canvas class="field" id="f12" width="150" height="150" token="None"&gt;&lt;/canvas&gt; &lt;canvas class="field" id="f13" width="150" height="150" token="None"&gt;&lt;/canvas&gt; &lt;/div&gt; &lt;div class="row"&gt; &lt;canvas class="field" id="f21" width="150" height="150" token="None"&gt;&lt;/canvas&gt; &lt;canvas class="field" id="f22" width="150" height="150" token="None"&gt;&lt;/canvas&gt; &lt;canvas class="field" id="f23" width="150" height="150" token="None"&gt;&lt;/canvas&gt; &lt;/div&gt; &lt;div class="row"&gt; &lt;canvas class="field" id="f31" width="150" height="150" token="None"&gt;&lt;/canvas&gt; &lt;canvas class="field" id="f32" width="150" height="150" token="None"&gt;&lt;/canvas&gt; &lt;canvas class="field" id="f33" width="150" height="150" token="None"&gt;&lt;/canvas&gt; &lt;/div&gt; &lt;div class="row"&gt; &lt;canvas id="reset" width="150" height="50"&gt;&lt;/canvas&gt; &lt;/div&gt; &lt;/div&gt; </code></pre> <p>tic_tac_toe.js</p> <pre><code>var tokenAttributeName = 'token'; var idAttributeName = 'id'; var circleTokenName = 'Circle'; var crossTokenName = 'Cross'; var noTokenName = 'None'; var circleColor = 'green'; var crossColor = 'red'; var fontColor = 'black'; var font = "bold 30px Helvetica"; var resetText = "Reset"; var hoverOnOpacity = 1.0; var hoverOffOpacity = 0.75; var highlightTime = 100; var turn = circleTokenName; var won = false; $(document).ready(function() { drawResetCanvas(); $('canvas#reset').click(function(e) { location.reload(); }); $('canvas').hover( function(e) { var field = $(this); field.animate({ opacity: hoverOnOpacity }, highlightTime); }, function(e) { var field = $(this); field.animate({ opacity: hoverOffOpacity }, highlightTime); }); $('canvas.field').click(function(e) { var field = $(this); var fieldId = field.attr(idAttributeName); if (field.attr(tokenAttributeName) != noTokenName || won) { return; } if (turn == circleTokenName) { drawCircle(fieldId); field.attr(tokenAttributeName, circleTokenName); } else { drawCross(fieldId); field.attr(tokenAttributeName, crossTokenName); } //field.animate({opacity: 1.0}, 0, function() { field.animate({opacity:0.75},2000)}); if (checkWin(turn)) { alert(turn + ' won!'); won = true; } else if (checkDraw()) { alert('Draw!'); }; turn = turn == circleTokenName ? crossTokenName : circleTokenName; }); }); function checkWin(figure) { return ( checkRows(figure) || checkCols(figure) || checkDiagonals(figure) ); }; function checkRows(figure) { return ( checkRow(1, figure) || checkRow(2, figure) || checkRow(3, figure) ); }; function checkRow(rowId, figure) { return ( checkField(rowId, 1, figure) &amp;&amp; checkField(rowId, 2, figure) &amp;&amp; checkField(rowId, 3, figure) ); }; function checkCols(figure) { return ( checkCol(1, figure) || checkCol(2, figure) || checkCol(3, figure) ); }; function checkCol(colId, figure) { return ( checkField(1, colId, figure) &amp;&amp; checkField(2, colId, figure) &amp;&amp; checkField(3, colId, figure) ); }; function checkDiagonals(figure) { return ( checkField(1, 1, figure) &amp;&amp; checkField(2, 2, figure) &amp;&amp; checkField(3, 3, figure) ) || ( checkField(1, 3, figure) &amp;&amp; checkField(2, 2, figure) &amp;&amp; checkField(3, 1, figure) ); }; function checkDraw() { return !( checkField(1, 1, noTokenName) || checkField(1, 2, noTokenName) || checkField(1, 3, noTokenName) || checkField(2, 1, noTokenName) || checkField(2, 2, noTokenName) || checkField(2, 3, noTokenName) || checkField(3, 1, noTokenName) || checkField(3, 2, noTokenName) || checkField(3, 3, noTokenName) ); }; function checkField(rowId, colId, figure) { return $('canvas#f' + rowId + colId).attr(tokenAttributeName) == figure } function drawCircle(fieldId) { var canvas = document.getElementById(fieldId); var context = canvas.getContext('2d'); var centerX = canvas.width / 2; var centerY = canvas.height / 2; var innerRadius = 0.5 * canvas.width / 2; var outerRadius = 0.75 * canvas.width / 2; context.beginPath(); context.arc(centerX, centerY, outerRadius, 0, 2 * Math.PI, false); context.arc(centerX, centerY, innerRadius, 0, 2 * Math.PI, true); context.fillStyle = circleColor; context.fill(); }; function drawCross(fieldId) { var canvas = document.getElementById(fieldId); var context = canvas.getContext('2d'); var centerX = canvas.width / 2; var centerY = canvas.height / 2; var innerMostPointsOffset = 0.20 * canvas.width / 2; var innerEndingPointsXOffset = 0.4 * canvas.width / 2; var innerEndingPointsYOffset = 0.75 * canvas.width / 2; var outerEndingPointsXOffset = 0.75 * canvas.width / 2; var outerEndingPointsYOffset = 0.75 * canvas.width / 2; context.fillStyle = crossColor; context.beginPath(); context.moveTo(centerX - innerMostPointsOffset, centerY); context.lineTo(centerX - outerEndingPointsXOffset, centerY - outerEndingPointsYOffset); context.lineTo(centerX - innerEndingPointsXOffset, centerY - innerEndingPointsYOffset); context.lineTo(centerX, centerY - innerMostPointsOffset); context.lineTo(centerX + innerEndingPointsXOffset, centerY - innerEndingPointsYOffset); context.lineTo(centerX + outerEndingPointsXOffset, centerY - outerEndingPointsYOffset); context.lineTo(centerX + innerMostPointsOffset, centerY); context.lineTo(centerX + outerEndingPointsXOffset, centerY + outerEndingPointsYOffset); context.lineTo(centerX + innerEndingPointsXOffset, centerY + innerEndingPointsYOffset); context.lineTo(centerX, centerY + innerMostPointsOffset); context.lineTo(centerX - innerEndingPointsXOffset, centerY + innerEndingPointsYOffset); context.lineTo(centerX - outerEndingPointsXOffset, centerY + outerEndingPointsYOffset); context.closePath(); context.fill(); }; function drawResetCanvas() { var canvas = document.getElementById("reset"); var context = canvas.getContext("2d"); context.fillStyle = fontColor; context.font = font; context.fillText(resetText, 35, 35); }; </code></pre> <p>tic_tac_toe.css</p> <pre><code>canvas { background-color: #DDDDDD; width: 150px; border: 1px solid white; float: left; opacity: 0.75; } canvas.field { height: 150px; } div.row { width: 456px; margin: 0 auto; } div#container { width: 100%; } canvas#reset { height: 50px; margin-top: 30px; margin-left: 152px; } </code></pre>
[ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-05-10T23:57:09.997", "Id": "86934", "Score": "0", "body": "http://jsfiddle.net/sd563/" } ]
[ { "body": "<p>First, a (proper) HTML document looks like this:</p>\n\n<pre><code>&lt;!DOCTYPE html&gt;\n&lt;html&gt;\n &lt;head&gt;\n &lt;title&gt;Tic tac toe&lt;/title&gt;\n &lt;/head&gt;\n &lt;body&gt;\n &lt;!-- Stuff --&gt;\n &lt;/body&gt;\n&lt;/html&gt;\n</code></pre>\n\n<p>Html, head, body, and title are strongly recommended, tho <a href=\"https://stackoverflow.com/questions/5641997/is-it-necessary-to-write-head-body-and-html-tags\">not required</a>.</p>\n\n<p>You seem to be using <code>&lt;canvas&gt;</code>s a lot… why? Can't you just make them images?</p>\n\n<pre><code>&lt;div class=\"row\"&gt;\n &lt;img class=\"field\" /&gt;\n &lt;img class=\"field\" /&gt;\n &lt;img class=\"field\" /&gt;\n&lt;/div&gt;\n&lt;div class=\"row\"&gt;\n &lt;img class=\"field\" /&gt;\n &lt;img class=\"field\" /&gt;\n &lt;img class=\"field\" /&gt;\n&lt;/div&gt;\n&lt;div class=\"row\"&gt;\n &lt;img class=\"field\" /&gt;\n &lt;img class=\"field\" /&gt;\n &lt;img class=\"field\" /&gt;\n&lt;/div&gt;\n</code></pre>\n\n<p>Canvases are ugly and pixely, images are beautiful and potentially vector (or at least easier to make high-res (important for retina devices)). The only downside is you have to create the images… but I just did it for you (tweak to your liking):</p>\n\n<pre><code>&lt;svg xmlns=\"http://www.w3.org/2000/svg\" width=\"50\" height=\"50\" fill=\"#f00\"&gt; &lt;!-- An X --&gt;\n &lt;polygon points=\"0,4 4,0 50,46 46,50\" /&gt;\n &lt;polygon points=\"50,4 4,50 0,46 46,0\" /&gt;\n&lt;/svg&gt;\n&lt;svg xmlns=\"http://www.w3.org/2000/svg\" width=\"50\" height=\"50\" stroke=\"#090\" stroke-width=\"5\" fill=\"none\"&gt; &lt;!-- An O --&gt;\n &lt;circle cx=\"25\" cy=\"25\" r=\"22\" /&gt;\n&lt;/svg&gt;\n</code></pre>\n\n<p>Don't make a bajillion <code>id</code>s. Instead of <code>$('canvas#f' + rowId + colId)</code>:</p>\n\n<pre><code>document.getElementById('container').children[rowId].children[colId]\n</code></pre>\n\n<p>Yeah, I hate jQuery. Especially the animations. CSS transitions are <a href=\"http://caniuse.com/#search=transition\" rel=\"nofollow noreferrer\">supported</a> wide enough that you should probably use that instead. It's smoother - the DOM isn't meant to be messed around with every 20ms (as is the case with jQuery animations).</p>\n\n<p>So, pretty good job for recent unzoomed desktop browsers with users who can't notice jQuery's slowness. Now just make it vector and vanilla and not have a bunch of… things in the DOM (ids, \"tokens\" (invalid attribute)) which can be put in arrays.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-05-05T19:03:26.147", "Id": "49008", "ParentId": "48995", "Score": "7" } }, { "body": "<p>I will only focus on your method to determine wins / draws, if you need so much code then you are probably doing something wrong ;)</p>\n\n<p>Given that tic tac toe is 3 by 3, I find that simply hard-coding is unbeatable in expressing what you want the logic to check.</p>\n\n<p>Furthermore, for determining a draw, if you are going to use jQuery, you might as well ask through jQuery whether any element has the attribute value <code>noTokenName</code>.</p>\n\n<p>So I would counter suggest something like this:</p>\n\n<pre><code>function checkWin(figure) {\n var winningTriplets = [\n [ [1,1] , [1,2] , [1,3] ], //Column 1\n [ [2,1] , [2,2] , [2,3] ], //Column 2\n [ [3,1] , [3,2] , [3,3] ], //Column 3\n [ [1,1] , [2,1] , [3,1] ], //Row 1\n [ [1,2] , [2,2] , [3,2] ], //Row 1\n [ [1,3] , [2,3] , [3,3] ], //Row 1\n [ [1,1] , [2,2] , [3,3] ], //Diagonal 1\n [ [1,3] , [2,2] , [3,1] ] //Diagonal 1\n ];\n\n for( var i = 0 ; i &lt; winningTriplets.length ; i++ ){\n if( checkTriplet( winningTriplets[i] , figure ) ){\n return true;\n }\n }\n};\n\n/* Check 3 coordinates for a given triplet\n a triplet is an array with 3 entries ( arrays ) with 2 entries \n index 0 is col, index 1 row */\nfunction checkTriplet( triplet , figure) {\n var X = 0, Y = 1;\n return (\n checkField( triplet[0][X], triplet[0][Y] , figure) ||\n checkField( triplet[1][X], triplet[1][Y] , figure) ||\n checkField( triplet[2][X], triplet[2][Y] , figure); \n );\n};\n\nfunction checkDraw() {\n var queryString = \"[\" + tokenAttributeName + \"='\" + noTokenName + \"']\";\n return !$( queryString ).length\n};\n\nfunction checkField(rowId, colId, figure) {\n return $('canvas#f' + rowId + colId).attr(tokenAttributeName) == figure\n}\n</code></pre>\n\n<p>The biggest problem I see, is that you are using the HTML elements to contain the state of your game. HTML elements were not meant for that. You should have a JS object with the game state, and then using that object you can draw the game.</p>\n\n<p>However, since this is a small game, I guess you can get away with your approach.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-05-05T19:22:30.430", "Id": "49009", "ParentId": "48995", "Score": "3" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "1", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-05-05T16:02:20.093", "Id": "48995", "Score": "11", "Tags": [ "javascript", "jquery", "game", "css", "html5" ], "Title": "HTML5 / JavaScript Tic-Tac-Toe" }
48995
<p>I have this basic Java code to find average of eight immediate neighbors of a matrix.</p> <p>Is there any way to simplify or merge any part of it, or can I refactor it?</p> <p>I'm a beginner in Java programming and am trying to improve myself. </p> <pre><code>// CODE STSRT import java.util.Scanner; import java.lang.*; class Matrixer { double[][] matrix, computedMatrix; final int rows, cols; public Matrixer(int N, int M, double[][] imatrix) { rows = N; cols = M; matrix = imatrix; computedMatrix = new double[N][M]; } public void computeAverages() { for (int i = 1; i &lt; rows - 1; i++) { for (int j = 1; j &lt; cols - 1; j++) { computedMatrix[i][j] = cellNeighborsAverage(i, j); } } } private double cellNeighborsAverage(int row, int col) { // Ignore center cell And tack Neighbors double sum = matrix[row - 1][col - 1] + matrix[row - 1][col] + matrix[row - 1][col + 1] + matrix[row][col - 1] + matrix[row][col + 1] + matrix[row + 1][col - 1] + matrix[row + 1][col] + matrix[row + 1][col + 1]; return sum / 8; } public void printComputedMatrix() { for (int i = 0; i &lt; rows; i++) { for (int j = 0; j &lt; cols; j++) { System.out.printf("%.0f", computedMatrix[i][j]); System.out.print(" "); } System.out.println(); } } public static void main(String[] args) throws NullPointerException { //This part for defined the size if matrix int R,C; Scanner rc = new Scanner(System.in); System.out.println("Enter the number of matrix's rows :"); R = rc.nextInt(); Scanner cc = new Scanner(System.in); System.out.println("Enter the number of matrix's columns :"); C = cc.nextInt(); //End of defined part // condition part To see if columns and rows not greater than 2 stop execution if(R&lt;3){System.out.println("ERROR! \n Columns and rows should be greater than 2"); }else{ // condition part To see if columns not equal rows stop execution if(R!=C){ System.out.println("ERROR! \n The number of rows should equal number of columns"); } else{ Scanner sc = new Scanner(System.in); double[][] inputMatrix = new double[R][C]; try { System.out.println("Enter The Elementt of matrix ("+R+"x"+C+")"); for (int i = 0; i &lt; R; i++) { for (int j = 0; j &lt; C; j++) { inputMatrix[i][j] = sc.nextInt(); } } Matrixer mx = new Matrixer(R, C, inputMatrix); System.out.println(" average of eight immediate neighbors is \n"); mx.computeAverages(); mx.printComputedMatrix(); } catch (NullPointerException e) { e.printStackTrace(); } } } //End of conditions part }} //END OF THE CODE </code></pre>
[]
[ { "body": "<p>Welcome to CodeReview! </p>\n\n<h1>Class naming</h1>\n\n<p>Maybe it's a term I'm not familiar with but <code>Matrixer</code> does not seem to ring a bell. Is it supposed to identify a \"creator of matrixes\"? Is it the name of your project? If you haven't made a conscious decision for this name, I would suggest turning it into something \"universally\" descriptive like <code>MatrixCalculator</code> (pretty much anything that contains the essence of what your class is supposed to achieve).</p>\n\n<h1>Indentation</h1>\n\n<p>Several places are indented incorrectly/inconsistently. Use a tab (4 spaces) for each new block level.</p>\n\n<p>I would also layout code like your <code>cellNeighborsAverage</code> like this:</p>\n\n<pre><code>double sum = matrix[row - 1][col - 1] + matrix[row - 1][col]\n + matrix[row - 1][col + 1] + matrix[row][col - 1]\n + matrix[row][col + 1] + matrix[row + 1][col - 1]\n + matrix[row + 1][col] + matrix[row + 1][col + 1];\n</code></pre>\n\n<p>It's just a bit easier to read.</p>\n\n<p>Likewise for your <code>main</code> method: the indentation is all over the place; maybe something went wrong when copy-pasting it here? Keep your <code>if</code> statements in this format:</p>\n\n<pre><code>if(condition) {\n doSomething();\n} elseif (anotherCondition) {\n doAnotherThing();\n} else {\n doNothing();\n}\n</code></pre>\n\n<h1>Parameter naming</h1>\n\n<p>Your constructor takes variables <code>N</code> and <code>M</code> in a scientific-oriented context this is an acceptable practice so it will depend on how you view this code but standard conventions state that variables use the lowerCamelCase convention.</p>\n\n<p>I would also make their meaning clearer: <code>N</code> could become <code>rows</code> and <code>M</code> would be <code>columns</code>.</p>\n\n<p>Likewise your parameter is named <code>imatrix</code>. What does that <code>i</code> signify? You can simply call it <code>matrix</code> and use <code>this.matrix</code> to refer to the instance variable inside the constructor body.</p>\n\n<p>I would also distinguish between <code>matrix</code> and <code>computedMatrix</code>. Computed what exactly? Maybe <code>sourceMatrix</code> and <code>averagedMatrix</code> are more appropriate terms?</p>\n\n<h1>Method naming</h1>\n\n<p><code>cellNeighborsAverage</code> doesn't really tell me much about what goes on in there. Something about the neighbours average, that's for sure. But what exactly does it do? Does it calculate it? Return it? Do I have to set it?</p>\n\n<p>Conventions state that your method names are built up like <code>[verb][subject]</code> which would become <code>getAverageFromNeighbours</code>.</p>\n\n<h1>NullPointerException</h1>\n\n<p>The NPE is something you should always prevent and guard against instead of throwing/catching it at runtime. You know the flow of your program and thus you should be able to determine where a NPE could occur. Guard yourself against this by validating parameters, instantiating fields inline when you can, avoid returning <code>null</code>, etc.</p>\n\n<h1>Scanners</h1>\n\n<p>You only need one <code>Scanner</code> on your <code>System.in</code> which you re-use to get input. </p>\n\n<h1>Returning instead of printing</h1>\n\n<p>Right now you're working with <code>void</code> methods that print the information directly to the console. This will bring problems when you decide to publish your library (class) online and let people use it. What if that person now wants to write the results to a textfile instead of the console?</p>\n\n<p>Likewise for unit testing this will become troublesome.</p>\n\n<p>Therefore I suggest that you return the results from your methods instead of printing to the console inside <code>Matrixer</code> itself; let the <code>main</code> class decide what happens with your results.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-05-05T21:54:17.467", "Id": "86094", "Score": "4", "body": "I'm sorry but that's not something you should ask from another person. I have given you several pointers on how you can improve your code, it's up to you to apply them." } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-05-05T18:17:19.423", "Id": "49004", "ParentId": "48996", "Score": "14" } }, { "body": "<p><a href=\"https://codereview.stackexchange.com/a/49004/38383\">Everything Jeroen Vannevel said</a>, plus the following:</p>\n\n<h1>Use guard clauses</h1>\n\n<p>Instead of using <code>if/else { /* the rest of the program */ }</code> structures, write out those conditions as <a href=\"http://refactoring.com/catalog/replaceNestedConditionalWithGuardClauses.html\" rel=\"nofollow noreferrer\">guard clauses</a>, more like <code>if(notGood) { System.err.println(\"bad\"); return; }</code> or, preferably, <code>if(notGood) { System.err.println(\"bad\"); System.exit(1); }</code> where <code>1</code> is returned as the <a href=\"http://en.wikipedia.org/wiki/Exit_status\" rel=\"nofollow noreferrer\">exit status</a> to indicate error.</p>\n\n<h1>Don't ask for two dimensions if it's a square</h1>\n\n<p>You ask for two dimensions to the array, but then error out if they are not equal. Better to ask once and indicate to the end user that it will be used for both dimensions.</p>\n\n<h1>Don't pass in parameters you can otherwise derive directly</h1>\n\n<p>Your <code>Matrixer</code> constructor takes two (poorly named) parameters <code>N</code> and <code>M</code>, in addition to the array to work from. <code>N</code> and <code>M</code> appear to represent the dimensions of the array, but these dimensions can be extracted directly from the <code>length</code> property of the <code>imatrix</code> array and first subarray. Since we know the array must be square, we can just use the array length for both. (We assume what we are getting is correct because we are the ones providing the input. If we are not the ones providing the input array, we should provide a checking mechanism to ensure proper function.)</p>\n\n<h1>Comments</h1>\n\n<p>There are a few issues with your comments. Some comments are extraneous and redundant, such as <code>// condition part To see if columns and rows not greater than 2 stop execution</code>, which literally says exactly the same thing as the code. In this case, let the code speak for itself, as it is sufficiently self-explanatory. Other comments seem to divide the code into sections. It is often better to make those divisions explicit in the code instead, for example by making it a separate method. Yet other comments have spelling errors. Comments are for communication with other human beings, and will be used especially where the code cannot be clear enough. Proper spelling and grammar are especially important to ensure that communication is as clear as possible.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-05-05T23:04:30.473", "Id": "49025", "ParentId": "48996", "Score": "6" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-05-05T16:46:52.080", "Id": "48996", "Score": "10", "Tags": [ "java", "beginner", "object-oriented", "matrix" ], "Title": "Finding average of eight immediate neighbors of a matrix" }
48996
<p>This is a simple GTK+ program that takes a spun article as input and shows a random output every time the user clicks the "Spin" button.</p> <p>It supports many levels of nested spinning like:</p> <blockquote> <pre class="lang-none prettyprint-override"><code>The {car|automobile} is {{very |}fine|{really {pretty |}|}cool|all right} </code></pre> </blockquote> <p>I tested it and it seems to be correct, but I would like to receive any suggestions on how to improve the code, specially if there's some bug I didn't notice.</p> <pre class="lang-c prettyprint-override"><code>#include &lt;gtk/gtk.h&gt; #include &lt;stdlib.h&gt; #include "dynamic_string.h" #include &lt;time.h&gt; #define SUCCESS 1 #define ERROR 0 GtkWidget *output_text; size_t get_size(const char *src) { const char *start = src; while(*++src &amp;&amp; *src != '}') if(*src == '{') src += get_size(src) - 1; return (src - start) + 1; } size_t get_count(const char *src) { size_t count = 1; while(*++src){ if(*src == '}') break; else if(*src == '|') ++count; else if(*src == '{') src += get_size(src) - 1; } return count; } const char *get_word_n(const char *start, size_t n) { size_t count = 0; while(*++start){ if(count == n) return start; if(*start == '}') break; else if(*start == '|') ++count; else if(*start == '{') start += get_size(start) - 1; } puts("Invalid format or there are not as many words as you expected."); return NULL; } int choose_one(const char *src, Dynamic_String *dest) { size_t count = get_count(src); const char *str = get_word_n(src, rand() % count); if(str == NULL) return ERROR; while(*str &amp;&amp; *str != '}' &amp;&amp; *str != '|'){ if(*str == '{'){ if(choose_one(str, dest) == ERROR) return ERROR; str += get_size(str) - 1; } else if(ds_push_back(dest, *str) == DS_ERROR) exit(1); ++str; } return SUCCESS; } gboolean spin(GtkButton *button, GdkEvent *event, GtkWidget *input) { Dynamic_String output; ds_allocate(&amp;output, 4095); GtkTextBuffer *buffer = gtk_text_view_get_buffer(GTK_TEXT_VIEW(input)); GtkTextIter start, end; gtk_text_buffer_get_bounds(buffer, &amp;start, &amp;end); char *content = gtk_text_buffer_get_text(buffer, &amp;start, &amp;end, FALSE); for(size_t i = 0; content[i] != '\0'; ++i){ if(content[i] == '{'){ if(choose_one(&amp;content[i], &amp;output) == ERROR) goto end; i += get_size(&amp;content[i]) - 1; } else if(ds_push_back(&amp;output, content[i]) == DS_ERROR) exit(1); } buffer = gtk_text_view_get_buffer(GTK_TEXT_VIEW(output_text)); gtk_text_buffer_set_text(buffer, output.cstring, -1); end: free(content); ds_free(&amp;output); return FALSE; } int main(int argc, char **argv) { srand(time(NULL)); gtk_init(&amp;argc, &amp;argv); /* Main window */ GtkWidget *window = gtk_window_new(GTK_WINDOW_TOPLEVEL); gtk_window_set_title(GTK_WINDOW(window), "Article Viewer"); gtk_container_set_border_width(GTK_CONTAINER(window), 0); gtk_window_set_default_size(GTK_WINDOW(window), 1280, 720); g_signal_connect(window, "destroy", G_CALLBACK(gtk_main_quit), NULL); /* Text container, scrolling */ GtkWidget *scrolled_window = gtk_scrolled_window_new(NULL, NULL); gtk_scrolled_window_set_policy( GTK_SCROLLED_WINDOW(scrolled_window), GTK_POLICY_AUTOMATIC, GTK_POLICY_AUTOMATIC ); gtk_widget_set_hexpand(scrolled_window, TRUE); gtk_widget_set_vexpand(scrolled_window, TRUE); /* Text container */ GtkWidget *input_text = gtk_text_view_new(); gtk_text_view_set_border_window_size( GTK_TEXT_VIEW(input_text), GTK_TEXT_WINDOW_TOP, 10 ); gtk_text_view_set_border_window_size( GTK_TEXT_VIEW(input_text), GTK_TEXT_WINDOW_BOTTOM, 10 ); gtk_text_view_set_border_window_size( GTK_TEXT_VIEW(input_text), GTK_TEXT_WINDOW_LEFT, 10 ); gtk_text_view_set_border_window_size( GTK_TEXT_VIEW(input_text), GTK_TEXT_WINDOW_RIGHT, 10 ); gtk_text_view_set_wrap_mode(GTK_TEXT_VIEW(input_text), GTK_WRAP_WORD_CHAR); /* Add text to container */ gtk_container_add(GTK_CONTAINER(scrolled_window), input_text); /* Append input tab */ GtkWidget *notebook = gtk_notebook_new(); GtkWidget *label = gtk_label_new("Input"); gtk_notebook_append_page(GTK_NOTEBOOK(notebook), scrolled_window, label); /* Output container */ GtkWidget *box = gtk_box_new(GTK_ORIENTATION_VERTICAL, 0); gtk_box_set_homogeneous(GTK_BOX(box), FALSE); /* Spin button */ GtkWidget *button = gtk_button_new_with_label("Spin"); g_signal_connect(button, "button-release-event", G_CALLBACK(spin), input_text); /* Add button to box */ gtk_box_pack_start(GTK_BOX(box), button, FALSE, FALSE, 0); /* Output scrolling */ scrolled_window = gtk_scrolled_window_new(NULL, NULL); gtk_scrolled_window_set_policy( GTK_SCROLLED_WINDOW(scrolled_window), GTK_POLICY_AUTOMATIC, GTK_POLICY_AUTOMATIC ); gtk_widget_set_hexpand(scrolled_window, TRUE); gtk_widget_set_vexpand(scrolled_window, TRUE); /* Output text */ output_text = gtk_text_view_new(); gtk_text_view_set_border_window_size( GTK_TEXT_VIEW(output_text), GTK_TEXT_WINDOW_TOP, 10 ); gtk_text_view_set_border_window_size( GTK_TEXT_VIEW(output_text), GTK_TEXT_WINDOW_BOTTOM, 10 ); gtk_text_view_set_border_window_size( GTK_TEXT_VIEW(output_text), GTK_TEXT_WINDOW_LEFT, 10 ); gtk_text_view_set_border_window_size( GTK_TEXT_VIEW(output_text), GTK_TEXT_WINDOW_RIGHT, 10 ); gtk_text_view_set_wrap_mode(GTK_TEXT_VIEW(output_text), GTK_WRAP_WORD_CHAR); /* Add output text to scrolling */ gtk_container_add(GTK_CONTAINER(scrolled_window), output_text); /* Add scrolled window to box */ gtk_box_pack_start(GTK_BOX(box), scrolled_window, TRUE, TRUE, 0); /* Append output tab */ label = gtk_label_new("Output"); gtk_notebook_append_page(GTK_NOTEBOOK(notebook), box, label); gtk_container_add(GTK_CONTAINER(window), notebook); gtk_widget_show_all(window); gtk_main(); return 0; } </code></pre> <p><strong>dynamic_string.h</strong></p> <pre class="lang-c prettyprint-override"><code>#ifndef DYNAMIC_STRING_H #define DYNAMIC_STRING_H #include &lt;stdbool.h&gt; #include &lt;stdlib.h&gt; //Size and expansion #define MULTIPLIER 1.00 //add 100% every time #define FIXED_STEP 0 //overrides multiplier #define STARTING_SIZE 32 //Return codes #define DS_SUCCESS 1 #define DS_ERROR 0 //ds_fix return codes #define DS_FIX_FULLY_WORKED DS_SUCCESS #define DS_FIX_OVERWRITTEN DS_ERROR //Can set other memory functions #define allocate malloc #define deallocate free #define reallocate realloc //Main structure #ifndef DS_IMPLEMENTATION typedef struct { char *cstring; char *position; char *end; //1 past the end } Dynamic_String; #else typedef struct { char *content; char *position; char *end; //1 past the end } Dynamic_String; #endif //Allocate a dynamic string container and call ds_allocate Dynamic_String *ds_new(size_t custom_size); //Free contents and container void ds_delete(Dynamic_String *ds); //Allocate initial space and set the structure members, return pointer to //newly allocated memory. Available for use is custom_size. It doesn't //allocate space for the structure itself int ds_allocate(Dynamic_String *ds, size_t custom_size); void ds_free(Dynamic_String *ds); //Keep memory allocated, clear contents void ds_clear(Dynamic_String *ds); /* If the content is manipulated without using these functions, but the memory allocated is the same and there's a '\0', it corrects the string position. Otherwise it writes a new '\0' at the end. The string should be usable after calling this function. */ int ds_fix(Dynamic_String *broken); //Equivalent to strlen size_t ds_length(const Dynamic_String *ds); //Total memory allocated size_t ds_capacity(const Dynamic_String *ds); //Space available, accounts for '\0' size_t ds_space(const Dynamic_String *ds); bool ds_is_empty(const Dynamic_String *ds); bool ds_is_full(const Dynamic_String *ds); //Resize memory and update the structure. int ds_resize(Dynamic_String *ds, size_t new_size); //Allocate more bytes int ds_reserve(Dynamic_String *ds, size_t amount); //Deallocate part of memory int ds_shrink(Dynamic_String *ds, size_t amount); //Reduce allocated storage so it's just enough for the current content int ds_shrink_to_fit(Dynamic_String *ds); //Push character to the end of string, return pointer to it int ds_push_back(Dynamic_String *ds, int c); //Append one dynamic string to another, return content position int ds_append(Dynamic_String *destination, const Dynamic_String *source); //Crop out part of the string void ds_crop(Dynamic_String *ds, size_t total); //Append at most n characters from source to destination. Return location of //source inside destination int ds_append_n( Dynamic_String *destination, const Dynamic_String *source, size_t max ); //Compare two dynamic strings and return 0 if equal, positive if first //differing character is greater on str1 or negative if smaller int ds_compare(const Dynamic_String *str1, const Dynamic_String *str2); //Compare up to n characters int ds_compare_n( const Dynamic_String *str1, const Dynamic_String *str2, size_t max ); //Swap one dynamic string for another void ds_swap(Dynamic_String *ds1, Dynamic_String *ds2); /////////////////////// ////// Functions to work with dynamic and regular strings //Takes an already allocated regular string and put it into a container. Making //it a normal dynamic string. Container must not hold an allocated string or //there will be memory leaks. void ds_from_cstring(Dynamic_String *container, char *c_string); //Reduce storage to the minimum, and return content as C string char *ds_to_cstring(Dynamic_String *ds); //Join a list of Dynamic_Strings and return their content as C string //The list must be delimited by NULL char *ds_join_list_to_cstring(Dynamic_String **ds_list); //Return an allocated copy of Dynamic_String content char *ds_content_copy(const Dynamic_String *ds); //Append regular C string to Dynamic_String int ds_append_cstring(Dynamic_String *destination, const char *c_string); //Appending a C string of known size is faster int ds_append_cstring_by_length( Dynamic_String *destination, const char *c_string, size_t length ); #endif </code></pre> <p><strong>dynamic_string.c</strong></p> <pre class="lang-c prettyprint-override"><code>#define DS_IMPLEMENTATION #include &lt;string.h&gt; #include &lt;stdlib.h&gt; #include "dynamic_string.h" //////////////////////////// ///////// Internal methods /////////////////////////// static inline size_t max(size_t x, size_t y) { return (x &gt; y) ? x : y; } static inline size_t min(size_t x, size_t y) { return (x &lt; y) ? x : y; } //Compile a different function set depending on settings #if FIXED_STEP &gt; 0 //Expand according to multiplier or fixed step static inline int expand(Dynamic_String *ds) { return ds_reserve(ds, FIXED_STEP); } //Expand by at least a minimum value static inline int expand_by_at_least(Dynamic_String *ds, size_t minimum) { return ds_reserve(ds, max(FIXED_STEP, minimum)); } #else //Multiplier will be used //Expand according to multiplier or fixed step static inline int expand(Dynamic_String *ds) { return ds_reserve(ds, ds_capacity(ds) * MULTIPLIER); } static inline int expand_by_at_least(Dynamic_String *ds, size_t minimum) { return ds_reserve(ds, max(ds_capacity(ds) * MULTIPLIER, minimum)); } #endif //////////////////////////// ///////// Public methods /////////////////////////// //Allocate container and space for characters Dynamic_String *ds_new(size_t custom_size) { Dynamic_String *temp = allocate(sizeof(Dynamic_String)); if(temp == NULL) return NULL; if(ds_allocate(temp, custom_size) == DS_ERROR){ free(temp); return NULL; } return temp; } void ds_delete(Dynamic_String *ds) { ds_free(ds); deallocate(ds); } /* Allocate initial space and set the structure members, return pointer to newly allocated memory. Available for use is custom_size. It doesn't allocate space for the structure itself */ int ds_allocate(Dynamic_String *ds, size_t custom_size) { size_t size = (custom_size &gt; 0) ? custom_size : STARTING_SIZE; char *start = allocate(size + 1); if(start == NULL) return DS_ERROR; ds-&gt;content = ds-&gt;position = start; ds-&gt;end = start + size + 1; *start = '\0'; return DS_SUCCESS; } void ds_free(Dynamic_String *ds) { deallocate(ds-&gt;content); } //Keep memory allocated, clear contents void ds_clear(Dynamic_String *ds) { ds-&gt;position = ds-&gt;content; *ds-&gt;position = '\0'; } /* If the content is manipulated without using these functions, but the memory allocated is the same and there's a '\0', it corrects the string position. Otherwise it writes a new '\0' at the end. The string should be usable after calling this function. */ int ds_fix(Dynamic_String *broken) { broken-&gt;position = memchr(broken-&gt;content, '\0', ds_capacity(broken)); if(broken-&gt;position == NULL){ broken-&gt;position = broken-&gt;end - 1; *broken-&gt;position = '\0'; return DS_FIX_OVERWRITTEN; } return DS_FIX_FULLY_WORKED; } //Equivalent of strlen size_t ds_length(const Dynamic_String *ds) { return ds-&gt;position - ds-&gt;content; } //Total memory allocated size_t ds_capacity(const Dynamic_String *ds) { return ds-&gt;end - ds-&gt;content; } //Space available, accounts for '\0' size_t ds_space(const Dynamic_String *ds) { return ds-&gt;end - ds-&gt;position - 1; } bool ds_is_empty(const Dynamic_String *ds) { return ds-&gt;position == ds-&gt;content; } bool ds_is_full(const Dynamic_String *ds) { return ds_space(ds) == 0; } //Resize memory and update the structure. Return new location int ds_resize(Dynamic_String *ds, size_t new_size) { //Location might change size_t position_offset = ds_length(ds); //Make sure there's at least 1 byte so the string won't break char *temp = reallocate(ds-&gt;content, max(new_size, 1)); if(temp == NULL){ return DS_ERROR; } ds-&gt;content = temp; ds-&gt;end = temp + new_size; //Position still in range? if(position_offset &lt; new_size){ ds-&gt;position = temp + position_offset; } else { ds-&gt;position = ds-&gt;end - 1; *ds-&gt;position = '\0'; } return DS_SUCCESS; } //Allocate more bytes int ds_reserve(Dynamic_String *ds, size_t amount) { return ds_resize(ds, ds_capacity(ds) + amount); } //Deallocate part of memory int ds_shrink(Dynamic_String *ds, size_t amount) { if(amount &gt;= ds_capacity(ds)) return DS_ERROR; return ds_resize(ds, ds_capacity(ds) - amount); } //Reduce allocated storage so it's just enough for the current content int ds_shrink_to_fit(Dynamic_String *ds) { return ds_resize(ds, ds_length(ds) + 1); //There's a '\0' } //Push character to the end of string, return pointer to it int ds_push_back(Dynamic_String *ds, int c) { if(ds_is_full(ds) &amp;&amp; expand(ds) == DS_ERROR){ return DS_ERROR; } *ds-&gt;position++ = c; *ds-&gt;position = '\0'; return DS_SUCCESS; } //Append one dynamic string to another int ds_append(Dynamic_String *destination, const Dynamic_String *source) { size_t destination_space = ds_space(destination); size_t source_length = ds_length(source); //Check if there's space, try to allocate more if there isn't if(source_length &gt; destination_space &amp;&amp; expand_by_at_least(destination, source_length - destination_space) == DS_ERROR) return DS_ERROR; //Update info, where to append? char *insertion_point = destination-&gt;position; destination-&gt;position += source_length; *destination-&gt;position = '\0'; memcpy(insertion_point, source-&gt;content, source_length); return DS_SUCCESS; } /* Append at most n characters from source to destination. Return location of source inside destination */ int ds_append_n( Dynamic_String *destination, const Dynamic_String *source, size_t max ) { //Avoid copying too much max = min(max, ds_length(source)); size_t space = ds_space(destination); if(max &gt; space &amp;&amp; expand_by_at_least(destination, max - space) == DS_ERROR){ return DS_ERROR; } char *insertion_point = destination-&gt;position; destination-&gt;position += max; *destination-&gt;position = '\0'; memcpy(insertion_point, source-&gt;content, max); return DS_SUCCESS; } void ds_crop(Dynamic_String *ds, size_t total) { } /* Compare two dynamic strings and return 0 if equal, positive if first differing character is greater on str1 or negative if smaller */ int ds_compare(const Dynamic_String *str1, const Dynamic_String *str2) { size_t length = min(ds_length(str1), ds_length(str2)); return memcmp(str1-&gt;content, str2-&gt;content, length + 1); } //Compare up to n characters int ds_compare_n( const Dynamic_String *str1, const Dynamic_String *str2, size_t max ) { size_t length = min(ds_length(str1), ds_length(str2)); return memcmp(str1-&gt;content, str2-&gt;content, min(length + 1, max)); } //Swap one dynamic string for another void ds_swap(Dynamic_String *ds1, Dynamic_String *ds2) { Dynamic_String temp = {ds1-&gt;content, ds1-&gt;position, ds1-&gt;end}; ds1-&gt;content = ds2-&gt;content; ds1-&gt;position = ds2-&gt;position; ds1-&gt;end = ds2-&gt;end; ds2-&gt;content = temp.content; ds2-&gt;position = temp.position; ds2-&gt;end = temp.end; } //////////////////////////// ///////// Functions to work with dynamic and regular strings /////////////////////////// /* Takes an already allocated regular string and put it into a container. Making it a normal dynamic string. Container must not hold an allocated string or there will be memory leaks. */ void ds_from_cstring(Dynamic_String *container, char *c_string) { container-&gt;content = c_string; container-&gt;position = strchr(c_string, '\0'); container-&gt;end = container-&gt;position + 1; } //Return an allocated copy of Dynamic_String content char *ds_content_copy(const Dynamic_String *ds) { size_t length = ds_length(ds); char *temp = malloc(length + 1); if(temp == NULL) return NULL; return memcpy(temp, ds-&gt;content, length + 1); } //Reduce storage to the minimum, and return content as C string char *ds_to_cstring(Dynamic_String *ds) { //Assume reducing storage will work, if it doesn't return with extra space ds_shrink_to_fit(ds); return ds-&gt;content; } //Join a list of Dynamic_Strings and return their contents as C string //The list must be delimited by NULL char *ds_join_list_to_cstring(Dynamic_String **ds_list) { //If all have length 0, return an string with '\0' size_t total_size = 1; for(size_t i = 0; ds_list[i] != NULL; ++i) total_size += ds_length(ds_list[i]); //Create a temporary string to hold all contents Dynamic_String temp; if(ds_allocate(&amp;temp, total_size) == DS_ERROR) return NULL; for(size_t i = 0; ds_list[i] != NULL; ++i) ds_append(&amp;temp, ds_list[i]); return temp.content; } //Append regular C string to Dynamic_String int ds_append_cstring(Dynamic_String *dest, const char *c_string) { return ds_append_cstring_by_length(dest, c_string, strlen(c_string)); } //Appending a C string of known length is faster int ds_append_cstring_by_length( Dynamic_String *dest, const char *c_string, size_t length ) { size_t space = ds_space(dest); if(space &lt; length &amp;&amp; expand_by_at_least(dest, length - space) == DS_ERROR) return DS_ERROR; char *insertion_point = dest-&gt;position; dest-&gt;position += length; *dest-&gt;position = '\0'; memcpy(insertion_point, c_string, length); return DS_SUCCESS; } </code></pre>
[ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-05-05T18:48:25.267", "Id": "86055", "Score": "0", "body": "Tried to compile but apparently you've made some changes to the interface of `Dynamic_String`. Specifically, is there a new member `cstring`?" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-05-05T19:08:51.953", "Id": "86059", "Score": "0", "body": "@Edward it's just a different name for `content`. Sorry about that." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-05-05T19:17:22.307", "Id": "86061", "Score": "0", "body": "@Edward I tried to compile too and I noticed there are many changes. Please check the code I just posted. I hadn't posted it before because there are a lot of improvements that could be made." } ]
[ { "body": "<p>This may be disappointing but: I didn't find much wrong with it. That said, there are a few small points that might be useful.</p>\n\n<h2>Reducing memory leaks</h2>\n\n<p>I almost didn't even write this one because the GTK library is notorious for leaking memory. With that said, there are a few things one can and should do. First, is that the top-level <code>GtkWidget *window</code> is created as a floating reference and isn't \"owned\" by anything. To make sure it's properly freed after it's done you can add this:</p>\n\n<pre><code>/* Main window */\nGtkWidget *window = gtk_window_new(GTK_WINDOW_TOPLEVEL);\ng_object_ref_sink(window); /* create a reference to the window */\n/* ... */\ngtk_main();\ngtk_widget_destroy(window); /* ask for window to be released */\ng_object_unref(window); /* remove last reference to window */\n</code></pre>\n\n<p>There's a <a href=\"http://www.cs.hunter.cuny.edu/~sweiss/course_materials/csci493.70/lecture_notes/GTK_memory_mngmt.pdf\" rel=\"nofollow noreferrer\">document that describes GTK memory management</a> but consensus seems to be that if you use GTK <a href=\"https://stackoverflow.com/questions/16659781/memory-leaks-in-gtk-hello-world-program\">your program WILL leak memory</a>.</p>\n\n<h2>Use <code>g_free</code> for GTK allocated items</h2>\n\n<p>Within the <code>spin</code> function, the <code>gtk_text_buffer_get_text</code> function is called which allocates a new UTF-8 buffer. You're freeing it, which is good, but with <code>free</code> rather than <code>g_free</code>. It probably doesn't matter in this case, but get in the habit of using <code>g_free</code> for GTK+-allocated items.</p>\n\n<h2>Reconsider malformed strings</h2>\n\n<p>The program doesn't crash (good!) but it also doesn't like input of the form:</p>\n\n<pre><code>{big|fat} hog{\n</code></pre>\n\n<p>It prints to the console, but it could just as easily handle this input the same way that it handles </p>\n\n<pre><code>{big|fat} hog}\n</code></pre>\n\n<p>which is simply to print the trailing <code>}</code> like any other character.</p>\n\n<h2>Consolidate <code>get_count</code> and <code>get_word_n</code></h2>\n\n<p>The content of the <code>get_count</code> and <code>get_word_n</code> functions is similar and overlapping and they are only called once back-to-back from within <code>choose_one()</code>. </p>\n\n<p>In all it seemed pretty solid code.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-05-06T01:41:26.293", "Id": "49029", "ParentId": "49000", "Score": "6" } }, { "body": "<p>I just have some minor things in addition to what has been said:</p>\n\n<ul>\n<li><p>For organization, I would not mix up header files and libraries:</p>\n\n<blockquote>\n<pre><code>#include &lt;gtk/gtk.h&gt;\n#include &lt;stdlib.h&gt;\n#include \"dynamic_string.h\"\n#include &lt;time.h&gt;\n</code></pre>\n</blockquote>\n\n<p>You should have header files before libraries as this will avoid possible dependency issues resulting from forcing header files to be exposed to certain libraries.</p>\n\n<pre><code>#include \"dynamic_string.h\"\n#include &lt;gtk/gtk.h&gt;\n#include &lt;stdlib.h&gt;\n#include &lt;time.h&gt;\n</code></pre></li>\n<li><p>I don't think you need your own <code>DS</code> return codes when you already have <code>&lt;stdbool.h&gt;</code>:</p>\n\n<blockquote>\n<pre><code>//Return codes\n#define DS_SUCCESS 1\n#define DS_ERROR 0\n</code></pre>\n</blockquote></li>\n<li><p>Do not display an error message in <code>get_word_n()</code>; its intent does not include error-reporting. Instead, display it in the calling code if the function returns <code>NULL</code>. You could also add a comment next to the return statement, stating the reason(s) for returning <code>NULL</code>.</p></li>\n<li><p>To help with maintenance, consider using curly braces for single-line statements as well.</p></li>\n</ul>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-06-11T16:34:25.863", "Id": "53999", "ParentId": "49000", "Score": "5" } } ]
{ "AcceptedAnswerId": "49029", "CommentCount": "3", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-05-05T17:49:25.397", "Id": "49000", "Score": "4", "Tags": [ "c", "gui" ], "Title": "Spun article reader" }
49000
<p>In <a href="https://codereview.stackexchange.com/a/48987/23788">this answer</a> I suggested using a <em>fluent interface</em> "builder" to replace all the hard-coded, repetitive and quite error-prone inline XML string concatenations.</p> <p>This code might need a bit of tweaking to work <em>perfectly</em> with the OP's code in the question this code is following-up on, but it seems to work as expected. Thoughts?</p> <pre><code>public enum XmlQueryOperator { Equals, LessThan, LessThanOrEqual, GreaterThan, GreaterThanOrEqual } </code></pre> <pre><code>public class XmlQueryBuilder&lt;TEntity&gt; where TEntity : class { private readonly XDocument _xDoc = new XDocument(); private readonly XElement _queryNode = new XElement("query"); public XmlQueryBuilder() { var rootNode = new XElement("queryxml"); rootNode.SetAttributeValue("version", "1.0"); var entityNode = new XElement("entity"); entityNode.Value = typeof (TEntity).Name; rootNode.Add(entityNode); _xDoc.Add(rootNode); } public XmlQueryBuilder&lt;TEntity&gt; Where&lt;TProperty&gt;(Expression&lt;Func&lt;TEntity, TProperty&gt;&gt; property, XmlQueryOperator operation, string value) { var xCondition = new XElement("condition"); var xField = new XElement("field"); xField.Value = GetPropertyName(property); var xExpression = new XElement("expression"); xExpression.SetAttributeValue("op", operation.ToString()); xExpression.Value = value; xField.Add(xExpression); xCondition.Add(xField); _queryNode.Add(xCondition); return this; } public override string ToString() { var parent = _xDoc.Element("queryxml"); if (parent == null) throw new InvalidOperationException("root node was not created."); parent.Add(_queryNode); return _xDoc.ToString(); } private string GetPropertyName&lt;TSource, TProperty&gt;(Expression&lt;Func&lt;TSource, TProperty&gt;&gt; propertyLambda) { // credits http://stackoverflow.com/questions/671968/retrieving-property-name-from-lambda-expression/672212#672212 (modified to return property name) var type = typeof(TSource); var member = propertyLambda.Body as MemberExpression; if (member == null) throw new ArgumentException(string.Format("Expression '{0}' refers to a method, not a property.", propertyLambda)); var propInfo = member.Member as PropertyInfo; if (propInfo == null) throw new ArgumentException(string.Format("Expression '{0}' refers to a field, not a property.", propertyLambda)); if (type != propInfo.ReflectedType &amp;&amp; !type.IsSubclassOf(propInfo.ReflectedType)) throw new ArgumentException(string.Format("Expresion '{0}' refers to a property that is not from type {1}.", propertyLambda, type)); return propInfo.Name; } } </code></pre> <hr> <p>Usage - given a <code>TestEntity</code>:</p> <pre><code>public class TestEntity { public string Test1 { get; set; } public int Test2 { get; set; } public DateTime Test3 { get; set; } } </code></pre> <p>This program produces the expected output:</p> <pre><code>class Program { static void Main(string[] args) { var builder = new XmlQueryBuilder&lt;TestEntity&gt;() .Where(t =&gt; t.Test1, XmlQueryOperator.Equals, "abc") .Where(t =&gt; t.Test2, XmlQueryOperator.GreaterThan, "def") .Where(t =&gt; t.Test3, XmlQueryOperator.LessThanOrEqual, DateTime.Now.ToString()); Console.WriteLine(builder.ToString()); Console.ReadLine(); } } </code></pre> <p>Output:</p> <pre class="lang-xml prettyprint-override"><code>&lt;queryxml version="1.0"&gt; &lt;entity&gt;TestEntity&lt;/entity&gt; &lt;query&gt; &lt;condition&gt; &lt;field&gt;Test1&lt;expression op="Equals"&gt;abc&lt;/expression&gt;&lt;/field&gt; &lt;/condition&gt; &lt;condition&gt; &lt;field&gt;Test2&lt;expression op="GreaterThan"&gt;def&lt;/expression&gt;&lt;/field&gt; &lt;/condition&gt; &lt;condition&gt; &lt;field&gt;Test3&lt;expression op="LessThanOrEqual"&gt;2014-05-05 14:14:57&lt;/expression&gt;&lt;/field&gt; &lt;/condition&gt; &lt;/query&gt; &lt;/queryxml&gt; </code></pre>
[ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-05-05T20:10:37.963", "Id": "86071", "Score": "3", "body": "I'm not sure I like the name `Where`. In LINQ, `Where` means filtering, here it means something quite different." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-05-05T20:14:10.717", "Id": "86072", "Score": "1", "body": "What I would probably do is to treat query as a collection of conditions and initialize it as such: `new Query<TestEntity> { { t => t.Test1, XmlQueryOperator.Equals, \"abc\" }, … }`." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-05-05T20:16:45.283", "Id": "86074", "Score": "0", "body": "@svick that's a good idea, I didn't know if OP could have more than just `condition` nodes though. But I agree if it's all that's needed the fluent interface is probably overkill (although was cool to implement [first-time-I-do-this])." } ]
[ { "body": "<p><code>ToString()</code> does too many things, it should only be calling <code>_xDoc.ToString()</code>; it has side-effects that make it dangerous to call more than once:</p>\n\n<pre><code>var foo = builder.ToString()\nConsole.WriteLine(builder.ToString());\nConsole.ReadLine();\n</code></pre>\n\n<p>Will <strong>not</strong> produce the expected output, and will not throw an exception either, resulting in an XML document with <code>_queryNode</code> showing up as many times as <code>ToString()</code> was called.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-05-05T18:34:39.017", "Id": "49006", "ParentId": "49003", "Score": "4" } }, { "body": "<p>One thing I really like about LINQ to XML is that it can be very <em>declarative</em>. For example, this code:</p>\n\n<pre><code>var rootNode = new XElement(\"queryxml\");\nrootNode.SetAttributeValue(\"version\", \"1.0\");\n\nvar entityNode = new XElement(\"entity\");\nentityNode.Value = typeof (TEntity).Name;\n\nrootNode.Add(entityNode);\n_xDoc.Add(rootNode);\n</code></pre>\n\n<p>can be alternatively written as:</p>\n\n<pre><code>_xDoc.Add(\n new XElement(\n \"queryxml\",\n new XAttribute(\"version\", \"1.0\"),\n new XElement(\"entity\", typeof(TestEntity).Name)));\n</code></pre>\n\n<p>This approach can be taken too far (e.g. maybe I should have kept the <code>rootNote</code> variable?), but I think that judicious use can make the code more readable, especially since it means the code becomes hierarchical, just like the XML you're building.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-05-05T20:33:51.747", "Id": "49014", "ParentId": "49003", "Score": "2" } } ]
{ "AcceptedAnswerId": "49014", "CommentCount": "3", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-05-05T18:15:48.113", "Id": "49003", "Score": "7", "Tags": [ "c#", "xml", "fluent-interface" ], "Title": "Fluent Interface for a XmlQueryBuilder" }
49003
<p>I haven't done much .NET development in several years. Now I'm enjoying some of the new stuff with modern .NET. I just want to make sure I'm using things correctly. I'm a solo developer with no one else to bounce ideas off of.</p> <p>I have a new MVC web application. I'm using the Massive micro-ORM. I'm a big believer in caching database requests. I've also created an EnumWrapper class. </p> <p>Does anything look terrible in this code?</p> <p>My caching class:</p> <pre><code>using System; using System.Runtime.Caching; namespace ULH.Common { public static class Caching { private static readonly object _cacheLock = new object(); public static dynamic LoadFromCache(string cacheKey, int secondsToCache, Func&lt;object&gt; query) { object result; if (secondsToCache == 0) { // if we're not caching, clear the cache and return result directly MemoryCache.Default.Remove(cacheKey); result = query.Invoke(); } else { // otherwise do the caching, but use a double-check lock result = MemoryCache.Default[cacheKey]; if (result == null) { lock (_cacheLock) { result = MemoryCache.Default[cacheKey]; if (result == null) { result = query.Invoke(); MemoryCache.Default.Add(cacheKey, result, DateTime.UtcNow.AddSeconds(secondsToCache)); } } } } return result; } } } </code></pre> <p>An example of one of my data model objects:</p> <pre><code>using System; using ULH.Common; namespace ULH.Intranet.Chaplaincy { public class EncounterTypes : BaseModel { private EncounterTypes() { this.TableName = "EncounterTypes"; this.PrimaryKeyField = "Id"; } public static dynamic GetActive() { return Caching.LoadFromCache("EncounterTypes_GetActive", 120, () =&gt; { dynamic tbl = new EncounterTypes(); return tbl.Find(Enabled: 1); }); } public static dynamic GetById(int id) { string cacheKey = "EncounterTypes_GetById_" + id.ToString(); return Caching.LoadFromCache(cacheKey, 600, () =&gt; { dynamic tbl = new EncounterTypes(); return tbl.First(ID: id); }); } } } </code></pre> <p>Here is my EnumWrapper class, where I also cache the List that is created:</p> <pre><code>using System; using System.Collections; using System.Collections.Generic; namespace ULH.Common { public sealed class EnumWrapper : ReadOnlyCollectionBase { Type _enumType; Type _basetype; public static EnumWrapper Wrap(Type type) { if (type == null || !type.IsEnum) throw new ArgumentException("Type must be an enum", "type"); return Caching.LoadFromCache("EnumWrapper:" + type.ToString() , 600, () =&gt; { return new EnumWrapper(type); }); } private EnumWrapper(Type type) { _enumType = type; _basetype = Enum.GetUnderlyingType(type); foreach (var item in Enum.GetValues(_enumType)) { this.InnerList.Add( new KeyValuePair&lt;object, string&gt;( Convert.ChangeType(item, _basetype), item.ToString() ) ); } } } } </code></pre> <p>I'm using <code>dynamic</code> quite a bit due to the Massive ORM. </p> <p>This won't be a huge system, so I don't want to deal with IOC containers. I'll have one common library (ULH.Common) with caching, the Massive ORM, EnumWrapper, and other common functions. There will then be several small websites using that library.</p> <p>Suggestions? Does everything look okay?</p> <p><strong>Edit:</strong> George Howarth made some interesting points. I was unaware that MemoryCache was thread-safe. I've now modified my LoadFromCache() method to this:</p> <pre><code>public static dynamic LoadFromCache(string cacheKey, int secondsToCache, Func&lt;object&gt; query) { object tocache = null; // result will always get the value here // tocache will only have the value when it was pulled from our method object result = MemoryCache.Default[cacheKey] ?? (tocache = query.Invoke()); if (secondsToCache &gt; 0) { if (tocache != null) // only save to cache if it wasn't there MemoryCache.Default.Add(cacheKey, tocache, DateTime.UtcNow.AddSeconds(secondsToCache)); } else { // remove from cache only if secondsToCache was zero or less MemoryCache.Default.Remove(cacheKey); } return result; } </code></pre>
[ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-05-06T20:22:53.313", "Id": "86233", "Score": "0", "body": "A question. If you are loading the enum from cache what happens if two different objects with the same enum type get cached. Will you lose information as one will overwrite the other?" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-05-07T11:38:30.377", "Id": "86321", "Score": "0", "body": "@dreza, My `EnumWrapper` class is used to store an instance of the enum for populating drop-downs and other UI widgets. It's selected value is not saved." } ]
[ { "body": "<ul>\n<li><p><code>MemoryCache</code> is actually thread-safe, so you don't need a double-check lock</p>\n\n<pre><code>public static class Caching\n{\n public static dynamic LoadFromCache(string cacheKey, int secondsToCache, Func&lt;object&gt; query)\n {\n object result = query.Invoke();\n\n if (secondsToCache == 0)\n {\n // if we're not caching, clear the cache and return result directly\n MemoryCache.Default.Remove(cacheKey);\n }\n else\n {\n if (!MemoryCache.Default.Contains(cacheKey))\n {\n MemoryCache.Default.Add(cacheKey, result, DateTime.UtcNow.AddSeconds(secondsToCache));\n }\n }\n\n return result;\n }\n}\n</code></pre></li>\n</ul>\n\n<p><strong>Edit</strong>: Updated answer about the if statement, wasn't thinking straight.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-05-06T13:14:16.590", "Id": "86164", "Score": "0", "body": "Your changes always do the query.Invoke(), which could be an expensive operation. I was unaware that MemoryCache was threadsafe. I checked MSDN, and am happy to confirm it. I'm editing my post to show my new LoadFromCache() method." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-05-06T13:16:07.467", "Id": "86166", "Score": "0", "body": "Yeah, looking at your code again it looks like a mistake. I guess you could call `Contains` first before adding." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-05-06T13:20:26.710", "Id": "86168", "Score": "0", "body": "Your edited version will return null when the value is cached. Go ahead. Have another cup of coffee. :)" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-05-06T13:23:33.043", "Id": "86169", "Score": "0", "body": "Yes this is what happens when you can't rely on ReSharper..." } ], "meta_data": { "CommentCount": "4", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-05-06T12:54:30.660", "Id": "49068", "ParentId": "49005", "Score": "5" } }, { "body": "<p>I found a huge problem with the architecture I was working on. The cached object is still an object inheriting from <code>DynamicModel</code> - part of the Massive ORM.</p>\n\n<p>This led to the database being queried even from a cached collection. That defeats the purpose of caching.</p>\n\n<p>One way of handling this would be to add a new method to create <code>ExpandoObject</code>s (and collections of them) that did not inherit from <code>DynamicModel</code>. This seems more effort than it's worth. I'm still trying to determine my best course of action.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-05-09T17:02:33.680", "Id": "49354", "ParentId": "49005", "Score": "0" } } ]
{ "AcceptedAnswerId": "49354", "CommentCount": "2", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-05-05T18:33:24.443", "Id": "49005", "Score": "4", "Tags": [ "c#", "mvc", "cache" ], "Title": "ASP.NET MVC architecture questions" }
49005
<p>I would like to know what you think:</p> <pre><code>&lt;?php $nav_normal = array("1. Home","2. Read Me","3. License Agreement","4. General Information","5. Database Installer","6. Create an Account","7. Create Config","8. Successfully installed" ); $last_normal = array_pop(array_keys($nav_normal)); foreach($nav_normal as $name){ if($Nav_ID == $name){ $Nav_Type = "Selected"; }else{ $Nav_Type = "Unselected"; } ?&gt;&lt;li class="&lt;?php echo($Nav_Type); ?&gt;"&gt;&lt;?php echo($name); ?&gt;&lt;/li&gt;&lt;?php //this part is only for the (google chrome) view-source:\\ //this will not be shown into the normal layout/output\\ if($name != $last_normal){ echo("\n "); }else{ echo("\n"); } } </code></pre> <p>On each page I write at the place of the navigation bar:</p> <pre><code>&lt;?php $Nav_ID = "1. Home"; //etc. etc.\\ include_once("navigation.php"); ?&gt; </code></pre> <p>I hope you can give me a review on what you think is either good or bad. Just give your opinion.</p>
[ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-05-05T20:45:51.083", "Id": "86080", "Score": "0", "body": "Thanks for editing it I guess just don't see why php is wrong and \"must\" be PHP" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-05-05T20:50:45.293", "Id": "86081", "Score": "0", "body": "What are you trying to achieve with $last_normal? Multiple spaces in html are displayed as 1 space, so both conditions based on $name != $last_normal would look the same in a web browser?" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-05-05T20:54:05.913", "Id": "86082", "Score": "0", "body": "the multiple spaces is working great it's to line out in the view-code: also the last_normal gives the last item in the array so while the $name is not the last_normal (last item) then it shows the correct way in the view-code: else it just shows it back as normal with just one next space... (if you get what I mean)" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-05-05T23:39:30.813", "Id": "86103", "Score": "0", "body": "Instead of view source, you could use Chrome's (or Firefox's or etc.) inspection functionality, which presents the HTML in a formatted fashion (with other features too). Then you won't need all the logic for spacing." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-05-06T21:47:51.070", "Id": "86236", "Score": "0", "body": "well I thought it would be nicer for that kind of view aswell else it would be like {spaces}item {n} item | now it's: {spaces}item {n} {spaces}item" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-05-08T08:18:05.167", "Id": "86498", "Score": "0", "body": "Don't add extra complexity for the sake of whitespace when viewing the source in a browser Chrome Inspector, Firebug and anything else worth it salt will already handle this for you." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-05-08T08:57:15.313", "Id": "86499", "Score": "0", "body": "when I just did it normally like we else would it didn't work but don't mind it too much it's just for the look of view-source:" } ]
[ { "body": "<pre><code>&lt;?php\n\n// first up i have removed the numbers, those numbers can be automatically added using an ordered list,\n// then if you add a menu option later you don't have to renumber everything and look through every file to check the $Nav_ID matches\n$nav_normal = array(\"Home\",\"Read Me\",\"License Agreement\",\"General Information\",\"Database Installer\",\"Create an Account\",\"Create Config\",\"Successfully installed\");\n\n// removed as documented below\n// $last_normal = array_pop(array_keys($nav_normal));\n\n// we need to start the list somewhere?, using an ordered list will automatically number the menu options\necho \"&lt;ol&gt;\";\n\nforeach($nav_normal as $name){\n\n if($Nav_ID == $name){\n // $Nav_Type is not very descriptive\n // $Nav_Type = \"Selected\";\n $Nav_Selected = \"Selected\";\n } else {\n $Nav_Selected = '';\n // it is not necessary to have a state for unselected\n// $Nav_Type = \"Unselected\";\n }\n\n // the last if/else block could be replaced by this single line\n $Nav_Selected = ($Nav_ID == $name) ? \"Selected\" : '';\n\n\n\n // it is not worth escaping php for a single, line, it is easier just to embed the html and echo it\n // make sure we call htmlspecialchars or characters like &gt;&lt; &amp; \" etc will stuff up your html\n echo \"&lt;li class=\\\"$Nav_Selected\\\"&gt;\".htmlspecialchars($name).\"&lt;/li&gt;\";\n\n // this makes no visible difference, multiple spaces are rendered as one in html\n// if($name != $last_normal){\n// echo(\"\\n \");\n// }else{\n echo \"\\n\";\n// }\n\n}\n\n// if we want extra spaces after the last item in the loop, just echo them after the loop has finished\necho \" \";\n\n// don't forget to close the ordered list too\necho \"&lt;/ol&gt;\";\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-05-05T21:17:16.630", "Id": "86084", "Score": "0", "body": "just a few issues with your script array pop bla bla gave me an issue when I added a new item so..\nalso it may not make a visual difference but the view-code: does and I am going to use it in my forum software (open-source) thanks for the tips tho" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-05-05T21:49:45.633", "Id": "86092", "Score": "0", "body": "also my nav_type is a class (selected = class part && unselected = class part) regarding to my css rile :)" } ], "meta_data": { "CommentCount": "2", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-05-05T21:06:34.370", "Id": "49018", "ParentId": "49015", "Score": "3" } }, { "body": "<p>Make better use of the array for the configuration of your items.</p>\n\n<pre><code>&lt;?php\n// Your array\n$navigation[\n id =&gt; 'my-navigation',\n class =&gt; 'my-nav-class',\n items =&gt; [\n [label =&gt; 'Home', href =&gt; '/home/', active =&gt; true],\n [label =&gt; 'Read me', href =&gt; '/readme/'],\n [label =&gt; 'License Agreement', href =&gt; '/agreement/'],\n ]\n];\n\n\n// The output\necho '&lt;ul id=\"' . $navigation['id'] . '\" class=\"' . $navigation['class'] . '\"&gt;';\n\nforeach( $navigation['items'] as $item ){ \n // Build up other item classes\n if( $item['active'] ) $class += ' active';\n if( $item['class'] ) $class += ' ' . $item['class'];\n\n echo '&lt;li class=\"' . $class . '\"&gt;';\n echo '&lt;a href=\"' . $item['href'] ?: '#' . '\"&gt;' . $item['label'] . '&lt;/a&gt;';\n echo '&lt;/li&gt;';\n}\n\necho '&lt;/ul&gt;'\n</code></pre>\n\n<p>You'll end up with a more flexible solution this way, although there is also nothing wrong with how you've done it really. </p>\n\n<p>Considering you're controlling the content I wouldn't bother using htmlspecialchars() i'd instead build the array with the appropriate markup.</p>\n\n<p>Certainly wouldn't break out of the tags for the markup, it's harder to read and more error prone. It would be better to have true separation of markup with a template language like twig.</p>\n\n<p>Without knowing context of how it's going to be used it hard to give anymore pointers really.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-05-06T14:13:47.887", "Id": "86177", "Score": "0", "body": "I think an object for each item would be great too so he could loop the items array and check if the url matches the route to flag it as active" } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-05-06T14:03:31.617", "Id": "49073", "ParentId": "49015", "Score": "1" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "7", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-05-05T20:38:44.757", "Id": "49015", "Score": "3", "Tags": [ "php", "html" ], "Title": "Navigation bar using PHP" }
49015
<p>Is there a more efficient approach to this code?</p> <pre><code>// save associated tag let saveTag question = if question.Tag = null then () else let tagCount = query{ for row in db.Tags_Tags_Tags do where (row.Tag = question.Tag) select row count } if tagCount &gt; 0 then () else let tagToSave = dbSchema.ServiceTypes.Tags_Tags_Tags( Tag = question.Tag ) insertRowIn db.Tags_Tags_Tags tagToSave saveToDb() </code></pre>
[]
[ { "body": "<p>You don't need the empty <code>if</code> branches. An <code>if</code> without an <code>else</code> automatically returns <code>unit</code>. So you can simplify it to:</p>\n\n<pre><code>let saveTag question = \n\n if question.Tag &lt;&gt; null then\n let tagCount = \n query{\n for row in db.Tags_Tags_Tags do\n where (row.Tag = question.Tag)\n select row\n count\n } \n\n if tagCount = 0 then\n let tagToSave = \n dbSchema.ServiceTypes.Tags_Tags_Tags(\n Tag = question.Tag\n )\n insertRowIn db.Tags_Tags_Tags tagToSave\n saveToDb()\n</code></pre>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-05-05T22:10:30.320", "Id": "49021", "ParentId": "49016", "Score": "4" } }, { "body": "<p>In addition to Daniel's answer, the <code>select row</code> in your tagCount query is redundant. You can simplify the query to:</p>\n\n<pre><code> let tagCount = \n query {\n for row in db.Tags_Tags_Tags do\n where (row.Tag = question.Tag)\n count\n } \n</code></pre>\n\n<p>But you could further improve your query. In this case you don't actually need to know the exact count, you just need to know if there's at least one match or not.</p>\n\n<pre><code>let tagExists =\n query {\n for row in db.Tags_Tags_Tags do\n exists (row.Tag = question.Tag)\n }\n\nif not tagExists then\n ...\n</code></pre>\n\n<p>This way the query can stop processing as soon as it finds a match, instead of continuing on until it has an exact count of how many matches. It's a bit more efficient that way when there's lots of data.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-05-05T22:18:17.050", "Id": "49022", "ParentId": "49016", "Score": "4" } } ]
{ "AcceptedAnswerId": "49021", "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-05-05T20:54:56.210", "Id": "49016", "Score": "2", "Tags": [ "linq", "f#" ], "Title": "Check database for item and create it if it doesn't exist" }
49016
<p>I recently posted some sample code that I was providing students with and got great feedback so figured I post another one of the examples I will be providing students with. (See <a href="https://codereview.stackexchange.com/questions/48109/simple-example-of-an-iterable-and-an-iterator-in-java">Simple Example of an Iterable and an Iterator in Java</a>) </p> <p>This one is a simple postfix calculator. The main learning objectives are basic inheritance, trees, post-order and in-order traversals and stack based parsing of postfix expressions.</p> <p>First, the CLI code:</p> <pre><code>import java.util.Scanner; public class PostfixCLI { public static void main(String[] args) { System.out.println("Enter postfix expression to evaluate, 'exit' to exit."); Scanner in = new Scanner(System.in); while (true) { try { System.out.print("&gt;&gt;&gt; "); String input = in.nextLine(); if (input.equals("exit")) { break; } Expression expression = Expression.parsePostOrder(input); System.out.format("%s = %.4f\n", expression.toString(), expression.evaluate()); } catch (InvalidExpressionException e) { System.out.println("Invalid expression: " + e.getMessage()); continue; } catch (RuntimeException e) { System.out.println("Runtime error: " + e.getMessage()); continue; } catch (Exception e) { System.out.println("Unknown error: " + e.getMessage()); continue; } } } } </code></pre> <p>And the <code>Expression.java</code> file that does most of the work.</p> <pre><code>import java.util.Stack; import java.util.Scanner; public abstract class Expression { public abstract double evaluate(); public String toPostOrder() { return this.toString(); } public String toInOrder() { return this.toString(); } /* * Parse an expresssion tree given a string and return the resulting tree. * InvalidExpressionException is raised in cases of invalid input. */ public static Expression parsePostOrder(String expression) throws InvalidExpressionException { Scanner tokenizer = new Scanner(expression); Stack&lt;Expression&gt; stack = new Stack&lt;Expression&gt;(); while (tokenizer.hasNext()) { String token = tokenizer.next(); try { double number = Double.parseDouble(token); stack.push(new Number(number)); } catch (NumberFormatException e) { // If control reaches here it's because the token is not a // number, so it must be an operator. if (stack.size() &lt; 2) { throw new InvalidExpressionException( "Not enough parameters for " + token); } Expression right = stack.pop(); Expression left = stack.pop(); stack.push(BinaryOperator.fromSymbol(token, left, right)); } } if (stack.size() != 1) { throw new InvalidExpressionException("Not enough operators."); } // The single item left on the stack is the root of the tree. return stack.pop(); } } class Number extends Expression { double number; public Number(double num) { super(); this.number = num; } @Override public double evaluate() { return this.number; } @Override public String toString() { return Double.toString(this.number); } } abstract class BinaryOperator extends Expression { Expression left; Expression right; protected abstract String getOperatorSymbol(); public BinaryOperator(Expression left, Expression right) { super(); this.left = left; this.right = right; } @Override public String toString() { return this.toInOrder(); } @Override public String toInOrder() { return "(" + this.left.toInOrder() + " " + this.getOperatorSymbol() + " " + this.right.toInOrder() + ")"; } @Override public String toPostOrder() { return this.left.toPostOrder() + " " + this.right.toPostOrder() + " " + this.getOperatorSymbol(); } public static BinaryOperator fromSymbol(String symbol, Expression left, Expression right) throws InvalidExpressionException { if (symbol.equals("+")) { return new AddOperator(left, right); } else if (symbol.equals("-")) { return new SubtractOperator(left, right); } else if (symbol.equals("*")) { return new MultiplyOperator(left, right); } else if (symbol.equals("/")) { return new DivideOperator(left, right); } else { throw new InvalidExpressionException("Invalid operator: " + symbol); } } } final class AddOperator extends BinaryOperator { protected AddOperator(Expression left, Expression right) { super(left, right); } @Override protected String getOperatorSymbol() { return "+"; } @Override public double evaluate() { return this.left.evaluate() + this.right.evaluate(); } } final class SubtractOperator extends BinaryOperator { protected SubtractOperator(Expression left, Expression right) { super(left, right); } @Override protected String getOperatorSymbol() { return "-"; } @Override public double evaluate() { return this.left.evaluate() - this.right.evaluate(); } } final class MultiplyOperator extends BinaryOperator { protected MultiplyOperator(Expression left, Expression right) { super(left, right); } @Override protected String getOperatorSymbol() { return "*"; } @Override public double evaluate() throws RuntimeException { return this.left.evaluate() * this.right.evaluate(); } } final class DivideOperator extends BinaryOperator { protected DivideOperator(Expression left, Expression right) { super(left, right); } @Override protected String getOperatorSymbol() { return "/"; } @Override public double evaluate() { double left = this.left.evaluate(); double right = this.right.evaluate(); if (right == 0) { throw new RuntimeException("Division by zero in " + this.toString()); } return left / right; } } </code></pre>
[]
[ { "body": "<p><strong>General</strong> </p>\n\n<ul>\n<li><p>Use full JavaDoc for method comments. Instead of \"Throw X in case Y\" go for \"@throws X if Y\"</p></li>\n<li><p>You never need to call the <em>default</em> (zero-argument) superclass constructor. If the first statement of a constructor isn't a call to <em>some</em> superclass constructor, a call to the default constructor is inserted if there is one. If not, the class won't compile. (Thanks @cHao!)</p></li>\n<li><p>You can drop <code>this.</code> when accessing other members unless there's ambiguity. If you find yourself needing to use it outside constructors and setters--which contain lines like <code>this.field = field</code>--take it as a subtle hint that you may need to refactor the method or rename a local variable.</p></li>\n<li><p>The protected access level on a constructor for a final class is equivalent to package-private; drop <code>protected</code> to be explicit. That being said, if this is a beginning class you may want to stick with public classes until you can cover the reasons for using package-private.</p></li>\n</ul>\n\n<blockquote>\n <p><strong>Update:</strong> I expand a bit on some of the original items and address some more higher-level design issues below.</p>\n</blockquote>\n\n<p><strong>PostfixCLI</strong></p>\n\n<p>This class is very simple, but there are a couple small changes you can make to start teaching good habits to your students right away.</p>\n\n<ul>\n<li><p>Keep <code>main</code> to a few lines, enough to instantiate the REPL class and run it. This makes reusing it and writing unit tests easier and limits <code>main</code> to bridging the gap between the JVM launching your application with arguments and the application itself.</p></li>\n<li><p>As @Vogel612 states, you should <em>rarely</em> catch the top-level exceptions (<code>RuntimeException</code>, <code>Exception</code>, <code>Throwable</code>, et al). Especially when learning it's better to let them propagate to the JVM and kill the process.</p>\n\n<p>Since you've created your own exception hierarchy, the only exceptions getting through should be utterly unanticipated: <code>OutOfMemoryError</code>, <code>StackOverflowException</code> and the like. There's nothing you can do about these here, and they will indicate a serious problem in the code that requires attention.</p>\n\n<p>Granted, in a customer-facing application you'd end up catching these in a generic fashion, logging them for a debug session, and exiting the application as gracefully as possible. Rarely will you be able to do anything more than let the exception bubble up, and students won't be at the level of experience to do anything better for a long while.</p>\n\n<p>I'm pushing hard on this one because every project on which I've worked has required going through pages of code to remove <code>catch (Exception e) { e.printStackTrace(); }</code> as it makes tracking down errors very difficult.</p></li>\n</ul>\n\n<p><strong>Expression (minus the parser)</strong></p>\n\n<ul>\n<li><p><code>Expression.toInOrder</code> calls <code>toString</code> while <code>BinaryExpression.toString</code> calls <code>toInOrder</code>. This works, but it's very confusing. Is there a better way? (Maybe not)</p></li>\n<li><p><strike>Should <code>evaluate</code> return a <code>Number</code> instead of a raw <code>double</code>?</strike></p></li>\n</ul>\n\n<p><strong>Number</strong></p>\n\n<ul>\n<li>To go with <code>evaluate</code> and differentiate it from <code>Number</code>, consider renaming the <code>number</code> field to <code>value</code>. The constructor argument can also be <code>value</code> since there's no reason to shorten it to <code>val</code> or <code>num</code>.</li>\n</ul>\n\n<p><strong>BinaryOperator</strong></p>\n\n<ul>\n<li><p>Add a field to store the operator in <code>BinaryOperator</code> and pass it from each subclass constructor, removing the need for <code>getOperatorSymbol()</code>.</p></li>\n<li><p>Instead of throwing a generic <code>RuntimeException</code> when dividing by zero, create a custom <code>DivideByZeroException</code> or better still, handle <code>NaN</code> inside <code>Number</code> and the other operators.</p></li>\n<li><p>It would be great to separate the operator itself from its use in an expression with left and right values. However, I understand you must keep it simple enough for your students, so I'll leave it at that. :)</p></li>\n</ul>\n\n<p><strong>Parser</strong></p>\n\n<ul>\n<li><p>If the user enters \"2.42.74\", it will be erroneously reported as not having enough operands. Instead, parse the token to an operator, and only when that passes do you know the real problem.</p></li>\n<li><p>Once you change the above, you can handle unary operators like \"1/x\". The operator should know how many operands it needs, and it should be given the stack itself rather than pulling off two values in the loop.</p></li>\n</ul>\n\n<p>The parser is doing way too much to cram it into a single method, and that it knows every operator requires two operands paints yourself into a corner. The first step is to move this code into a separate class that can maintain the stack and do the work to manipulate it across methods.</p>\n\n<p>The parsing method needs to be refactored into methods to scan the input, parse each token, apply it to the stack, and finally return the result. Here's a rough cut:</p>\n\n<pre><code>public class Parser {\n private final Stack&lt;Expression&gt; stack = new Stack&lt;&gt;();\n\n public Expression parse(String input) {\n Scanner tokens = new Scanner(expression);\n while (tokens.hasNext()) {\n parse(tokens.next());\n }\n if (stack.size() != 1) {\n throw new InvalidExpressionException(\"Not enough operators\");\n }\n return stack.pop();\n }\n\n private void parse(String token) {\n ... parse Number or Operator and place result on stack ...\n }\n}\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-05-06T11:29:50.690", "Id": "86150", "Score": "0", "body": "I do not agree with dropping `this.`, other than that, +1." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-05-06T21:53:54.463", "Id": "86238", "Score": "0", "body": "Just to make it explicit: Java will insert a call to the *default* (ie: 0-arg) constructor for you automatically, if your code doesn't call any of them. If you are passing arguments (as happens in the subclasses of `BinaryOperator`), though, you still need to call `super(left, right)` yourself." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-05-06T22:21:41.617", "Id": "86245", "Score": "0", "body": "@cHao Thanks, hopefully I've clarified that bullet point." } ], "meta_data": { "CommentCount": "3", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-05-06T01:44:05.297", "Id": "49030", "ParentId": "49027", "Score": "7" } }, { "body": "<pre><code> try {\n double number = Double.parseDouble(token);\n stack.push(new Number(number));\n } catch (NumberFormatException e) {\n // If control reaches here it's because the token is not a\n // number, so it must be an operator.\n }\n</code></pre>\n\n<p>This sounds like a job for <code>if (tokenizer.hasNextDouble())...</code>, as that improves readability.</p>\n\n<p>Will all operator symbols be a single-character <code>String</code>? </p>\n\n<p>If so, I suggest using <code>char</code>s instead. If you are keeping to single-character <code>String</code>s and developing using Java 7 or later, then I will also suggest using a <code>switch</code> in the static method <code>BinaryOperator.fromSymbol()</code> instead of the <code>if-else</code> ladder you have currently used. Alternatively, consider <code>enum</code>s too...</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-05-06T05:21:25.687", "Id": "86114", "Score": "0", "body": "When parsing, you have to consume the tokens no matter what since invalid ones are included in error messages. In this case you also must get to the next keyboard input." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-05-06T05:33:39.533", "Id": "86115", "Score": "0", "body": "Right, I was only selecting a code snippet in my answer. The full answer, I think, will be along the lines of (pseudo-code): `if (has-next-double) { get double value, add to stack } else { get next value as string, pop the last two expressions from the stack and pop in the result of BinaryOperator.fromSymbol }`" } ], "meta_data": { "CommentCount": "2", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-05-06T03:39:16.907", "Id": "49035", "ParentId": "49027", "Score": "5" } }, { "body": "<p>This answer will focus on the main method</p>\n\n<h3>Separation of concerns:</h3>\n\n<p>You have the full story in your main method. You do: Exception-Handling, printing, prompting and a little bit of parsing:</p>\n\n<p>You might want to move that to different methods. The abstraction level in main method should be so high, it reads more like plain english instead of code:</p>\n\n<pre><code>public static void main(String[] args){\n while(true){\n try{\n String input = promptUserForInput();\n if(isExitCode(input)){\n break;\n }\n parseExpressionAndPrintResults(input);\n }\n catch(Exception e){\n System.out.println(\"Unknown error: \" + e.getMessage());\n continue;\n }\n }\n}\n</code></pre>\n\n<h3>Error Handling:</h3>\n\n<p>Your catch of <code>RuntimeException</code> is redundant. Runtime Exceptions will also be caught when catching <code>Exception</code>. That is one of the reasons, why it is considered bad practice to catch <code>Exception</code>.</p>\n\n<p>Accordingly you can remove:</p>\n\n<blockquote>\n<pre><code>catch(RuntimeException e){\n System.out.println(\"Runtime Error: \" + e);\n continue;\n}\n</code></pre>\n</blockquote>\n\n<h3>Prompting the user for input:</h3>\n\n<p>I had an <a href=\"https://codereview.stackexchange.com/questions/46293/quadratic-expression-calculator/46298#46298\">answer on a different post</a>, which mostly concerned itself with that, you might want to have a look at it for more on parsing numbers.</p>\n\n<p>Other than that: </p>\n\n<blockquote>\n<pre><code>System.out.println(\"Enter postfix expression to evaluate, 'exit' to exit.\");\n</code></pre>\n</blockquote>\n\n<p>It is generally considered easier to use named constants instead of long strings, how does this look to you:</p>\n\n<pre><code>System.out.println(PROMPT);\n</code></pre>\n\n<p>And while we're at it, the prompt you issue will be \"shoved\" out of the screen. I prefer prompting the user before every input. That's why I would write the aforementioned <code>promtUserForInput()</code> as follows:</p>\n\n<pre><code>private String promptUserForInput(){\n final String PROMPT = \"Enter postfix expression to evaluate, 'exit' to exit.\\n &gt;&gt;&gt; \";\n System.out.println(PROMPT);\n Scanner in = new Scanner(System.in); // you can move that to class-level if you\n //want to minimize the overhead from creating it.\n return in.nextLine();\n}\n</code></pre>\n\n<h3>Parsing the input:</h3>\n\n<p>Well the rest is simple, I'd just move the code that you didn't see yet into the <code>parseExpressionAndPrintResults</code> method.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-05-06T09:09:26.200", "Id": "49050", "ParentId": "49027", "Score": "8" } }, { "body": "<p>One thing in particular stands out to me here in your program, and it is that you are making it very difficult to extend this to allow for other types of operators.</p>\n\n<p>If I were to add only a single new binary operator, modulus division (<code>%</code>), I would have to also add a new case to the switch statement. A slightly better option would be to have an array of operator factory objects, which would have a method to themselves check if the symbol matches their operator.</p>\n\n<p>If I wanted to add a unary operator, such as negation, square root, factorial, or something like that, I would not only have to add a case, I would need to define a brand new base class for Unary Operators, and a factory methods for producing them, and a number of other things. Instead, make the operator base class less specific to binary operators, and just have one version that takes a varargs parameters</p>\n\n<p>And then there are the Generalized Stack Manipulation Operators: duplicate (copy top element), exchange (swap top elements), pop (delete top element), clear (delete all elements), store (place top element in separate storage), load (retrieve element from external storage), and dozens of others. These commands all either produce multiple results, take different numbers of arguments depending on the values of other arguments, or are stateful, their exact meaning changing depending on earlier parts of the program.</p>\n\n<p>No amount of magic will be able to make these operators fit into the paradigim of expression-producing-binary-operators that pervades your code. If you intend to support these more general operators, then you will need to remap some responsibilities of the classes:</p>\n\n<p>I would recommend separating <code>Operator</code>s completely from <code>Expression</code>s. Operators are not by themselves expressions - operators are used to combine different expressions into one expression.</p>\n\n<p>Then, make the <code>Operator</code>s responsible for handling adjustment of the stack. When you determine that a particular operator is to be employed , say <code>Add</code>, just call <code>Add.operate(stack)</code>. <code>Add</code> is then responsible for taking the top two <code>Expression</code>s from the stack, and placing an <code>AdditionExpression</code> formed from them onto the stack.</p>\n\n<p>Once you have support for these generalized operators, you can build an interactive console on top of it, where users issue commands that are then added to the stack, which is then persisted between prompts, allowing for extended computations. and experimentation with the stack structure.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-05-07T00:58:19.800", "Id": "49109", "ParentId": "49027", "Score": "2" } } ]
{ "AcceptedAnswerId": "49030", "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-05-06T01:05:23.600", "Id": "49027", "Score": "8", "Tags": [ "java", "tree", "inheritance" ], "Title": "Basic Postfix Calculator in Java" }
49027
<p>Fellow students are supposed to review and tell what my code is doing for a grade, this is why I'm asking on here first. I want to see if its clear enough. </p> <pre><code>public class SpellParser { private static final String SPELL_PACKAGE_LOCATION = "edu.swosu.wordcraft.spells."; private Document dom; public SpellParser() { setUpDom(); } public void setUpDom(){ DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance(); try { DocumentBuilder docBuilder = dbf.newDocumentBuilder(); dom = docBuilder.parse("resources/Spells.xml"); } catch(Exception e) { e.printStackTrace(); } } public void parse(){ //get the root element Element docEle = dom.getDocumentElement(); //get a nodelist of elements NodeList nl = docEle.getElementsByTagName("spell"); if(nl != null &amp;&amp; nl.getLength() &gt; 0) { for(int i = 0 ; i &lt; nl.getLength();i++) { //get the spell element Element el = (Element)nl.item(i); //get the Employee object Spell s = getSpell(el); //add it to list Spell.addSpell(s); } } } </code></pre>
[ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-05-06T02:06:34.147", "Id": "86110", "Score": "0", "body": "Welcome to CR! I have edited the code block so as to include the fist few lines, feel free to edit the indentation to reflect what's in your IDE (might have to do with the fact that our \"ask-a-question\" boxes don't like tabs)." } ]
[ { "body": "<ul>\n<li><p>Your comments don't help much. They should explain why you're doing what you're doing, not just paraphrase the code. If you can't tell the reader anything more than the code already does, then a comment is pretty much just noise.</p></li>\n<li><p><code>setUpDom()</code> should probably be <code>private</code>. Or possibly, done away with altogether, and its contents moved into one of the other methods. It's doing stuff that looks like it should only be done once per XML document, and thus either once over the whole lifetime of the object or once each time you parse. But it shouldn't be done by anything but your code.</p></li>\n<li><p>If you can't handle an exception, you shouldn't be catching it. And \"printing a stack trace\" is not handling. :P</p>\n\n<p>Once <code>setUpDom()</code> fails, the object is broken, so it doesn't make much sense to continue. Let the exceptions propagate (declaring them in a <code>throws</code> clause instead), or throw your own exception type that describes what went wrong, including <code>e</code> as the inner exception.</p></li>\n<li><p>You don't need to check that <code>nl</code> is an object, or worry about the length. The <code>Document</code> class should always hand you back a <code>NodeList</code>, and your <code>for</code> loop will already loop 0 times if the list is empty, as the condition <code>i &lt; nl.getLength()</code> will be false before the very first iteration.</p></li>\n<li><p>The <code>getSpell</code> function and <code>Spell</code> class don't seem to be here. So there's not a whole lot more to say, other than \"fix your indents\". (I half-expect that that is a copy/paste issue, but it should still be mentioned.)</p>\n\n<p>It does appear that <code>Spell</code> has some static variables, though, which is usually not a great solution. And you're hard-coding where the data comes from and where it goes.</p>\n\n<p>I'd personally suggest a <code>SpellBook</code> class or the like, that holds spells. You could pass an instance of such a type (and the name of the XML file) either to your constructor or to <code>parse</code>. Among other things, that leaves open the possibility for multiple sets of spells.</p>\n\n<p>If that's one of your classmates' part, though, and you can't change that...eh. Carry on.</p></li>\n</ul>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-05-06T06:34:28.960", "Id": "86122", "Score": "0", "body": "IMHO I disagree that the \"comments don't help much\" - given today's syntax highlighting, basic comments like this allow the reader to skim through a lot of code much more quickly than otherwise. If I'm taking on a project, new to a team, this type of commented summary helps a lot getting a feel for the project. Bigger comments are appropriate for more complex tasks, but I would never advocate that comments are noise." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-05-06T13:18:14.490", "Id": "86167", "Score": "1", "body": "@RichardLeMesurier: A prime example of why these comments are noise: `// get the Employee object` `Spell s = getSpell(el);` Wait, what? Employee? This code has changed since that comment was introduced. But since no one updated the comment as well, it is now lying to us. At some point in the code's life, *this almost always happens*. And you wouldn't know it if you weren't already reading the code too. That makes the comment useless." } ], "meta_data": { "CommentCount": "2", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-05-06T02:41:35.913", "Id": "49034", "ParentId": "49028", "Score": "5" } }, { "body": "<p>Is SPELL_PACKAGE_LOCATION used?\nThis also seems like the case for a public static parse() method, which would call the private static setupDom() function. This would eliminated the need to make a new Object every time you want to read the spells. As cHao mentioned, you should probably pass some kind of a list of spells as a parameter to the parse() function and read into that list.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-05-06T10:43:26.197", "Id": "49056", "ParentId": "49028", "Score": "3" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "1", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-05-06T01:18:46.550", "Id": "49028", "Score": "6", "Tags": [ "java", "game" ], "Title": "SpellParser for a text-based RPG" }
49028
<p>I implemented the <code>group</code> function:</p> <pre><code>group' :: (Ord a) =&gt; [a] -&gt; [[a]] group' [] = [] group' xs = takeWhile (== head' xs) (sorted xs) : (group' $ dropWhile (== head' xs) (sorted xs)) where sorted ys = mergesort' (ys) head' (x:_) = x </code></pre> <p>Note - please assume <code>mergesort</code> is implemented properly. </p> <p>Its signature is: <code>[a] -&gt; [a]</code> where the latter list is sorted.</p> <p>How's it look? Is <code>head'</code>'s pattern matching exhaustive? It seems to me it is since <code>group xs</code> will only be reached if <code>group</code>'s argument is non-empty, i.e. it'll always have a <code>head</code>.</p>
[]
[ { "body": "<p>You have made some uncommon stylistic choices which are not to your benefit, and a few things aren't doing what I think you think they're doing. </p>\n\n<p>First, the stylistic elements. Your whitespace is excessive, there's no need to push everything that far to the right and out of line with the beginning of the RHS. I also would move the colon down to begin the next line, this is mostly a matter of personal style. The parentheses around <code>ys</code> are unnecessary and while harmless noise for the compiler will distract your human reader. My version would look like this.</p>\n\n<pre><code>group' xs = takeWhile (== head' xs) (sorted xs)\n : group' (dropWhile (== head' xs) (sorted xs))\n where sorted ys = mergesort' ys\n head' (x:_) = x\n</code></pre>\n\n<p>Now to the meat of it. As it is, your definition of <code>sorted</code> is just giving a different name to <code>mergesort'</code>. The two uses in the main body of the function will cause <code>sorted xs</code> to be recomputed each time (ie twice!). The correct definition is not to create an inner function which is passed a list to be sorted as a parameter, but to bind a sorted version of the outer function's parameter.</p>\n\n<pre><code>group' xs = takeWhile (== x) sorted : group' (dropWhile (== x) sorted)\n where sorted = mergesort' xs -- Computed once, the result is used twice\n x = head sorted\n</code></pre>\n\n<p>You'll notice that I gave the same treatment to <code>head'</code>, this is less of a performance hit and more a matter of consistency. If you wanted to be really pedantic you could bind the section as well, but (and this is an art not a science) I feel that this version is less readable.</p>\n\n<pre><code>group' xs = takeWhile p sorted : ...\n where ...\n p = (== head sorted)\n</code></pre>\n\n<p>This is still doing more work than it needs though! Once you've made the first recursive call, the tail passed to <code>group'</code> will always already be sorted, and doesn't need to be resorted with each recursive step. One way to handle this would be to pull the main functionality of <code>group'</code> into an inner function named something like <code>group''</code> and change the body of <code>group'</code> to just be <code>group'' (mergesort' xs)</code>. Now the list is only sorted once.</p>\n\n<p>I think it makes more sense though to separate the two functions entirely. There is in fact no requirement that the list being grouped is sorted, so let's relax that constraint.</p>\n\n<pre><code>group' :: (Eq a) =&gt; [a] -&gt; [[a]]\ngroup' [] = []\ngroup' (x:xs) = (x : takeWhile (== x) xs) : group' (dropWhile (== x) xs)\n\nelementSets :: (Ord a) =&gt; [a] -&gt; [[a]] -- Same functionality as original group'\nelementSets = group' . mergeSort'\n</code></pre>\n\n<p>And just so you see what's happening,</p>\n\n<pre><code>&gt; group' [2,2,1,2,2,2]\n[[2,2],[1],[2,2,2]]\n&gt; elementSets [2,2,1,2,2,2]\n[[1],[2,2,2,2,2]]\n</code></pre>\n\n<p>Note that we can now find the head of the list through pattern matching instead of calling <code>head</code> because we don't need to assume the list may be out of order. We do however have to remember to add that element back to the prefix of what we're returning!</p>\n\n<p>There's one more improvement we can make though! As it is, our <code>group'</code> function will walk the prefix of the list equal to the first element twice each recursive step (once for <code>takeWhile</code>, and once for <code>dropWhile</code>). We can eliminate that inefficiency by using <code>span</code> which returns the prefix matching the predicate and the remainder in one go.</p>\n\n<pre><code>group' (x:xs) = (x : prefix) : group' remainder\n where (prefix, remainder) = span (== x) xs\n</code></pre>\n\n<p>And there we have it.</p>\n\n<p>Regarding your question about whether <code>head'</code>'s pattern matching was exhaustive, the answer is that it is not exhaustive because the definition of <code>head'</code> contained no case which would match every possible pattern (ie <code>head' []</code>). It was however \"safe\" to use because of how <code>group'</code> was defined, and the case of the empty list was handled through pattern matching at the outer level. In general you shouldn't rely on tricky business like that, it can be difficult to notice when coming back to code you or someone else has written, and can blow up on you if you have to change the definition of the function.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-05-09T01:16:33.050", "Id": "86656", "Score": "0", "body": "Thanks! Besides your excellent, detailed post, I especially learned from your last sentence - ` In general you shouldn't rely on tricky business like that`" } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-05-06T07:38:28.370", "Id": "49045", "ParentId": "49031", "Score": "5" } } ]
{ "AcceptedAnswerId": "49045", "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-05-06T01:56:45.807", "Id": "49031", "Score": "5", "Tags": [ "haskell", "reinventing-the-wheel" ], "Title": "Haskell's `group` Function" }
49031
<p>In the below example I have tried to show how we can break a long running background task running in a service into different states of a state machine and notify the front end UI about each and every stage as they occur in the service.</p> <p>Here I have used a service called <code>LongRunningService</code> which actually (theoretically) does the task of downloading a big file from a network server (however, for simplicity I have just stubbed out the actual download code with a thread having delay of 1000 ms). This background task has been split into different states according to the state machine like "Start Connection", "Connection Completed", "Start Downloading" and "Stop Downloading". This application also showcases the concept of communicating from a background service to the frontend UI through Android messenger framework.</p> <p>Please review this code and provide me with your valuable feedback.</p> <p><strong><em>The Main Activity:</em></strong> </p> <pre><code>package com.somitsolutions.android.example.statepatterninservice; import android.app.Activity; import android.content.Context; import android.content.Intent; import android.os.Bundle; import android.os.Handler; import android.os.Message; import android.os.Messenger; import android.view.Menu; import android.view.View; import android.view.View.OnClickListener; import android.widget.Button; import android.widget.Toast; public class MainActivity extends Activity implements OnClickListener{ private static final int CONNECTING = 1; private static final int CONNECTED = 2; private static final int DOWNLOADSTARTED = 3; private static final int DOWNLOADFINISHED = 4; Button startButton; private MessageHandler handler; private static MainActivity mMainActivity; public Messenger mMessenger = new Messenger(new MessageHandler(this)); private class MessageHandler extends Handler{ private Context c; MessageHandler(Context c){ this.c = c; } @Override public void handleMessage(Message msg) { switch(msg.what){ case CONNECTING: Toast.makeText(getApplicationContext(), "Connecting", Toast.LENGTH_LONG).show(); break; case CONNECTED: Toast.makeText(getApplicationContext(), "Connected", Toast.LENGTH_LONG).show(); break; case DOWNLOADSTARTED: Toast.makeText(getApplicationContext(), "Download Started", Toast.LENGTH_LONG).show(); break; case DOWNLOADFINISHED: Toast.makeText(getApplicationContext(), "Download Finished", Toast.LENGTH_LONG).show(); break; default: super.handleMessage(msg); } } } @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); mMainActivity = this; startButton = (Button)findViewById(R.id.button1); startButton.setOnClickListener(this); } @Override public boolean onCreateOptionsMenu(Menu menu) { // Inflate the menu; this adds items to the action bar if it is present. getMenuInflater().inflate(R.menu.main, menu); return true; } public static MainActivity getMainActivity(){ return mMainActivity; } @Override public void onClick(View arg0) { // TODO Auto-generated method stub Intent serv = new Intent(MainActivity.this, LongRunningService.class); startService(serv); } } </code></pre> <p><strong><em>The Service Class</em></strong></p> <pre><code>package com.somitsolutions.android.example.statepatterninservice; import android.app.Service; import android.content.Intent; import android.os.Handler; import android.os.HandlerThread; import android.os.IBinder; import android.os.Looper; import android.os.Message; import android.os.Messenger; import android.os.RemoteException; import android.widget.Toast; public class LongRunningService extends Service { private static final int CONNECTING = 1; private static final int CONNECTED = 2; private static final int DOWNLOADSTARTED = 3; private static final int DOWNLOADFINISHED = 4; private Looper mServiceLooper; private ServiceHandler mServiceHandler; // Handler that receives messages from the thread private final class ServiceHandler extends Handler { public ServiceHandler(Looper looper) { super(looper); } @Override public void handleMessage(Message msg) { Messenger messenger= MainActivity.getMainActivity().mMessenger; try { messenger.send(Message.obtain(null, CONNECTING, "Connecting")); // Normally we would do some work here, like download a file. // For our sample, we just sleep for 10 seconds. Thread.sleep(1000); // Normally we would do some work here, like download a file. // For our sample, we just sleep for 10 seconds. messenger.send(Message.obtain(null, CONNECTED, "Connected")); // Normally we would do some work here, like download a file. // For our sample, we just sleep for 10 seconds. Thread.sleep(1000); messenger.send(Message.obtain(null, DOWNLOADSTARTED, "Download Started")); // Normally we would do some work here, like download a file. // For our sample, we just sleep for 10 seconds. Thread.sleep(1000); messenger.send(Message.obtain(null, DOWNLOADFINISHED, "Download Finished")); } catch (InterruptedException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (RemoteException e) { // TODO Auto-generated catch block e.printStackTrace(); } // Stop the service using the startId, so that we don't stop // the service in the middle of handling another job stopSelf(msg.arg1); } } @Override public void onCreate() { // Start up the thread running the service. Note that we create a // separate thread because the service normally runs in the process's // main thread, which we don't want to block. We also make it // background priority so CPU-intensive work will not disrupt our UI. HandlerThread thread = new HandlerThread("ServiceStartArguments", Thread.NORM_PRIORITY); thread.start(); // Get the HandlerThread's Looper and use it for our Handler mServiceLooper = thread.getLooper(); mServiceHandler = new ServiceHandler(mServiceLooper); } @Override public int onStartCommand(Intent intent, int flags, int startId) { Toast.makeText(this, "download service starting", Toast.LENGTH_SHORT).show(); // For each start request, send a message to start a job and deliver the // start ID so we know which request we're stopping when we finish the job Message msg = mServiceHandler.obtainMessage(); msg.arg1 = startId; mServiceHandler.sendMessage(msg); // If we get killed, after returning from here, restart return START_STICKY; } @Override public IBinder onBind(Intent intent) { // We don't provide binding, so return null return null; } @Override public void onDestroy() { Toast.makeText(this, "service done", Toast.LENGTH_SHORT).show(); } } </code></pre>
[]
[ { "body": "<p>I would replace</p>\n\n<pre><code>private static final int CONNECTING = 1;\nprivate static final int CONNECTED = 2;\nprivate static final int DOWNLOADSTARTED = 3;\nprivate static final int DOWNLOADFINISHED = 4;\n</code></pre>\n\n<p>by an Enum which would add typesafety and also helps your IDE to detect e.g. if a state is not handled in your <code>switch</code> statement.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2016-04-22T00:00:21.953", "Id": "235960", "Score": "0", "body": "Enums are frowned apon in Android, instead it is recommended to use the IntDef and StringDef annotations: http://developer.android.com/reference/android/support/annotation/IntDef.html" } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-05-08T13:03:59.940", "Id": "49224", "ParentId": "49032", "Score": "3" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-05-06T02:20:37.667", "Id": "49032", "Score": "1", "Tags": [ "java", "android" ], "Title": "Implementation of Finite State machine in long running task in an Android service" }
49032
<p>I got three classes for MySQL Database access/manipulation:</p> <ol> <li><code>Conector</code>. It has got methods for connecting, disconnecting, querying and updating db.</li> <li><code>ConectorCliente</code>. It simply extends first and got its constructor receiving <code>user</code>, <code>password</code>, <code>host</code>, <code>port</code> and <code>db</code>.</li> <li>I have written has several different methods per each DB, depending on data which will be needed to be selected, updated or deleted.</li> </ol> <p>These are my classes in the mentioned order:</p> <h1>First class</h1> <pre><code>public class Conector { private Connection connection = null; private Statement statement = null; private ResultSet set = null; String host; String port; String login; String password; String url; public Conector (String login, String password, String db, String host, String port) { this.login = login; this.password = password; this.host = host; this.port = port; url = "jdbc:mysql://"+host+":"+port+"/"+db; Conectar (); } public void Desconectar () { connection = null; } private void Conectar() { try { DriverManager.registerDriver(new com.mysql.jdbc.Driver ()); } catch (SQLException ex) { Logger.getLogger(Conector.class.getName()).log(Level.SEVERE, null, ex); } try { connection = DriverManager.getConnection(url, login, password); statement = connection.createStatement(); } catch (SQLException e) { Logger logger = Logger.getLogger(Conector.class.getName()); logger.log(Level.SEVERE, e.getSQLState(), e); } } public ResultSet Query(String query){ try { statement = connection.createStatement(); set = statement.executeQuery(query); } catch (Exception e) { System.out.println("Exception in query method:\n" + e.getMessage()); } return set; } public boolean Update (String update) { try { statement = connection.createStatement(); statement.executeUpdate(update); } catch (SQLException e) { System.out.println("Exception in update method:\n" + e.getMessage()); return false; } return true; } public void cierraConexion(){ try { connection.close(); connection = null; } catch(Exception e) { System.out.println("Problema para cerrar la conexión a la base de datos "); } } } </code></pre> <h1>Second class</h1> <pre><code>public class ConectorCliente extends Conector { public ConectorCliente(String login, String password, String db, String host, String port) { // Con super llamamos y ocupamos el constructor de la clase padre super(login, password, db, host, port); } } </code></pre> <h1>Example of third class</h1> <pre><code>public class InteraccionDB { private static final ConectorCliente conector = new ConectorCliente("user", "pass","db", "127.0.0.1", "3306"); public static int obtenerNumRegistros() { ResultSet resultado = conector.Query("SELECT COUNT(*) FROM tweets;"); try { while (resultado.next()) { return resultado.getInt("COUNT(*)"); } } catch (SQLException ex) { Logger.getLogger(InteraccionDB.class.getName()).log(Level.SEVERE, null, ex); } return -1; } public static void insertarTweet(String id) { conector.Update("INSERT INTO tweets (id) VALUES ('"+id+"')"); } public static void eliminarTweet(String id) { conector.Update("DELETE FROM tweets WHERE id = '"+id+"'"); } public static HashMap&lt;String, Integer&gt; obtenerHoraTweet(String id) { HashMap&lt;String, Integer&gt; resultados = new HashMap&lt;&gt;(); ResultSet resultado = conector.Query("SELECT hora, min FROM tweets WHERE id = '"+id+"'"); try { while (resultado.next()) { resultados.put("Hora", resultado.getInt(1)); resultados.put("Minuto", resultado.getInt("min")); } } catch (SQLException ex) { Logger.getLogger(InteraccionDB.class.getName()).log(Level.SEVERE, null, ex); } return resultados; } public static ArrayList&lt;String&gt; obtenerIdsRetweets(int retweets) { ArrayList&lt;String&gt; resultados = new ArrayList&lt;&gt;(); ResultSet resultado = conector.Query("SELECT id FROM tweets WHERE retweets &gt; "+retweets); try { while (resultado.next()) { resultados.add(resultado.getString("id")); } } catch (SQLException ex) { Logger.getLogger(InteraccionDB.class.getName()).log(Level.SEVERE, null, ex); } return resultados; } } </code></pre> <p>In my case, I prefer to make third class to return structures like <code>ArrayList</code>'s or <code>HashTable</code>'s making code cleaner at invocation side.</p> <p>I care to improve:</p> <ul> <li>Exception handling (I know I'm not doing nothing for it so far)</li> <li>Going for Interfaces</li> <li>Security</li> <li>Java / OOP stuffs</li> </ul>
[ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-05-06T09:32:01.727", "Id": "86143", "Score": "3", "body": "May be pedantic to say, but I'd **really** advise against using non-english names (I'm guessing this is Spanish) in code." } ]
[ { "body": "<p>Just for starters...</p>\n\n<ul>\n<li>Method names in your <code>Conector</code> class should be in <code>camelCase</code> too</li>\n<li>There is no need for <code>ConectorCliente</code> if all it does is to extend <code>Conector</code> and use the same constructor.</li>\n<li>Your <code>try-catch</code> across the two classes is either printing out to console directly or creating a new <code>Logger</code> each time. I will suggest creating a <code>static final Logger.getLogger(&lt;class name&gt;)</code> in each class to do logging.</li>\n<li>Methods' return types should be an interface instead of an implementation, i.e. <code>List&lt;&gt;</code> instead of <code>ArrayList&lt;&gt;</code></li>\n<li>I don't think your connection class should be a static field inside <code>InteraccionDB</code>, and in fact I don't think its methods should be all static either... how do you intend to test your code? </li>\n<li>Too many empty lines, please trim for readability</li>\n<li>Reduce the <code>try-catch</code> scope inside <code>Conector.Query()</code> <code>Conector.cierraConexion()</code> for <code>Exception</code> to something like <code>SQLException</code> (as you have done in other methods)</li>\n</ul>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-05-06T05:35:49.573", "Id": "86116", "Score": "0", "body": "Thanks, about static methods. I find it easier that way, assuming quite any web or even desktop app connection to DB *depends* upon the DB connection, something failing there and being catched will make the application react.\n\nHow would this affect testing?" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-05-06T05:41:08.953", "Id": "86117", "Score": "0", "body": "For example, changing database connection parameters to test against different databases will imply a code change. One recommended approach is that you can still have a class similar to `InteraccionDB`, but it gets a database connection instance and can explicitly initialize or close the connection if required." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-05-06T05:43:29.063", "Id": "86118", "Score": "0", "body": "I agree about it, however I planned `InteraccionDB` to be ever rewritten. And assume at it that there will already be a connection going through." } ], "meta_data": { "CommentCount": "3", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-05-06T05:30:21.583", "Id": "49037", "ParentId": "49036", "Score": "5" } }, { "body": "<p>I seen a lot of things what can better so I'm glad you came here to learn.</p>\n\n<h2>First :</h2>\n\n<p>Your <code>Conector</code>is a normal class.<br/>\nThe <code>ConectorCliente</code> extends that class and do just calling the super constructor without anything else.<br/>\nHere is a problem : Or you set your first class abstract if you know you are going to have other implementations (preferable with more code) or your first class should be an interface.</p>\n\n<h2>Second :</h2>\n\n<pre><code>private Connection connection = null;\nprivate Statement statement = null;\nprivate ResultSet set = null;\n\nString host;\nString port;\nString login;\nString password;\nString url;\n</code></pre>\n\n<p>Why do you do it right for Connection, Statement an Resultset and don't set a modifier before all the strings?<br/>\nThe best practice is make them all private and if you need them outside the class make an getter/setter for it.</p>\n\n<h2>Third :</h2>\n\n<pre><code>private void Conectar() {\n</code></pre>\n\n<p>should be :</p>\n\n<pre><code>private void conectar() {\n</code></pre>\n\n<p><a href=\"http://java.about.com/od/javasyntax/a/nameconventions.htm\" rel=\"nofollow\">Method names do not start with a capital</a>.<br/>\nstarting with a capital is for classes.</p>\n\n<h2>Fourth :</h2>\n\n<p>You rely on users of your class that they close your connection.<br/>\nYou will have memory leaks cause they will forget to close your connection.</p>\n\n<p>There are 2 possibilities what you can do.</p>\n\n<p><b>First :</b></p>\n\n<pre><code>@Override\nprotected void finalize() throws Throwable {\n super.finalize();\n cierraConexion();\n}\n</code></pre>\n\n<p>So override the finalize of the class and close the connection there.<br/>\nThis is called when the class is destroyd.<br/>\nI prefer the second one cause the finalize has issues that it could be that it is never called.\nAs it seems in the comment a nice discussion on this issue :).</p>\n\n<p><b>Second :</b></p>\n\n<p>Open and close your connection before you do an action to the DB.\nDo a <a href=\"http://docs.oracle.com/javase/tutorial/essential/exceptions/tryResourceClose.html\" rel=\"nofollow\">try-with-resource</a> or close the connection in the <a href=\"http://docs.oracle.com/javase/tutorial/essential/exceptions/finally.html\" rel=\"nofollow\">finally block</a> of the try-catch.</p>\n\n<p><b>Edit : added sample code.</b></p>\n\n<pre><code>// Register the driver once in the constructor.\n\nprivate Connection getConectar() throws SQLException {\n return DriverManager.getConnection(url, login, password);\n}\n\npublic boolean Update (String update) {\n int result;\n try (Connection connection = getConectar(),\n Statement statement = connection.createStatement()) {\n result = statement.executeUpdate(update);\n } catch (SQLException e) {\n System.out.println(\"Exception in update method:\\n\" + e.getMessage());\n return false;\n }\n return (result!=0); // if 0 is returned there is NO row changed =&gt; means nothing is updated.\n}\n</code></pre>\n\n<h2>Fifth :</h2>\n\n<p>Your <code>InteraccionDB</code> has only all static methods and variable. <br/>So no instanciation has to be made.<br/> Why not make the class static and maybe even final when you want to be sure nobody may extend that class.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-05-06T07:02:55.890", "Id": "86125", "Score": "1", "body": "I wouldn't recommend relying on `finalize()` though... many resources online indicate likewise, e.g. this SO link: http://stackoverflow.com/a/2506509/2754160" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-05-06T07:07:28.687", "Id": "86127", "Score": "1", "body": "@h.j.k. like I said, personally prefer the second one because I know it has issues. Still a possibility worth mentioning in mine oppinion." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-05-06T07:12:47.287", "Id": "86129", "Score": "0", "body": "Thanks so much, deeply, can you give some code snippets of some of the advices (least 4 which is obvious)" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-05-06T07:13:26.153", "Id": "86130", "Score": "0", "body": "Fourth 3: Implement AutoCloseable, and use Class as resource. Very nice review +1" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-05-06T07:18:20.420", "Id": "86132", "Score": "2", "body": "Openings connection is a high-overhead operation, so I don't advise closing it too automatically. Explicit close, with an automatic close in `finalize()` in case the client forgets, is preferable." } ], "meta_data": { "CommentCount": "5", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-05-06T06:51:47.763", "Id": "49042", "ParentId": "49036", "Score": "7" } }, { "body": "<p>Some things that hasn't been mentioned already:</p>\n<h1>SQL INJECTION!</h1>\n<p>Use <a href=\"http://docs.oracle.com/javase/7/docs/api/java/sql/Connection.html#prepareStatement%28java.lang.String%29\" rel=\"nofollow noreferrer\">prepared statements</a>. They are much more secure than normal statements as they prevent SQL injection, which your code currently is vulnerable to. Never use string concatenation to create an SQL statement!</p>\n<hr />\n<p>As your <code>ResultSet set</code> is only used inside the <code>query</code> method, I would use it as a local variable inside that method. I would also rename the variable to <code>queryResult</code>.</p>\n<pre><code>public ResultSet Query(String query) {\n ResultSet queryResult = null;\n try {\n statement = connection.createStatement();\n queryResult = statement.executeQuery(query);\n }\n catch (Exception e) {\n System.out.println(&quot;Exception in query method:\\n&quot; + e.getMessage());\n }\n return queryResult;\n}\n</code></pre>\n<hr />\n<p>Once the constructor is finished, you're not using your String variables again, pass them on to the connect method and remove them as class fields. Only pass them on as parameters.</p>\n<hr />\n<pre><code>public void Desconectar () {\n connection = null;\n}\n</code></pre>\n<p><strong>Close</strong> the connection <em>before</em> you set it to null! (And rename the method to <code>disconnect</code>)</p>\n<hr />\n<h3>String or int?</h3>\n<p>Many of your parameters are <code>String</code>s. I would use them as ints. A port number is an <strong>int</strong>, an id for a tweet is (most likely) an <strong>int</strong>. Don't use them as strings!</p>\n<hr />\n<p>Only a suggestion: Use <a href=\"http://hibernate.org/\" rel=\"nofollow noreferrer\">Hibernate</a> (object-relational mapper) and/or <a href=\"http://sourceforge.net/projects/c3p0/\" rel=\"nofollow noreferrer\">C3p0</a> (connection pooling). They can be difficult to get started with but they are wildly used in many Java projects, for good reasons. Learning them can be both good for your program, and good for your Java knowledge.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-05-06T11:22:28.480", "Id": "49062", "ParentId": "49036", "Score": "4" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "1", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-05-06T05:12:20.053", "Id": "49036", "Score": "8", "Tags": [ "java", "mysql", "database" ], "Title": "Java and MySQL connection classes and method implementations" }
49036
<p>Is this a good approach or is there some other solution that I am not aware of?</p> <pre><code>//C++ program to count number of words in text file #include&lt;fstream&gt; #include&lt;iostream&gt; #include&lt;string&gt; using namespace std; int main() { ifstream inFile; //Declares a file stream object string fileName; string word; int count = 0; cout &lt;&lt; "Please enter the file name "; getline(cin,fileName); inFile.open(fileName.c_str()); while(!inFile.eof()) { inFile &gt;&gt; word; count++; } cout &lt;&lt; "Number of words in file is " &lt;&lt; count; inFile.close(); cin.get(); return 0; } </code></pre>
[ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-05-06T06:11:52.520", "Id": "86119", "Score": "2", "body": "Please do add some comment, like what your class have to do. Are there some specific things we need to review?" } ]
[ { "body": "<p>Your code has a few problems.</p>\n\n<ol>\n<li>You should learn to <em>not</em> use <code>using namespace std;</code>. It's generally frowned upon.</li>\n<li>You should <em>never</em> use <code>while(!inFile.eof())</code>. It's pretty much a guaranteed bug.</li>\n<li>You <em>should</em> use standard algorithms when they're applicable (as they are here).</li>\n<li>Prefer to fully initialize variables at creation (e.g., pass file name when you create a filestream object).</li>\n<li>Generally let the destructor handle destruction (e.g., let the filestream object close when it goes out of scope)<sup>1</sup>.</li>\n</ol>\n\n<p>I'd also strongly prefer to take command line arguments over prompting for input at run time.</p>\n\n<p>I'd write the code using the standard <code>distance</code> algorithm, something like this:</p>\n\n<pre><code>#include &lt;fstream&gt;\n#include &lt;algorithm&gt;\n#include &lt;iterator&gt;\n#include &lt;iostream&gt;\n#include &lt;string&gt;\n#include &lt;cstdlib&gt;\n\nint main(int argc, char **argv) {\n if (argc &lt; 2) {\n std::cerr &lt;&lt; \"Usage: count_words &lt;infile&gt;\\n\";\n return EXIT_FAILURE;\n }\n\n std::ifstream infile(argv[1]);\n\n std::istream_iterator&lt;std::string&gt; in{ infile }, end;\n\n std::cout &lt;&lt; \"Word count: \" &lt;&lt; std::distance(in, end);\n}\n</code></pre>\n\n<hr>\n\n<ol>\n<li>There are a few cases where it makes sense to manually close a file. For example, if you're moving a file between file systems by copying its content, then deleting the original, you want to do <em>everything</em> you can to ensure the copy completed successfully (including successful closing) before you remove the original. Anything that might destroy the user's data calls for extraordinary measures to assure safety. This isn't one of those cases though.</li>\n</ol>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-05-06T07:49:03.040", "Id": "86137", "Score": "0", "body": "I wouldn't put two variables in one line (like you did with `in` and `end`." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-05-07T01:15:02.397", "Id": "86269", "Score": "0", "body": "Darn you. That's a nice easy question. The one thing I would add (which is not worth a separate answer). Is not to bother open file on a separate line (ie constructor) or manually close a file (ie dstructor. rely on RAII)." } ], "meta_data": { "CommentCount": "2", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-05-06T06:17:32.900", "Id": "49039", "ParentId": "49038", "Score": "19" } }, { "body": "<p><code>using namespace std;</code> is a <a href=\"https://stackoverflow.com/questions/1452721/why-is-using-namespace-std-considered-bad-practice\">bad habit</a>.</p>\n\n<hr>\n\n<p>Declare variables as close to use as possible. (for example, declare <code>count</code> about the while loop rather than at the top).</p>\n\n<hr>\n\n<p>An <code>eof</code> loop control does not work the way you think it does. <code>eof</code> is not reached until after the end of file is attempted to be read past. This means that your last read can silently fail.</p>\n\n<p>The more natural way to write that loop is:</p>\n\n<pre><code>while (inFile &gt;&gt; word) { ++count; }\n</code></pre>\n\n<hr>\n\n<p>I would put a newline after the count output. It's rare to have a program output without a trailing newline. (Although I'm only familiar with linux--maybe no break is normal under Windows.)</p>\n\n<hr>\n\n<p>Rather than using <code>cin.get()</code>, I would just run the application inside of a console. It's a bit of a strange behavior to have the program hang until you hit a key. Imagine if programs like <code>grep</code>, <code>cat</code> or <code>wc</code> did that. It would be a pain to use.</p>\n\n<hr>\n\n<p>Since you're only using one parameter and there's no real advantage to using a user prompt, I would take the filename as an argument to the program rather than reading it from the console. (In other words, I would use <code>argv</code>.)</p>\n\n<hr>\n\n<p>If a program can't fail, it's fairly common to omit a return code. That clearly signals that the program can't fail. (Note: <code>main</code> is a special case. Return values are always required in other functions.)</p>\n\n<hr>\n\n<p>If you wanted to leverage the standard library, you could actually do this much shorter:</p>\n\n<pre><code>ifstream fs(...);\nstd::size_t count = std::distance(std::istream_iterator&lt;std::string&gt;(fs), \n std::istream_iterator&lt;std::string&gt;());\n</code></pre>\n\n<p>The specifics of this are a bit advanced, but the basic idea is that <code>istream_iterator</code> is a simple wrapper around <code>operator&gt;&gt;</code> and that it performs extractions until it no longer can. Since <code>std::distance</code> runs the length of the first iterator until the second, this will just read as many tokens as it can and return the distance (i.e. count). (Technically it doesn't always actually iterate along the iterators. When it can, it will just do a simple subtraction. That's irrelevant here though.)</p>\n\n<hr>\n\n<p>I wouldn't bother closing the file. Unless you plan on doing actual error handling, it's best to just let the scope of the file handle the close of it. When it goes out of scope, the destructor will run which will close the file if it's still open.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-05-06T06:18:03.523", "Id": "49040", "ParentId": "49038", "Score": "14" } }, { "body": "<p>Plus what ppl mentioned, you need to double check if the file is opened successfully otherwise you should not manipulate it. </p>\n\n<pre><code>if ( inFile.fail() )\n{\n // do something\n return -1;\n}\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-05-07T19:39:57.473", "Id": "86416", "Score": "1", "body": "It's typically a bad idea to return negative values. The only values guaranteed to be meaningful are `EXIT_SUCCESS` and `EXIT_FAILURE`, but more importantly, certain systems (like linux) use unsigned numbers to represent exit statuses, so that -1 silently becomes a large positive number. It doesn't matter as long you're only checking `code == 0` or not, but considering there's no advantage over `EXIT_FAILURE`, there's no real reason to use anything else." } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-05-07T09:32:54.613", "Id": "49129", "ParentId": "49038", "Score": "2" } }, { "body": "<p>It's better to put <code>using namespace</code> inside your code block (main()) or don't use it. Otherwise it will generate some namespace conflicts when you write a large project.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-05-09T04:21:18.767", "Id": "49296", "ParentId": "49038", "Score": "1" } } ]
{ "AcceptedAnswerId": "49039", "CommentCount": "1", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-05-06T06:01:08.530", "Id": "49038", "Score": "14", "Tags": [ "c++", "file" ], "Title": "Count number of words in a text file" }
49038
<p>I am using PDO for the first time in my project. In my previous project someone suggested me to use PDO as my queries were wide open to inject. I am pasting a sample code of my project. Can you please let me know how safe my code and query is?</p> <pre><code>&lt;?php require('config.php'); try { $pid = $_GET['pid']; $conn = new PDO("mysql:host=" . $DB_HOST . ";dbname=" . $DB_NAME, $DB_USER, $DB_PASS); $sql = "SELECT * FROM packages_to_be_shipped_on_bremail_address WHERE package_id=$pid"; $q = $conn-&gt;prepare($sql); $q-&gt;execute(); $q-&gt;bindColumn(1, $pid); $q-&gt;bindColumn(2, $custemail); $q-&gt;bindColumn(3, $shipcompany); $q-&gt;bindColumn(4, $deliverydate); $q-&gt;bindColumn(5, $trackingid); $q-&gt;bindColumn(6, $destaddress); $q-&gt;bindColumn(7, $destzip); $q-&gt;bindColumn(8, $status); $q-&gt;bindColumn(9, $rate); $q-&gt;bindColumn(10, $rates_sent_status); $q-&gt;bindColumn(11, $customer_response); while($q-&gt;fetch()){ echo "Shipping Company - ".$shipcompany."&lt;br /&gt;&lt;hr /&gt;"; echo "Expected Delivery Date - ".$deliverydate."&lt;br /&gt;&lt;hr /&gt;"; } } catch(PDOException $e) { echo $e-&gt;getMessage(); } ?&gt; </code></pre>
[ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-05-06T07:37:02.663", "Id": "86134", "Score": "1", "body": "It is still wide open to sql injection. This is never sanitized $pid = $_GET['pid']; and is used directly in your query." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-05-06T07:38:21.967", "Id": "86135", "Score": "0", "body": "This might help, http://stackoverflow.com/questions/60174/how-can-i-prevent-sql-injection-in-php/60496#60496" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-05-06T07:39:44.703", "Id": "86136", "Score": "0", "body": "Just another note, I would name the columns in your select. If you ever alter the table, the column order may not match what you expect, and it will probably silently fail." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-05-06T08:32:06.190", "Id": "86140", "Score": "0", "body": "@bumperbox what is the solution of if i alter the column order?" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-05-06T12:28:31.190", "Id": "86157", "Score": "0", "body": "@RajeshVishnani: cf my answer: use `$stmt->fetch(PDO::FETCH_ASSOC)`, which will return each row as an associative array, where the column (field) names are the indexes: `$row = $stmt->fetch(PDO::FETCH_ASSOC); echo $row['package_id'];` will always work, regardless of column/field order..." } ]
[ { "body": "<p>Not safe at all, I'm afraid. Sure, you're calling <code>PDO::prepare</code>, to create a prepared statement, and that's all fine and dandy, but you are directly concatenating unsanitized user data into the string form which the query is prepared:</p>\n\n<pre><code> $pid = $_GET['pid'];\n $sql = \"SELECT * FROM packages_to_be_shipped_on_bremail_address WHERE package_id=$pid\";\n</code></pre>\n\n<p>What if I were to pass any of the following values as <em>\"pid\"</em>:</p>\n\n<pre><code>1 OR package_id &gt; 0;\n//or:\n?\n</code></pre>\n\n<p>That would mean that, in the first case, you're executing the query:</p>\n\n<pre><code>SELECT * FROM packages_to_be_shipped_on_bremail_address WHERE package_id = 1 OR package_id &gt; 0;\n-- which translates to:\nSELECT * FROM packages_to_be_shipped_on_bremail_address;\n</code></pre>\n\n<p>The second case is, in a way, even more subtle:</p>\n\n<pre><code>SELECT * FROM packages_to_be_shipped_on_bremail_address WHERE package_id = ?\n</code></pre>\n\n<p>This is a perfectly valid string to be passed to the <code>PDO::prepare</code> method. The <code>?</code> is a placeholder for a value that will be bound later on in the code (at least, that's what PDO, and MySQL expects).<Br>\nThat means that your code will won't see anything wrong with the query, but once <code>PDOStatement::execute</code> is called, it'll throw an exception saying there is a problem. Something along the lines of <em>\"<code>PDOStatement::execute</code> expects one parameter, received null\"</em><br>\nJust <a href=\"http://www.php.net/manual/en/pdo.prepare.php\" rel=\"nofollow\">check the docs</a>, and check the examples of how <code>PDO::prepare</code> should be used. What you're after should be:</p>\n\n<pre><code>$stmt = $pdo-&gt;prepare(\n 'SELECT *\n FROM packages_to_be_shipped_on_bremail_address\n WHERE package_id = :pid'\n);\n$stmt-&gt;execute(\n array(\n ':pid' =&gt; $pid\n )\n);\nwhile($row = $stmt-&gt;fetch(PDO::FETCH_OBJ))//or FETCH_ASSOC\n{\n echo 'Shipping Company - ', $row-&gt;shipcompany,\n '&lt;br&gt;&lt;hr&gt;Expected Delivery Date ', $row-&gt;deliverydate, '&lt;br&gt;&lt;hr&gt;';\n}\n</code></pre>\n\n<p>Before you ask: Yes, those are comma's in the <code>echo</code> statement. <code>echo</code> is a language construct that works pretty similarly to C++'s <code>std::COUT</code>. You can push multiple values to it, separated by comma's.<Br>\nThe upshot is that PHP can then skip the string concatenation step, making the statement more efficient.<br>\nThe downside? Well, there isn't one AFAIK.</p>\n\n<p>Anyway: How does this produce safer queries? Well, that's easy: you send the query, without the user-supplied data to the server. MySQL can already compile and optimize the query. Often, MySQL will even be able to pre-fetch some of the data you need.<Br>\nWhen you execute the query, and provide the data that makes up the <code>WHERE</code> clause (or other parts of your query), then MySQL can escape them properly, and since the query is already compiled, there's no real danger of the user supplied data being able to alter the query itself. This is just a short, very basic, and incomplete explanation of prepared statements. For more details: ask Google.</p>\n\n<p><em>Other Niggles</em><br>\nThere are some other issues that should be fixed, too:</p>\n\n<pre><code>$pid = $_GET['pid'];\n</code></pre>\n\n<p>What if <code>$_GET</code> isn't set, or the <code>pid</code> parameter wasn't passed? In that case, PHP will emit a notice (undefined index or something). Simply <em>check</em> before you attempt to assign:</p>\n\n<pre><code>if (!isset($_GET['pid']))\n exit();//or do something else\n$pid = $_GET['pid'];\n</code></pre>\n\n<p><em>Avoid <code>SELECT * FROM</code> queries as much as you can</em>. Sure <code>SELECT *</code> is quick and easy to write, but it does what it says on the tin: it <strong>selects every field</strong>. You only seem to be using 2 fields per row.<br>\nWhy, then, do you feel compelled to select everything? Wouldn't:</p>\n\n<pre><code>SELECT shipcompany, deliverydate FROM your_wacky_tbl_name WHERE package_id = :pid\n</code></pre>\n\n<p>Work, too? As an added bonus: it's easier to see/understand for anyone maintaining this code what the query does, and what it selects. If you need some other field later on, then you can simply add that to the query.</p>\n\n<p>Next, you've wrapped <em>everything</em> in a <code>try</code> block. Probably expecting <code>PDO</code> to throw up exceptions if any of the calls fail (<code>PDO::prepare</code>, <code>PDOStatement::execute</code> and <code>PDOStatement::fetch</code> or even that <code>PDOStatement::bindColumn</code> call that really serves no purpouse here, IMO).</p>\n\n<p>This isn't going to work as you expect it to, because you haven't set <code>PDO</code>'s error-mode so that it will throw exceptions. To do so, either pass an array to the constructor or call <code>PDO::setAttribute</code>:</p>\n\n<pre><code>$pdo = new PDO($dsn, $user, $pass,\n array(\n PDO::ATTR_ERRMODE =&gt; PDO::ERRMODE_EXCEPTION\n )\n);\n//or\n$pdo-&gt;setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);\n</code></pre>\n\n<p>See <a href=\"http://www.php.net/manual/en/pdo.setattribute.php\" rel=\"nofollow\">a list of attributes that you can set</a>, either by passing them as an assoc array to the constructor, or by calling <code>PDO::setAttribute</code>.</p>\n\n<p><strong><em>Pokémon Exception Handling</em></strong><Br>\nAt the moment, you're just blindly catching <em>any</em> of the possible <code>PDOException</code>s that might be thrown. This is called Pokémon Exception Handling, when you <em>\"gotta catch 'em all\"</em>. Another term you could use for this is <em>code smell</em>.</p>\n\n<p>Depending on what part of your code that encounters problems, you should handle that problem differently: if the <code>new PDO()</code> line failed, then stop there but whatever you do: You don't <code>echo</code> the message to the user, as it is likely to contain information about your server.<br>\nLog the exception, and either throw up a new, more general <code>RuntimeException('Server says no')</code> exception.</p>\n\n<p>If the <code>PDOStatement</code> calls fail, you can be a tad more specific in the error message you send to the user, but again: you don't show them the <code>PDOException</code> message. That message is likely to reveal information on your <em>database or table</em>.<br>\nLog the message, and present the user with a polite message, saying that you couldn't find his/her <code>$_GET['pid']</code> product.</p>\n\n<p>Basically, if you're going to work with exceptions, then have a handler registered that logs the exceptions that are thrown and present the user with a generic error message, hiding your server layout as much as possible.<br>\nIt's easy to do, and increases the overall security of your application a bit.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-05-06T07:41:48.200", "Id": "49046", "ParentId": "49041", "Score": "3" } } ]
{ "AcceptedAnswerId": "49046", "CommentCount": "5", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-05-06T06:20:26.563", "Id": "49041", "Score": "1", "Tags": [ "php", "mysql", "pdo", "sql-injection" ], "Title": "How safe is my MySQL query?" }
49041
<p>I have a script that creates an active CSS on link, but I think there are a lot of <code>if</code> statements. Can someone help me refactor this?</p> <pre><code>var link = window.location.pathname; var currentPageName = window.location.href.match(/[^\/]+$/)[0]; var hl = $('#ih').val(); if (hl == 'True') { var currentPageName = 'WVD'; } if (window.location.href.indexOf("R") &gt; -1) { var currentPageName = window.location.href.match(/[^\/]+$/)[0]; } if (window.location.href.indexOf("C") &gt; -1) { var currentPageName = window.location.href.match(/[^\/]+$/)[0]; } if (location.pathname == "/") { var currentPageName = 'MD'; } $(".main-navigation ul li a").each(function () { var link = $(this).attr("href"); if (link.indexOf(currentPageName) &gt; -1) { $(this).addClass("active"); $(this).css("color", "white"); $(this).css("text-decoration", "bold"); } }); </code></pre>
[ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-05-06T08:20:15.230", "Id": "86138", "Score": "0", "body": "Can you explain how you came up with this? That way we can find other ways to do it. I'm pretty sure setting an `active` based on the url isn't this long." } ]
[ { "body": "<p>Please consider that using Javascript might not be the best solution. If you use something like PHP, passing a variable to the file generating the html setting which one is active is a cleaner solution.</p>\n\n<p>Anyway..</p>\n\n<p>First it seems that the following variable is unused and can be removed:</p>\n\n<pre><code>var link = window.location.pathname;\n</code></pre>\n\n<p>Then this line:</p>\n\n<pre><code>var currentPageName = window.location.href.match(/[^\\/]+$/)[0];\n</code></pre>\n\n<p>will trigger an error if the url is root (<a href=\"http://www.example.com/\" rel=\"nofollow\">http://www.example.com/</a>)\nand it's the same as in these ifs, which also can be combined to one:</p>\n\n<pre><code>if (window.location.href.indexOf(\"R\") &gt; -1) {\n var currentPageName = window.location.href.match(/[^\\/]+$/)[0];\n}\n\nif (window.location.href.indexOf(\"C\") &gt; -1) {\n var currentPageName = window.location.href.match(/[^\\/]+$/)[0];\n}\n</code></pre>\n\n<p>which means that one of them is redundant and can be removed. </p>\n\n<p>You can also remove <code>var</code> in all but the first <code>var currentPageName</code></p>\n\n<p>An easier way to add the active effect would be to use the <a href=\"http://api.jquery.com/attribute-contains-selector/\" rel=\"nofollow\">attribute contains selector</a> like this:</p>\n\n<pre><code>selector = '.main-navigation ul li a[href*=\"'+currentPageName+'\"]\"'\n$(selector).css({\n 'color': 'white',\n 'font-weight': 'bold',\n}).addClass('active');\n</code></pre>\n\n<p>This means that the complete code could look like this:</p>\n\n<pre><code>var match = window.location.href.match(/[^\\/]+$/);\nvar currentPageName = '';\n\nif (location.pathname == '/') {\n currentPageName = 'MD';\n} else if (match != null) {\n currentPageName = match[0];\n}\n\nvar hl = $('#ih').val();\n\nif (hl == 'True') {\n currentPageName = 'WVD';\n}\n\nselector = '.main-navigation ul li a[href*=\"'+currentPageName+'\"]\"'\n$(selector).css({\n 'color': 'white',\n 'font-weight': 'bold',\n}).addClass('active');\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-05-07T12:08:27.147", "Id": "86326", "Score": "0", "body": "Txnaks only this one I have to added to maake it work if (window.location.href.indexOf(\"R\") > -1) {\n var currentPageName = window.location.href.match(/[^\\/]+$/)[0];\n}\n\nif (window.location.href.indexOf(\"C\") > -1) {\n var currentPageName = window.location.href.match(/[^\\/]+$/)[0];\n}" } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-05-06T09:06:17.407", "Id": "49049", "ParentId": "49043", "Score": "1" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "1", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-05-06T07:01:45.050", "Id": "49043", "Score": "1", "Tags": [ "javascript", "jquery" ], "Title": "Script that creates an active CSS on link" }
49043
<p>I'm developing a win forms application in MVP pattern. In the application, there is a small module to show the branch offices (called points) where the attendance entering process has been completed. Those details should be shown in a data grid view. </p> <p>So I have a form (View), a presenter and a data service classes. For the simplicity I'm not using a "model class" for this as the only intended functionality is populating the grid view. </p> <p>Form <code>frmAttendancePoints</code> and <code>DataService</code> class have implemented <code>IAttendancePointsView</code> and <code>IDataService</code> interfaces respectively.</p> <p>My question: Is the way I'm populating the grid correct? If not could you please let me know a better solution.</p> <p><strong>View</strong></p> <pre><code>public partial class frmAttendancePoints : Form, IAttendancePointsView { private void frmEnterAttendance_Load(object sender, EventArgs e) { ShowAttendancePoints(sender, e); } public void LoadAttendacePointsGridWithData(DataTable dt) { dgAttendancePoints.DataSource = dt; } public event EventHandler ShowAttendancePoints; } </code></pre> <p><strong>Presenter</strong></p> <pre><code>class AttendancePointPresenter : BasePresenter { IAttendancePointsView _View; IDataService _ds; public AttendancePointPresenter(IAttendancePointsView View, IDataService ds) { _View = View; _ds = ds; WireUpViewEvents(); } private void WireUpViewEvents() { this._View.ShowAttendancePoints +=new EventHandler(_View_ShowAttendancePoints); } private void _View_ShowAttendancePoints(object sender, EventArgs e) { ShowAttendancePoints(); } private void ShowAttendancePoints() { var dt = _ds.GetAttendancePoints(); this._View.LoadAttendacePointsGridWithData(dt); } public void Show() { _View.ShowDialog(); } } </code></pre> <p><strong>DataService</strong></p> <pre><code>public class DataServie { public DataTable GetAttendancePoints() { string selectStatement = "SELECT PID, point_name + ', ' + point_add AS point, area, sm, atten_status FROM Point WHERE Status='Active'"; using (SqlConnection sqlConnection = new SqlConnection(db.GetConnectionString)) { using (SqlCommand sqlCommand = new SqlCommand(selectStatement, sqlConnection)) { using (SqlDataAdapter da = new SqlDataAdapter(sqlCommand)) { using (DataSet ds = new DataSet()) { using (DataTable dt = new DataTable()) { ds.Tables.Add(dt); sqlConnection.Open(); da.Fill(dt); return dt; } } } } } } } </code></pre> <p><strong>Programme</strong></p> <pre><code> IAttendancePointsView AttendancePointView = new frmAttendancePoints(); IDataService ds = new DataService(); var Presenter = new AttendancePointPresenter(AttendancePointView, ds); Presenter.Show(); </code></pre>
[]
[ { "body": "<blockquote>\n <p><em>For the simplicity I'm not using a \"model class\" for this [...]</em></p>\n</blockquote>\n\n<p>Then it's not <em>Model</em>-View-Presenter you have here.</p>\n\n<blockquote>\n<pre><code>var Presenter = new AttendancePointPresenter(AttendancePointView, ds);\n</code></pre>\n</blockquote>\n\n<p>I love it. What you've done here, is called <em>Dependency Injection</em> - more specifically, <em>constructor injection</em>. It's a technique that, when applied consistently, greatly contributes to making your code more <em>cohesive</em> and less <em>coupled</em>.</p>\n\n<p>I think <code>AttendancePointView</code> being a local variable, should be named <code>attendancePointView</code>, or simply <code>view</code> - same for <code>Presenter</code>, it's a local variable, should be <code>presenter</code>; and <code>ds</code> could simply be called <code>service</code>, so the presenter code would read:</p>\n\n<pre><code>var presenter = new AttendancePointPresenter(view, service);\npresenter.Show();\n</code></pre>\n\n<p>Which is awesome! Well done!</p>\n\n<p>The only thing is that in <code>Program.cs</code> it doesn't matter that the view and the service are injected as interfaces, since <code>Program</code> is <em>coupled</em> with <code>frmAttendancePoints</code> and <code>DataService</code> anyway. I'd write it like this:</p>\n\n<pre><code>var view = new frmAttendancePoints();\nvar service = new DataService();\n\nvar presenter = new AttendancePointPresenter(view, service);\npresenter.Show();\n</code></pre>\n\n<p>The presenter still receives its dependencies as abstractions, per its constructor.</p>\n\n<hr>\n\n<blockquote>\n <p><strong>View</strong></p>\n</blockquote>\n\n<p>You're declaring an event that <em>looks</em> more like a method:</p>\n\n<blockquote>\n<pre><code>public event EventHandler ShowAttendancePoints;\n</code></pre>\n</blockquote>\n\n<p>Seeing that it's raised when the form gets loaded...</p>\n\n<blockquote>\n<pre><code>private void frmEnterAttendance_Load(object sender, EventArgs e)\n{\n ShowAttendancePoints(sender, e);\n}\n</code></pre>\n</blockquote>\n\n<p>That event does nothing that <code>Load</code> doesn't do. I think you should have an <code>IView</code> interface that exposes that <code>Load</code> event, and everything a presenter needs to know about any view:</p>\n\n<pre><code>public interface IView\n{\n event EventHandler Load;\n void ShowDialog();\n void BindModel(IModel model);\n}\n</code></pre>\n\n<p>Now the form's code can look like this<sup>*</sup>:</p>\n\n<pre><code>public partial class frmAttendancePoints : Form, IView\n{\n public frmAttendancePoints()\n {\n InitializeComponents();\n }\n\n public void BindModel(IModel model)\n {\n dgAttendancePoints.DataSource = model;\n }\n}\n</code></pre>\n\n<hr>\n\n<blockquote>\n <p><strong>DataService</strong></p>\n</blockquote>\n\n<p>This class should spit out your <em>model</em>, not a boilerplate-level <code>DataTable</code>.</p>\n\n<p>One thing though, is that you can stack the <code>using</code> blocks for fewer levels of indentation:</p>\n\n<pre><code>using (SqlConnection sqlConnection = new SqlConnection(db.GetConnectionString))\nusing (SqlCommand sqlCommand = new SqlCommand(selectStatement, sqlConnection))\nusing (SqlDataAdapter da = new SqlDataAdapter(sqlCommand))\nusing (DataSet ds = new DataSet())\nusing (DataTable dt = new DataTable())\n{\n ds.Tables.Add(dt); \n sqlConnection.Open();\n da.Fill(dt);\n return dt;\n}\n</code></pre>\n\n<hr>\n\n<p><sub>*This might need a bit of work, I'm not sure a WinForms <code>DataGridView.DataSource</code> can be assigned just like that, but you get the idea ;)</sub></p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-05-07T05:18:16.953", "Id": "86288", "Score": "0", "body": "Thanks 4 ur quick rpl! \"That event does nothing that Load doesn't do...\" >> I'm under the impression that instead of having another event, I can utilize form's existing load event to start the process. So that I have to put a listener in the presenter to this load event and then the presenter can call BindModel() method in the form correct? \"This class should spit out your model, not a boilerplate-level DataTable.\" >> Yeah I have to find a way of doing this as it is supposed to return not a single model rather set of models (All branch offices)" } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-05-06T16:51:26.657", "Id": "49086", "ParentId": "49044", "Score": "7" } } ]
{ "AcceptedAnswerId": "49086", "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-05-06T07:27:33.483", "Id": "49044", "Score": "4", "Tags": [ "c#", ".net", "winforms", "mvp" ], "Title": "Populating a Data Grid View in MVP" }
49044
<blockquote> <p><strong>Problem Statement</strong></p> <p>A group of farmers has some elevation data, and we’re going to help them understand how rainfall flows over their farmland. </p> <p>We’ll represent the land as a two-dimensional array of altitudes and use the following model, based on the idea that water flows downhill: </p> <p>If a cell’s eight neighboring cells all have higher altitudes, we call this cell a basin; water collects in basin. </p> <p>Otherwise, water will flow to the neighboring cell with the lowest altitude. </p> <p>Cells that drain into the same sink – directly or indirectly – are said to be part of the same basin. </p> <p>A few examples are below:</p> <pre><code>----------------------------------------- Input: Output: 1 1 2 1 4 ( basin is 1, and size is 4) 1 1 7 3 6 9 </code></pre> </blockquote> <p>Looking for code review optimizations and best practices. Complexity - both time and space is O(n*m)</p> <pre><code>final class BasinData { private final int item; private final int count; public BasinData(int item, int count) { this.item = item; this.count = count; } public int getItem() { return item; } public int getCount() { return count; } @Override public int hashCode() { final int prime = 31; int result = 1; result = prime * result + count; result = prime * result + item; return result; } @Override public boolean equals(Object obj) { if (this == obj) return true; if (obj == null) return false; if (getClass() != obj.getClass()) return false; BasinData other = (BasinData) obj; if (count != other.count) return false; if (item != other.item) return false; return true; } } /** * References: * http://www.geeksforgeeks.org/flipkart-interview-set-2-for-sde-1/ * * Complexity: * O(n2) */ public final class Basin { private Basin() {} private static enum Direction { NW(-1, -1), N(0, -1), NE(-1, 1), E(0, 1), SE(1, 1), S(1, 0), SW(1, -1), W(-1, 0); int rowDelta; int colDelta; Direction(int rowDelta, int colDelta) { this.rowDelta = rowDelta; this.colDelta = colDelta; } public int getRowDelta() { return rowDelta; } public int getColDelta() { return colDelta; } } /** * Returns the minimum basin. * If more than a single minimum basin exists then returns any arbitrary basin. * * @param m : the input matrix * @return : returns the basin item and its size. */ public static BasinData getMaxBasin(int[][] m) { final List&lt;BasinCount&gt; basinCountList = new ArrayList&lt;BasinCount&gt;(); final boolean[][] visited = new boolean[m.length][m[0].length]; for (int i = 0; i &lt; m.length; i++) { for (int j = 0; j &lt; m[0].length; j++) { if (!visited[i][j]) { basinCountList.add(scan(m, visited, i, j, m[i][j], new BasinCount(0, true, m[i][j]))); } } } int maxCount = Integer.MIN_VALUE; int item = 0; for (BasinCount c : basinCountList) { if (c.basin) { if (c.count &gt; maxCount) { maxCount = c.count; item = c.item; } } } return new BasinData(item, maxCount); } private static class BasinCount { int count; boolean basin; int item; BasinCount(int count, boolean basin, int item) { this.count = count; this.basin = basin; this.item = item; } }; private static BasinCount scan(int[][] m, boolean[][] visited, int row, int col, int val, BasinCount baseCount) { if (row &lt; 0 || row == m.length || col &lt; 0 || col == m[0].length) return baseCount; if (m[row][col] &lt; val) { baseCount.basin = false; return baseCount; } if (visited[row][col]) { return baseCount; } if (m[row][col] &gt; val) return baseCount; visited[row][col] = true; baseCount.count++; for (Direction dir : Direction.values()) { scan(m, visited, row + dir.getRowDelta(), col + dir.getColDelta(), val, baseCount); } return baseCount; } } public class BasinTest { @Test public void testBlock() { int[][] m1 = { {1, 1, 2}, {1, 1, 3}, {4, 5, 6}, }; assertEquals(new BasinData(1, 4), Basin.getMaxBasin(m1)); } @Test public void testRandomlyShapedBasin() { int[][] m2 = { {1, 1, 1, 1}, {1, 1, 3, 1}, {4, 5, 6, 2} }; assertEquals(new BasinData(1, 7), Basin.getMaxBasin(m2)); } @Test public void testSingleElementBasin() { int[][] m3 = { {1, 1, 1, 1}, {1, 1, 3, 1}, {4, 5, 6, 0} }; assertEquals(new BasinData(0, 1), Basin.getMaxBasin(m3)); } } </code></pre>
[]
[ { "body": "<p>I find this a nice piece of code.</p>\n\n<p>Still I found 1 minor and 1 bigger issue.</p>\n\n<h2>Bigger issue :</h2>\n\n<p>You say in the javadoc that if more then 1 bassin is found the biggest must be returned.<br/>\nYou implement nice testing but this I don't find back in the testings.<br/>\nAll your testings have 1 lowest bassin.<br/>\nI should add this to the test :</p>\n\n<pre><code>@Test\npublic void testSingleElementBasin() {\n int[][] m4 = { {1, 0, 0, 1},\n {1, 0, 3, 1},\n {4, 5, 6, 0} };\n assertEquals(new BasinData(0, 3), Basin.getMaxBasin(m4));\n}\n</code></pre>\n\n<h2>Minor :</h2>\n\n<p>I should refactor the <code>public static BasinData getMaxBasin(int[][] m)</code></p>\n\n<pre><code>public static BasinData getMaxBasin(int[][] m) {\n final List&lt;BasinCount&gt; basinCountList = getBassinCountList(m);\n return getMaxBassin(basinCountList);\n}\n</code></pre>\n\n<p>You put the space because you know you are doing 2 different things, just do that extra step to refactor to 2 methods.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-05-06T09:17:19.383", "Id": "49051", "ParentId": "49048", "Score": "10" } }, { "body": "<h1>private final</h1>\n<p>I think this is not the first time I'm telling you this. The ints in your enum really should be <code>private final</code> (At least final!)</p>\n<pre><code>int rowDelta;\nint colDelta;\n</code></pre>\n<p>Consider the code: <code>Direction.S.rowDelta = 42; // OOPS!</code></p>\n<p>That said, I think your <code>Direction</code> enum is good enough to be <code>public</code>. This is not the first time I see you use this enum. You're not <em>copying</em> it each time I hope? If you need to use it in several projects, create a project where you keep the common classes and then add that project as a required project to your build path.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-05-06T12:12:20.703", "Id": "86153", "Score": "0", "body": "good catch, didn't saw that." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-05-06T18:13:33.037", "Id": "86219", "Score": "0", "body": "@Simon - you have very good points - and apologize for neglecting valuable comment ! Noted." } ], "meta_data": { "CommentCount": "2", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-05-06T11:36:23.850", "Id": "49065", "ParentId": "49048", "Score": "7" } }, { "body": "<p>There a few minor, and one bigger issue others haven't mentioned yet.</p>\n\n<h2>Simplifying <code>BasinData</code></h2>\n\n<p>I have a feeling that <code>BasinData</code> is something closely tied to <code>Basin</code>, it will never be extended, and it will never be part of a public API. As such, I think it's safe to simplify like this:</p>\n\n<ul>\n<li>Drop the <code>private</code> qualifier on fields, as <code>final</code> already protects them</li>\n<li>Drop the <code>getItem</code>, <code>getCount</code> accessors, you're not using them anyway</li>\n</ul>\n\n<p>More important, the <code>equals</code> method implementation is awkward and hard to read. This would be simpler and better:</p>\n\n<pre><code>@Override\npublic boolean equals(Object obj) {\n if (obj instanceof BasinData) {\n BasinData other = (BasinData) obj;\n return count == other.count &amp;&amp; item == other.item;\n }\n return false;\n}\n</code></pre>\n\n<h2>Improving <code>Direction</code></h2>\n\n<p>As others have pointed out, make the fields <code>final</code>. And as with <code>BasinData</code>, I think you can drop the accessors.</p>\n\n<h2>Improving the main algorithm</h2>\n\n<p>Most important of all, your algorithm is unnecessarily complicated and hard to read. How about something like this instead:</p>\n\n<ul>\n<li>Find the minimum value in the elevation matrix and its coordinates</li>\n<li>Use a recursive flood-fill method to find its size:\n<ul>\n<li>Check if the current position is valid (inside the matrix), otherwise return 0</li>\n<li>Check if the current position has the same elevation value, otherwise return 0</li>\n<li>Return 1 + the result of recursively calling the method for the positions up, down, left, right</li>\n</ul></li>\n</ul>\n\n<p>Here's an implementation of that, shorter and simpler:</p>\n\n<pre><code>// A simple \"struct\", to hold a group of values describing a basin:\n// - the i, j coordinates in the matrix\n// - the elevation value, storing here for convenience\nclass BasinInfo {\n final int i;\n final int j;\n final int elevation;\n\n BasinInfo(int i, int j, int elevation) {\n this.i = i;\n this.j = j;\n this.elevation = elevation;\n }\n}\n\nclass BasinFinder {\n // A value to use as marker in the flood-fill technique\n // used in the `getBasinSize` method.\n // The value should be something unique, that cannot be in the input matrix.\n private static final int FLOODFILL_MARKER = Integer.MIN_VALUE;\n\n // Find an arbitrary point in the matrix that has the minimum\n // elevation value and return its coordinates and the value\n // in a `BasinInfo` instance.\n private BasinInfo findMinElevation(int[][] matrix) {\n int minI = 0;\n int minJ = 0;\n int minValue = matrix[0][0];\n\n for (int i = 0; i &lt; matrix.length; ++i) {\n for (int j = 0; j &lt; matrix[i].length; ++j) {\n if (matrix[i][j] &lt; minValue) {\n minValue = matrix[i][j];\n minI = i;\n minJ = j;\n }\n }\n }\n return new BasinInfo(minI, minJ, minValue);\n }\n\n // A utility method to deep-clone a matrix,\n // so we don't modify the original matrix with flood-fill\n private int[][] cloneMatrix(int[][] matrix) {\n int[][] newMatrix = new int[matrix.length][];\n for (int i = 0; i &lt; matrix.length; ++i) {\n newMatrix[i] = matrix[i].clone();\n }\n return newMatrix;\n }\n\n // The flood-fill method, exploring the matrix from some starting point,\n // marking visited positions, and spreading up to positions with matching value\n private int getBasinSize(int[][] matrix, int i, int j, int value) {\n if (isValidPosition(matrix, i, j)) {\n if (matrix[i][j] == value) {\n matrix[i][j] = FLOODFILL_MARKER;\n return 1\n + getBasinSize(matrix, i + 1, j, value)\n + getBasinSize(matrix, i - 1, j, value)\n + getBasinSize(matrix, i, j + 1, value)\n + getBasinSize(matrix, i, j - 1, value)\n ;\n }\n }\n return 0;\n }\n\n private boolean isValidPosition(int[][] matrix, int i, int j) {\n return i &gt;= 0 &amp;&amp; j &gt;= 0 &amp;&amp; i &lt; matrix.length &amp;&amp; j &lt; matrix[i].length;\n }\n\n private BasinData getBasinData(int[][] matrix, BasinInfo basinInfo) {\n int size = getBasinSize(cloneMatrix(matrix), basinInfo.i, basinInfo.j, basinInfo.elevation);\n return new BasinData(basinInfo.elevation, size);\n } \n\n // The main method, performing the task in 2 phases:\n // 1. Find an arbitrary point with minimum elevation\n // 2. Measure the extent of the basin and return as a `BasinData` instance\n public BasinData findBasin(int[][] matrix) {\n BasinInfo basinInfo = findMinElevation(matrix);\n return getBasinData(matrix, basinInfo);\n }\n}\n</code></pre>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-05-11T18:45:04.220", "Id": "49477", "ParentId": "49048", "Score": "3" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-05-06T08:53:56.707", "Id": "49048", "Score": "10", "Tags": [ "java", "algorithm", "matrix", "backtracking" ], "Title": "Find biggest basin" }
49048
<p>In this function I'm parsing the page of the item in the online shop. Some items lack the picture, some lack price etc, so there are few <code>if-else</code> checks.</p> <p>My questions are:</p> <ol> <li>How to get rid of these ugly <code>if-else</code> checks?</li> <li>How I can "pythonize" my code further?</li> <li><p>Is it correct? I.e when I manipulate the variable value using previously assigned value:</p> <pre><code>name = soup.find('span',{"class":"project_name"}) if name is not None: name = re.sub(r'[«,»]','', name.text) </code></pre></li> </ol> <p>Below is my full code:</p> <pre><code>def grab_properties(url,html): soup = BeautifulSoup(html) link = soup.find('iframe', {"src":"e.smth.com"}) if link is not None: link = link.get("src") id = re.match(".*\[(\w+)\].*", link).group(1) if id is not None: if id not in ids: name = soup.find('span',{"class":"project_name"}) if name is not None: name = re.sub(r'[«,»]','', name.text) if (soup.find('img',{"id":"item0image"}) is not None): img_url = soup.find('img',{"id":"item0image"}).get('src') price = soup.find('span',{"class":"project_price"}) if price is not None: price = price.text price = re.sub(u'[руб,\., ]','', price) else: price =u"Call us!" return [id.encode('utf8'), name.encode('utf8'), url.encode('utf8'), img_url.encode('utf8'), price.encode('utf8')] </code></pre>
[ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-05-06T10:14:59.057", "Id": "86146", "Score": "1", "body": "Welcome to CodeReview.SE! I think we are missing the definition for (at least) `ids`. Am I right ?" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-05-06T12:23:45.023", "Id": "86155", "Score": "0", "body": "Yes, this is a global variable to control which items have been already added to the output file. I only pasted code for the function to make it easier to follow the logic." } ]
[ { "body": "<p>You cannot get rid of those if-else checks, but you can get rid of the nesting. For example:</p>\n\n<pre><code>if foo:\n if bar:\n return foo + bar\n</code></pre>\n\n<p>could be flattened to</p>\n\n<pre><code>if not foo:\n return None\nif not bar:\n return None\nreturn foo + bar\n</code></pre>\n\n<p>While this is is in fact longer, such code tends to be easier to read.</p>\n\n<p>If we apply that to your code (and fix some style issues like putting a space after <em>each</em> comma), then we end up with:</p>\n\n<pre><code>def grab_properties(url, html):\n soup = BeautifulSoup(html)\n\n link = soup.find('iframe', {\"src\": \"e.smth.com\"})\n if link is None:\n return None\n link = link.get(\"src\")\n\n id = re.match(\".*\\[(\\w+)\\].*\", link).group(1)\n if (id is None) or (id in ids):\n return None\n\n name = soup.find('span', {\"class\": \"project_name\"})\n if name is None:\n return None\n name = re.sub(r'[«,»]', '', name.text)\n\n image_element = soup.find('img', {\"id\": \"item0image\"})\n if image_element is None:\n return None\n img_url = image_element.get('src')\n\n price = soup.find('span', {\"class\": \"project_price\"})\n if price is None:\n price = u\"Call us!\"\n else\n price = re.sub(u'[руб,\\., ]', '', price.text)\n\n return [attr.encode('utf8') for atr in (id, name, url, img_url, price)]\n</code></pre>\n\n<p>Notice that I created the <code>image_element</code> variable to avoid searching for the same element multiple times, that I used a list comprehension to encode various strings to UTF-8, and that I used empty lines to separate the code for unrelated attributes, thus making the code easier to understand. I also swapped the <code>if price is not None</code> condition around to avoid a confusing negation.</p>\n\n<p>We should now talk about regular expressions (see also the <a href=\"https://docs.python.org/2/library/re.html\"><code>re</code> library documentation</a>). The <code>[…]</code> is a <em>character class</em>. It matches any of the contained characters, so <code>[abc]</code> will match either <em>a</em> or <em>b</em> or <em>c</em>, but not the whole string <code>abc</code>. The comma is not special inside a character class, so <code>[«,»]</code> will match left or right guillemets, or a comma. To match just the angled quotation marks, use <code>[«»]</code>. Similarly, <code>[руб,\\., ]</code> will match either <em>р</em> or <em>у</em> or <em>б</em> or a comma or a period or a space. Note that inside a character class, the period is not a metacharacter and does not have to be escaped. So that charclass would be equivalent to <code>[р,у б.]</code> (the order of characters does not matter). If you want to match alternative patterns, use the <code>|</code> regex operator: <code>руб|[. ]</code>, which matches either the substring <code>руб</code> or a period or a space.</p>\n\n<p>You could also consider precompiling your regular expressions, which might improve performance if you call your function very often:</p>\n\n<pre><code>RE_GUILLEMETS = re.compile('[«»]')\n\ndef ...:\n ...\n name = RE_GUILLEMETS.sub('', name.text)\n</code></pre>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-05-06T10:59:11.710", "Id": "49059", "ParentId": "49052", "Score": "5" } } ]
{ "AcceptedAnswerId": "49059", "CommentCount": "2", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-05-06T09:47:05.880", "Id": "49052", "Score": "5", "Tags": [ "python", "beautifulsoup" ], "Title": "Parsing item page for an online shop" }
49052
<p>As part of a simple (naive) internationalization attempt in Go, I am trying to come up with a number formatting routine with customizable decimal and thousands separator.</p> <p>Is this approach alright? </p> <pre><code>var decLen = 1 var decSep = "." var thouLen = 1 var thouSep = "," func numberFormat(floatVal float64, precision int) string { intPart := int(math.Floor(math.Abs(floatVal))) var decimalPart int // estimate length of str var dec int if floatVal == 0 { dec = 1 } else { dec = (int)(math.Log10(math.Abs(floatVal))) + 1 } thou := dec / 3 // dec / 3 are thousands groups size := dec + (thou * thouLen) if precision &gt; 0 { // dec sep + precision size += decLen + precision // (floatVal - intPart) * 10 ^ precision decimalPartFloat := (math.Abs(floatVal) - math.Floor(math.Abs(floatVal))) * math.Pow(10.0, float64(precision)) decimalPart = int(math.Floor(decimalPartFloat + 0.5)) } // negative if floatVal &lt; 0 { size += 1 } thouGroups := make([]int, 0, thou+1) if intPart == 0 { thouGroups = append(thouGroups, 0) } else { i := intPart for i != 0 { thouGroups = append(thouGroups, i%1000) i = i / 1000 } } b := make([]byte, 0, size) if floatVal &lt; 0 { b = append(b, '-') } for i := len(thouGroups) - 1; i &gt;= 0; i-- { b = append(b, []byte(strconv.Itoa(thouGroups[i]))...) if i != 0 { b = append(b, []byte(thouSep)...) } } if precision &gt; 0 { b = append(b, []byte(decSep)...) b = append(b, []byte(strconv.Itoa(decimalPart))...) var decimalLen int if decimalPart != 0 { decimalLen = (int)(math.Log10(float64(decimalPart))) + 1 } else { decimalLen = 1 } if decimalLen &lt; precision { // pad zeros b = append(b, []byte(strings.Repeat("0", precision-decimalLen))...) } } // remove NUL bytes return strings.Trim(string(b), "\x00") } </code></pre> <p><a href="http://play.golang.org/p/_sjiziI0DD" rel="nofollow">Here is also a link to the playground</a></p>
[]
[ { "body": "<p>Your approach is ok, but I think it could make better use of some of the existing library functionality. Also, this looks like something that should be a user-facing function, so let's rename it to <code>NumberFormat</code> (since anything starting with a lower case letter is not exported from a package in Go).</p>\n\n<p>However, let's back up for a little bit. Code to do number to string conversions can have quite a number of corner cases, and can be quite difficult to get correct in all those cases. For a function like this, I think using Test-Driven Development (TDD) would be ideal. Go's <code>testing</code> package makes this fairly pain-free. First thing would be to define a number of corner cases to test. Here's some I can think of:</p>\n\n<ul>\n<li>The number 0</li>\n<li>A short number, with less than 3 digits before the decimal point</li>\n<li>A number with only a fractional part specified</li>\n<li>A negative number</li>\n<li>An \"overspecified\" format (that is, more decimal places specified than decimal places)</li>\n<li>A number with no fractional part (integers)</li>\n</ul>\n\n<p>This is just a quick list off the top of my head. Let's turn them into test cases:</p>\n\n<pre><code>package numformat\n\nimport (\n \"testing\"\n)\n\nfunc TestNegPrecision(test *testing.T) {\n s := NumberFormat(123456.67895414134, -1)\n if s != \"123,456\" {\n test.Fatalf(\"Number format failed on negative precision test\\n\")\n }\n}\n\nfunc TestShort(test *testing.T) {\n s := NumberFormat(34.33384, 1)\n expected := \"34.3\"\n if s != expected {\n test.Fatalf(\"Number format failed short test: Expected: %s, \" +\n \"Actual: %s\\n\", expected, s)\n }\n}\n\nfunc TestOverSpecified(test *testing.T) {\n s := NumberFormat(9432.839, 5)\n expected := \"9,432.83900\"\n if s != expected {\n test.Fatalf(\"Number format failed over specified test: Expected %s, \" +\n \"Actual: %s\\n\", expected, s)\n }\n}\n\nfunc TestZero(test *testing.T) {\n s := NumberFormat(0, 0)\n expected := \"0\"\n if s != expected {\n test.Fatalf(\"Number format failed short test: Expected: %s, \" +\n \"Actual: %s\\n\", expected, s)\n }\n}\n\nfunc TestNegative(test *testing.T) {\n s := NumberFormat(-348932.34989, 4)\n expected := \"-348,932.3499\"\n if s != expected {\n test.Fatalf(\"Number format failed short test: Expected: %s, \" +\n \"Actual: %s\\n\", expected, s)\n }\n}\n\nfunc TestOnlyDecimal(test *testing.T) {\n s := NumberFormat(.349343, 3)\n expected := \"0.349\"\n if s != expected {\n test.Fatalf(\"Number format failed short test: Expected: %s, \" +\n \"Actual: %s\\n\", expected, s)\n }\n}\n</code></pre>\n\n<p>Running these with <code>go test</code> and your implementation passes, so that's good.</p>\n\n<p>Now, to look at the implementation. The first thing is that the <code>strconv</code> package has a <code>FormatFloat</code> function that could do a chunk of the work here for you. Likewise, <code>strings.SplitString</code> is another function that can take care of some of the work. Here's a different implementation that uses these, as well as slices to do the work instead:</p>\n\n<pre><code>var thousand_sep = byte(',')\nvar dec_sep = byte('.')\n\n// Parses the given float64 into a string, using thousand_sep to separate\n// each block of thousands before the decimal point character.\nfunc NumberFormat(val float64, precision int) string {\n // Parse the float as a string, with no exponent, and keeping precision\n // number of decimal places. Note that the precision passed in to FormatFloat\n // must be a positive number.\n use_precision := precision\n if precision &lt; 1 { use_precision = 1 }\n as_string := strconv.FormatFloat(val, 'f', use_precision, 64)\n // Split the string at the decimal point separator.\n separated := strings.Split(as_string, \".\")\n before_decimal := separated[0]\n // Our final string will need a total space of the original parsed string\n // plus space for an additional separator character every 3rd character\n // before the decimal point.\n with_separator := make([]byte, 0, len(as_string) + (len(before_decimal) / 3))\n\n // Deal with a (possible) negative sign:\n if before_decimal[0] == '-' {\n with_separator = append(with_separator, '-')\n before_decimal = before_decimal[1:]\n }\n\n // Drain the initial characters that are \"left over\" after dividing the length\n // by 3. For example, if we had \"12345\", this would drain \"12\" from the string\n // append the separator character, and ensure we're left with something\n // that is exactly divisible by 3.\n initial := len(before_decimal) % 3\n if initial &gt; 0 {\n with_separator = append(with_separator, before_decimal[0 : initial]...)\n before_decimal = before_decimal[initial:]\n if len(before_decimal) &gt;= 3 {\n with_separator = append(with_separator, thousand_sep)\n }\n }\n\n // For each chunk of 3, append it and add a thousands separator,\n // slicing off the chunks of 3 as we go.\n for len(before_decimal) &gt;= 3 {\n with_separator = append(with_separator, before_decimal[0 : 3]...)\n before_decimal = before_decimal[3:]\n if len(before_decimal) &gt;= 3 {\n with_separator = append(with_separator, thousand_sep)\n }\n }\n // Append everything after the '.', but only if we have positive precision.\n if precision &gt; 0 {\n with_separator = append(with_separator, dec_sep)\n with_separator = append(with_separator, separated[1]...)\n }\n return string(with_separator)\n}\n</code></pre>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-05-15T02:11:20.983", "Id": "49788", "ParentId": "49055", "Score": "3" } } ]
{ "AcceptedAnswerId": "49788", "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-05-06T10:16:00.660", "Id": "49055", "Score": "4", "Tags": [ "formatting", "go", "floating-point", "i18n" ], "Title": "Number formatting" }
49055
<p>I'm looking to change a single jQuery plugin option when the window hits certain breakpoints.</p> <p>The code below works, however I'm conscious of repeating code and feel there is a more elegant way writing code for examples like this.</p> <p>My initial thoughts would be to store the first call in a variable.</p> <pre><code>$(window).smartresize(function () { if ( config.wWidth &gt;= 768 &amp;&amp; config.wWidth &lt;= 1024 ) { $('#va-accordion').vaccordion({ accordionW : config.wWidth, accordionH : config.wHeight, visibleSlices : 2, expandedHeight : 600, expandedWidth : 1000, contentAnimSpeed : 200 }); } else if ( config.wWidth &lt; 768 ) { $('#va-accordion').vaccordion({ accordionW : config.wWidth, accordionH : config.wHeight, visibleSlices : 1, expandedHeight : 600, expandedWidth : 1000, contentAnimSpeed : 200 }); } else { $('#va-accordion').vaccordion({ accordionW : config.wWidth, accordionH : config.wHeight, visibleSlices : 3, expandedHeight : 600, expandedWidth : 1000, contentAnimSpeed : 200 }); } }); $(window).trigger("smartresize"); </code></pre>
[]
[ { "body": "<p>You might extract your code to a function to remove the repeated code, passing the values ​​that change as parameters:</p>\n\n<pre><code>$(window).smartresize(function () {\n\n if (config.wWidth &gt;= 768 &amp;&amp; config.wWidth &lt;= 1024) {\n createVaccordion(config, 2);\n\n } else if (config.wWidth &lt; 768) {\n createVaccordion(config, 1);\n\n } else {\n createVaccordion(config, 3);\n }\n\n function createVaccordion(config, slices) {\n $('#va-accordion').vaccordion({\n accordionW: config.wWidth,\n accordionH: config.wHeight,\n visibleSlices: slices,\n expandedHeight: 600,\n expandedWidth: 1000,\n contentAnimSpeed: 200\n });\n }\n});\n\n$(window).trigger(\"smartresize\");\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-05-07T08:19:50.290", "Id": "86297", "Score": "0", "body": "This is a method I hadn't considered, thank you. I've gone with an alternative solution, but marked this up." } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-05-06T17:11:19.073", "Id": "49088", "ParentId": "49057", "Score": "3" } }, { "body": "<pre><code>$(window).smartresize(function () {\n\n var chosenSettings;\n\n // We could map out the defaults first.\n var defaults = {\n accordionW: config.wWidth,\n accordionH: config.wHeight,\n visibleSlices: 0,\n expandedHeight: 600,\n expandedWidth: 1000,\n contentAnimSpeed: 200\n };\n\n // Then, depending on the conditions, create an object of the modifications\n // This way, it's easier to add in more differences.\n if (config.wWidth &gt;= 768 &amp;&amp; config.wWidth &lt;= 1024) {\n chosenSettings = {visibleSlices: 2};\n } else if (config.wWidth &lt; 768) {\n chosenSettings = {visibleSlices: 1};\n } else {\n chosenSettings = {visibleSlices: 3};\n }\n\n // Then use extend to create an object with the chosen settings\n var settings = $.extend({}, defaults, chosenSettings);\n $('#va-accordion').vaccordion(settings); \n\n// Assuming smartresize returns the same object, we can chain trigger.\n}).trigger('smartresize');\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-05-07T08:18:46.347", "Id": "86296", "Score": "0", "body": "This is exactly what I was after... it will be a great help for my future work as well, thank you" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-05-07T14:33:55.330", "Id": "86345", "Score": "0", "body": "That's a great solution Joseph! Let me suggest moving the if block to a method that receives config and returns the chosenSettings. I think that will be even better! :)" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-05-07T16:02:39.053", "Id": "86377", "Score": "0", "body": "@Juliano I didn't do that because I assumed this function gets called on resize, and a function inside this would be bad for performance as it is created everytime it is called." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-05-07T17:17:03.203", "Id": "86389", "Score": "0", "body": "I didn't think about it, excellent point!" } ], "meta_data": { "CommentCount": "4", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-05-06T18:16:51.067", "Id": "49094", "ParentId": "49057", "Score": "4" } } ]
{ "AcceptedAnswerId": "49094", "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-05-06T10:45:32.890", "Id": "49057", "Score": "3", "Tags": [ "javascript", "jquery", "plugin" ], "Title": "Changing a single jQuery plugin option on window resize" }
49057
<p>Now FizzBuzz itself isn't a big challenge but I agree that it can be a good tool to see if someone can code or not. I wanted to practice my LINQ a little bit so here's my single line FizzBuzz solution.</p> <pre><code>Enumerable.Range(1,100).Select( n =&gt; (n % 15 == 0) ? "FizzBuzz" : (n % 3 == 0) ? "Fizz" : (n % 5 == 0) ? "Buzz" : n.ToString()) .ToList() .ForEach(Console.WriteLine); </code></pre>
[ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-05-06T12:14:59.637", "Id": "86154", "Score": "14", "body": "Would you care to ask a question? :)" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-05-06T14:21:13.307", "Id": "86178", "Score": "3", "body": "Apart from the alignment, this is exactly how I'd do it." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-05-07T08:47:38.917", "Id": "86300", "Score": "1", "body": "This question (and answers) seem more suitable for CodeGolf SE's as popularity contest question" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-05-29T10:08:48.327", "Id": "477098", "Score": "1", "body": "Linq doesn't really add anything. Also, note, that ForEach isn't linq.\n\nUsing switch expressions, this one liner does fizzbuzz:\n\n foreach (var n in Enumerable.Range(1, 100)) Console.WriteLine((n % 3 == 0, n % 5 == 0) switch {(true, true) => \"fizzbuzz\", (true, _ ) => \"fizz\", ( _, true) => \"buzz\", _ => $\"{n}\"});" } ]
[ { "body": "<p>Overall, I like this. It is concise, and neat, and all. My only beef is the nested ternaries.</p>\n<p>In general, ternary operator precedence is complicated by the lack of blocks.... The need for the parenthesis on the modulo precedence makes the conditions clear ( <code>(n % 15 == 0)</code> ) and the actual indenting you have, makes the logic a little clearer, but precedence is not that simple, and I have seen bugs where subtle precedence problems have caused the wrong execution-path through the nested ternaries....</p>\n<p>.... bottom line, is for simple statements, ternaries are great, but the readability is compromised when there are multi-levels of ternaries. Nice for small things, ugly for big.</p>\n<p>I would have preferred if you made the coditionals more obvious ... by extracting to a function maybe... but that would ruin your 1-liner.....</p>\n<p>How about ... (Shown in <a href=\"http://ideone.com/aEqDDc\" rel=\"noreferrer\">this ideone here</a>):</p>\n<pre><code>Enumerable.Range(1,100).Select(\n n =&gt; \n (n % 15 == 0) ? &quot;FizzBuzz&quot; : \n (\n (n % 3 == 0) ? &quot;Fizz&quot; :\n (\n (n % 5 == 0) ? &quot;Buzz&quot; : n.ToString())\n )\n )\n .ToList()\n .ForEach(Console.WriteLine);\n</code></pre>\n<hr />\n<h2>EDIT: The above answer is not as good as I wanted it to be.....</h2>\n<p>The exact problem with ternary precedence is that it is right-associative. This makes the logic potentially buggy, and hard to understand.....</p>\n<p>Consider the ternaries:</p>\n<pre><code>expa = boola ? expc : expd;\nexpb = boolb ? expe : expf;\n\nresult = boolc ? expa : expb;\n</code></pre>\n<p>You can modify this to be:</p>\n<pre><code>expa = boola ? expc : expd;\n\nresult = boolc ? expa : boolb ? expe : expf;\n</code></pre>\n<p>Or, rewriting it in 'your' style, as:</p>\n<pre><code>expa = boola ? expc : expd;\n\nresult = boolc ? expa :\n boolb ? expe :\n expf;\n</code></pre>\n<p>But, you cannot 'inline' expa in the above as easily:</p>\n<pre><code>expb = boolb ? expe : expf;\n\nresult = boolc ? (boola ? expc : expd) : expb;\n</code></pre>\n<p>You need the parenthesis.</p>\n<p>Inlining ternaries is just plain ugly.</p>\n<hr />\n<h2>Better solution</h2>\n<p>I regret suggesting to use the parenthesis to block the code in a more readable format. There is no more readable format, other than to extract the function, which is the 'right' thing to do:</p>\n<pre><code> static private string FizzBuzz(int value)\n {\n if (value % 15 == 0)\n {\n return &quot;FizzBuzz&quot;;\n }\n if (value % 3 == 0)\n {\n return &quot;Fizz&quot;;\n }\n if (value % 5 == 0)\n {\n return &quot;Buzz&quot;;\n }\n return value.ToString();\n }\n\n\n\n public static void Main()\n {\n foreach(var val in Enumerable.Range(1, 100).Select(n =&gt; FizzBuzz(n)))\n Console.WriteLine(val);\n }\n</code></pre>\n<p>Note, I have also undone the slow, and unnecessary conversion of the Enumerable to the <code>ToList().ForEach()</code> operation. Converting it to the list before re-converting it to an Enumeration is a waste of effort.</p>\n<p>Bottom line, is that the 1-liner is not the best, or most readable format.</p>\n<p>I have put this in <a href=\"http://ideone.com/fvjIL0\" rel=\"noreferrer\">an ideone, to show it working</a>.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-05-06T13:33:36.447", "Id": "86172", "Score": "0", "body": "I'm not sure that helps much. At first glance it looks like the block runs if `n` *is* divisible by 15. (And shouldn't those be parens, not braces?)" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-05-06T21:54:40.490", "Id": "86239", "Score": "1", "body": "If you're going to do this, at least get the \"Fizz\" and \"Buzz\" right, and ditch the 15 in favor of concatenation. You only need an explicit 15 condition in a ternary where you can't concatenate." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-05-06T22:01:09.380", "Id": "86241", "Score": "0", "body": "@Magus - the concatenation would require a more complicated function... if you have an alternate solution, you should put it together in an answer (with reasoning as to why it improves the original code)." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-05-06T22:12:16.330", "Id": "86243", "Score": "0", "body": "As I've said above, the OP does it just fine. I'm not allergic to ternaries. I just don't quite agree that three hardcoded strings are better than two." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-05-06T22:23:29.457", "Id": "86246", "Score": "1", "body": "@Magus: Three hard-coded strings ends up *simpler*, and in that respect better, than two. It's easier to see what's going on than if you concatenate." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-05-07T00:30:07.060", "Id": "86261", "Score": "0", "body": "I find the ternary if from the original solution way more readable than your first attempt, although creating a separate function and writing the ifs is certainly the most readable. But in any non brain-dead language (sorry PHP you're out.. again) the ternary operator is imo rather intuitive." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-05-07T00:32:03.780", "Id": "86262", "Score": "3", "body": "@Voo the ternary is intuitive, and I love it, but *not for nesting if blocks* . This usage is too nested. A single ternary in each statements is all I am saying." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-05-07T07:40:28.463", "Id": "86294", "Score": "0", "body": "_Minor point_ but `List<T> inherits `IEnumerable<T>`. There is next to zero cost to use a `List<T>` in a `foreach`. HAving said that, `.ToList().Foreach()` is one of my biggest pet hates." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2016-04-22T23:40:38.623", "Id": "236240", "Score": "0", "body": "I like the ternary fine. But I've taken the time to learn how to read multiple nested ternaries. As long as the whitespace is done well it's fine by me. Others who spend all their time with boring if else will always complain when they see a ternary." } ], "meta_data": { "CommentCount": "9", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-05-06T12:26:34.087", "Id": "49066", "ParentId": "49058", "Score": "24" } }, { "body": "<p>Your code is nice, relatively simple and a good attemp at LINQ - I've written very similar code before. However I have the following critiques:</p>\n\n<ul>\n<li>A list is created unnecessarily, eagerly loading the data. LINQ loves being deferred and streamed when possible - what happens if we never execute the code? What happens if we decide that we only need the first 50 results?</li>\n<li>The foreach method, while I like it, is considered poor code - LINQ shouldn't rely upon side effects, and the foreach keyword is roughly the same length.</li>\n<li>You're not using the LINQ paradigm - merely using the Enumerable and Select as a loop construct. This is why you have to use the Ternary if. Where is the Query? What are your data collections? And most importantly is it declarative - are you asking <em>what</em> you want rather than telling the computer <em>how</em> to get there?</li>\n</ul>\n\n<p>Keeping within the '1LOC' idea:</p>\n\n<pre><code>foreach (var result in from number in Enumerable.Range(1, 100)\n let match = (from condition in new[] \n { \n new {Key =15, Format= \"FizzBuzz\" },\n new {Key =5, Format= \"Buzz\" },\n new {Key =3, Format= \"Fizz\" },\n new {Key =1, Format= \"{0}\" }\n }\n where number % condition.Key == 0\n select condition.Format).First()\n select string.Format(match, number))\n Console.WriteLine(result);\nConsole.ReadLine();\n</code></pre>\n\n<h2>Why This Way?</h2>\n\n<p>I spent a fair bit of time coming up with this particular example - though its possible improvements could be made. Since this question and this answer have some interest, I'd explain why I chose this format. </p>\n\n<p>My decision is simple: I want to use the LINQ Paradigm as much as possible, but want to stick within the artificial 1LOC requirement (otherwise I'm not really answering the question).</p>\n\n<p>Let's break it down into steps:</p>\n\n<pre><code>Get a collection (0 to infinity) of values.\nGet from a collection (0 to infinity) of 'conditions' \n the format of the first condition where 'key' matches the value\nSelect the value formatted by the format.\n</code></pre>\n\n<p>Now the cool thing is that this basic structure is very generic. For example the collection of values can be XML, or maybe an infinite IEnumerable. The conditions could be a simple array, or a remotely hosted database. That's not forgetting that 'value' and 'condition' can be defined in many different ways - e.g. value could be an exception log and condition could be a function that formats or raises alerts based said exception. </p>\n\n<pre><code>foreach (var result in from log in Log.LastRun() //gets log entries\n let match = (from logHandler in Log Handling.Current //finds appropriate handlers\n where log.Type == logHandler.Key\n select logHandler.Handler).First()\n select match(log).Result) //handle log - e.g. send SMS, alert user, create statistics, do nothing\n Console.WriteLine(result); //E.g. 'Successfully SMS'd Error to User'\nConsole.ReadLine();\n</code></pre>\n\n<p>Of course, returning to our simple number variant, LINQ can be useful for making our problem easier to modify. For example, I require a version of FizzBuzz that prints \"Douglas Adams\" on mod 42 == 0, and will give me values 1 through to Infinity - and will ignore all values between 600 and 700.</p>\n\n<pre><code>foreach (var result in (from number in Counter(start: 1)\n where number &lt; 600 || number &gt; 700\n let match = from condition in new[] \n { \n new {Key =42, Format= \"Douglas Adams\" },\n new {Key =15, Format= \"FizzBuzz\" },\n new {Key =5, Format= \"Buzz\" },\n new {Key =3, Format= \"Fizz\" },\n new {Key =1, Format= \"{0}\" }\n }\n where number % condition.Key == 0\n select condition.Format).First()\n select string.Format(match, number))\n Console.WriteLine(result);\nConsole.ReadLine();\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-05-06T14:46:10.563", "Id": "86186", "Score": "0", "body": "Thanks, you're revised solution is quite good - keeping the imperative code separate from the declarative LINQ. +1. I tried to keep it all declarative (at least, to my ability) due to the question for learning purposes, even though it's not great production code." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-05-06T15:06:59.467", "Id": "86195", "Score": "0", "body": "Other than the fact that `.ForEach()` is not LINQ (it's an instance method on `List<T>`), I agree completely." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-05-06T15:24:36.360", "Id": "86199", "Score": "3", "body": "This solution seems, to me, to be harder to read than the original." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-05-06T16:05:04.960", "Id": "86204", "Score": "4", "body": "I like it, although to me, it would be cleaner to use an anonymous type instead of a tuple, so I would for example replace `Tuple.Create (15, \"FizzBuzz\" )` with `new { number = 15, text = \"FizzBuzz\" }`." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-05-06T21:29:25.087", "Id": "86235", "Score": "0", "body": "Does C# know better than to create a new array of tuples for each item in the range? Cause if not, this seems like it would create quite a bit of unnecessary garbage." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-05-06T21:57:31.497", "Id": "86240", "Score": "0", "body": "@cHao: Probably irrelevant tbh. Not something you should be thinking of when writing code in c#." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-05-06T22:18:59.093", "Id": "86244", "Score": "0", "body": "@Magus: It shouldn't be a *primary* concern, that much i agree with. If you need to make an object, make an object. But it should at least enter your mind...even if you then shoo it away in the interest of simplicity, expressiveness, or simply getting stuff done." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-05-06T22:32:54.600", "Id": "86247", "Score": "0", "body": "@cHao: I'm mostly saying that with regard to the context. This is a one-liner solving a trivial problem, so even considering efficiency is useless. Generally speaking though, it still isn't a problem. The GC is good at it's job. No, you shouldn't mindlessly ignore efficiency, but until there's a serious problem, it isn't *really* more important than solving the problem in front of you." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-05-07T00:11:58.723", "Id": "86259", "Score": "0", "body": "@Magus: I tend to think of answers here not only as applying to the problem at hand, but also as general advice on good practices. For this example, you're right, it doesn't matter a whole lot. In general, though, you're better off not creating tons of objects for the heck of it." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-05-07T06:11:16.123", "Id": "86292", "Score": "0", "body": "@cHao this is an example of LINQ works, rather than a production example. For example, replace the condition array with a DB sitting on a remote server. Yes, in this particular example over instantiating is bad (I write a lot of C# in Unity3d where the GC is terrible, so am well aware of this) - but it's a hack to fit within the 1LOC requirement. If you can improve it, feel free ;)" } ], "meta_data": { "CommentCount": "10", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-05-06T14:27:31.817", "Id": "49077", "ParentId": "49058", "Score": "15" } }, { "body": "<p>Here's a variation on NPSF3000's example, but using method syntax and a Dictionary instead of a Tuple[]:</p>\n\n<pre><code>Enumerable.Range(1, 100)\n.Select(n =&gt; new Dictionary&lt;int, string&gt;\n { {15, \"FizzBuzz\"}, {3, \"Fizz\"}, {5, \"Buzz\"}, {1, n.ToString()} }\n .First(kv =&gt; n % kv.Key == 0).Value)\n.ToList()\n.ForEach(Console.WriteLine);\n</code></pre>\n\n<p>Update: as noted in the comments, Dictionary doesn't guarantee order, even though this example works correctly on my machine. So if you use <a href=\"https://stackoverflow.com/questions/11694910/how-do-you-use-object-initializers-for-a-list-of-key-value-pairs/11695018#11695018\">this KeyValueList implementation</a>, you can replace <code>Dictionary&lt;int, string&gt;</code> with <code>KeyValueList&lt;int, string&gt;</code> and still use the dictionary initializer syntax. I prefer this to using the SortedDictionary since it doesn't change the ordering shown in code and therefore doesn't require using Last() instead of First().</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-05-07T09:15:30.383", "Id": "86301", "Score": "1", "body": "There's no guarantee that enumerating a `Dictionary` will return the entries in the order in which you added them. You could call `OrderBy` before `First` each time but since you're not using the `O(1)` lookup of the dictionary you may as well use a `List` or other ordered collection." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-05-07T09:58:03.817", "Id": "86303", "Score": "1", "body": "Well, you could use a `SortedDictionary` and `Last` instead of `First`; but the only advantange over a simple array would be the nice collection initializer syntax instead of using an anonymous type." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-05-07T18:46:38.963", "Id": "86409", "Score": "0", "body": "Thanks, you're both correct. I've added an update that hopefully addresses your points." } ], "meta_data": { "CommentCount": "3", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-05-06T22:49:21.587", "Id": "49103", "ParentId": "49058", "Score": "4" } }, { "body": "<p>It's not necessary to extract the function. A multi-statement lambda will suffice:</p>\n\n<pre><code>Enumerable.Range(1,100).Select(n =&gt; {\n if (n % 3 == 0) {\n return n % 5 == 0 ? \"FizzBuzz\" : \"Fizz\";\n }\n return n % 5 == 0 ? \"Buzz\" : n.ToString();\n}).ForEach(Console.WriteLine);\n</code></pre>\n\n<p>I prefer to use my own ForEach extension method rather than put the whole collection into a List:</p>\n\n<pre><code>public static void ForEach&lt;T&gt;(this IEnumerable&lt;T&gt; collection, Action&lt;T&gt; fn)\n{\n foreach(T item in collection) { fn(item); }\n}\n</code></pre>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-05-07T17:41:48.080", "Id": "49167", "ParentId": "49058", "Score": "3" } }, { "body": "<p>I've used some answers here with a little refactoring, so you can easily add more numbers to divide:</p>\n\n<pre><code>var dic = new Dictionary&lt;int, string&gt; { { 3, \"Fizz\" }, { 5, \"Buzz\" } };\n\nvar t = \n from number in Enumerable.Range(1, 100)\n let names = dic.Where(kv =&gt; number % kv.Key == 0).Select(kv =&gt; kv.Value)\n select names.Any() ? string.Join(\"\", names) : number.ToString();\n\nt.ToList().ForEach(Console.WriteLine);\n</code></pre>\n\n<p>Notice that it concatenates all the names that a number has, if it doesnt have any, it returns the number.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2015-09-14T23:28:30.670", "Id": "104684", "ParentId": "49058", "Score": "4" } } ]
{ "AcceptedAnswerId": "49066", "CommentCount": "4", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-05-06T10:53:42.753", "Id": "49058", "Score": "24", "Tags": [ "c#", "linq", "fizzbuzz" ], "Title": "Single line FizzBuzz solution in LINQ" }
49058
<p>Can you give me some performance advice on how to optimize the time of execution of the following calculation of E?</p> <pre><code>package calculatee; import java.math.BigDecimal; import java.math.MathContext; import java.math.RoundingMode; public class CalculateE { static long start1 = System.nanoTime(); public static BigDecimal factorial(int x) { BigDecimal prod = new BigDecimal("1"); for (int i = x; i &gt; 1; i--) { prod = prod.multiply(new BigDecimal(i)); } return prod; } public static void main(String[] args) { BigDecimal e = BigDecimal.ONE; for (int i = 1; i &lt; 1000; i++) { e = e.add(BigDecimal.valueOf(Math.pow(3 * i, 2) + 1).divide(factorial(3 * i),new MathContext(10000, RoundingMode.HALF_UP))); } System.out.println("e = " + e); long stop = System.nanoTime(); long diff = stop - start1; System.out.println(diff + " ns"); } } </code></pre> <p>The time of execution is about 3055588556 ns.</p>
[]
[ { "body": "<p>you can split up the calculation in your <code>for</code> loop into threads and sum up the results afterwards: here an example for 4 Threads: Use as many Threads as you have <code>CPU</code>s. It's important to add the result inside a <code>synchronized</code> block, otherwise you result could be corrupted by <a href=\"http://en.wikipedia.org/wiki/Race_condition\" rel=\"nofollow\">race conditions</a>. I get a speed up of 50% with 4 threads compared to a single core execution.</p>\n\n<pre><code>import java.math.BigDecimal;\nimport java.math.MathContext;\nimport java.math.RoundingMode;\n\npublic class CalculateE {\n\n static long start1 = System.currentTimeMillis();\n\n static BigDecimal result = BigDecimal.ONE;\n\n public static BigDecimal factorial(int x) {\n BigDecimal prod = new BigDecimal(\"1\");\n for (int i = x; i &gt; 1; i--) {\n prod = prod.multiply(new BigDecimal(i));\n }\n return prod;\n }\n\n public static Runnable getRunner(final int from, final int to) {\n Runnable runner = new Runnable() {\n @Override\n public void run() {\n BigDecimal e = BigDecimal.ZERO;\n for (int i = from; i &lt; to; i++) {\n e = e.add(BigDecimal\n .valueOf(Math.pow(3 * i, 2) + 1)\n .divide(factorial(3 * i),\n new MathContext(10000, RoundingMode.HALF_UP)));\n }\n addResult(e);\n }\n };\n return runner;\n }\n\n public static synchronized void addResult(BigDecimal e){\n result = result.add(e);\n }\n\n public static void main(String[] args) throws InterruptedException {\n Runnable r1 = getRunner(1, 251);\n Runnable r2 = getRunner(251, 501);\n Runnable r3 = getRunner(501, 751);\n Runnable r4 = getRunner(751, 1000);\n Thread t1 = new Thread(r1);\n t1.start();\n Thread t2 = new Thread(r2);\n t2.start();\n Thread t3 = new Thread(r3);\n t3.start();\n Thread t4 = new Thread(r4);\n t4.start();\n t1.join();\n t2.join();\n t3.join();\n t4.join();\n System.out.println(\"e = \" + result);\n long stop = System.currentTimeMillis();\n long diff = stop - start1;\n System.out.println(diff + \" ms\");\n }\n\n}\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-05-06T11:52:18.630", "Id": "86152", "Score": "1", "body": "Nice that you say use as many processors as you have. Pitty you don't make it generic by asking the pc his available processors by using : `Runtime.getRuntime().availableProcessors();` and using one AtomicInteger what you use in the 4 threads for counting to the end, so if one thread crash, the other ones shall continue to do the whole work." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-05-06T12:43:21.677", "Id": "86160", "Score": "0", "body": "@chillworld why would one thread crash, and why is it ok to continue if it did?" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-05-06T12:47:56.140", "Id": "86161", "Score": "0", "body": "In this example normally there shall not be a crash, but this is a system you can use for every task splitting. The advantage is also that your x threads finish simultane, what is maybe not true when you split it in x equal divisions." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-05-06T12:49:14.657", "Id": "86162", "Score": "0", "body": "@chillworld Good point. It is unlikely that the work is the same for all threads." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-05-06T12:50:49.333", "Id": "86163", "Score": "0", "body": "Sometimes optimising the code gives you more improvement than using more threads." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-05-07T01:03:11.117", "Id": "86264", "Score": "0", "body": "Although you might want to use an [`AtomicBigDecimal`](http://www.coderanch.com/t/566492/threads/java/AtomicBigDecimal-class-interesting-find) instead of using synchronized blocks." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-05-07T01:07:48.697", "Id": "86268", "Score": "0", "body": "Also, why are you constructing a brand new `MathContext` in each iteration of the loop? You should just reuse a single instance." } ], "meta_data": { "CommentCount": "7", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-05-06T11:20:37.580", "Id": "49061", "ParentId": "49060", "Score": "3" } }, { "body": "<p>This is 4.5x faster than the original code.</p>\n\n<p>On my machine, the single threaded version was about the same speed as the multi-threaded version I wrote. The single thread version was much simpler.</p>\n\n<pre><code>import java.math.BigDecimal;\n\npublic class CalculateE {\n public static void main(String... ignored) {\n long start = System.nanoTime();\n BigDecimal e = BigDecimal.ONE;\n BigDecimal factorial = BigDecimal.ONE;\n for (int i = 1; i &lt; 1000; i++) {\n long x = i * 3;\n factorial = factorial.multiply(BigDecimal.valueOf(x * (x - 1) * (x - 2)));\n e = e.add(BigDecimal.valueOf(9L * i * i + 1).divide(factorial, 9200, BigDecimal.ROUND_HALF_UP));\n }\n long time = System.nanoTime() - start;\n System.out.println(\"e = \" + e);\n System.out.println(\"Took \" + time / 1e9 + \" seconds to calculate\");\n }\n}\n</code></pre>\n\n<p>prints</p>\n\n<pre><code>e = 2.7.....\nTook 0.796560819 seconds to calculate\n</code></pre>\n\n<p>Note: running the multi-threaded example above reported</p>\n\n<pre><code>2626 ms\n</code></pre>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-05-06T12:41:07.523", "Id": "49067", "ParentId": "49060", "Score": "2" } }, { "body": "<p>A standalone <code>factorial()</code> function is always a big red flag. Same goes for <code>pow()</code>. When calculating power series most often they just not needed.</p>\n\n<p>Consider a Horner schema instead (pseudocode below):</p>\n\n<p>In a most straightforward way, without using <code>3i</code> trick, the calculation would looks like</p>\n\n<pre><code>e = 1.0\nfor i = N, i &gt; 0, i -= 1\n e = 1.0 + e/i\n</code></pre>\n\n<p>No factorials, no powers.</p>\n\n<p>If using the trick, I'd first split the formula into two sums:</p>\n\n<pre><code>e = sum(1 / (3i)!) + sum((3i)**2 / (3i)!)\n</code></pre>\n\n<p>calculate them independently, and add the results. The first schema is a trivial adaptation of the above one; the second one is just a bit more involved:</p>\n\n<pre><code>result = 1.0\nfor i = 3*N, i &gt; 0, i -= 3\n result = i*i * (1.0 + result/(i*(i-1)*(i-2)))\n</code></pre>\n\n<p>No factorials, no powers. No need for big integers as well.</p>\n\n<p>PS: the biggest problem with the Horner schema is estimating the iteration count for the desired accuracy. Sometimes a heavy math is necessary. In such a simple case like <code>e</code> it is almost trivial.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-05-06T19:34:49.010", "Id": "49098", "ParentId": "49060", "Score": "2" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-05-06T11:15:08.307", "Id": "49060", "Score": "5", "Tags": [ "java", "performance", "mathematics" ], "Title": "Better performance in calculating E" }
49060
<p>Inspired by some older questions, I decided to create my own postfix calculator using Java 8. I'd like to have all aspects reviewed.</p> <pre><code>public enum Operator implements DoubleBinaryOperator { PLUS ("+", (l, r) -&gt; l + r), MINUS ("-", (l, r) -&gt; l - r), MULTIPLY("*", (l, r) -&gt; l * r), DIVIDE ("/", (l, r) -&gt; l / r); private final String symbol; private final DoubleBinaryOperator binaryOperator; private Operator(final String symbol, final DoubleBinaryOperator binaryOperator) { this.symbol = symbol; this.binaryOperator = binaryOperator; } public String getSymbol() { return symbol; } @Override public double applyAsDouble(final double left, final double right) { return binaryOperator.applyAsDouble(left, right); } } </code></pre> <hr> <pre><code>public class CalculationFailedException extends RuntimeException { private static final long serialVersionUID = 6849565649585489467L; public CalculationFailedException() { super(); } public CalculationFailedException(final String message) { super(message); } public CalculationFailedException(final Throwable cause) { super(cause); } public CalculationFailedException(final String message, final Throwable cause) { super(message, cause); } } </code></pre> <hr> <pre><code>public interface Calculator { public double calculate(final String input); } </code></pre> <hr> <pre><code>public class PostfixCalculator implements Calculator { private static final List&lt;String&gt; OPERATORS_LIST = Arrays.stream(Operator.values()) .map(Operator::getSymbol) .collect(Collectors.toList()); private static final Map&lt;String, Operator&gt; STRING_TO_OPERATOR_MAPPING = Arrays.stream(Operator.values()) .collect(Collectors.toMap(op -&gt; op.getSymbol(), op -&gt; op)); private final Stack&lt;Double&gt; numberStack = new Stack&lt;&gt;(); @Override public double calculate(final String input) throws IllegalArgumentException { try { Arrays.stream(input.split(" ")).forEach(this::processElement); return safePop(); } catch (CalculationFailedException | NumberFormatException ex) { throw new CalculationFailedException("Calculation has failed for expression: " + input); } } private void processElement(final String element) { Objects.requireNonNull(element); if (OPERATORS_LIST.contains(element)) { processOperator(STRING_TO_OPERATOR_MAPPING.get(element)); } else { processNumber(Double.parseDouble(element)); } } private void processOperator(final Operator operator) { double right = safePop(); double left = safePop(); numberStack.push(operator.applyAsDouble(left, right)); } private void processNumber(final double number) { numberStack.push(number); } private double safePop() { if (numberStack.isEmpty()) { throw new CalculationFailedException(); } return numberStack.pop(); } } </code></pre> <p>Code can be called for example with:</p> <pre><code>Calculator calculator = new PostfixCalculator(); double result = calculator.calculate("3 4 +"); </code></pre> <p>Which will give <code>7.0</code> as result.</p> <p>Another example:</p> <pre><code>Calculator calculator = new PostfixCalculator(); double result = calculator.calculate("5 1 2 + 4 * + 3 -"); </code></pre> <p>Which gives <code>14.0</code> as result.</p>
[]
[ { "body": "<p>I like how the Functions have simplified the enum, but, you have put logic in the implementation class that belongs in the enum....</p>\n\n<p>The code:</p>\n\n<blockquote>\n<pre><code>private static final List&lt;String&gt; OPERATORS_LIST = Arrays.stream(Operator.values())\n .map(Operator::getSymbol)\n .collect(Collectors.toList());\n\nprivate static final Map&lt;String, Operator&gt; STRING_TO_OPERATOR_MAPPING = Arrays.stream(Operator.values())\n .collect(Collectors.toMap(op -&gt; op.getSymbol(), op -&gt; op));\n</code></pre>\n</blockquote>\n\n<p>should be part of the <code>Operator</code> enum.... and there should be a static method on the enum:</p>\n\n<pre><code>public static Operator operatorFor(String op) {\n return STRING_TO_OPERATOR_MAPPING.get(op);\n}\n</code></pre>\n\n<p>Then, your calling class would have the code:</p>\n\n<pre><code>private void processElement(final String element) {\n Objects.requireNonNull(element);\n Operator op = Operator.operatorFor(element);\n if (op != null) {\n processOperator(op);\n }\n else {\n processNumber(Double.parseDouble(element));\n }\n}\n</code></pre>\n\n<p>Also, you should be trapping the NumberFormatException closer to where it is thrown....</p>\n\n<blockquote>\n<pre><code> processNumber(Double.parseDouble(element));\n</code></pre>\n</blockquote>\n\n<p>should be:</p>\n\n<pre><code>try {\n processNumber(Double.parseDouble(element));\n} catch (NumberFormatException nfe) {\n throw new CalculationFailedException(\"Unable to parse value \" + element + \" as a double.\", nfe);\n}\n</code></pre>\n\n<p>That way, you can identify which value failed to parse.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-05-12T21:06:16.847", "Id": "87180", "Score": "0", "body": "Good answer, but you might not want to echo the value that failed to parse exactly as entered. If you do that, your application will be vulnerable to command injection if someone is trying to use its output on the command line again (for example, as an argument to another program)." } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-05-06T12:59:14.357", "Id": "49069", "ParentId": "49063", "Score": "7" } } ]
{ "AcceptedAnswerId": "49069", "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-05-06T11:29:40.767", "Id": "49063", "Score": "15", "Tags": [ "java" ], "Title": "Simple Postfix Calculator using Java 8" }
49063
<p>I'm working on some teaching examples showing the perils of accessing the Dictionary class concurrently. In the code below each function is designed to do a word count across a number of files. (This isn't the best way of doing the count but it's there to make a point about Dictionary.)</p> <p>The first example, using a Dictionary and no parallelism works fine.</p> <p>The second example, using a Dictionary and Array.parallel can fail with an exception and also produces different results each time. This is deliberate and is there to make the point.</p> <p>The final example uses ConcurrentDictionary and seems to me to work fine. My concern is: given this uses a delegate to do the count addition, is this version genuinely thread safe?</p> <pre><code>// Simple version: let WordCount dirPath wildCard = let wordCounts = Dictionary&lt;string, int&gt;() let ProcessFile fileName = let text = File.ReadAllText(fileName) text.Split([|'.'; ' '; '\r'|], StringSplitOptions.RemoveEmptyEntries) |&gt; Array.map (fun w -&gt; w.Trim()) |&gt; Array.filter (fun w -&gt; w.Length &gt; 2) |&gt; Array.iter (fun w -&gt; let ok, count = wordCounts.TryGetValue(w) if ok then wordCounts.[w] &lt;- count+1 else wordCounts.[w] &lt;- 1) Directory.EnumerateFiles(dirPath, wildCard) |&gt; Seq.iter ProcessFile wordCounts // |&gt; Seq.sumBy (fun kv -&gt; kv.Value) |&gt; Seq.sortBy (fun kv -&gt; -kv.Value) // Naive concurrent version: let WordCount2 dirPath wildCard = let wordCounts = Dictionary&lt;string, int&gt;() let ProcessFile fileName = let text = File.ReadAllText(fileName) text.Split([|'.'; ' '; '\r'|], StringSplitOptions.RemoveEmptyEntries) |&gt; Array.map (fun w -&gt; w.Trim()) |&gt; Array.filter (fun w -&gt; w.Length &gt; 2) |&gt; Array.iter (fun w -&gt; let ok, count = wordCounts.TryGetValue(w) if ok then wordCounts.[w] &lt;- count+1 else wordCounts.[w] &lt;- 1) Directory.EnumerateFiles(dirPath, wildCard) |&gt; Array.ofSeq |&gt; Array.Parallel.iter ProcessFile wordCounts |&gt; Seq.sumBy (fun kv -&gt; kv.Value) // |&gt; Seq.sortBy (fun kv -&gt; -kv.Value) // Safe concurrent version: let WordCount3 dirPath wildCard = let wordCounts = ConcurrentDictionary&lt;string, int&gt;() let ProcessFile fileName = let text = File.ReadAllText(fileName) text.Split([|'.'; ' '; '\r'|], StringSplitOptions.RemoveEmptyEntries) |&gt; Array.map (fun w -&gt; w.Trim()) |&gt; Array.filter (fun w -&gt; w.Length &gt; 2) |&gt; Array.iter (fun w -&gt; wordCounts.AddOrUpdate(w, 1, (fun _ count -&gt; count+1 )) |&gt; ignore) Directory.EnumerateFiles(dirPath, wildCard) |&gt; Array.ofSeq |&gt; Array.Parallel.iter ProcessFile wordCounts |&gt; Seq.sumBy (fun kv -&gt; kv.Value) // |&gt; Seq.sortBy (fun kv -&gt; -kv.Value) </code></pre>
[ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-05-06T14:05:58.403", "Id": "86176", "Score": "0", "body": "Why _wouldn't_ it be thread-safe? Isn't that what `ConcurrentDictionary` is for?" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-05-06T14:31:36.373", "Id": "86181", "Score": "1", "body": "`ConcurrentDictionary` provides thread-safety through atomic operations, so you shouldn't call `ContainsKey` followed by `Item`, you should call `TryGetValue`. That's why it has methods like `GetOrAdd` and `AddOrUpdate` that the regular `Dictionary` doesn't." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-05-06T14:38:09.193", "Id": "86182", "Score": "0", "body": "@Daniel Yes, I know. All I'm saying is that it makes sense to ask “Am I using `ConcurrentDictionary` correctly?” Because you *can* use it incorrectly." } ]
[ { "body": "<p>If you just used your original code (<code>TryGetValue</code> followed by an indexer set) with <code>ConcurrentDictionary</code>, then that wouldn't be thread-safe.</p>\n\n<p>But you're using the <code>AddOrUpdate</code> method instead, which is guaranteed to be thread-safe (i.e. atomic), so this use is thread-safe.</p>\n\n<hr>\n\n<p>One other nitpick:</p>\n\n<pre><code>Directory.EnumerateFiles(dirPath, wildCard)\n|&gt; Array.ofSeq\n</code></pre>\n\n<p>If you don't actually want <code>seq</code>, but an array, <code>Directory</code> has a method just for that: <a href=\"http://msdn.microsoft.com/en-us/library/wz42302f\" rel=\"nofollow\"><code>Directory.GetFiles</code></a>.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-05-06T14:36:49.147", "Id": "49079", "ParentId": "49064", "Score": "3" } } ]
{ "AcceptedAnswerId": "49079", "CommentCount": "3", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-05-06T11:36:11.860", "Id": "49064", "Score": "2", "Tags": [ "f#", "hash-map" ], "Title": "Is this use of ConcurrentDictionary truly thread safe?" }
49064
<p>I am writing some code in Ruby on Rails to <strong>Create an object</strong>.</p> <p>I am using <strong>Ruby 2.0</strong> and <strong>Rails 4.0.3</strong> in my Application.</p> <p>I have a Model called:</p> <pre><code>class GroupUsers &lt; ActiveRecord::Base belongs_to :users belongs_to :group </code></pre> <p>This is basically a ManyToMany mapping between Users and Groups. So, today I was creating an object for this Model.</p> <p>But I found out I could follow <strong>two syntax</strong> for this, as follows</p> <pre><code>GroupUsers.create( :user =&gt; user, :group =&gt; group ) </code></pre> <p>Or</p> <pre><code>GroupUsers.create( user: user, group: group ) </code></pre> <p>Basically since this is <strong>related to creating a Hash</strong> so it must be a question of <strong>the best practice in Ruby</strong>. </p> <p><strong>Which syntax should be preferred ?</strong></p>
[ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-05-06T17:54:59.897", "Id": "86215", "Score": "0", "body": "I suggest adopting a style guide appropriate to the Ruby version of your project and adhering to that. ruby-style-guide enforces Ruby 1.9 style hash syntax for Ruby 1.9+ projects, for example." } ]
[ { "body": "<p>Depends on the Ruby version you're using. If you're using Ruby 1.9.2+ then the second syntax is cleaner in terms of readability. </p>\n\n<p>If you're using Ruby 1.8 then you can't use the second syntax anyway and you have not choice.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-05-06T14:39:10.950", "Id": "86183", "Score": "4", "body": "Please expand this answer a bit, to explain *why* a syntax is cleaner with such or such version of Ruby." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-05-07T13:56:09.590", "Id": "86340", "Score": "0", "body": "@Mat'sMug edited." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-05-07T14:03:18.213", "Id": "86342", "Score": "0", "body": "I Added \"cleaner in terms of readability\"" } ], "meta_data": { "CommentCount": "3", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-05-06T14:17:48.030", "Id": "49076", "ParentId": "49071", "Score": "0" } }, { "body": "<p>Well, you can also create an ActiveRecord object with a <a href=\"http://blog.plataformatec.com.br/2012/07/active-record-loves-blocks/\" rel=\"nofollow\">block passed</a>:</p>\n\n<pre><code>GroupUsers.create do |gu|\n gu.user = user\n gu.group = group\nend\n</code></pre>\n\n<p>though I don't think it's suitable with just a few attributes being set. However, I'd suggest renaming the robot-like <code>GroupUsers</code> into <code>Membership</code>, for example.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-05-12T18:59:03.793", "Id": "49556", "ParentId": "49071", "Score": "0" } }, { "body": "<p>It depends. I prefer the newer syntax because I feel that it is more readable. As others have pointed out, however, the newer syntax is only compatible with Ruby 1.9.2+.</p>\n\n<p>You should be aware, however, that the new syntax does not entirely replace the hash rocket syntax. This is because you can only use the newer syntax with symbols.</p>\n\n<pre><code>{ \"text\": :hello } #=&gt; syntax error, unexpected ':', expecting =&gt;\n</code></pre>\n\n<p>If you want to use strings and methods, you will still need to use the has rocket:</p>\n\n<pre><code>{ method_name =&gt; :hello }\n{ \"a_string\" =&gt; :hello }\n</code></pre>\n\n<p>Personally, from my experience of reading and watching educational materials, the newer syntax is preferred where possible. It's also less keystrokes: <code>:</code> instead of <code>=&gt;</code> is easier for me.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-05-12T19:23:03.790", "Id": "49557", "ParentId": "49071", "Score": "3" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "1", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-05-06T13:32:02.673", "Id": "49071", "Score": "2", "Tags": [ "ruby", "ruby-on-rails" ], "Title": "Which syntax is preferred to create a Hash in Ruby on Rails?" }
49071
<p>I'm creating a 2D tile based platformer with AABB (Axis aligned bounding boxes), and it works, I just want to organize and optimize my setup. Here are methods in my player class and entity class that are relevant to the collision. How could I make this better? I'm harshly looking at that <code>public boolean[]</code> method, but I cant figure out another way without using state.</p> <p><strong>AbstractEntity.java</strong> </p> <pre><code>public boolean[] getCornersAreSolid(double x, double y) { int leftTile = (int)(x / Tile.SIZE); int rightTile = (int)((x + this.collisionBox.getWidth()) / Tile.SIZE); int topTile = (int)(y / Tile.SIZE); int bottomTile = (int)((y + this.collisionBox.getHeight()) / Tile.SIZE); boolean topLeft; boolean topRight; boolean bottomLeft; boolean bottomRight; if(leftTile &lt; 0 || leftTile &gt;= map.getWidth() || topTile &lt; 0 || topTile &gt;= map.getHeight()) topLeft = false; else topLeft = map.getTileAt(leftTile, topTile).getAttribute(Attribute.SOLID); if(rightTile &lt; 0 || rightTile &gt;= map.getWidth() || topTile &lt; 0 || topTile &gt;= map.getHeight()) topRight = false; else topRight = map.getTileAt(rightTile, topTile).getAttribute(Attribute.SOLID); if(leftTile &lt; 0 || leftTile &gt;= map.getWidth() || bottomTile &lt; 0 || bottomTile &gt;= map.getHeight()) bottomLeft = false; else bottomLeft = map.getTileAt(leftTile, bottomTile).getAttribute(Attribute.SOLID); if(rightTile &lt; 0 || rightTile &gt;= map.getWidth() || bottomTile &lt; 0 || bottomTile &gt;= map.getHeight()) bottomRight = false; else bottomRight = map.getTileAt(rightTile, bottomTile).getAttribute(Attribute.SOLID); return new boolean[]{topLeft, topRight, bottomLeft, bottomRight}; } /* * @return next position */ public Vec2D getNextPosition() { int currCol = (int)getX() / Tile.SIZE; int currRow = (int)getY() / Tile.SIZE; double xdest = getX() + this.velocity.x; double ydest = getY() + this.velocity.y; double xtemp = getX(); double ytemp = getY(); boolean[] corners = getCornersAreSolid(getX(), ydest); boolean topLeft = corners[0]; boolean topRight = corners[1]; boolean bottomLeft = corners[2]; boolean bottomRight = corners[3]; if(this.velocity.y &lt; 0) { if(topLeft || topRight) { this.velocity.y = 0; ytemp = currRow * Tile.SIZE; } else { ytemp += this.velocity.y; } } else if(this.velocity.y &gt; 0) { if(bottomLeft || bottomRight) { this.velocity.y = 0; ytemp = (currRow + 1) * Tile.SIZE - this.collisionBox.getHeight() % Tile.SIZE - 1 ; } else { ytemp += this.velocity.y; } } corners = getCornersAreSolid(xdest, getY()); topLeft = corners[0]; topRight = corners[1]; bottomLeft = corners[2]; bottomRight = corners[3]; if(this.velocity.x &lt; 0) { if(topLeft || bottomLeft) { this.velocity.x = 0; xtemp = currCol * Tile.SIZE; } else { xtemp += this.velocity.x; } } if(this.velocity.x &gt; 0) { if(topRight || bottomRight) { this.velocity.x = 0; xtemp = (currCol + 1) * Tile.SIZE - this.collisionBox.getWidth() % Tile.SIZE -1 ; } else { xtemp += this.velocity.x; } } return new Vec2D(xtemp, ytemp); } </code></pre> <p><strong>PlayerEntity.java</strong> extends Abstract Entity</p> <pre><code>@Override public void update() { this.setPosition(this.getNextPosition()); if(this.movingLeft) this.velocity.x = -WALK_SPEED; if(!this.movingLeft &amp;&amp; this.velocity.x &lt; 0) this.velocity.x *= COEF_FRIC; if(this.movingRight) this.velocity.x = WALK_SPEED; if(!this.movingRight &amp;&amp; this.velocity.x &gt; 0) this.velocity.x *= COEF_FRIC; animations.update(); } @Override public void keyPressed(KeyEvent e) { switch(e.getKeyCode()){ case KeyEvent.VK_A: this.movingLeft = true; break; case KeyEvent.VK_D: this.movingRight = true; break; case KeyEvent.VK_W: this.velocity.y = -5; break; } } @Override public void keyReleased(KeyEvent e) { switch(e.getKeyCode()){ case KeyEvent.VK_A: this.movingLeft = false; break; case KeyEvent.VK_D: this.movingRight = false; break; } } </code></pre>
[]
[ { "body": "<p>You play around with different ordering (depending on you data) it may be faster to check absolutes first, or last.</p>\n\n<pre><code>if(leftTile &lt; 0 || leftTile &gt;= map.getWidth() || topTile &lt; 0 ||....\n</code></pre>\n\n<p>can become</p>\n\n<pre><code>if(leftTile &lt; 0 || topTile &lt; 0 || leftTile &gt;= map.getWidth()...\n</code></pre>\n\n<p>Also, notice that you throw away half your answers after a fast check, plenty of room for improvement.</p>\n\n<pre><code> if(this.velocity.y &lt; 0) { ...\n</code></pre>\n\n<p>Depending on how many objects versus tiles you have or if the collision map is static, consider rendering the collision map to a array to eliminate lookup overhead</p>\n\n<p>You are creating a new Vec2d at the end of each test, you can reuse a object or just set the result where it belongs.</p>\n\n<p>This is just suggestions, always benchmark. Always.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-05-06T15:47:26.537", "Id": "49082", "ParentId": "49072", "Score": "5" } }, { "body": "<p>I bet you could cut your code in half here, since you do a lot of things twice, just in a slightly modified way. That's a a good indication that you're not writing things as modular as you could. There's also a lot of code duplication static analysis tools out there that can help you out because you're only causing yourself more work in these cases. Especially when you decide to change just one tiny thing...</p>\n\n<p><strong>getCornersAreSolid()</strong></p>\n\n<p>I immediately question why you're returning a boolean array. My fear that you're storing the result of the four corners in it soon realizes itself. In my own personal opinion, there are few uses for raw arrays anymore, since they just open the door to a world of index out of bounds exceptions. Consider a new small class that communicates all of this in a semantic way. <code>corners[0]</code> means nothing unless you trace through all the code. <code>solidCorners.isSolid(Direction.TOP_LEFT)</code> is clear without any further explanation (though I admit better variable names could be used).</p>\n\n<p><code>int leftTile = (int)(x / Tile.SIZE);</code></p>\n\n<p>This is just a personal point of mine, but why not add a space between <code>(int)</code> and the rest? When I read this, or <code>if(leftTile &lt; 0 ||....</code>, I think why are you writing codewithnospacesbetweenyourwords? Again, highly personal and stylistic, so don't take too seriously.</p>\n\n<pre><code>boolean topLeft;\nboolean topRight;\nboolean bottomLeft;\nboolean bottomRight;\n</code></pre>\n\n<p>These are all set by default to <code>false</code>, though it wouldn't be a bad idea to make it explicit:</p>\n\n<pre><code>boolean topLeft = false;\nboolean topRight = false;\nboolean bottomLeft = false;\nboolean bottomRight = false;\n</code></pre>\n\n<p>so that when you see</p>\n\n<pre><code>if(leftTile &lt; 0 || leftTile &gt;= map.getWidth() || topTile &lt; 0 || topTile &gt;= map.getHeight())\n topLeft = false;\nelse\n topLeft = map.getTileAt(leftTile, topTile).getAttribute(Attribute.SOLID);\n</code></pre>\n\n<p>you ask yourself why you might be setting these variables to false twice.</p>\n\n<p>This can be replaced with </p>\n\n<pre><code>if(leftTile &gt;= 0 &amp;&amp; leftTile &lt; map.getWidth() &amp;&amp; topTile &gt;= 0 &amp;&amp; topTile &lt; map.getHeight()) {\n topLeft = map.getTileAt(leftTile, topTile).getAttribute(Attribute.SOLID);\n}\n</code></pre>\n\n<p>Here, I removed the first condition, since that is covered by the default boolean variable initialization value, and applied <a href=\"https://en.wikipedia.org/wiki/De_Morgan%27s_laws\" rel=\"nofollow\">DeMorgan's law</a> to the inverse of it to check only the <code>else</code> case.</p>\n\n<p>Also note the use of curly braces. There's no reason to ever write a control statement without them. That is,</p>\n\n<pre><code>if(leftTile &lt; 0 || leftTile &gt;= map.getWidth() || topTile &lt; 0 || topTile &gt;= map.getHeight())\n topLeft = false;\nelse\n topLeft = map.getTileAt(leftTile, topTile).getAttribute(Attribute.SOLID);\n</code></pre>\n\n<p>should always be written as </p>\n\n<pre><code>if(leftTile &lt; 0 || leftTile &gt;= map.getWidth() || topTile &lt; 0 || topTile &gt;= map.getHeight()) {\n topLeft = false;\n}\nelse {\n topLeft = map.getTileAt(leftTile, topTile).getAttribute(Attribute.SOLID);\n}\n</code></pre>\n\n<p>(or whatever your preference of block placement.) White space is free, so don't be frugal.</p>\n\n<p>And as was alluding to at the start, you have the exact same code here repeated four times, with only the parameters changing. Why not just add a method:</p>\n\n<pre><code>private boolean hasAttribute(YourMapClass map, Attribute attribute, int tileY, int tileX) {\n boolean result = false;\n\n if (tileX &gt;= 0 &amp;&amp; tileX &lt; map.getWidth() &amp;&amp; tileY &gt;= 0 &amp;&amp; tileY &lt; map.getHeight()) {\n result = map.getTileAt(tileX, tileY).isAttribute(attribute);\n }\n\n return result;\n}\n</code></pre>\n\n<p>Notice that this method can be used for any attribute, and with this,</p>\n\n<pre><code>boolean topLeft;\nboolean topRight;\nboolean bottomLeft;\nboolean bottomRight;\n\nif(leftTile &lt; 0 || leftTile &gt;= map.getWidth() || topTile &lt; 0 || topTile &gt;= map.getHeight())\n topLeft = false;\nelse\n topLeft = map.getTileAt(leftTile, topTile).getAttribute(Attribute.SOLID);\nif(rightTile &lt; 0 || rightTile &gt;= map.getWidth() || topTile &lt; 0 || topTile &gt;= map.getHeight())\n topRight = false;\nelse\n topRight = map.getTileAt(rightTile, topTile).getAttribute(Attribute.SOLID);\nif(leftTile &lt; 0 || leftTile &gt;= map.getWidth() || bottomTile &lt; 0 || bottomTile &gt;= map.getHeight())\n bottomLeft = false;\nelse\n bottomLeft = map.getTileAt(leftTile, bottomTile).getAttribute(Attribute.SOLID);\nif(rightTile &lt; 0 || rightTile &gt;= map.getWidth() || bottomTile &lt; 0 || bottomTile &gt;= map.getHeight())\n bottomRight = false;\nelse\n bottomRight = map.getTileAt(rightTile, bottomTile).getAttribute(Attribute.SOLID);\n</code></pre>\n\n<p>can be simplified to</p>\n\n<pre><code>boolean topLeft = hasAttribute(map, Attribute.Solid, topTile, leftTile);\nboolean topRight = hasAttribute(map, Attribute.Solid, topTile, rightTile);\nboolean bottomLeft = hasAttribute(map, Attribute.Solid, bottomTile, leftTile);\nboolean bottomRight = hasAttribute(map, Attribute.Solid, bottomTile, rightTile);\n</code></pre>\n\n<p><strong>getNextPosition()</strong></p>\n\n<pre><code>double xdest = getX() + this.velocity.x;\n</code></pre>\n\n<p>This doesn't follow stand Java camel case, and should be </p>\n\n<pre><code>double xDest = getX() + this.velocity.x;\n</code></pre>\n\n<p>or better</p>\n\n<pre><code>double destX = getX() + this.velocity.x;\n</code></pre>\n\n<p>I also wouldn't be suggest using the <code>this</code> qualifier here. I know IDEs will automatically put that in wherever they can, but really the only time I feel you need to is in a case like</p>\n\n<pre><code>final int bar;\n\npublic Foo(int bar) {\n this.bar = bar;\n}\n</code></pre>\n\n<p>Couple lines down,</p>\n\n<pre><code>double xtemp = getX();\ndouble ytemp = getY();\n</code></pre>\n\n<p>Same comments about the naming. More importantly though, something smells here because immediately after this you work with those terrifying arrays I mentioned at the start, and then have this:</p>\n\n<pre><code>if(this.velocity.y &lt; 0) {\n if(topLeft || topRight) {\n this.velocity.y = 0;\n ytemp = currRow * Tile.SIZE;\n }\n else {\n ytemp += this.velocity.y;\n }\n}\nelse if(this.velocity.y &gt; 0) {\n if(bottomLeft || bottomRight) {\n this.velocity.y = 0;\n ytemp = (currRow + 1) * Tile.SIZE - this.collisionBox.getHeight() % Tile.SIZE - 1 ;\n }\n else {\n ytemp += this.velocity.y;\n }\n}\n</code></pre>\n\n<p>And the fact that you do this again for the horizontal case should scream out that you should introduce a new method.</p>\n\n<p>There's a a lot of things going on in this block, including the modification of public variables in another object (<em>gasp!</em>). You can perform all of this in a new method that you reuse again below for the horizontal case. This would be even easier if you use a new class to hold the directional boolean values as I metioned earlier.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-05-07T04:35:49.920", "Id": "49117", "ParentId": "49072", "Score": "4" } }, { "body": "<p>Forgive me if I get the syntax wrong, I'm not really a Java programmer, but I have a suggestion that might help.</p>\n\n<p>The first thing I would do to get rid of the array of booleans is create a class that represents what they are.</p>\n\n<pre><code>class SolidCorners\n{\n boolean topLeft;\n boolean topRight;\n boolean bottomLeft;\n boolean bottomRight;\n}\n</code></pre>\n\n<p>Doing this make's all of the other code simpler and more readable because it becomes self documenting. For example, getCornersAreSolid method becomes:</p>\n\n<pre><code>public SolidCorners getCornersAreSolid(double x, double y) {\n int leftTile = (int)(x / Tile.SIZE);\n int rightTile = (int)((x + this.collisionBox.getWidth()) / Tile.SIZE);\n int topTile = (int)(y / Tile.SIZE);\n int bottomTile = (int)((y + this.collisionBox.getHeight()) / Tile.SIZE);\n\n SolidCorners corners;\n\n if(leftTile &lt; 0 || leftTile &gt;= map.getWidth() || topTile &lt; 0 || topTile &gt;= map.getHeight())\n corners.topLeft = false;\n else\n corners.topLeft = map.getTileAt(leftTile, topTile).getAttribute(Attribute.SOLID);\n\n // and so on..\n\n return corners;\n}\n</code></pre>\n\n<p>And when you use the method you don't need to know the correct index positions in the array..</p>\n\n<pre><code>corners = getCornersAreSolid(xdest, getY());\n//topLeft = corners[0];\n//topRight = corners[1];\n//bottomLeft = corners[2];\n//bottomRight = corners[3];\n\nif(corners.topLeft || corners.bottomLeft) {\n</code></pre>\n\n<p>Creating an extra class up front may feel like more work, but usually it turns out to be less in the long run.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-05-08T01:06:41.913", "Id": "49198", "ParentId": "49072", "Score": "3" } } ]
{ "AcceptedAnswerId": "49082", "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-05-06T13:35:09.157", "Id": "49072", "Score": "6", "Tags": [ "java", "game", "collision" ], "Title": "Orginizing/Optimising my collision detection setup" }
49072
<p>It's a dynamic array, the elements can be accessed normally and it supports any type. I believe I'm relying on undefined behavior when I treat every pointer to pointer as <code>void **</code> and I would like to know if it will work on the main platforms.</p> <p>Every call to <code>da_reserve()</code> and <code>da_push_back()</code> might cause the array address to change. The meta data is hidden behind the pointer that is returned by <code>da_new()</code>.</p> <p>I know it's kind of a hack and I appreciate any suggestions on how to make it a proper dynamic array.</p> <p><strong>dynamic_array.h</strong></p> <pre><code>#ifndef DYNAMIC_ARRAY_H #define DYNAMIC_ARRAY_H #include &lt;stdlib.h&gt; #include &lt;stdbool.h&gt; #define DA_SUCCESS 1 #define DA_ERROR 0 extern void *DA_EMPTY; #define Dynamic_Array(type)type * #define Dynamic_Array_Ptr(da)(void **)da #define da_new(type, slots) da_new_(sizeof(type), (slots)) void *da_new_(size_t size, size_t slots); void da_delete(void *da); int da_push_back(void **da, void *element); void *da_pop_back(void *da); size_t da_get_count(void *da); size_t da_available_slots(void *da); bool da_is_empty(void *da); bool da_is_full(void *da); void da_clear(void *da); void da_reserve(void **da, size_t total_slots); #endif </code></pre> <p><strong>dynamic_array.c</strong></p> <pre><code>#include "dynamic_array.h" #include &lt;string.h&gt; typedef struct { size_t size; size_t position; size_t slots; } Index; static char dummy; void *DA_EMPTY = &amp;dummy; static inline Index *get_index(void *da) { return (Index *)da - 1; } static inline void *get_da(Index *index) { return index + 1; } void *da_new_(size_t size, size_t slots) { Index *index = malloc(sizeof(Index) + size * slots); if(index == NULL) return NULL; index-&gt;size = size; index-&gt;position = 0; index-&gt;slots = slots; return get_da(index); } void da_delete(void *da) { free(get_index(da)); } static int expand(void **da) { Index *index = get_index(*da); size_t new_size = index-&gt;slots * 2; if((index = realloc(index, new_size * index-&gt;size + sizeof(Index))) == NULL) return DA_ERROR; index-&gt;slots = new_size; *da = get_da(index); return DA_SUCCESS; } int da_push_back(void **da, void *element) { Index *index = get_index(*da); if(index-&gt;position == index-&gt;slots) if(expand(da) == DA_ERROR) return DA_ERROR; else index = get_index(*da); memcpy((char *)*da + index-&gt;position++ * index-&gt;size, element, index-&gt;size); return DA_SUCCESS; } void *da_pop_back(void *da) { Index *index = get_index(da); if(index-&gt;position == 0) return DA_EMPTY; return (char *)da + --index-&gt;position * index-&gt;size; } size_t da_get_count(void *da) { Index *index = get_index(da); return index-&gt;position; } size_t da_available_slots(void *da) { Index *index = get_index(da); return index-&gt;slots - index-&gt;position; } bool da_is_empty(void *da) { Index *index = get_index(da); return index-&gt;position == 0; } bool da_is_full(void *da) { Index *index = get_index(da); return index-&gt;position == index-&gt;slots; } void da_clear(void *da) { Index *index = get_index(da); index-&gt;position = 0; } void da_reserve(void **da, size_t total_slots) { Index *index = get_index(*da); if(index-&gt;slots &gt;= total_slots) return; if((index = realloc(index, total_slots * index-&gt;size + sizeof(Index))) == NULL) return; index-&gt;slots = total_slots; *da = get_da(index); } </code></pre> <p><strong>usage</strong></p> <pre><code>#include &lt;stdio.h&gt; #include &lt;stdlib.h&gt; #include &lt;time.h&gt; #include "dynamic_array.h" int main(void) { srand(time(NULL)); Dynamic_Array(int) numbers = da_new(int, 500); for(size_t i = 0; i &lt; 50000; ++i){ int random = rand(); da_push_back(Dynamic_Array_Ptr(&amp;numbers), &amp;random); } size_t count = da_get_count(numbers); for(size_t i = 0; i &lt; count; ++i) printf("Random number: %d\n", numbers[i]); da_delete(numbers); return 0; } </code></pre>
[ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-07-28T04:42:59.123", "Id": "104485", "Score": "1", "body": "I don't have time to write a detailed answer right now, but to put your doubts to rest: yes, this implementation relies on undefined behaviour, not because of `void **` but because of memory alignment, and, yes, it can be fixed in various ways. If you are still interested I can post an answer later" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-08-01T22:52:24.560", "Id": "105729", "Score": "0", "body": "@Thomas I would actually like to see an answer along those lines. It would certainly earn my upvote, I'm sure." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-09-21T17:49:44.137", "Id": "115982", "Score": "0", "body": "I don't understand what is the meaning of Index + 1 for getting the array position. Can you explain that ?" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-12-14T21:21:32.140", "Id": "133827", "Score": "0", "body": "Why would you need to check for fullness? As a dynamic structure, it shouldn't be set to a certain size, but grow as new elements are added." } ]
[ { "body": "<h1>Nasty Hack</h1>\n<p>I grant that it's a hack but I'd like to know of a platform where the following doesn't fix the alignment issue:</p>\n<pre><code>typedef struct {\n size_t size;\n size_t position;\n size_t slots;\n size_t padding;//NOT USED.\n} Index;\n</code></pre>\n<p>The alignment issue is that although <code>malloc(.)</code> returns a universally aligned address, the <code>sizeof(Index)</code> may not be a multiple of the alignment of the element type.</p>\n<p>So for example if <code>sizeof(size_t)==4</code> (i.e. typical 32-bit platform) it is likely that the <code>Index</code> in the OP will be such that <code>sizeof(Index)=12</code> but if the elements are say <code>double</code> requiring alignment of 8 the array will start at an address that is 4 mod 8 not 0 mod 8 as required. Operations on the elements as <code>double</code> 'in situ' will have undefined behaviour.</p>\n<p>The reason my hack will work is that given there is no reason to pad <code>Index</code> then as I propose it <code>sizeof(Index)=4*sizeof(size_t)</code> giving 4 byte alignment off the bat.</p>\n<p>If <code>sizeof(size_t)==2</code> (e.g. 16-bit platform) it will be 8 byte aligned.</p>\n<p>If <code>sizeof(size_t)==4</code> (e.g. 32-bit platform) it will be 16 byte aligned.</p>\n<p>If <code>sizeof(size_t)==8</code> (e.g. 64-bit platform) it will be 32 byte aligned.</p>\n<p>So the 'breaking' case is a platform with a data type having an alignment greater than 4 times the word size. I know of none and think such a thing unlikely.</p>\n<h1>Doing It Properly</h1>\n<p>If you want to do it all properly you need to work out the alignment of the stored type.\nThere is no guaranteed standard way to achieve that.\nIn C++11 you can use <code>alignof(.)</code> but this is a C challenge.\nThe most portable way (I know of) is:</p>\n<pre><code>#include &lt;stddef.h&gt; //Defines offsetof(.,.) macro.\n#define alignment_of(type) offsetof(struct { char w;type v;},v)\n</code></pre>\n<p>Here's a skeleton of a fixed dynamic array.\nI leave completion as an exercise.\nNoteworthy features are:</p>\n<ol>\n<li><p>Addresses alignment using best available practice (above).</p>\n</li>\n<li><p>Uses 1 for error and 0 for success. That is so ingrained it is beyond a matter of taste. See comments.</p>\n</li>\n<li><p>Engages in a bit of type punning to provide a bit of type-safety. <code>void*</code> parameters are asking for trouble.</p>\n</li>\n<li><p>Adds a bit of type-safety by size checking values pushed onto the array.</p>\n</li>\n</ol>\n<p>I would suggest 1 &amp; 2 are mandatory but 3 &amp; 4 are ideas to consider.</p>\n<pre><code>#include &lt;stdint.h&gt;//Defines MAX_SIZE\n#include &lt;stddef.h&gt;//Defines the little known offsetof macro.\n#include &lt;stdlib.h&gt;\n#include &lt;stdio.h&gt;\n#include &lt;string.h&gt;//Defines memcpy(.,.,.). I know! I know!\n\n//Defined as a macro so we can implement a bit of dynamic type safety.\n#define da_push_back(DA,ELEM) da_push_back_(&amp;(DA),&amp;(ELEM),sizeof(ELEM))\n\n//Best known practice for determining type alignment in C.\n#define alignment_of(type) offsetof(struct { char w;type v;},v)\n\n#define da_new(type,slots) da_new_(sizeof(type),slots,alignment_of(type),#type)\n\n//Overwhelming convention is to use zero as 'success' and non-zero as 'error'.\n//This allows the definition of diagnostic error codes and meaningful constructs \n// like int error=da_thing(); if(error){ handle error... }\nconst int DA_SUCCESS=0;\nconst int DA_ERROR=1;\n\nstruct dynamic_struct;\n\ntypedef struct dynamic_struct* dynamic_array;\n\ntypedef struct {\n size_t size;\n size_t position;\n size_t slots;\n size_t offset;//This will be store the amount of dynamically calculated alignment padding.\n const char* name;//Optional run-time type info. See stringizing # in macro.\n} Index;\n\n\ndynamic_array da_new_(size_t size,size_t slots,size_t align,const char* name){\n\n //Get alignment for both elements &amp; Index.\n size_t falign=alignment_of(Index);\n if(falign&lt;align){\n falign=align;\n }\n \n //offset will be the padding to go before Index.\n const size_t over=sizeof(Index)%falign;\n const size_t offset=over==0?0:falign-over;\n\n //Allocate the padding the Index and the slots.\n const size_t headersize=offset+sizeof(Index);\n char*const block=malloc(headersize+size*slots);\n if(block==NULL){\n return NULL;//allocation failed - behave like malloc(.).\n }\n \n //Notice we are padding at the start.\n //If we pad between Index and the elements we get in to a muddle.\n //To find the index from the array we need the offset but it's in the Index!\n //It's important to remember this offset so we can free the right point at the end.\n Index* index=(Index*)(block+offset);\n \n index-&gt;size=size;\n index-&gt;position=0;\n index-&gt;slots=slots;\n index-&gt;offset=offset;\n index-&gt;name=name;\n return (dynamic_array)(block+headersize);\n}\n\n\nIndex* da_get_index(dynamic_array da){\n return ((Index*)da)-1;\n}\n\nconst char* da_get_typename(dynamic_array da){\n return da_get_index(da)-&gt;name;\n}\n\nsize_t da_get_slots(dynamic_array da){\n return da_get_index(da)-&gt;slots; \n}\n\nint da_delete(dynamic_array da){\n //remember kids only render unto free(.) what malloc(.) has rendered unto thee.\n //Or calloc(.) or realloc(.) obviously. But you get the point.\n //We need to find the bottom of the block including any offset padding.\n Index*const index=da_get_index(da);\n const size_t offset=index-&gt;offset;\n void*const block=((char*const)index)-offset;\n free(block);\n return DA_SUCCESS;\n}\n\n//We pass in sizecheck from the macro as a bit of type safety.\n//Obviously this is no guarantee but will at least protect against some gross errors.\nint da_push_back_(dynamic_array* da,const void*const element,const size_t sizecheck){\n Index* index=da_get_index(*da);\n const size_t size=index-&gt;size;\n const size_t position=index-&gt;position;\n const size_t slots=index-&gt;slots;\n \n if(sizecheck!=size){\n return DA_ERROR;//element not compatible with array...\n }\n \n if(position&gt;=slots){\n size_t newslots;\n if(slots&gt;SIZE_MAX/2){\n if(slots==SIZE_MAX){\n return DA_ERROR;//Exceeded size_t. \n }\n newslots=SIZE_MAX;\n }else{\n newslots=slots==0?1:slots*2;\n }\n const size_t offset=index-&gt;offset;\n const size_t headersize=offset+sizeof(Index);\n void*block=((char*)index)-offset;\n char* newblock=realloc(block,headersize+newslots*size);\n if(newblock==NULL){\n return DA_ERROR;//Re-allocation failed.\n }\n *da=(dynamic_array)(newblock+headersize);\n index=da_get_index(*da);\n index-&gt;slots=newslots;\n }\n \n char* array=(char*)*da;\n memcpy(array+position*size,element,size);\n ++(index-&gt;position);\n return DA_SUCCESS;\n}\n\nvoid* da_get_array(dynamic_array da){\n return da;\n}\n\nint main(void) {\n int errors=0;\n dynamic_array array=da_new(double,3);\n\n double val=-2.718;\n errors+=da_push_back(array,val); \n\n double*access=da_get_array(array);\n access[1]=1234.0;\n access[2]=3.1415926535;\n\n printf(&quot;type-name is \\&quot;%s\\&quot;\\n&quot;,da_get_typename(array));\n printf(&quot;%p %f %f %f\\n&quot;,(void *)access,access[0],access[1],access[2]);\n \n da_delete(array);\n \n dynamic_array grow=da_new(int,3);\n \n if(da_get_slots(grow)&lt;3){\n ++errors;\n }\n \n int vint=99;\n errors+=da_push_back(grow,vint);\n vint=88;\n errors+=da_push_back(grow,vint);\n vint=77;\n errors+=da_push_back(grow,vint);\n \n //Now we make it grow...\n vint=66;\n errors+=da_push_back(grow,vint);\n \n if(da_get_slots(grow)&lt;4){\n ++errors;\n }\n\n \n int* ints=da_get_array(grow);\n \n if(ints[0]!=99||ints[1]!=88||ints[2]!=77||ints[3]!=66){\n ++errors;\n }\n \n printf(&quot;%d %d %d %d\\n&quot;,ints[0],ints[1],ints[2],ints[3]);\n \n da_delete(grow);\n \n dynamic_array longd=da_new(long double,10);\n \n //Stringizing will 'normalise' the white-space in the typename.\n //The source has multiple white-space characters\n if(strcmp(&quot;long double&quot;,da_get_typename(longd))!=0){\n ++errors;\n }\n da_delete(longd);\n \n //But it will consider aliases to be different.\n //Notice how these two arrays have the same type but not type-name.\n dynamic_array uinta=da_new(unsigned,10);\n if(strcmp(&quot;unsigned&quot;,da_get_typename(uinta))!=0){\n ++errors;\n }\n \n dynamic_array uintb=da_new(unsigned int,10);\n if(strcmp(&quot;unsigned int&quot;,da_get_typename(uintb))!=0){\n ++errors;\n }\n \n da_delete(uinta);\n da_delete(uintb); \n \n if(errors!=0){\n printf(&quot;ERRORS - %d\\n&quot;,errors);\n }else{\n printf(&quot;** SUCCESS **\\n&quot;);\n }\n return errors==0?EXIT_SUCCESS:EXIT_FAILURE;\n}\n</code></pre>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-12-31T14:42:15.813", "Id": "75351", "ParentId": "49078", "Score": "2" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "4", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-05-06T14:27:58.190", "Id": "49078", "Score": "7", "Tags": [ "c", "array" ], "Title": "Dynamic array in C" }
49078
<p>I had a jQuery program that displays some hover-over messages when touching an icon, in order to make it disappear the user needs to click again in the icon.</p> <pre><code>am.homepage.Index.prototype.touchableTitleBinding = function () { var that = this; $('.' + this.bindingClassForTouchableTitle).on('touchend', function (e) { e.stopPropagation(); $('.' + that.toggleClassForTouchableTitle).not(this).toggleClass(that.toggleClassForTouchableTitle); $(this).toggleClass(that.toggleClassForTouchableTitle); }); } </code></pre> <p>The variables are passed to the .js file from an mvc view. and the touchableBinding funciton is called on dom load.</p> <p>Thing is that now I'd like to make it disappear whenever you click outside any of those icons, so I wrote this:</p> <pre><code>am.homepage.Index.prototype.hideTouchableTitleBinding = function () { var that = this, classForTouchabletitle = '.' + this.bindingClassForTouchableTitle; am.personExpenditure.Index.prototype.hideTouchableTitleBinding = function () { var that = this, classForTouchabletitle = '.' + this.bindingClassForTouchableTitle; $('*:not(' + classForTouchabletitle + ')').on('touchend', function (e) { e.stopPropagation(); $('.' + that.toggleClassForTouchableTitle).removeClass(that.toggleClassForTouchableTitle); }); } </code></pre> <p>Is it too heavy to select all the elements apart from the ones with <code>toggleClassForTouchableTitle</code>? Is it worth binding like this?</p> <pre><code>am.homepage.Index.prototype.hideTouchableTitleBinding = function() { var that = this, classForTouchabletitle = '.' + this.bindingClassForTouchableTitle; $(body).on('touchend', '*:not(' + classForTouchabletitle + ')', function(e) { e.stopPropagation(); $('.' + that.toggleClassForTouchableTitle).removeClass(that.toggleClassForTouchableTitle); }); }; </code></pre> <p>Is it another way of doing it more elegant/performant?</p> <p>At the end I've changed to this</p> <pre><code>am.homepage.Index.prototype.touchableTitleBinding = function() { var that = this, removeTouchableTitleClass = function (e) { e.stopPropagation(); $('.' + that.toggleClassForTouchableTitle).removeClass(that.toggleClassForTouchableTitle); }; $('.' + this.bindingClassForTouchableTitle).on('touchend', function(e) { e.stopPropagation(); $('.' + that.toggleClassForTouchableTitle).not(this).toggleClass(that.toggleClassForTouchableTitle); //If we've displayed the title for one icon we rebind to hide it when clicking outside //just once, if we've hide it we stop listening to touch other elements for dealing with this $('body').off('touchend', ':not(' + that.toggleClassForTouchableTitle + ')'); if ($(this).hasClass(that.toggleClassForTouchableTitle)) { $(this).removeClass(that.toggleClassForTouchableTitle); } else { $(this).addClass(that.toggleClassForTouchableTitle); $('body').on('touchend', ':not(' + that.toggleClassForTouchableTitle + ')', removeTouchableTitleClass); } }); }; </code></pre> <p>In which case only once after displaying the tile will listen for the touch in any other part of the screen. I think this is probably slightly less readable but more performant</p>
[]
[]
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-05-06T14:45:14.487", "Id": "49080", "Score": "1", "Tags": [ "javascript", "jquery" ], "Title": "Hide element when clicking anywhere but some elements using jQuery" }
49080
<p>I'm creating an extension method that can be used on any type. The idea is that if this method is called, it checks if value is null. If null, it needs to return a default instance of the specified type.</p> <pre><code>public static dynamic CreateDefaultIfNull&lt;T&gt;(this object item) { if(item == null) { var type = typeof(T); if(type.IsArray) { return Array.CreateInstance(type.GetElementType(), 0); } if(type.GetConstructor(Type.EmptyTypes) == null) { var paramCount = type.GetConstructors().First().GetParameters().Count(); var paramNullList = new List&lt;object&gt;(); for(int i = 0; i &lt; paramCount; i++) { paramNullList.Add(null); } return Activator.CreateInstance(type, paramNullList.ToArray()); } return Activator.CreateInstance(type); } return (T)item; } </code></pre> <p>I'm looking for a review of my code, and any pitfalls that I may encounter or may have missed.</p> <p>The idea is that this method should be used anytime that a null value cannot be used and a default must be returned.</p> <p>I'm not worried about null values being passed into parameterized constructors, as this is doing. The constructor of those objects should be handling if null values are passed into their constructors.</p> <p>EDIT: Based on the information provided, I've updated my code. The current version is below:</p> <pre><code>public static dynamic CreateDefaultIfNull&lt;T&gt;(this T item) { if (item != null) return item; var type = typeof(T); if (type.IsArray) { return Array.CreateInstance(type.GetElementType(), 0); } if (type.GetConstructor(Type.EmptyTypes) == null) { var paramCount = type.GetConstructors().Min(construct =&gt; construct.GetParameters().Count()); var constructorToUse = type.GetConstructors().Where(construct =&gt; construct.GetParameters().Count() == paramCount).First(); var paramNullList = new object[paramCount]; var parameters = constructorToUse.GetParameters(); for (int i = 0; i &lt; paramCount; i++) { paramNullList[i] = parameters[i].ParameterType.IsValueType ? Activator.CreateInstance(parameters[i].ParameterType) : null; } return Activator.CreateInstance(type, paramNullList); } return Activator.CreateInstance(type); } </code></pre>
[ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-05-06T14:57:22.823", "Id": "86193", "Score": "2", "body": "What will happen if the \"first\" constructor's parameter list has value types (such as `int`)? Will assigning `null` to it blow up?" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-05-06T15:00:32.250", "Id": "86194", "Score": "0", "body": "I attempted that, it assigned the default value for the value type. For example, int defaulted to 0, bool defaulted to false, etc." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-05-06T15:08:32.203", "Id": "86196", "Score": "2", "body": "Huh, cool. Not sure if that's defined behavior, but I like the behavior!" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-05-06T15:09:36.507", "Id": "86197", "Score": "0", "body": "Me too, I was afraid of having to make this more complicated for value types." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-05-06T15:46:04.320", "Id": "86201", "Score": "4", "body": "I'm slightly horrified that this is an extension on `object` and returns `dynamic`. You couldn't just use `T`? Then you'd get type inference at the call site, which might be nice." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-05-06T15:58:03.543", "Id": "86203", "Score": "0", "body": "That was a good catch Magus. Feel free to add that in the answer section and I'll upvote, and if no other responses given, accept" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-05-06T16:28:11.207", "Id": "86206", "Score": "0", "body": "I have my reservations about adding `null` and hoping for the best when it comes to value types. Perhaps using [a small helper method](http://stackoverflow.com/questions/325426/programmatic-equivalent-of-defaulttype) might be warranted? I don't know how far your current usage is defined." } ]
[ { "body": "<p>The biggest problem for me is that this is an extension method on <code>System.Object</code> and returns a <code>dynamic</code>.</p>\n\n<p>Because this is already generic on <code>T</code>, <code>T</code> can be inferred if used as the parameter and return type. It will make invocation simpler at the very least.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-05-06T18:10:25.110", "Id": "49092", "ParentId": "49081", "Score": "5" } }, { "body": "<p>Took a quick look at your code and a few things came to mind.</p>\n\n<hr>\n\n<p>As <a href=\"https://codereview.stackexchange.com/questions/49081/extension-method-to-return-a-default-value-for-any-null-value#comment86201_49081\">Magus</a> mentioned in the comments it seems odd that you have a generic extension method on the <code>object</code> class, which returns a dynamic type. You should (with a few modifications) be able to use the generic type instead:</p>\n\n<pre><code>public static T CreateDefaultIfNull&lt;T&gt;(this T item)\n</code></pre>\n\n<p>Since it rarely makes sense to check value types for null, you could also restrict it to reference types only.</p>\n\n<pre><code>public static T CreateDefaultIfNull&lt;T&gt;(this T item) where T : class\n</code></pre>\n\n<p>You will have to cast the result of <code>CreateInstance</code> before returning.</p>\n\n<hr>\n\n<p>The name is bothering me. The default value for a reference type <em>is</em> null, so if I saw your method used somewhere I would wonder what exactly it returns. (I don't know of a better name though. This method could return all kinds of things.)</p>\n\n<hr>\n\n<p>I would invert the first <code>if</code> statement. It would reduce some of the indentation and I think it looks cleaner:</p>\n\n<pre><code>if(item != null)\n{\n return item;\n}\n...\n</code></pre>\n\n<hr>\n\n<p>I haven't worked much with the <code>GetConstructors</code> method, but in what order is the constructors returned? If there is no guarantee, can you be sure that the first constructor is the most appropriate? </p>\n\n<p>I have often seen constructors that throw exceptions when given null. Is that the behavior you want?</p>\n\n<p>EDIT: If you look <a href=\"http://msdn.microsoft.com/en-us/library/vstudio/e687hf0d\" rel=\"nofollow noreferrer\">here</a>, you will see that there is <em>no</em> guarantee of the order and it is not recommended to depend on the order.</p>\n\n<blockquote>\n <p>The GetConstructors method does not return constructors in a particular order, such as declaration order. Your code must not depend on the order in which constructors are returned, because that order varies.</p>\n</blockquote>\n\n<hr>\n\n<p>Also, as mentioned in the comments, you should probably look into the situation mentioned by <a href=\"https://codereview.stackexchange.com/questions/49081/extension-method-to-return-a-default-value-for-any-null-value#comment86193_49081\">Jesse</a> in the comments. </p>\n\n<blockquote>\n <p>What will happen if the \"first\" constructor's parameter list has value types (such as int)..</p>\n</blockquote>\n\n<p>It might/might not work as you expect in all situations. (I don't know what the defined behavior is)</p>\n\n<hr>\n\n<p>You should be able to change</p>\n\n<pre><code>var paramNullList = new List&lt;object&gt;();\nfor(int i = 0; i &lt; paramCount; i++)\n{\n paramNullList.Add(null);\n}\nreturn Activator.CreateInstance(type, paramNullList.ToArray());\n</code></pre>\n\n<p>to</p>\n\n<pre><code>var nullParams = new object[paramCount]; //All elements null by default.\nreturn Activator.CreateInstance(type, nullParams);\n</code></pre>\n\n<hr>\n\n<p>Finally, your method doesn't work if there is no public constructor. What should happen in that case? You can't select the first constructor if there are none, so <code>First</code> would throw an exception (<code>InvalidOperationException</code> if I remember correctly). </p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-05-06T18:19:13.687", "Id": "86220", "Score": "0", "body": "When I change the return type from dynamic to T, the CreateInstance methods throw an error saying it can't cast to T. I've looked into the issue with the value types, attempting multiple value types as params, and it worked as expecting, giving the default value for the type as if I had called default(T)." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-05-06T18:25:39.940", "Id": "86222", "Score": "0", "body": "With the issue on GetConstructors, allowing nulls passed in is acceptable in this case. If the construction requires values that aren't null, then I want it to throw the exception in that object with the NullPointerException. This helps ensure that if this occurs, that the nulls get handled in the constructor, or that they are explicitly creating a new object with the proper parameters." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-05-06T18:27:43.853", "Id": "86223", "Score": "0", "body": "Seems odd you can't cast to `T`. Create instance is supposed to create an instance of type `T`. If it is the Array.CreateInstance, try to cast to an `object` before casting to `T`." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-05-06T18:29:36.387", "Id": "86224", "Score": "0", "body": "If it is the expected behavior, then that's fine. I was just pointing it out in case you had not thought about it. \nUnless `GetConstructors` is specific about the order of the returned constructors, I still find it odd to \"just select the first\"." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-05-06T19:06:46.407", "Id": "86226", "Score": "0", "body": "I was running on an assumption about the constructors, but probably incorrect, that it would give me the constructors with the least amount of parameters first. I may need to explicitly check the parameter count. My assumption is that the less parameters there is, the less likely of causing obtrusive errors." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-05-06T19:11:58.207", "Id": "86227", "Score": "1", "body": "I just looked it up and found [this](http://msdn.microsoft.com/en-us/library/vstudio/e687hf0d): _The GetConstructors method does not return constructors in a particular order, such as declaration order._" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-05-06T19:18:09.660", "Id": "86229", "Score": "0", "body": "Thanks. I'm updating to search to give me a Min result on a count of params. If there are multiple constructors with the same param count, then I'll take the first constructor it finds that matches the param count." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-05-06T19:44:09.397", "Id": "86231", "Score": "0", "body": "I've looked into the private constructor issue. If there aren't any public constructors, I will get an InvalidOperationException. I believe this is what I want to occur. If a constructor is private, it tells me that an instance of the class shouldn't be made and this method's sole purpose is to create an instance of a class." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-05-06T19:48:45.727", "Id": "86232", "Score": "1", "body": "If it is the expected behavior I will recommend that you throw the exception yourself and not rely on the `First` method to throw the exception. That way it is clear that it really is intended behavior and you can provide an appropriate message." } ], "meta_data": { "CommentCount": "9", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-05-06T18:12:48.607", "Id": "49093", "ParentId": "49081", "Score": "6" } } ]
{ "AcceptedAnswerId": "49093", "CommentCount": "7", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-05-06T14:49:21.650", "Id": "49081", "Score": "6", "Tags": [ "c#", "extension-methods", "null" ], "Title": "Extension method to return a default value for any null value" }
49081
<p>I wrote this memory pool as a code sample for a job interview. It provides a per-class memory pool that can offer faster runtime performance for classes that need to be traversable and (de)allocatable during runtime.</p> <p>Specifically, it provides in-order traversal of the allocated data blocks, to improve cache effectiveness. Both allocation and deallocation are \$O(1)\$ operations. Traversal of the allocated blocks is linear in the number of allocated blocks, with a one-time potentially full traversal of the pool upon the first call to <code>begin()</code> after (de)allocation.</p> <p>The pool stores metadata about the (un)allocated data in two structures both store in a singly linked list. The list of free blocks behaves like a stack: upon an allocation request a single block is popped off the front and upon deallocation a single block is pushed onto it. The list of allocated blocks functions as a singly linked list, and is mainly used for efficient traversal.</p> <p>Any suggestions? Obvious issues? Glaring mistakes?</p> <pre><code>#pragma once #include &lt;iostream&gt; #include &lt;iterator&gt; #include &lt;cassert&gt; template&lt;class T&gt; class Pool { friend class iterator; private: struct Node { T* data; Node* next; bool alloc; }; unsigned int size; ///&lt; The total number of instances that fit in the pool unsigned int nrOfAllocs; ///&lt; How many instances have been allocated T* pool; ///&lt; Starting address of the data block Node* metadata; ///&lt; Storage for the free and allocated block list Node* firstFree, *firstAlloc; ///&lt; Pointers to the first blocks of both lists bool dirty; ///&lt; Flag that is set upon (de)allocation, indicates that cleanup() should be called static Node EndNode; ///&lt; Used by the iterator public: class iterator : public std::iterator&lt;std::forward_iterator_tag, T&gt; { friend class Pool; public: bool operator == (iterator const&amp; rhs) const {return node-&gt;data == (*rhs);} bool operator != (iterator const&amp; rhs) const {return node-&gt;data != (*rhs);} bool operator &lt; (iterator const&amp; rhs) const {return node-&gt;data &lt; (*rhs);} bool operator &lt;= (iterator const&amp; rhs) const {return node-&gt;data &lt;= (*rhs);} bool operator &gt; (iterator const&amp; rhs) const {return node-&gt;data &gt; (*rhs);} bool operator &gt;= (iterator const&amp; rhs) const {return node-&gt;data &gt;= (*rhs);} iterator operator ++ () { node = node-&gt;next == nullptr ? &amp;Pool::EndNode : node-&gt;next; return (*this); } iterator operator ++ (int){ iterator original(*this); node = node-&gt;next == nullptr ? &amp;Pool::EndNode : node-&gt;next; return original; } T* operator * () const { return node-&gt;data; } private: iterator(Pool::Node* node):node(node){} Pool::Node* node; }; class const_iterator : public std::iterator&lt;std::forward_iterator_tag, const T&gt; { friend class Pool; public: bool operator == (const_iterator const&amp; rhs) const {return node-&gt;data == (*rhs);} bool operator != (const_iterator const&amp; rhs) const {return node-&gt;data != (*rhs);} bool operator &lt; (const_iterator const&amp; rhs) const {return node-&gt;data &lt; (*rhs);} bool operator &lt;= (const_iterator const&amp; rhs) const {return node-&gt;data &lt;= (*rhs);} bool operator &gt; (const_iterator const&amp; rhs) const {return node-&gt;data &gt; (*rhs);} bool operator &gt;= (const_iterator const&amp; rhs) const {return node-&gt;data &gt;= (*rhs);} const_iterator operator ++ () { node = node-&gt;next == nullptr ? &amp;Pool::EndNode : node-&gt;next; return (*this); } const_iterator operator ++ (int){ const_iterator original(*this); node = node-&gt;next == nullptr ? &amp;Pool::EndNode : node-&gt;next; return original; } const T* operator * () const { return node-&gt;data; } private: const_iterator(Pool::Node* node):node(node){} Pool::Node* node; }; /** \note Calling begin() triggers a potentially full traversal of the pool after a (de)allocation. */ iterator begin() { cleanup(); if ( firstAlloc == nullptr ) return iterator(&amp;Pool&lt;T&gt;::EndNode); return iterator(firstAlloc); } iterator end() const { return iterator(&amp;Pool&lt;T&gt;::EndNode); } /** \param size Integer representing the number of instances that should be able to fit in the pool. */ Pool(unsigned int size = 1024):size(size),nrOfAllocs(0),dirty(false),firstAlloc(nullptr) { // Allocate pool and metadata pool = static_cast&lt;T*&gt;(malloc(size * sizeof(T))); metadata = new Node[size]; firstFree = &amp;metadata[0]; assert(firstFree != nullptr); // Initialise nodes for ( int i = 0; i &lt; size; ++i ) { metadata[i].data = pool + i; metadata[i].next = &amp;metadata[i+1]; assert(metadata[i].next != nullptr); metadata[i].alloc = false; } metadata[size-1].next = nullptr; // Setup end node Pool::EndNode.data = pool + size; } ~Pool() { free(pool); delete[] metadata; } /// Called by new. Pops a free block, marks it and returns the associated pool address T* alloc() { // Check if we have free blocks left if ( firstFree == nullptr ) { std::cout &lt;&lt; "Pool out of memory!" &lt;&lt; std::endl; abort(); } // Pop front free node Node* n = firstFree; firstFree = n-&gt;next; // Set metadata n-&gt;alloc = true; ++nrOfAllocs; dirty = true; // Fix head if ( firstAlloc == nullptr || firstAlloc-&gt;data &gt; n-&gt;data ) firstAlloc = n; return n-&gt;data; } /// Called by delete. Marks the block as unused, and pushes it on the free list. void free(void* block) { // Get node T* data = static_cast&lt;T*&gt;(block); int i = data - pool; assert(i &gt;= 0 &amp;&amp; i &lt; size); Node* n = &amp;metadata[i]; assert(n-&gt;data == block); // Fix head if ( firstAlloc == n ) firstAlloc = n-&gt;next; // Return node to free list n-&gt;next = firstFree; firstFree = n; // Set metadata n-&gt;alloc = false; --nrOfAllocs; dirty = true; } /// Called by begin if the pool is marked as dirty. Recreates the linked list for allocated blocks for efficient traversal. void cleanup() { if ( dirty &amp;&amp; nrOfAllocs &gt; 0 ) { int allocsFound = 0; int i = firstAlloc-&gt;data - pool; Node* n = firstAlloc; // Only search within the range we know has allocated blocks while ( allocsFound &lt; nrOfAllocs &amp;&amp; (i+1) &lt; size ) { if ( metadata[i+1].alloc ) { ++allocsFound; n-&gt;next = &amp;metadata[i+1]; assert(n-&gt;next != nullptr); n = &amp;metadata[i+1]; } ++i; } n-&gt;next = nullptr; dirty = false; } } }; template &lt;class T&gt; typename Pool&lt;T&gt;::Node Pool&lt;T&gt;::EndNode = {nullptr, nullptr, false}; </code></pre>
[]
[ { "body": "<blockquote>\n <p>Any suggestions? Obvious issues? Glaring mistakes?</p>\n</blockquote>\n\n<p>A few observations:</p>\n\n<ul>\n<li>you are including iostream ... consider removing it, since you have no i/o code (none that I could see)</li>\n<li>consider defining your allocation data as:</li>\n</ul>\n\n<p>Code:</p>\n\n<pre><code>struct Node { // name should be changed\n T* data;\n bool alloc;\n};\n</code></pre>\n\n<p>... and defining your allocation list using std::forward_list; This way you will make your code smaller and more idiomatic, increase code reuse and use an already tested implementation of a list.</p>\n\n<ul>\n<li><p>Your iterator and const_iterator classes are identical, except for one defining a <code>T*</code> accessor and the other one a <code>const T*</code> accessor. Consider either writing a templated, common implementation and <code>typedef</code>-ing it to iterator and const_iterator depending on the type, or (as some std:: implementations of iterators do) implementing first the const_iterator, then inheriting the iterator from it and adding a non-const accessor to the implementation.</p></li>\n<li><p>Never mix malloc/free and new/delete in the same code; for C++, always use new and delete, and prefer to not do so directly.</p></li>\n</ul>\n\n<p>That means, replace this code:</p>\n\n<pre><code>Node* metadata;\n\n// ...\n\nPool(unsigned int size = 1024) // ...\n{\n // Allocate pool and metadata\n pool = static_cast&lt;T*&gt;(malloc(size * sizeof(T)));\n metadata = new Node[size];\n firstFree = &amp;metadata[0];\n</code></pre>\n\n<p>with this:</p>\n\n<pre><code>std::vector&lt;T&gt; pool;\nstd::vector&lt;Node&gt; metadata;\n\n// ...\n\nPool(unsigned int size = 1024) // ...\n{\n // Allocate pool and metadata\n pool.reserve(size);\n metadata.reserve(size);\n firstFree = &amp;metadata[0];\n</code></pre>\n\n<p>This will make your destructor trivial, and after this, your destructor should be removed (the code that is easiest to maintain is the one you don't have to write at all).</p>\n\n<ul>\n<li>Use assertions for checking your invariants, not failed operations; For operations that can fail, use exceptions.</li>\n</ul>\n\n<p>Example:</p>\n\n<pre><code> pool = static_cast&lt;T*&gt;(malloc(size * sizeof(T)));\n metadata = new Node[size];\n firstFree = &amp;metadata[0];\n assert(firstFree != nullptr); // &lt;- if(!firstFree) throw &lt;your-exception-here&gt;\n</code></pre>\n\n<p>Otherwise you will have a class that (instead of reporting an error to client code) stops your application with <em>assertion failed</em>. Consider that, as it is right now, you will be unable to write a unit test for <code>Pool(100000000);</code> (such a unit test would not pass with a \"failed allocations\" message, but stop your unit testing suite execution).</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-05-07T10:38:08.913", "Id": "86316", "Score": "0", "body": "Thank you for your suggestions. Good points about the asserts and template for the iterators, I am going to look into that. :) The iostream header is currently used for displaying the error message upon overflow of the memory pool. I don't think the forward_list would work here, since I basically store two linked lists (one for allocated blocks and one for free blocks) in one list. Also, if I were to use new for the memory block allocation instead of malloc, I would call the constructors, wouldn't I? I explicitly need to call the constructor upon the call to alloc()." } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-05-07T07:41:02.713", "Id": "49122", "ParentId": "49084", "Score": "1" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-05-06T16:32:48.613", "Id": "49084", "Score": "3", "Tags": [ "c++", "memory-management" ], "Title": "Traversable memory pool" }
49084
<pre><code>Student http://semisalsaja.com/sekolah/student.asmx?WSDL - studentList Mentor http://semisalsaja.com/sekolah/mentor.asmx?WSDL - mentorList study http://semisalsaja.com/sekolah/study.asmx?WSDL - studyList </code></pre> <p>I'm trying to get data from some SOAP resources (mentioned above):</p> <pre><code>class SchoolSoap { protected $_config = array(); public $_soap, $_error, $_params, $_result; public function __construct($params = array()) { $this-&gt;_config = $params; try { $this-&gt;_soap = new SoapClient($this-&gt;_config['url'], array('trace' =&gt; 1, 'exception' =&gt; 1)); } catch (Exception $e) { $this-&gt;_error = $e-&gt;getMessage(); } } public function actionSoap($function) { try { $result = $this-&gt;_soap-&gt;__soapCall($function, array('parameters' =&gt; $this-&gt;_params)); $this-&gt;_result = $result; return true; } catch (Exception $e) { $this-&gt;_error = $e-&gt;getMessage(); return false; } } public function setParam($params) { $this-&gt;_params = $params; return $this; } } </code></pre> <p>The 1<sup>st</sup> class is for calling SOAP and it will be called/ instanced from static classes.</p> <pre><code>class StudentHelper { public static function getStudentList($config, $params, SchoolSoap $soap = null) { $function = 'studentList'; if ($soap == null) { $soap = new SchoolSoap($config); } $result = $soap-&gt;setParam($params)-&gt;actionSoap($function); if ($result == false) { return false; } else { return $soap-&gt;_result-&gt;$function; } } } class MentorHelper { #similar with class StudentHelper } class StudyHelper { #similar with class StudentHelper } </code></pre> <p>The next next classes (I called Helper) are static class. I created resources <code>Student</code>, <code>Mentor</code>, <code>Study</code>, for every SOAP. For example, in class <code>StudentHelper</code>, there is a method named <code>getStudentList</code> that will get the student's data, and it will be called from a function (next code). class <code>Mentor</code> and <code>Study</code> are similar.</p> <p><strong>Usage</strong></p> <pre><code>function printStudentList() { $config = array( 'url' =&gt; 'http://semisalsaja.com/sekolah/student.asmx?WSDL', 'username' =&gt; 'user123', 'key' =&gt; 'abcdefghij' ); $params = array('start' =&gt; 1, 'limit' =&gt; 20); return StudentHelper::getStudentList($config, $params); } </code></pre> <p>Next is function to call Static class (example, call <code>StudentHelper</code>). I passed configs and params in this function, and it will return bool false if soap failed and data of student if soap succeeded.</p> <pre><code>$student_list = printStudentList(); print_r($student_list); </code></pre> <p>Here I call parse function into variable, then print the variable.</p> <p>Is my design correct with the concept of OOP in PHP? Any suggestion for me to make it better? I'm still new to learning about programming, especially OOP.</p>
[ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-05-08T12:49:04.363", "Id": "86510", "Score": "0", "body": "Hi Jamal,\nThank you for editing my question so can be more understandable for others." } ]
[ { "body": "<p>Ok, given that you're after some CR on your understanding (and usage) of OO techniques, I'll go through your code almost line by line. If my criticisms strike you as blunt, please keep in mind that my goal is to help, not to offend.</p>\n\n<p><strong><em>Coding standards</em></strong><Br>\nThis has become a bit of a hang-up of mine, but I can't stress enough how important it is to write code that conforms to some form of standard. PHP, of course, does not (yet) have an official standard as such, but the unofficial <a href=\"http://www.php-fig.org\" rel=\"nofollow noreferrer\">PHP-FIG</a> standard is widely accepted, and all major players (Zend, Symfony, CakePHP, ... the list is on the site) subscribe to this standard. As should you.</p>\n\n<p>This entails, among other things:</p>\n\n<ul>\n<li>property names don't start with an underscore to indicate visibility (private, protected). That's what we did in the PHP4 days. I think none of us is willing to go back to that era.</li>\n<li>Opening braces for methods, functions and classes go on a new line</li>\n<li>Code is indented by spaces, 4 of them, tabs are not to be used. If you use nothing but tabs, then that's an acceptable deviation from the standard, but be consistent. SVC's like Git will give you grief otherwise.</li>\n<li>access modifiers aren't optional, they are required.</li>\n<li>Method names are camelCased, variables/properties are either camelCased or you can use underscores. Either way: be consistent. I prefer camelCased properties.</li>\n</ul>\n\n<p><strong><em>Type-hinting all the way</em></strong><br>\nI see you use the occasional type-hint. That's great! Fantastic even, but you're not using them as much as you can. You can't hint for primitive types, but you <em>can</em> use doc-blocks, casts and you <strong>can</strong> hint for <code>array</code> variables.<br>\nMore on this later.</p>\n\n<p><strong><em>Your code, at a glance</em></strong><br>\nRather than listing my recommendations and linking to the wiki of the <a href=\"http://en.wikipedia.org/wiki/SOLID_(object-oriented_design)\" rel=\"nofollow noreferrer\">SOLID principles</a>, let's get stuck in and review your actual code. I'll already change a thing or 2 to make your code more readable (ie conforming to the PHP-FIG standards):</p>\n\n<pre><code>class SchoolSoap\n{\n /**\n * @var array\n */\n protected $config = array();\n</code></pre>\n\n<p>Stop here (yes, already). I've removed the underscore, but I wonder: why are you initializing your property to an empty array, if you have a constructor that will always re-assign that property? Just initialize the properties to <code>null</code> if you don't need them to have a specific default value.<br>\nI've also added a doc-block that makes it clear to everyone what this property is expected to be, what you'll assign it to, and how it'll be used. This will help your IDE provide you with useful auto-completion info, and error reporting.</p>\n\n<pre><code> /**\n * @var \\SoapClient\n */\n public $soap = null;\n /**\n * @var string|null\n */\n public $error = null;\n //add your own doc-blocks from now on :)\n public $params = null;\n public $result = null;\n</code></pre>\n\n<p>Now, the methods:</p>\n\n<pre><code> /**\n * Some info about the construct, will show in auto-complete\n * with any decent IDE\n * @param array $params = array()\n * @return $this\n */\n public function __construct(array $params = array())\n {\n $this-&gt;config = $params;\n try\n {//this is non-standard, but I use allman indentation\n //that's my guilty pleasure\n $this-&gt;soap = new SoapClient(\n $this-&gt;config['url'],\n array(\n 'trace' =&gt; 1,\n 'exception' =&gt; 1\n )\n );\n }\n catch (Exception $e)\n {\n $this-&gt;error = $e-&gt;getMessage();\n }\n }\n</code></pre>\n\n<p>So, I've cleaned up a bit, but there are still quite a few issues left. For starters: you allow for the user to pass an array <code>$params</code> to the constructor. If he fails to do so, then that's fine, but the array defaults to an <em>empty array</em>. That, too, isn't a problem, but what is problematic is that you create the instance of <code>SoapClient</code> using <code>$this-&gt;config</code> as though it <em>is an associative array</em> and as though it has <em>certain keys set</em>!. You don't do any <code>isset</code> checks (meaning your code might emit notices).</p>\n\n<p>Then, if the <code>SoapClient</code> could not be constructed, you catch any <code>Exception</code> that might have been thrown. But <code>SoapClient</code> doesn't throw <code>Exception</code> instances, it throws a specific type of exceptions: <code>SoapFault</code>.<br>\nCatching any higher (as in parent of a particular exception) type of exception is known as <a href=\"http://www.dodgycoder.net/2011/11/yoda-conditions-pokemon-exception.html\" rel=\"nofollow noreferrer\">pokemon exception handling</a>. It reads as if the code was written by somebody who didn't really know what to expect.</p>\n\n<p>Not that this really matters, because your entire class revolves around this <code>SoapClient</code> instance being set. If it fails, then your class shouldn't be allowed to exist. It's likely that the code creating the instance contains a bug, and provided faulty data. That kind of thing should be communicated immediately: the error shouldn't be caught by you, because you can't fix it: the error should be thrown back to the user! That's Why I'd suggest you write this as a constructor:</p>\n\n<pre><code>/**\n * Simple wrapper constructor\n * @param string $wsdl\n * @param array $options = null\n * @return $this\n * @throw SoapFault\n */\npublic function __construct($wsdl, array $options = null)\n{//make options null by default, but force wsdl to be passed explicitly\n $this-&gt;config = $options\n $this-&gt;soap = new SoapClient(\n $wsdl,\n $this-&gt;config\n );\n}\n</code></pre>\n\n<p>We end up with less code, but again: with a decent IDE, you'll get more information about what this constructor does when you type <code>new SchoolSoap(</code>.<br>\nYou no longer need the <code>$this-&gt;error</code> property, and don't have to hope that the user will check that property's value: if an error occurred, he'll get an exception thrown at him, which is as it should be!</p>\n\n<p>The other methods should be easy to improve, along the same lines:</p>\n\n<pre><code>/**\n * Perform a soapCall to $function, passing $parameters\n * If no parameters are provided, $this-&gt;params will be used\n * @param string $function\n * @param array $parameters = null\n * @return bool\n * @throw SoapFault\n */\npublic function actionSoap($function, array $parameters = null)\n{\n if ($parameters === null)\n $parameters = $this-&gt;params;\n //assign to property directly, don't use temp var... no need\n $this-&gt;result = $this-&gt;soap-&gt;__soapCall(\n $function,\n array(\n 'parameters' =&gt; $parameters\n )\n );\n return true;//wouldn't return $this-&gt;result; be more usefull?\n}\n</code></pre>\n\n<p>The setter methods are a great idea. I especially like their being fluent (chainable), nothing but formatting needs to change there:</p>\n\n<pre><code>public function setParam($params)\n{\n $this-&gt;params = $params;\n return $this;\n}\n</code></pre>\n\n<p><strong><em>A wrapper is best when it exposes its object</em></strong><Br>\nWhat you have written here is, essentially, a wrapper object: it wraps an instance of <code>SoapClient</code>, to offer a different (possibly neater, safer and clearer) API.<br>\nHowever, I need a <em>reason</em> to use a wrapper, it should allow me to do what I want. This wrapper severely restricts my usage of the <code>SoapClient</code> class. What's to stop me from simply writing this:</p>\n\n<pre><code>$schoolSoap = new SoapClient($wsdl, $options);\n$result = $schoolSoap-&gt;__soapCall($function, $params);\n</code></pre>\n\n<p>A wrapper should somehow expose some of the internals of the wrapped object, but perhaps check the arguments that the user is trying to pass, or at least offer constants that the user can use to facilitate the manipulation of the wrapped object. The blindest, slowest, but easiest way to do so is by implementing a magic <code>__call</code> method in your <code>SchoolSoap</code> class:</p>\n\n<pre><code>public function __call($method, array $args)\n{\n if (method_exists($this-&gt;soap, $method))\n {//perhaps add an is_callable check here, too\n $return = call_user_func_array(\n array($this-&gt;soap, $method),\n $args\n );\n if ($return === $this-&gt;soap)\n return $this;//don't return the wrapped object\n return $return;\n }\n throw new \\BadMethodCallException(\n sprintf(\n \"Method '%s' does not exist in classes %s and %s\",\n $method,\n __CLASS__,\n get_class($this-&gt;soap)\n )\n );\n}\n</code></pre>\n\n<p>Of cours, a safer way is to implement certain methods of the wrapped objects in your wrapper, check the arguments and <em>then</em> call the wrapped object's method:</p>\n\n<pre><code>public function getLastResponse($fromObject = false)\n{\n if ($fromObject === false)\n return $this-&gt;result;//as set in the `actionSoap` method\n return $this-&gt;soap-&gt;__getLastResponse();//from wrapped object\n}\n</code></pre>\n\n<p>This is a clean, easy to maintain and safe way to expose your wrapped object, and it doesn't give me, as a user, a reason <em>not</em> to use your class.<br>\nOf course, if you do this, then you don't need that slow magic <code>__call</code> method anymore, and you can simply do away with that (as well you should).<br>\nAn in-between solution is to have a <code>private</code> property, holding an array with methods that can be called by the user, and use those in your <code>__call</code> method. That saves you some <code>method_exists</code> calls.</p>\n\n<p>Ok, I'll leave you with this final recommendation concerning the first of your classes:</p>\n\n<p>Passing arrays to constructors is easy, and shortens the number of arguments your methods take. I can see why one would do this. However, if you are going to write OO code, then it can be safer/better still to pass <em>data objects</em> containing that same information. You can type-hint for those specific objects, and be sure that the properties you need will exist.</p>\n\n<p>I could post an example here, but instead I'd invite you to check <a href=\"https://github.com/EVODelavega/activecampaign-api-php\" rel=\"nofollow noreferrer\">this github fork of mine</a>, and in particular <a href=\"https://github.com/EVODelavega/activecampaign-api-php/blob/master/src/AC/Arguments/Config.php\" rel=\"nofollow noreferrer\">the <code>Config</code> class</a>. The <code>Config</code> is what, logically, configures the behaviour of all classes that make API calls. By hinting for an instance of that object in the constructor, I can rest assured that things like the url, usage mode, user and API-KEY will be set, and ready to be used. I use getters and setters throughout the code, to ensure my data is correctly formatted and sanitized, too.<br>\nthere are some magic getters and setters, and I thing also a magic <code>__call</code> method somewhere, but I'm still working on the code, to get rid of them.</p>\n\n<p>If you compare my fork to the code I started off with, I think it's pretty clear that passing data objects is a big step forwards.</p>\n\n<hr>\n\n<p>There are other things in your code that I will discuss further (like your use of the dreaded <code>static</code> keyword), so I will be adding to this answer from time to time. For now, though, I think I've given you sufficient food for thought.</p>\n\n<p><strong><em>Update</em></strong></p>\n\n<p>As promised: Back for some more reviewing-stuff. I'll start off with that one helper class you've included, and take it from there. I already mention the <code>static</code> keyword isn't to my liking. Why isn't it? Well, <code>static</code> properties/variables are variables that retain their state. That means that, if a function has a static variable, and you assign a value to that var, that value is kept in memory in between function calls.<br>\nClass properties work similarly, but that value is shared between all instances of that class. You can also access that property at without an instance, as though it were a global variable. And that's the problem with statics: they are, essentially globals in OO disguise, and we all know globals are bad.</p>\n\n<p>Same goes for your method: it works like a function, and is globally accessible, like a global function. Only, static method calls are slower than function calls! Then why bother with a class, and not simply create a function?<br>\nThat would, indeed be better than what you have now, but it's not in tune with your wanting to write more OO code</p>\n\n<p>So let's make it object oriented, and make good use of the advantages of OOP: you can use properties to store certain things, and like, for example your <code>SoapClient</code> instance. At the moment, you create a new <code>SoapClient</code> instance every time you instantiate <code>SchoolSoap</code>. Wouldn't it be nice if we only had to do that once? Your static method now creates a new <code>SchoolSoap</code> instance every time it is called, without being passed an existing instance already, because its functionality <em>depends</em> on that <code>SchoolSoap</code> being there. What's more: it's function in your program is a specific use-case of the capabilities of <code>SchoolSoap</code>. So its job is the same (performing a SOAP call), only its a specific type of call.</p>\n\n<p>In OO code, it wouldn't be uncommon to see <code>StudentHelper</code> being a child of <code>SchoolSoap</code>. Therefore, I suggest you go down that route, and use inheritance:</p>\n\n<pre><code>class StudentHelper extends SchoolSoap\n{\n public function getStudentList($params)\n {\n $result = $this-&gt;setParam($params)\n -&gt;actionSoap('studentList');\n if (!$result)\n return $result;\n return $result-&gt;studentList;//or $this-&gt;_result-&gt;studentList;\n }\n}\n</code></pre>\n\n<p>All the calls you have, that deal with students go in this class, and for each group of calls, you can create a new child class of <code>SchoolSoap</code>.<Br>\nThe usage is very simple:</p>\n\n<pre><code>$student = new StudentHelper($config);//what you pass to SchoolSoap's constructor\n$studentList = $student-&gt;getStudentList($params);\n$student-&gt;addStudent($params);//if that call exists\n</code></pre>\n\n<p>All of the goodies that <code>SchoolSoap</code> (methods and properties) are also properties of <code>StudentHelper</code> now (except for private properties), same goes for methods.</p>\n\n<p>Of course, now the name <code>StudentHelper</code> is a bit weird, because it isn't a helper anymore: it's a full-blown wrapper, too, so I'd change the name of <code>SchoolSoap</code> to <code>BaseSoap</code>, because it's your base class, and change <code>StudentHelper</code> to <code>StudentSoap</code> or something, to better reflect what the class is.</p>\n\n<p>I've posted a review of a singleton class on this site a while back. In it, I go into more details on why statics are to be avoided, feel free to check it out:</p>\n\n<p><a href=\"https://codereview.stackexchange.com/questions/42771/singleton-design-pattern/42847#42847\">Singleton design pattern</a></p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-05-08T12:47:40.560", "Id": "86509", "Score": "0", "body": "Hi Elias,\nThank you for your explanation. it is a positive feedback for me, because I am new in programming. I'll read it first and learn it. I also would be happy if you continue your explanation about static keyword. Thank you so much." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-05-08T13:05:00.507", "Id": "86511", "Score": "0", "body": "@Rijalulfikri: Rest assured, I will get into that `static` business. Quite busy ATM, but will try to get 'round to it in a couple of hours. Main thing is: your `static` methods work exactly the same way as regular functions do, only static methods are slower. There is an OO alternative, which I'll explain in detail... just a tip: it uses the class I already reviewed, and adds functionality to it ;-)" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-05-09T15:22:18.100", "Id": "86772", "Score": "0", "body": "@Rijalulfikri: As promised: I've edited my answer, adding information on the helper classes" } ], "meta_data": { "CommentCount": "3", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-05-07T14:19:15.090", "Id": "49148", "ParentId": "49095", "Score": "2" } } ]
{ "AcceptedAnswerId": "49148", "CommentCount": "1", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-05-06T18:21:09.707", "Id": "49095", "Score": "2", "Tags": [ "php", "object-oriented", "classes", "prototypal-class-design" ], "Title": "Get data from some SOAP resources" }
49095
<p>Implemented observers in C++11 in a generic and statically accessible way. Though an instance is created, it's used only for cleanup and lifetime management.</p> <pre><code>template&lt;typename... Args&gt; class Observers { private: unordered_map&lt;int, vector&lt;function&lt;void(Args...)&gt;&gt;&gt; observers; static Observers&lt;Args...&gt; *instance; public: Observers() { instance = this; } template&lt;typename Observer&gt; static void Register(int ev, Observer &amp;&amp;observer) { instance-&gt;observers[ev].push_back(forward&lt;Observer&gt;(observer)); } static void Notify(int ev, Args... args) { try { auto &amp;obs = instance-&gt;observers.at(ev); for (auto &amp;o : obs) o(args...); } catch (...){} } }; template&lt;typename... Args&gt; Observers&lt;Args...&gt; *Observers&lt;Args...&gt;::instance; </code></pre> <p>usage:</p> <pre><code>using IntIntObservers = Observers &lt; int, int &gt; ;//optional type declaration IntIntObservers o;//observer instance IntIntObservers::Register(1, [=](int a, int b){whatever}); IntIntObservers::Notify(1, 4, 5); </code></pre> <p>An observer set can be accessed statically as long as the instance is alive. Multiple instances of the same type could be achieved by adding an id parameter to the template declaration, making it </p> <pre><code>template&lt;int id, typename... Args&gt; </code></pre> <p>Anything that I missed and could be improved?</p>
[]
[ { "body": "<p>Briefly, I find the following:</p>\n\n<ul>\n<li><p>The current static behaviour is not <em>intuitive</em> (what does <code>int ev</code> really mean? why numbers and not names?), not <em>efficient</em> (why search in an <code>unordered map</code> rather that direct access?) and not <em>thread-safe</em> (<code>instance</code> is shared among all threads).</p></li>\n<li><p>A <code>list</code> might be more appropriate to store observers of one event, enabling easier management like <em>removing</em> an observer.</p></li>\n<li><p>Catching all <em>exceptions</em> in such a generic tool is a limitation. If needed, it could be at least parametrized.</p></li>\n<li><p>Parameter pack <code>Args...</code> does not take into account <em>return types</em>.</p></li>\n<li><p>Your <code>Notify</code> takes its arguments by value. Forwarding is not appropriate when calling multiple functions, but at least arguments should be passed <em>by reference</em>.</p></li>\n</ul>\n\n<p>At a very basic level, I would prefer an object, called e.g. <code>signal</code>, templated on full function signature e.g. <code>R(A...)</code>, with non-static members:</p>\n\n<ul>\n<li><p>(private) <code>observers</code>: <code>std::list</code> or some associative container of <code>std::function&lt;R(A...)&gt;</code></p></li>\n<li><p><code>add()/remove()</code> or <code>connect()/disconnect()</code> to manage the content of <code>observers</code>. <code>remove()</code> would need some form of identification of existing observers, hence the need for an associative container.</p></li>\n<li><p><code>operator()(A&amp;&amp;... a)</code> so that <code>signal</code> behaves like a function object. Arguments <code>a...</code> are passed without forwarding to underlying functions, so that they are copied if needed, and not invalidated between subsequent calls.</p></li>\n<li><p>additional management like <code>clear()/empty()</code>.</p></li>\n</ul>\n\n<p>Your example usage would be rather like</p>\n\n<pre><code>signal&lt;void(int, int)&gt; s;\ns.connect([=](int a, int b){whatever});\ns(4, 5);\n</code></pre>\n\n<p>Isn't that better? Since everything is non-static, the user controls how many instances there are, and names them properly. In fact, a single object may have e.g. ten methods, each with its own observers. Each such method is then a signal and behaves like a function object.</p>\n\n<p>Additionally</p>\n\n<ul>\n<li><p><code>std::function</code> expects the 1st argument of a call to be the object if bound on a <em>member function</em>. It would be much more convenient to have functionality such that the object is stored separately and the <code>signal</code>'s signature matches exactly that of the member function. In many applications everything is about objects + member functions rather than free functions.</p></li>\n<li><p>Though non-trivial, possibly provide a mechanism to collect return values of called (observer) functions plus policies to choose, compute and return a single return value from <code>operator()</code>.</p></li>\n</ul>\n\n<p>Have a look at <a href=\"http://www.boost.org/doc/libs/1_55_0/doc/html/signals.html\" rel=\"nofollow\">boost::signals</a> and <a href=\"http://www.boost.org/doc/libs/1_55_0/doc/html/signals2.html\" rel=\"nofollow\">boost::signals2</a> for more ideas.</p>\n\n<p>I have implemented my own model in the past, using <a href=\"http://www.codeproject.com/Articles/11015/The-Impossibly-Fast-C-Delegates\" rel=\"nofollow\">delegates</a> instead of <code>std::function</code>. There is an amazing amount of additional work if such \"signals\" are to fully mimic functions or member functions, including:</p>\n\n<ul>\n<li>default arguments (arbitrary values encoded into <em>types</em> in the signature itself)</li>\n<li>overloading (with different signatures)</li>\n<li>inheritance (overriding member functions in base/derived classes)</li>\n<li>virtual functions</li>\n<li>...</li>\n</ul>\n\n<p>I have used it as a full C++-compliant replacement for <a href=\"http://qt-project.org/doc/qt-4.8/signalsandslots.html\" rel=\"nofollow\">Qt signals/slots</a> and wrapped most of the <a href=\"http://qt-project.org/doc/qt-4.8/qtgui.html\" rel=\"nofollow\">Qt Gui module</a> so that a project can be built without <a href=\"http://qt-project.org/doc/qt-4.8/moc.html\" rel=\"nofollow\">moc</a> and without <a href=\"http://qt-project.org/doc/qt-4.8/qmake-manual.html\" rel=\"nofollow\">qmake</a>. One day I will hopefully clean and rewrite in C++11.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-05-07T10:00:19.153", "Id": "86304", "Score": "0", "body": "In my experience, std::list is slower than std::vector, even when complexity says otherwise. Arrays are just that much faster on C++. The event type is an int because I felt like using enums, it could be a templated type." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-05-07T10:54:26.310", "Id": "86318", "Score": "0", "body": "@user1560102 `std::list`: depends on usage. Event \"types\": ok, let us put all our `double` variables of a program into a static `unordered_map<int, double>` called `DoubleVariables` and use a number instead of a name to `Register` or `Get` each variable as an entry in this map. How does this look? To me, it looks like assembly." } ], "meta_data": { "CommentCount": "2", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-05-07T01:58:43.553", "Id": "49112", "ParentId": "49096", "Score": "2" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-05-06T18:32:48.493", "Id": "49096", "Score": "5", "Tags": [ "c++", "design-patterns", "c++11" ], "Title": "Generic observer pattern implementation in C++" }
49096
<p>I'm just starting out in Haskell and have been set an assignment for uni where I have to create a reverse index of words in a text file and find what line numbers they appear on. I also have to remove any stop words like "the" or "and" that aren't needed.</p> <p>So far I have this, but I feel that there should be a better way to remove duplicates from a list and to filter by non-letters:</p> <pre><code>module Main where import qualified Data.List as List import qualified Data.Char as Char import qualified Data.Set as Set import qualified Data.Maybe as Maybe main = do -- load file to be indexed and stop words text &lt;- readFile "test.txt" stopWords &lt;- readFile "stopWords.txt" -- convert all chars to lower case, split by lines, then split by words let word = map words (lines (map Char.toLower text)) let stopWord = map words (lines (map Char.toLower stopWords)) -- concatenate lists, remove non letters, then remove any empty list elements let word' = filter (not.null) (map (filter Char.isLetter) (concat word)) let stopWord' = filter (not.null) (map (filter Char.isLetter) (concat stopWord)) -- cast both lists to a set to remove duplicates and remove any instances of stopWord' from word' let index = Set.toList (Set.difference (Set.fromList word') (Set.fromList stopWord')) -- get line numbers from indexed words let lineNumbers = generateIndex index word -- zip index of words with line numbers and print mapM print (List.zip index lineNumbers) generateIndex :: [String] -&gt; [[String]] -&gt; [[Int]] generateIndex xs y = foldr (\ x -&gt; (++) [getLineNumbers x y]) [] xs getLineNumbers' :: String -&gt; [[String]] -&gt; Int -&gt; [Int] getLineNumbers' x [] n = [] getLineNumbers' x (y:ys) n | x `elem` y = n : getLineNumbers' x ys (n + 1) | otherwise = getLineNumbers' x ys (n + 1) getLineNumbers :: String -&gt; [[String]] -&gt; [Int] getLineNumbers x y = getLineNumbers' x y 1 </code></pre>
[]
[ { "body": "<p>Think carefully about what data structure you're using, lists aren't always the best choice. In this case you need to do two major things with your words.</p>\n\n<ol>\n<li>Associate words with the line number they first appear on.</li>\n<li>Remove words from one group using entries from another.</li>\n</ol>\n\n<p>Right off the bat whenever you need to associate one set of elements with another, you should think of a map. In Haskell, you'll want to look at the documentation for <a href=\"http://hackage.haskell.org/package/containers-0.5.5.1/docs/Data-Map-Lazy.html\" rel=\"nofollow\"><code>Data.Map</code></a>.</p>\n\n<p>By reordering and reconsidering the operations you're performing on lists and sets, you should be able to rewrite your code to use maps and significantly cut down the amount of code you have written and end up with something more expressive too.</p>\n\n<p>As it isn't clear that you've actually turned in this assignment I'm afraid I'll have to be coy, but here's the most pointed help I can give you on your specific questions.</p>\n\n<p>Regarding removing duplicate words, the trick is to rely on the fact that maps can only contain a given key once. Pay close attention to the various ways of constructing a list that are specified in the documentation for <code>Data.Map</code>.</p>\n\n<p>Filtering out the non-letters in a string doesn't get much simpler than <code>filter Char.isLetter</code> in your code above. The dissatisfaction you are feeling might be because of the gross duplication between the definitions of <code>word</code> and <code>stopWord</code>, and <code>word'</code> and <code>stopWord'</code>. Any time you have two lines in Haskell that are identical but for the value you're operating on, your code is crying out for a new function definition.</p>\n\n<p>Your code is lingering in IO far more than is necessary, pull the pure data manipulating machinery out into separate functions. To start you off, knowing no more than the type signatures I've given here, what do you think these functions do? What part of your code do they replace? Take a shot at defining them.</p>\n\n<pre><code>normalize :: String -&gt; String\n??? :: [a] -&gt; [(a, Int)]\n??? :: String -&gt; [([String], Int)]\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-05-07T13:02:44.900", "Id": "86328", "Score": "0", "body": "Thanks for the suggestions. I've made a normalize function like you suggested which took out a few messy lines of code and has made it a bit more readable. In terms of using a map to not allow duplicates, what's the difference between that and a set like I've used? A set won't allow duplicates either. I could be wrong, but I haven't found a way of having a list of Ints inside a map which is needed for an index" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-05-07T19:59:14.440", "Id": "86424", "Score": "0", "body": "The trick (and it's a little tricky) is to leverage one of the ways of constructing a `Map` to achieve both de-duping and associating words with the first line number they appear on at once. Check out [`fromListWith`](http://hackage.haskell.org/package/containers-0.5.5.1/docs/Data-Map-Lazy.html#v:fromListWith) (and maybe [`insertWith`](http://hackage.haskell.org/package/containers-0.5.5.1/docs/Data-Map-Lazy.html#v:insertWith) to understand its semantics)." } ], "meta_data": { "CommentCount": "2", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-05-07T00:07:11.880", "Id": "49107", "ParentId": "49099", "Score": "1" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-05-06T21:48:45.320", "Id": "49099", "Score": "2", "Tags": [ "haskell", "functional-programming" ], "Title": "Removing duplicates from list and filtering non-letter characters" }
49099
<p>This is an example of my filesystem:</p> <ul> <li>/code/ <ul> <li>internal/ <ul> <li>dev/</li> <li>main/</li> </ul></li> <li>public/ <ul> <li>dev/</li> <li>main/</li> <li>release/</li> </ul></li> <li>tools/</li> </ul></li> </ul> <p>/code/internal/dev/, /code/public/dev/ and /code/tools/ contain subdirectories for multiple projects. I work almost exclusively in the dev branches of /code/internal/ and /code/public/, and often I want to search for a text string in those directories along with /code/tools/ (which has no branches). In these instances I run a command like this:</p> <pre><code>grep -I -r FooBar /code/internal/dev/ /code/public/dev/ /code/tools/ </code></pre> <p>Additionally, sometimes I am only interested in certain file types. Then the command becomes:</p> <pre><code>grep -I -r FooBar /code/internal/dev/ /code/public/dev/ /code/tools/ | grep .c:\|.h: </code></pre> <p>I usually forget this command between usages and end up having to relearn it. To alleviate that problem, I created a script - which I would appreciate feedback on :)</p> <pre><code>search() { local t local OPTIND local pattern local files local types if [ $1 = --help ]; then echo "Usage: search [OPTION] ... PATTERN [FILE] ..." echo "Search for PATTERN in each FILE." echo "Example: search -t c -t h 'hello world' /code/internal/dev/ /code/public/dev/" echo echo "Output control:" echo " -t limit results to files of type" return fi while getopts ":t:" opt; do case $opt in t) t=(${t[@]} $OPTARG);; # create an array esac done shift $((OPTIND-1)) pattern=$1 files=${@:2} if [ -n "$t" ]; then # cast the array to a string types=${t[@]} # convert the string to a pattern usable by grep # example: "c h" becomes ".c:\|.h:" types=.${types// /':\|.'}: grep -I -r $pattern $files | grep $types else grep -I -r $pattern $files fi } </code></pre> <p>With this and a couple more shortcut scripts, I can (relatively) quickly find anything I'm looking for:</p> <pre><code>search-all-code() { search $@ /code/internal/dev/ /code/public/dev/ /code/tools/ } </code></pre> <p>Aside: I realize some versions of grep support <code>--include</code> and <code>--exlude</code> options, but the version of grep I'm stuck with doesn't.</p>
[]
[ { "body": "<p>I'd lean towards <code>find</code>. I'll provide some code review type comments at the bottom, but first a rewrite:</p>\n\n<pre><code>search() {\n local extensions\n local pattern\n local find_cmd\n local OPTIND opt\n\n local usage=$( cat - &lt;&lt; END\nUsage: $FUNCNAME [OPTION] ... PATTERN [FILE] ...\nSearch for PATTERN in each FILE.\nExample: $FUNCNAME -t c -t h 'hello world' /code/internal/dev/ /code/public/dev/\n\nOutput control:\n -t limit results to files of type\nEND\n)\n if [[ $1 == --help ]]; then\n echo \"$usage\"\n return\n fi\n\n extensions=()\n while getopts \":ht:\" opt; do\n case $opt in\n h) echo \"$usage\"; return;;\n t) extensions+=(\"$OPTARG\");;\n ?) echo \"invalid option: -$OPTARG\";;\n esac\n done\n shift $((OPTIND-1))\n\n if (( $# == 0 )); then\n echo \"no search term provided\"\n return\n fi\n\n pattern=$1\n shift\n\n if (( $# == 0 )); then\n echo \"no directories provided\"\n return\n fi\n # your directories to search are now the positional parameters\n\n find_cmd=(find \"$@\" '(')\n or=\"\"\n for type in \"${extensions[@]}\"; do\n find_cmd+=($or -name \"*.$type\")\n or=\"-o\"\n done\n find_cmd+=(')' -exec grep -I \"$pattern\" '{}' +)\n\n \"${find_cmd[@]}\"\n}\n</code></pre>\n\n<p>Notes</p>\n\n<ul>\n<li><code>[ $1 = --help ]</code> will give you syntax error if $1 is blank -- you get <code>[ = --help ]</code> and the = operator requires 2 operands. bash's <code>[[ ... ]]</code> is smarter about not dropping operands just because they're empty</li>\n<li>You can build up arrays bit-by-bit with <code>arr+=(\"$element\")</code></li>\n<li>you want to use more double quotes for your variables. If the pattern is \"hello world\", then <code>grep $pattern file1</code> will look for the pattern \"hello\" in files \"world\" and \"file1\" -- <code>grep \"$pattern\" file1</code> will work as you expect.</li>\n<li>I use <code>(( ... ))</code> arithmetic expression for numeric comparisons.</li>\n<li><p>I build up the find command piece by piece and execute it with <code>\"${arr[@]}\"</code> -- that specific syntax, indexing the array with <code>[@]</code> <em>and</em> surrounding it with double quotes, is the way you'll want to expand arrays most of the time. That specific syntax will expand the array into elements, but it will keep elements containing whitespace as a single argument. </p>\n\n<ul>\n<li><p>This includes using <code>\"$@\"</code> over <code>$@</code> -- the former gives you the actual arguments given by the user, the latter gives you all the words in the arguments. A demonstration:</p>\n\n<pre><code>set -- \"foo bar\" \"hello world\" # set the positional parameters\nprintf \"%s\\n\" \"$@\" | wc -l # print the parameters one per line \n # and count the lines -- 2\nprintf \"%s\\n\" $@ | wc -l # here you get 4\n</code></pre></li>\n</ul></li>\n</ul>\n\n\n\n<ul>\n<li>if <code>t</code> is an array, <code>$t</code> gives you the first element only.</li>\n</ul>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-05-07T01:54:05.967", "Id": "86272", "Score": "0", "body": "For the invalid option message, don't you want `$opt` instead of `$OPTARG`?" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-05-07T01:55:57.947", "Id": "86273", "Score": "0", "body": "Can you please explain or link to why you prefer parens for numeric tests vs. brackets? I've never seen that syntax, though I'm a Bash noob." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-05-07T01:57:49.460", "Id": "86274", "Score": "1", "body": "@DavidHarkness, nope. see http://www.gnu.org/software/bash/manual/bashref.html#index-getopts -- \"If an invalid option is seen, getopts places ‘?’ into name and, [...] the option character found is placed in OPTARG\"" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-05-07T01:58:26.803", "Id": "86275", "Score": "1", "body": "I like the look of `(( $x == 0 ))` versus `[[ $x -eq 0 ]]` -- documentation: http://www.gnu.org/software/bash/manual/bashref.html#Conditional-Constructs, scroll down for `((...))`" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-05-07T19:31:21.067", "Id": "86415", "Score": "0", "body": "Why use `==` instead of `=`? According to [this](http://www.tldp.org/LDP/abs/html/comparison-ops.html) it is the same, but with some quirky behavior." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-05-07T19:48:26.900", "Id": "86419", "Score": "0", "body": "Force of habit I guess. In double brackets, `=` and `==` are not string equality operators, they are pattern matching operators: `[[ foo = f* ]] && echo match`. If your pattern is a plain string (without [pattern matching chars](http://www.gnu.org/software/bash/manual/bashref.html#Pattern-Matching); or is quoted) the you effective have string equality -- `[[ foo = \"f*\" ]] || echo no match`" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-05-07T19:57:28.700", "Id": "86423", "Score": "0", "body": "I like that you've added the `-h` option and stored usage in a variable, but what is the advantage of using a here document instead of multi-line echo?" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-05-07T20:01:30.560", "Id": "86425", "Score": "0", "body": "Reuse. I use the $usage variable in multiple places. Consider a here-doc as a double-quoted string with embedded newlines." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-05-07T20:03:06.490", "Id": "86426", "Score": "0", "body": "I understand the purpose of storing usage in a variable is reuse, but my question was here-doc vs. `local usage=\"blah\\nblah\\nblah\"`. It just looks a little more confusing." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-05-07T20:04:43.670", "Id": "86427", "Score": "0", "body": "readable and maintainable code is a very high priority for me." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-05-07T20:19:39.053", "Id": "86435", "Score": "0", "body": "One more question: in `find_cmd+=( -exec grep -I \"$pattern\" + )` what's the trailing `+` for?" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-05-07T20:29:48.670", "Id": "86439", "Score": "0", "body": "Check your `find` man page for the `-exec` action. But there's a bug that I'll fix." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-05-08T16:17:34.380", "Id": "86552", "Score": "0", "body": "Dilemma: grepping the find results takes 41x longer than using grep alone." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-05-08T16:53:31.073", "Id": "86564", "Score": "0", "body": "Wow, that sucks. Is this with `-exec grep ... +` or `-exec grep ... \\;` ?" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-05-08T18:33:46.870", "Id": "86580", "Score": "0", "body": "`-exec grep ... \\;` I'm using a really old version of find that doesn't support `... +` syntax. I ended up grepping the grep results but used the rest of your ideas :)" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-05-08T18:36:49.740", "Id": "86581", "Score": "0", "body": "OK, that's most likely the source of the slow down: you need to spawn grep for each file found. You'll do much better with `find ... \\( -name ... \\) -print0 | xargs -0 grep -I \"$pattern\"` -- if your find/xargs does not have the -print0/-0 options, should not be a big problem assuming your file*names* do not contain newlines." } ], "meta_data": { "CommentCount": "16", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-05-07T01:40:52.453", "Id": "49111", "ParentId": "49102", "Score": "3" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-05-06T22:45:46.830", "Id": "49102", "Score": "4", "Tags": [ "bash", "console" ], "Title": "Shortcut script for elusive grep command" }
49102
<p>I use Gem in a Box, a Ruby project that allows to create personal self-hosted gem repositories. Gem in a Box uses <code>httpclient</code> to connect to the gem repository. After reviewing my server's TLS setup in the aftermath of the OpenSSL heartbleed bug, I decided only to allow protocol versions of TLSv1 and higher on my server. A decision quite a few fellow administrators made too, because of security vulnerabilities in SSLv3 and below.</p> <p>Now after I did this change, Gem in a Box refused to work with the following message:</p> <pre><code>OpenSSL::SSL::SSLError: SSL_connect returned=1 errno=0 state=SSLv3 read server hello A: sslv3 alert handshake failure </code></pre> <p>I traced this problem back until I found the source in <code>httpclient</code>. Even though OpenSSL can find the best protocol version to use by itself, you set it only to use SSLv3 by default. I think this is a very bad idea and created a patch which lets OpenSSL do its own decision again by default.</p> <p>As I am not so familiar with OpenSSL itself and the documentation of the Ruby binding is severely lacking I want to prevent introducing more problems than there were originally. Please review my changes and verify that it is doing what I intended.</p> <p>It is quite hard to post the actual changes here because they are only meaningful if one knows the context. So now I will try to describe what I did:</p> <p><code>httpclient</code> has a class called <code>SSLConfig</code> which seems to produce helper objects to configure OpenSSL sockets. It sets some default configurations in its #initialize method. Originally it had the <code>@ssl_version</code> instance variable set to <code>"SSLv3"</code>, When using the library an instance of <code>SSLConfig</code> is created and its <code>#set_context</code> method is called which applies the aforementioned defaults onto an instance of <code>OpenSSL::SSL::SSLContext</code>, which afterwards seems to be used to create OpenSSL sockets.</p> <p>I now changed to initial value of <code>@ssl_version</code> to the symbol <code>:auto</code> and modified the <code>#set_context</code> method to only set the actual value of <code>@ssl_version</code> to the <code>SSLContext</code> object, if its value is not <code>:auto</code>.</p> <p>Manual testing so far resulted in the exact effect I wanted to achieve.</p> <ul> <li><a href="https://github.com/nahi/httpclient" rel="nofollow">Here's a link</a> to the official GitHub repository of the <code>httpclient</code> library.</li> <li>See my <a href="https://github.com/aef/httpclient/commit/1753454f5d2c45d34f72eb52b456216ce4a95774" rel="nofollow">full commit on GitHub</a> for the mentioned changes.</li> <li>I also made a pull request to the <a href="https://github.com/nahi/httpclient/pull/204" rel="nofollow">original project</a>.</li> </ul> <p>Here are some relevant snippets from <code>lib/httpclient/ssl_config.rb</code>:</p> <pre><code>class SSLConfig ... # Which TLS protocol version (also called method) will be used. Defaults # to :auto which means that OpenSSL decides (In my tests this resulted # with always the highest available protocol being used). # # See the content of OpenSSL::SSL::SSLContext::METHODS for a list of # available versions in your specific Ruby environment. attr_reader :ssl_version ... # Creates a SSLConfig. def initialize(client) return unless SSLEnabled @client = client @cert_store = X509::Store.new @client_cert = @client_key = @client_ca = nil @verify_mode = SSL::VERIFY_PEER | SSL::VERIFY_FAIL_IF_NO_PEER_CERT @verify_depth = nil @verify_callback = nil @dest = nil @timeout = nil @ssl_version = :auto @options = defined?(SSL::OP_ALL) ? SSL::OP_ALL | SSL::OP_NO_SSLv2 : nil # OpenSSL 0.9.8 default: "ALL:!ADH:!LOW:!EXP:!MD5:+SSLv2:@STRENGTH" @ciphers = "ALL:!aNULL:!eNULL:!SSLv2" # OpenSSL &gt;1.0.0 default @cacerts_loaded = false end ... # interfaces for SSLSocketWrap. def set_context(ctx) # :nodoc: load_trust_ca unless @cacerts_loaded @cacerts_loaded = true # Verification: Use Store#verify_callback instead of SSLContext#verify*? ctx.cert_store = @cert_store ctx.verify_mode = @verify_mode ctx.verify_depth = @verify_depth if @verify_depth ctx.verify_callback = @verify_callback || method(:default_verify_callback) # SSL config ctx.cert = @client_cert ctx.key = @client_key ctx.client_ca = @client_ca ctx.timeout = @timeout ctx.options = @options ctx.ciphers = @ciphers ctx.ssl_version = @ssl_version unless @ssl_version == :auto end ... end </code></pre> <p>Here's what is using the <code>#set_context</code> method in <code>lib/httpclient/session.rb</code>:</p> <pre><code>... def create_openssl_socket(socket) ssl_socket = nil if OpenSSL::SSL.const_defined?("SSLContext") ctx = OpenSSL::SSL::SSLContext.new @context.set_context(ctx) ssl_socket = OpenSSL::SSL::SSLSocket.new(socket, ctx) else ssl_socket = OpenSSL::SSL::SSLSocket.new(socket) @context.set_context(ssl_socket) end ssl_socket end ... </code></pre>
[]
[ { "body": "<p>I've got a few things to say about the code, but having looked at the diff:</p>\n\n<pre><code>- @ssl_version = \"SSLv3\"\n+ @ssl_version = :auto\n</code></pre>\n\n<p>and:</p>\n\n<pre><code>- ctx.ssl_version = @ssl_version\n+ ctx.ssl_version = @ssl_version unless @ssl_version == :auto\n</code></pre>\n\n<p>your code changes seem minimal, and to the point doing exactly what they are supposed to do, and nothing more.</p>\n\n<p>What I think you <em>should</em> add are the tests to show your changes, and make sure no-one will break your code in the future.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-05-08T15:35:29.580", "Id": "49233", "ParentId": "49106", "Score": "2" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-05-07T00:01:30.053", "Id": "49106", "Score": "7", "Tags": [ "ruby", "security", "https", "openssl" ], "Title": "Let OpenSSL decide which TLS protocol version is used by default" }
49106
<p>I have a list of 6 items, and each one on click reveals a div that runs 100% wide under the row of list items. The code works, but the div opens very slowly and kind of choppy. Is there anything I can do to help it run more smoothly?</p> <p>My HTML is set up as such:</p> <pre><code> &lt;ul&gt; &lt;li&gt;&lt;a class="artist-logo" href="#artist-1"&gt;&lt;img src="images/looka-black-circle.png"&gt;&lt;/a&gt;&lt;/li&gt; &lt;div id="artist-1" class="artist-box"&gt; &lt;/div&gt; &lt;li&gt;&lt;a class="artist-logo" href="#artist-2"&gt;&lt;img src="images/looka-black-circle.png"&gt;&lt;/a&gt;&lt;/li&gt; &lt;div id="artist-2" class="artist-box"&gt; &lt;/div&gt; &lt;li&gt;&lt;a class="artist-logo" href="#artist-3"&gt;&lt;img src="images/looka-black-circle.png"&gt;&lt;/a&gt;&lt;/li&gt; &lt;div id="artist-3" class="artist-box"&gt; &lt;/div&gt; &lt;/ul&gt; </code></pre> <p>Here is my jscript:</p> <pre><code> $(document).ready(function(){ $(".artist-box").hide(); $(".artist-logo").click(function(e) { e.preventDefault(); // get the clicked element var clicked = $(this); // get the selected element var taggedWithSelect = $('.selected-artist'); // get the corresponding divs var clickPartner = $(clicked.attr('href')); var selectPartner = $(taggedWithSelect.attr('href')); var notClicked = $('.artist-logo').not(clicked); // we either want to close this one or open this one and close any others // if this one is open, it should be tagged with select if( clicked.hasClass('selected-artist') ) { clicked.removeClass('selected-artist'); notClicked.removeClass('blur-logo'); } else { clicked.addClass('selected-artist'); taggedWithSelect.removeClass('selected-artist'); selectPartner.slideToggle(); notClicked.addClass('blur-logo'); clicked.removeClass('blur-logo'); } clickPartner.slideToggle(); }); }); </code></pre>
[]
[ { "body": "<p>All this adding/removing classes are too much for this functionality. <strong>This makes it also very slow.</strong></p>\n\n<p><strong>You can iterate over all div elements, and say if div is !== hidden, than hide it.</strong> </p>\n\n<p>After that, you get the clicked element with $(this), and just say</p>\n\n<pre><code>$(this).next().slideToggle();\n</code></pre>\n\n<p>This is not proper code, but since you don't have thousands of divs to iterate over, just hide every open div, and open the clicked one.</p>\n\n<p>Maybe you have the problem of <strong>you want to close the already open one</strong>, so just make two if's. The first one should be like:</p>\n\n<blockquote>\n <p>if($(this).next().style.visible === \"true\"), hide it, if not, hide\n every visbile div and make just the next to the clicked one visible.</p>\n</blockquote>\n\n<p>This should be much faster, because you don't add/remove/readd classes.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-05-07T10:23:52.163", "Id": "49135", "ParentId": "49110", "Score": "1" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-05-07T01:27:00.650", "Id": "49110", "Score": "4", "Tags": [ "javascript", "optimization", "jquery", "performance", "html" ], "Title": "Hiding and revealing toggle responds very slow" }
49110
<p>I am wondering if I have overdone it with repositories in the following code, which is to save a sales order.</p> <p>I understand that the purpose of a repository is to decouple the domain layer from the persistence layer, but this code seems to be replicating what EF does anyway.</p> <pre><code>public SalesOrder FindSalesOrder(int id) { using (var uow = new UnitOfWork&lt;LogContext&gt;()) { using (var repository = new SalesOrderRepository(uow)) { var SalesOrder = repository.Find(s =&gt; s.Id == id, s =&gt; s.Site, s =&gt; s.User); if (SalesOrder != null) { using (var repository2 = new OrderLineRepository(uow)) { var OrderLines = repository2.GetList(o =&gt; o.SalesOrderId == id); foreach (var OrderLine in OrderLines) { OrderLine.SalesOrder = SalesOrder; SalesOrder.OrderLines.Add(OrderLine); using (var repository3 = new LineDetailRepository(uow)) { var LineDetails = repository3.GetList(v =&gt; v.OrderLineId == OrderLine.Id, v =&gt; v.PropertyName); foreach(var LineDetail in LineDetails) { LineDetail.OrderLine = OrderLine; OrderLine.LineDetails.Add(LineDetail); } } } } } return SalesOrder; } } } </code></pre> <p>[Update] I had a chat to my co-developer and think that perhaps the code is OK.</p> <p>Our reasoning is that EF itself is rather complicated so we want to have a wrapper around what we allow the UI layer to use.</p> <p>We did realize that we don't need the lineDetail repository as there are no instances where we need to access the lineDetails separate from the orderLines. That means we could make the orderLines return containing the lineDetails pre-populated. </p> <p>However that would then mean some of our repository's Find methods return entities with children and some don't. Thus I am thinking maybe we need a FindGraph method in our repositories which will return the full graph.</p> <p>However now I wonder whether the FindSalesOrder method should be in the SalesOrder repository itself instead of the UI layer?</p>
[ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-05-07T02:27:44.277", "Id": "86278", "Score": "1", "body": "Have you tried just returning the Sales Order? Typically if you have FK on your records EF will go off and fetch the values for you when you reference them later on i.e. SalesOrder.OrderLines will go off and fetch all the order lines belonging to the SalesOrder by Id" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-05-07T02:30:33.880", "Id": "86279", "Score": "0", "body": "I know, that's why i am wondering what use the above design is. I thought repositories were worth adopting but now i am having a hard time seeing their purpose." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-05-07T02:35:03.010", "Id": "86280", "Score": "3", "body": "They may be usefull for initial object querying when you don't have the parent object avaialble. ie. if you wanted to get all OrderLines by SalesId. Then a repository could do that. Otherwise I tend to leave EF as the repository and use a Service layer instead." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-05-07T09:35:13.897", "Id": "86302", "Score": "0", "body": "Why you are doning that?! SalesOrder has a list of OrderLines this is 1..n relationship just use lazy or eager loading to load them and not use the id !? same here between Orderline and LineDetail" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-05-07T11:15:27.747", "Id": "86320", "Score": "1", "body": "I'd be tempted to leave EF as is for this, however implementing your own repository pattern to sit on top of EF is a good idea if you plan on swapping EF out for something else, it can also help with testability." } ]
[ { "body": "<p>I find it interesting that you want to <em>decouple</em> layers, but that the method you have here is <em>tightly coupled</em> with <code>UnitOfWork&lt;LogContext&gt;</code> (and thus with <code>LogContext</code> as well), <code>OrderLineRepository</code> and <code>OrderDetailRepository</code>.</p>\n<p>To answer the question directly, yes, it's way overdone.</p>\n<p>I'd put a method like <code>SalesOrder FindSalesOrder(int id)</code> in a <em>service layer</em>:</p>\n<pre><code>public class SalesOrderService\n{\n private readonly IUnitOfWork _uow;\n\n public SalesOrderService(IUnitOfWork uow)\n {\n _uow = uow;\n }\n\n public SalesOrder FindSalesOrder(int id)\n {\n return _uow.Set&lt;SalesOrder&gt;() // get repository\n .Where(order =&gt; order.Id == id) // filter by id\n .Include(order =&gt; order.OrderLines) // eager-load details\n .ToList(); // materialize\n }\n}\n</code></pre>\n<p>What's <code>IUnitOfWork</code>, you'll ask? Just an <em>abstraction</em> that looks something like this:</p>\n<pre><code>internal interface IUnitOfWork\n{\n DbSet&lt;TEntity&gt; Set&lt;TEntity&gt;();\n void Commit();\n}\n</code></pre>\n<p>The EF context <em>itself</em> implements it:</p>\n<pre><code>public class MyDbContext : DbContext, IUnitOfWork\n{\n public IDbSet&lt;SalesOrder&gt; Orders { get; set; }\n \n public void Commit()\n {\n SaveChanges();\n }\n}\n</code></pre>\n<p>Entity Framework's <code>DbContext</code> <em>is</em> a unit-of-work implementation, and <code>IDbSet&lt;T&gt;</code> <em>is</em> a repository.</p>\n<p><em>Constructor-injecting</em> an <code>IUnitOfWork</code> in your service class effectively <em>decouples</em> your service class from EF, at least <em>good enough</em> for unit testing (you can <em>mock</em> what <code>Set&lt;T&gt;()</code> returns)... &quot;swapping the ORM&quot; <em>will require lots of work anyway</em>, and is highly hypothetical - the cost vs benefits ratio doesn't add up in favor of abstracting EF with repositories.</p>\n<hr />\n<h3>Your Code</h3>\n<p>There are a number of itchy spots with the code you've provided:</p>\n<ul>\n<li>Casing is annoyingly inconsistent for local variables. Should be <code>camelCase</code>, always: <code>var LineDetails</code> becomes <code>var lineDetails</code>, for example.</li>\n<li><code>using</code> blocks should be stacked whenever possible, to reduce unnecessary nesting:</li>\n</ul>\n<blockquote>\n<pre><code>using (var uow = new UnitOfWork&lt;LogContext&gt;())\n{\n using (var repository = new SalesOrderRepository(uow))\n {\n var SalesOrder = repository.Find(s =&gt; s.Id == id, s =&gt; s.Site, s =&gt; s.User);\n if (SalesOrder != null)\n {\n</code></pre>\n</blockquote>\n<p>Becomes:</p>\n<pre><code>using (var uow = new UnitOfWork&lt;LogContext&gt;())\nusing (var repository = new SalesOrderRepository(uow))\n{\n var SalesOrder = repository.Find(s =&gt; s.Id == id, s =&gt; s.Site, s =&gt; s.User);\n if (SalesOrder != null)\n {\n</code></pre>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-05-30T17:57:00.827", "Id": "52107", "ParentId": "49114", "Score": "2" } } ]
{ "AcceptedAnswerId": "52107", "CommentCount": "5", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-05-07T02:24:13.460", "Id": "49114", "Score": "4", "Tags": [ "c#", "entity-framework", "repository" ], "Title": "Saving a sales order - too many repositories?" }
49114
<p>I'm currently getting into MVC, and I'm working on a simple CRUD application but to make best use of relational database layout I need to use ViewModels so things look prettier on the UI.</p> <p>I have a ViewModel:</p> <pre><code>public class CreateAPIViewModel { [Display(Name = "Name")] public string Name { get; set; } [Display(Name = "Description")] public string Description { get; set; } [Display(Name = "Team")] public int TeamID { get; set; } [Display(Name = "Application")] public int ApplicationID { get; set; } [Display(Name = "Team")] public IEnumerable&lt;SelectListItem&gt; Team { get; set; } [Display(Name = "Application")] public IEnumerable&lt;SelectListItem&gt; Application { get; set; } [Display(Name = "Location")] public string Location { get; set; } [Display(Name = "Keywords")] public string Keywords { get; set; } } </code></pre> <p>And in my APIController I have this action:</p> <pre><code>public ActionResult Create() { CreateAPIViewModel viewModel = new CreateAPIViewModel(); //Fill team - seems a bit long doesn't it? listOfTeams = team.getAllTeams(); List&lt;SelectListItem&gt; listOfTeamsSelect = new List&lt;SelectListItem&gt;(); foreach (_Team_Detail item in listOfTeams) { listOfTeamsSelect.Add(new SelectListItem { Value = Convert.ToString(item.ID), Text = item.Name }); } viewModel.Team = listOfTeamsSelect; //Fill application - seems a bit long doesn't it? listOfApplications = application.getAllApplications(); List&lt;SelectListItem&gt; listOfApplicationsSelect = new List&lt;SelectListItem&gt;(); foreach (_Application item in listOfApplications) { listOfApplicationsSelect.Add(new SelectListItem { Value = Convert.ToString(item.ID), Text = item.Name }); } viewModel.Application = listOfApplicationsSelect; //Send view model back return View(viewModel); } </code></pre> <p>Is this the best way to be going about this process for creating a Create page so I can have dropdowns?</p>
[]
[ { "body": "<p>If you aren't considering using a mapping solution such as <em>AutoMapper</em>, you could make this code a bit more succient by removing some of the local variables and creating a couple of local methods that are responsible for creating the select lists.</p>\n\n<p>The end solution would look something along the lines of:</p>\n\n<pre><code>public ActionResult Create()\n{\n var viewModel = new CreateAPIViewModel\n {\n Team = ToSelectList(team.getAllTeams(),0),\n Application = ToSelectList(application.getAllApplications(),0)\n };\n\n //Send view model back\n return View(viewModel);\n}\n\nprivate List&lt;SelectListItem&gt; ToSelectList(IEnumerable&lt;Team&gt; applications, int selectedApplicationId)\n{\n return applications\n .ToList()\n .Select(p =&gt;\n new SelectListItem \n { \n Value = Convert.ToString(item.ID), \n Text = item.Name,\n Selected = item.ID == selectedApplicationId\n }); \n}\n\nprivate List&lt;SelectListItem&gt; ToSelectList(IEnumerable&lt;Team&gt; teams)\n{\n return teams\n .ToList()\n .Select(p =&gt;\n new SelectListItem \n { \n Value = Convert.ToString(item.ID), \n Text = item.Name,\n Selected = item.ID == selectedTeamId\n }); \n}\n</code></pre>\n\n<p>This has the added benefit in that you most likely have a Edit() action as well. You could re-use these methods.</p>\n\n<pre><code>public ActionResult Edit()\n{\n var viewModel = new CreateAPIViewModel\n {\n Team = ToSelectList(team.getAllTeams(),team.Id),\n Application = ToSelectList(application.getAllApplications(),application.Id)\n };\n\n //Send view model back\n return View(viewModel);\n}\n</code></pre>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-05-07T09:38:51.453", "Id": "49130", "ParentId": "49123", "Score": "3" } } ]
{ "AcceptedAnswerId": "49130", "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-05-07T07:54:17.437", "Id": "49123", "Score": "3", "Tags": [ "c#", "mvc", "asp.net-mvc" ], "Title": "View Model Filling Fields" }
49123
<p>Follow up for my initial question. Modified my earlier code and adding new changes. <a href="https://codereview.stackexchange.com/questions/48829/airline-hotel-reservation-system-in-python">Initial Question in Code Review</a></p> <pre><code>import random class Booking: def __init__(self): pass def checkAvailability(self,**kwargs): booking_type = kwargs['booking_type'] booking_class = kwargs['booking_class'] if booking_type == "Airline": departure_date = kwargs['departure_date'] airline = kwargs['airline'] if airline.AIRLINE_SEATS[booking_class] != 0 : print "Flight Available\n" return True else: print "Flight Not Available\n" return False elif booking_type == "Hotel": if H1.HOTEL_ROOM[booking_class] != 0: print "Hotel Available\n" return True else: print "Hotel Not Available\n" return False def makeReservation(self,**kwargs): booking_type = kwargs['booking_type'] customer = kwargs['customer'] availability_status = kwargs['availability_status'] if (availability_status == True) and (booking_type == "Airline"): booking_class = kwargs['booking_class'] airline = kwargs['airline'] airline.AIRLINE_SEATS[booking_class] -= 1 customer.customer_record['Wallet'] += airline.AIRLINE_PRICE[booking_class] customer.customer_record['Booking ID']['Airline'] = "AIR" + str(random.randrange(10,1000,2)) elif (availability_status == True) and (booking_type == "Hotel"): booking_class = kwargs['booking_class'] hotel = kwargs['hotel'] hotel.HOTEL_ROOM[booking_class] -= 1 customer.customer_record['Wallet'] += hotel.HOTEL_PRICE[booking_class] customer.customer_record['Booking ID']['Hotel'] = "HOT" + str(random.randrange(10,1000,2)) class Airline(Booking): def __init__(self,airline_name): Booking.__init__(self) self.airline_name = airline_name self.AIRLINE_SEATS = { 'Business Class' : 50, 'First Class' : 50, 'Premium Economy': 100, 'Regular Economy': 150 } self.AIRLINE_PRICE = { 'Business Class' : 2500, 'First Class' : 2000, 'Premium Economy': 1800, 'Regular Economy': 1500 } class Hotel(Booking): def __init__(self,hotel_name): Booking.__init__(self) self.hotel_name = hotel_name self.HOTEL_ROOM = {'Penthouse' : 10, 'King Deluxe Bedroom' : 20, 'Queen Deluxe Bedroom' : 20, 'Kind Standard Bedroom' : 30, 'Queen Standard Bedroom': 50 } self.HOTEL_PRICE = {'Penthouse' : 1000, 'King Deluxe Bedroom' : 700, 'Queen Deluxe Bedroom' : 600, 'Kind Standard Bedroom' : 450, 'Queen Standard Bedroom': 350 } class Customer: def __init__(self,f_name,l_name): self.f_name = f_name self.l_name = l_name self.cost = 0 self.customer_record = {'Name' : self.f_name + " " + self.l_name, 'Wallet': self.cost, 'Booking ID' : {} } def printcustomerrecord(self): for k,v in self.customer_record.items(): print k + "\t" + str(v) + "\n" C1 = Customer("Wayne","Rooney") A1 = Airline("Qantas") availability = A1.checkAvailability(airline = A1, booking_type = "Airline", booking_class = "Business Class", departure_date = "07072014") A1.makeReservation(airline = A1, customer = C1, booking_type = "Airline", booking_class = "Business Class", availability_status = availability) H1 = Hotel("Sheraton") availability = H1.checkAvailability(airline = H1, booking_type = "Hotel", booking_class = "Penthouse", checkin = "07072014", checkout = "07102014") H1.makeReservation(hotel = H1, customer = C1, booking_type = "Hotel", booking_class = "Penthouse", availability_status = availability) C1.printcustomerrecord() </code></pre> <p>I would really want some clarification on calling the </p> <pre><code>makeReservation checkAvailability </code></pre> <p>calls from their objects where i pass the objects as a parameter. I don't know if thats a proper way to do it. If there is a better way to do. I would be really happy to know about it.</p>
[ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-05-07T11:51:26.513", "Id": "86324", "Score": "3", "body": "I have got the feeling that you did not really take into account all of the advice from the previous review (*e.g.* using class attributes instead of instance attributes) :/" } ]
[ { "body": "<pre><code>def __init__(self):\n pass\n</code></pre>\n\n<p>The <strong>init</strong> call can be deleted.</p>\n\n<pre><code>def checkAvailability(self,**kwargs):\n booking_type = kwargs['booking_type']\n booking_class = kwargs['booking_class']\n</code></pre>\n\n<p>Be careful with <code>**kwargs</code> -- it's flexible but provides no clue as to what the function/method is actually expecting. You may want to add a doc string, or explicitly state which keywords the function expects in its signature. Regardless, you may want to consider adding either a check or a default if the keyword isn't there:</p>\n\n<pre><code>if 'booking_type' in kwargs:\n booking_type = kwargs['booking_type']\n</code></pre>\n\n<p>or </p>\n\n<pre><code>booking_type = kwargs.get('booking_type', default_booking_value)\n</code></pre>\n\n<p>As Morwenn also suggests, you may want to go back and look at the info in your previous answer -- right now you've still got logic for both airlines and hotels in your Booking class. In something like your check_availability method, that logic can be abstracted to see if a generalize resource is available, rather than being specifically for Hotels/Airlines/Jabberwockies/FooBars/Etc..</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-05-07T17:15:04.763", "Id": "49164", "ParentId": "49124", "Score": "4" } }, { "body": "<h2>Polymorphism</h2>\n\n<p>The biggest problem I see is that you're not using polymorphism at all. Instead of calling methods on <strong>Booking</strong> and using <code>if-else</code> to decide if it's a hotel or airline you're trying to book, you should implement the specialized logic in <strong>Hotel</strong> and <strong>Airline</strong>. For example like this:</p>\n\n<pre><code>class Bookable(object):\n def is_available(self, **kwargs):\n raise NotImplementedError\n\n def make_reservation(self, **kwargs):\n raise NotImplementedError\n\n\nclass Airline(Bookable): \n def is_available(self, booking_class):\n return self.seats[booking_class] &gt; 0\n\n def make_reservation(self, customer, booking_class):\n if self.is_available(booking_class):\n self.seats[booking_class] -= 1\n customer.customer_record['Wallet'] += self.prices[booking_class]\n</code></pre>\n\n<h2>Python standards</h2>\n\n<p>This is old-style class declaration:</p>\n\n<blockquote>\n<pre><code>class Customer:\n pass\n</code></pre>\n</blockquote>\n\n<p>Use this new style instead:</p>\n\n<pre><code>class Customer(object):\n pass\n</code></pre>\n\n<hr>\n\n<p>The modern way of calling superclass methods:</p>\n\n<pre><code>class Airline(Bookable):\n def __init__(self, airline_name):\n super(Airline, self).__init__()\n</code></pre>\n\n<hr>\n\n<p>If a method is unused, delete from your code, or at least omit from code review:</p>\n\n<blockquote>\n<pre><code>def __init__(self):\n pass\n</code></pre>\n</blockquote>\n\n<hr>\n\n<p>This has many unnecessary elements:</p>\n\n<blockquote>\n<pre><code>if (availability_status == True) and (booking_type == \"Airline\"):\n</code></pre>\n</blockquote>\n\n<p>You can simplify to:</p>\n\n<pre><code>if availability_status and booking_type == \"Airline\":\n</code></pre>\n\n<h2>Naming</h2>\n\n<p>There are many many naming issues in your code:</p>\n\n<ul>\n<li>Objects should have meaningful, lowercase names. For example instead of <code>C1</code>, call it <code>customer</code>, instead of <code>A1</code>, call it <code>airline1</code></li>\n<li>Don't name instance attributes with all caps, for example <code>AIRLINE_SEATS</code> could have been simply <code>seats</code></li>\n</ul>\n\n<h2>An example</h2>\n\n<p>I would simplify <strong>Airline</strong> like this:</p>\n\n<pre><code>class Airline(Bookable):\n CLASS_BUSINESS = 'Business Class'\n CLASS_FIRST = 'First Class'\n CLASS_PREMIUM_ECONOMY = 'Premium Economy'\n CLASS_ECONOMY = 'Regular Economy'\n\n def __init__(self, airline_name):\n super(Airline, self).__init__()\n self.airline_name = airline_name\n self.seats = {\n self.CLASS_BUSINESS: 50,\n self.CLASS_FIRST: 50,\n self.CLASS_PREMIUM_ECONOMY: 100,\n self.CLASS_ECONOMY: 150,\n }\n self.prices = {\n self.CLASS_BUSINESS: 2500,\n self.CLASS_FIRST: 2000,\n self.CLASS_PREMIUM_ECONOMY: 1800,\n self.CLASS_ECONOMY: 1500,\n }\n\n def is_available(self, booking_class):\n return self.seats[booking_class] &gt; 0\n\n def make_reservation(self, booking_class):\n if self.is_available(booking_class):\n self.seats[booking_class] -= 1\n</code></pre>\n\n<p>Your testing code example could be written as:</p>\n\n<pre><code>airline = Airline(\"Quantas\")\nbooking_class = Airline.CLASS_BUSINESS\nairline.make_reservation(booking_class)\n</code></pre>\n\n<p>I removed <strong>Customer</strong> from this example on purpose. An <strong>Airline</strong> should not know about the implementation details of a <strong>Customer</strong>, like in your post, updating <code>customer.customer_record['Wallet']</code>. At the minimum, <strong>Customer</strong> should have API methods like <code>add_cost</code>, hiding the implementation details. To go even further, the <strong>Airline</strong> should not update a <strong>Customer</strong>, it would be better to move that logic to a new class, something like a <strong>BookingManager</strong>.</p>\n\n<h2>UPDATE: another example</h2>\n\n<p>You're right that <strong>Bookable</strong> is not doing much useful in the previous simplified example. Here's another implementation example, with common logic moved from <strong>Airline</strong> to <strong>Bookable</strong> in a way that <strong>Hotel</strong> can reuse it too:</p>\n\n<pre><code>class Bookable(object):\n def is_available(self, booking_class):\n return self.get_items(booking_class) &gt; 0\n\n def make_reservation(self, customer, booking_class):\n if self.is_available(booking_class):\n self.decrement_items(booking_class)\n customer.customer_record['Wallet'] += self.get_price(booking_class)\n customer.customer_record['Booking ID'][self.get_class_name()] = self.get_id_prefix() + str(random.randrange(10, 1000, 2))\n\n def get_class_name(self):\n return self.__class__.__name__\n\n def get_items(self, booking_class):\n raise NotImplementedError\n\n def get_price(self, booking_class):\n raise NotImplementedError\n\n def decrement_items(self, booking_class):\n raise NotImplementedError\n\n def get_id_prefix(self):\n raise NotImplementedError\n\n\nclass Airline(Bookable):\n CLASS_BUSINESS = 'Business Class'\n CLASS_FIRST = 'First Class'\n CLASS_PREMIUM_ECONOMY = 'Premium Economy'\n CLASS_ECONOMY = 'Regular Economy'\n\n def __init__(self, airline_name):\n super(Airline, self).__init__()\n self.airline_name = airline_name\n self.seats = {\n self.CLASS_BUSINESS: 50,\n self.CLASS_FIRST: 50,\n self.CLASS_PREMIUM_ECONOMY: 100,\n self.CLASS_ECONOMY: 150,\n }\n self.prices = {\n self.CLASS_BUSINESS: 2500,\n self.CLASS_FIRST: 2000,\n self.CLASS_PREMIUM_ECONOMY: 1800,\n self.CLASS_ECONOMY: 1500,\n }\n\n def get_items(self, booking_class):\n return self.seats[booking_class]\n\n def decrement_items(self, booking_class):\n self.seats[booking_class] -= 1\n\n def get_id_prefix(self):\n return 'AIR'\n\n def get_price(self, booking_class):\n return self.prices[booking_class]\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-05-09T02:54:58.237", "Id": "86670", "Score": "0", "body": "if i am going to raise NotImplementedError in each of the methods in Booking class, I might as well not use that Booking class at all. I can just have two Airline and Hotel class ?. I am newbie to OOPs, so i am trying to clarify this here. How should I abstract these two methods as one in parent. They are both doing a similar functionality, but they are just acting on different data." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-05-09T05:57:26.483", "Id": "86684", "Score": "0", "body": "@Arman fair enough ;-) I added another, more detailed example where **Bookable** has some methods that both **Airline** and **Hotel** can benefit from." } ], "meta_data": { "CommentCount": "2", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-05-07T20:31:50.673", "Id": "49182", "ParentId": "49124", "Score": "13" } } ]
{ "AcceptedAnswerId": "49182", "CommentCount": "1", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-05-07T08:03:27.343", "Id": "49124", "Score": "7", "Tags": [ "python", "object-oriented" ], "Title": "Airline/Hotel reservation system in Python : Follow up" }
49124
<h2>Background</h2> <blockquote> <p>This is a problem from a programming contest. </p> <p>The Sharonians of planet Sharon, at the far end of our galaxy, have discovered various samples of English text from our electronic transmissions, but they did not find the order of our alphabet. Being a very organized and orderly species, they want to have a way of ordering words, even in the strange symbols of English. Hence they must determine their own order.</p> <p>For instance, if they agree on the alphabetical order: UVWXYZNOPQRSTHIJKLMABCDEFG</p> <p>Then the following words would be in sorted order based on the above alphabet order:</p> </blockquote> <pre><code>WHATEVER ZONE HOW HOWEVER HILL ANY ANTLER COW </code></pre> <p>The input format is:</p> <pre><code>&lt;N - number of words&gt; &lt;alphabet order&gt; &lt;0&gt; .. &lt;N&gt; </code></pre> <p></p> <h2>What I Did</h2> <p>I intended to use <code>List&lt;T&gt;.Sort</code> and use a custom Comparator so I don't have to implement a sorting algorithm from scratch. However, the alphabet input and the order is case insensitive and since <code>List&lt;T&gt;.Sort</code> uses an unstable QuickSort, words like "go" and "Go" would be swapped.</p> <p>My workaround is <strong>so</strong> dirty but it works by making a copy of the word list to serve as a look-up to preserve the order of equal words. </p> <h2>The Code As Is</h2> <pre><code>using System; using System.Collections.Generic; class Program { static void Main(string[] args) { List&lt;string&gt; words = new List&lt;string&gt;(); List&lt;string&gt; wordsCopy = new List&lt;string&gt;(); string firstLine = Console.ReadLine(); //assume correct input int numOfWords = int.Parse(firstLine.Split(" ".ToCharArray())[0]); string alphabet = firstLine.Split(" ".ToCharArray())[1].ToUpper(); for (int i = 1; i &lt;= numOfWords; i++) { words.Add(Console.ReadLine()); wordsCopy.Add(words[words.Count - 1]);//preserve index } Console.WriteLine(); //Quicksort is unstable (meaning "equal" elements will still be swapped, e.g. "go" and "Go") words.Sort(delegate(String x, String y) { int max = (x.Length &gt; y.Length) ? y.Length : x.Length; if (x.ToUpper().Equals(y.ToUpper())) { //dirty work-around to stablize the sort return wordsCopy.IndexOf(x) &lt; wordsCopy.IndexOf(y) ? -1 : 1; } for (int i = 0; i &lt; max; i++) { int indexX = alphabet.IndexOf(x[i].ToString(), StringComparison.InvariantCultureIgnoreCase); int indexY = alphabet.IndexOf(y[i].ToString(), StringComparison.InvariantCultureIgnoreCase); if (indexX &gt; indexY) { return 1; } else if (indexX &lt; indexY) { return -1; } } return 0; }); Console.Write(String.Join("\n", words)); Console.ReadLine(); } } </code></pre> <p>This code was good enough to win, but what could I have done better?</p>
[ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-05-07T10:24:07.153", "Id": "86308", "Score": "0", "body": "Is stability actual requirement of the problem? I don't see it in the (partial?) problem statement you gave us." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-05-07T10:29:25.203", "Id": "86310", "Score": "0", "body": "@svick I think I implied it since the code's output should match each sample output. Consider the word list: \"good, Good, horse..\". The correct output should be as is. However, if the sorting is unstable, the output would be: \"Good, good, horse...\"." } ]
[ { "body": "<p>First of all, I would take advantage of the fact that the other commonly used implementation of sorting in .Net is stable: <a href=\"http://msdn.microsoft.com/en-us/library/vstudio/bb549422\" rel=\"nofollow\">the <code>OrderBy()</code> extension method from LINQ</a>. Though it requires <code>IComparer</code> interface for custom sorting, it won't accept the <code>Comparer</code> delegate you're using.</p>\n\n<p>If you wanted to keep using <code>List.Sort()</code>, then I think your implementation is mostly okay, with the following caveats:</p>\n\n<ul>\n<li>It has the potential to balloon the time complexity of the sort from \\$\\mathcal{O}(n \\log n)\\$ to \\$\\mathcal{O}(n^2 \\log n)\\$. This is becuse every call to your comparison delegate can take \\$\\mathcal{O}(n)\\$ time, due to the calls to <code>IndexOf()</code>.</li>\n<li>It doesn't work correctly if some words in the list repeat themselves. For example “Good, good, Good” would be sorted as “Good, Good, good”.</li>\n</ul>\n\n<p>Neither of these might matter to you, but I think it's good to be aware of them.</p>\n\n<hr>\n\n<p>Your comparison doesn't work correctly for pairs where one word is the start of another (like “HOW” and “HOWEVER” from the sample list), it returns 0 for those, even though the words are not the same.</p>\n\n<hr>\n\n<p>Some small specific comments about your code:</p>\n\n<p>All your code is inside a single method. That's usually frowned upon, but I think it's probably okay when you have this little code. The same goes for separation of concerns.</p>\n\n<hr>\n\n<pre><code>int numOfWords = int.Parse(firstLine.Split(\" \".ToCharArray())[0]);\nstring alphabet = firstLine.Split(\" \".ToCharArray())[1].ToUpper();\n</code></pre>\n\n<p>I would avoid the repetition of <code>firstLine.Split(\" \".ToCharArray())</code> by extracting its result to a separate variable.</p>\n\n<p>Also, you don't actually need that <code>ToCharArray()</code>, since <code>Split()</code> is a <code>params</code> method.</p>\n\n<pre><code>string[] firstLineParts = firstLine.Split(' ');\n\nint numOfWords = int.Parse(firstLineParts[0]);\nstring alphabet = firstLineParts[1].ToUpper();\n</code></pre>\n\n<hr>\n\n<pre><code>wordsCopy.Add(words[words.Count - 1]);\n</code></pre>\n\n<p>I think creating <code>wordsCopy</code> would be simpler if you used the constructor of <code>List</code> that can copy existing collection:</p>\n\n<pre><code>List&lt;string&gt; wordsCopy = new List&lt;string&gt;(words);\n</code></pre>\n\n<hr>\n\n<pre><code>words.Sort(delegate(String x, String y)\n</code></pre>\n\n<p>You can use the lambda syntax here. That way, you don't have to (but can, if you want) specify the types of parameters:</p>\n\n<pre><code>words.Sort((x, y) =&gt;\n</code></pre>\n\n<hr>\n\n<pre><code>x.ToUpper().Equals(y.ToUpper())\n</code></pre>\n\n<p><code>ToUpper()</code> is culture-specific, which can cause problems in some cultures (<a href=\"http://blog.codinghorror.com/whats-wrong-with-turkey/\" rel=\"nofollow\">particularly Turkish</a>).</p>\n\n<p>But you probably don't need to care about that if you only ever expect to run this program on your computer.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-05-07T13:52:38.543", "Id": "86338", "Score": "3", "body": "In programming contests, the contestants are racing each other and a clock to solve the problems as quickly as possible, with solutions posted sometimes 5-10 minutes after the problem is shown. Your code style advice does apply to production code, but is wholly inappropriate for this one specific instance." } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-05-07T11:02:38.803", "Id": "49137", "ParentId": "49127", "Score": "6" } }, { "body": "<p>By implementing anonymous types, you could add an index for the original list order, without having to lookup afterwards, and at the same time getting the index inside the alphabet.</p>\n\n<p>All at once:</p>\n\n<pre><code> var indexed = words.Select( (w,li) =&gt; new { word = w, ListIndex = li, Len = w.Length}).ToArray();\n //at this point, each element in indexed containts word, ListIndex and string length.\n\n //sorting \n Array.Sort(indexed, (wi1, wi2) =&gt;\n {\n int min = (wi1.Len &lt; wi2.Len) ? wi1.Len : wi2.Len;\n\n for (int i = 0; i &lt; min; i++)\n {\n char c1 =char.ToUpper(wi1.word[i]), c2 = char.ToUpper(wi2.word[i]);\n if (c1 != c2) //only bother going for the alphabet index if the chars differ\n return alphabet.IndexOf(c1) - alphabet.IndexOf(c2);\n }\n\n if(wi1.Len == wi2.Len)\n return wi1.ListIndex - wi2.ListIndex; //if equal, use original list index\n\n return wi1.Len - wi2.Len; //prefer shortest first\n });\n\n //resetting the words list\n words = indexed.Select(w =&gt; w.word).ToList();\n</code></pre>\n\n<p>What happens in the anonymous type, is that all original listindexes are stored beforehand, preventing having to lookup in each compare.</p>\n\n<p><code>wordsCopy.IndexOf(x)</code> inside the compare is replaced by setting <code>ListIndex = li++</code></p>\n\n<p><strong>edit</strong>\nAs you stated correctly I was sloppy enough to only sort on the first character in the first version. Besides the ListIndex Storage, this isn't too different from your own code.</p>\n\n<p>One notable difference is that instead of always searching for the alphabet index, it is only searched once per comparison, when the characters do not match. e.g. for \"HOWG\" and \"HOWU\" only the indices for <code>U</code> and <code>G</code> are obtained. \nFor \"Cow\" and \"COW\", no char differences are found and no alphabet indices are searched for. Their length is the same, so listindex is compared.</p>\n\n<p>Another performance difference, the ToUpper isn't compared beforehand, preventing having to do an uppercase first, and ordinalcompare later on for non matching words, with that also preventing the ToString() call on char (<code>x[i].ToString()</code>) in the current implementation (which could be replaced by an indexof(char.ToUpper(x[i]) ) . \nFor example, comparing \"ARelativelyLongStringA\" and \"ARelativelyLongStringB\", would do a ToUpper first, find no match, and do a case insensitve alphabet index for each char in \"ARelativelyLongString\" until the difference is found, having compared those chars twice.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-05-07T14:36:48.227", "Id": "86347", "Score": "0", "body": "Clarification: I'm not too familiar with lambda expressions so correct me if I'm wrong but to my understanding, *AlphabetIndex* only stores info on the first character of every word. So if the first character is equal, why should we switch to the default Comparator instead of looking at the 2nd character and so on? (e.g. \"HOWU\" and \"HOWG\" will be sorted *alphabetically* instead of *custom-alphabetically*)" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-05-07T14:46:08.477", "Id": "86352", "Score": "0", "body": "Oops, spoke to soon, will update the anwer" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-05-07T15:34:57.183", "Id": "86366", "Score": "0", "body": "@helix, sorry for the misinterpretation and the delay, was focusing to much at the buffering within the anonymous type. Please see the updated answer. thanks" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-05-07T16:43:21.503", "Id": "86383", "Score": "0", "body": "Side effects in LINQ lambdas (like your `li++`) should be avoided. And in this case, there is a better solution: use the overload of `Select()` that also gives you the index." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-05-08T08:16:34.063", "Id": "86497", "Score": "0", "body": "True enough, altered it, thanks. Although don't think there would have been side effects without parallelism." } ], "meta_data": { "CommentCount": "5", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-05-07T13:29:35.180", "Id": "49144", "ParentId": "49127", "Score": "4" } } ]
{ "AcceptedAnswerId": "49137", "CommentCount": "2", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-05-07T09:08:10.483", "Id": "49127", "Score": "6", "Tags": [ "c#", "optimization", "sorting", "contest-problem" ], "Title": "Stable custom alphabetical order using List<T>.Sort" }
49127
<p>This post is a follow-up to <a href="https://codereview.stackexchange.com/questions/48187/bash-music-player">this</a>.</p> <p>I wanted further reviews since the code I provided became too old when I got replies, which is why I'm providing it again here.</p> <p>I'm hoping I could get reviews for the new code.</p> <pre><code>#!/bin/bash # # Need to sort music, try tinkering with sort -u at the end of the load_sites function .. # Need to organize error codes .. # mkdir -p "$HOME/Music" cd "$HOME/Music" clear # So that any download will be in the music directory ######################################### Initial Values and Declarations ############################# ##### needed global variables declare -r settings_file="$HOME/.config/PlayMusic/PlayMusic.settings" log_file="$HOME/Desktop/PlayMusic_log.log" # readonly variables declare -A Tracks # names are keys, sites are values declare FILE times_to_play=1 SITES=() ##### options &amp; features declare chosen=false dropbox=false just_download=false double_check=false all=false player='mplayer' ############################################## Functions ################################### function Play { # Function for playing music according to user preferences if [[ ${#1} -lt 23 ]];then notify-send "Now Playing: \"$1\" .." "$track" # Notifing the user, only if the track's name isn't too long fi for (( i=0 ; i &lt; times_to_play ; i++ ));do $player "$1" done } function Find { # function to look for a previously downloaded file on disk local IFS=$'\n' unset FILE echo "Looking for '$1' on disk .. " local files=$(find ~ -name "$1*.mp3" 2&gt;/dev/null) ; clear # The main file ( the found file, or null if not found ) .. if [[ $(echo "$files" | wc -l) -gt 1 ]];then # what to do if more than one file was found .. local file if ! $all;then # if the user is likely to be sitting on his computer and not sleeping .. echo 'File was found at various places .. Which one to use ?' select file in $files "Cancel";do [[ -n "$file" ]] || continue [[ "$file" == 'Cancel' ]] &amp;&amp; exit 0 FILE="$file" break done if IsYes -p 'Do you want to Delete the other ones ? ';then for file in $files;do [[ "$file" == "$FILE" ]] || rm "$file" # removing the file if not the selected file done fi else file="${files[0]}" # getting the nearest file mv -f "$file" "$HOME/Music" # moving it to the music directory FILE="$HOME/Music/$(basename "${files[0]}")" # getting that file for file in $files;do [[ "$file" == "$FILE" ]] || rm "$file" done fi else FILE="$files" fi ; clear } function IsNum { return $([[ "$1" =~ ^[0-9]+$ ]] &amp;&amp; echo 0 || echo 1) } function create_settings_file { mkdir -p "$(dirname "$settings_file")" cat &gt; "$settings_file" &lt;&lt;- EOF # the default music settings file $player # the first line is always the media player $dropbox # the second line is always for integration with dropbox # other than that is only sites .. http://ccmixter.org/view/media/samples/mixed http://ccmixter.org/view/media/remix http://mp3.com/top-downloads/genre/jazz/ http://mp3.com/top-downloads/ http://mp3.com/top-downloads/genre/rock/ http://mp3.com/top-downloads/genre/hip hop/ # empty or fully-commented lines are ignored .. http://mp3.com/top-downloads/genre/emo/ http://mp3.com/top-downloads/genre/pop/ # PS: '#' is marking a comment , and is ignored by the settings parser .. EOF if $2;then echo "# The settings file was recreated because the old one was useless or corrupt .." &gt;&gt; "$settings_file" nano "$settings_file" notify-send -t 450 'Here it is !' fi } function DOWNLOAD { local name="$track.mp3" Find "$track" # Looking for the specified track on disk if [[ -n $FILE ]] ;then # if the track was found on disk if [[ $(dirname "$FILE") != "$HOME/Music" ]];then # if the found file is not in the music directory notify-send "$track was found at ($(dirname "$FILE")) and was moved to ($HOME/Music)" # inform the user of the changes mv -f "$FILE" "$HOME/Music" &amp;&gt;/dev/null # move the file to the music home directory FILE="$HOME/Music/$name" # updating info fi name="$FILE" fi notify-send "Downloading ($track) .." "in [ $PWD ] .." wget -cO "$name" "${Tracks[$track]}" $dropbox &amp;&amp; cp "$name" "$HOME/Dropbox/Music" $1 &amp;&amp; Play "$name" } function UNINSTALL { IsYes -p 'Do you want to keep settings ? ' || rm "$HOME/.config/PlayMusic/PlayMusic.settings" sudo rm '/usr/local/bin/PlayMusic' &amp;&amp; sudo rm '/usr/local/man/man1/PlayMusic.1.gz' &amp;&amp; echo 'Uninstallation Success !' ; exit 0 } function load_sites { local counter=0 name site for SITE in "${SITES[@]}";do echo -e "\t\033[30;3mSite \033[37m#\033[1m$((++counter))\033[0m\033[30;3m: '\033[1;33;3m$SITE\033[1;30;3m'\033[0m" for site in $(lynx -source "$SITE" | egrep -o 'http://.*\.mp3');do # Grabbing all music links ( newline delimeted ) name="$(de_encode "$(basename "$site")" | sed -Ee 's/\.mp3$//' -e 's/\+|_/ /g' -e 's/^.+ - //')" Tracks["$name"]="$site" # Adding the name as the key, and the site as the value done done clear if [[ ${#Tracks[@]} == 0 ]];then echo 'No Music was Found ! ' echo 'Please either check your internet connection or recreate the settings file using "( '"$(basename "$0") -s )"'"' &gt;&amp;2 exit 1 fi } function parse_settings { # function to parse settings file local line_number=0 line if [[ -f "$settings_file" ]];then if [[ ! -r "$settings_file" ]];then echo "The Settings file ($settings_file) exists, but doesn't have read permission granted .." &gt;&amp;2 exit 1 fi while read -r line;do [[ -n "$line" ]] || continue case $((++line_number)) in 1 ) player="$line" ;; 2 ) if echo "$line" | egrep -q 'https?:.+';then # if a site .. SITES[${#SITES[@]}]="$line" # add it else # if not .. [[ "$line" == 'true' ]] &amp;&amp; dropbox=true || dropbox=false # if anything else, ignored .. fi $dropbox &amp;&amp; mkdir -p "$HOME/Dropbox/Music" ;; * ) SITES[${#SITES[@]}]="$line" ;; esac done &lt; &lt;(sed -Ee 's/^ +//g' -e 's/(.*) *#.*/\1/g' -e 's/( *)$//g' -e 's/ *#.*//g' -e 's/ /%20/g' "$settings_file") else notify-send "Settings File not Found .. !" if IsYes -p "You haven't created your settings file .. Do you want to create it ? ";then create_settings_file false else echo 'Then, The Default settings are going to be used this time ..' fi fi if [[ ${#SITES[@]} == 0 ]];then create_settings_file true fi $all &amp;&amp; echo -e "$(date)\n###############" &gt;&gt; "$log_file" } function EVERYTHING { $just_download &amp;&amp; notify-send 'Downloading Everything .. !' || notify-send 'Playing Everything .. !' for track in "${!Tracks[@]}";do $just_download &amp;&amp; DOWNLOAD false || Play "${Tracks[$track]}" done exit 0 } function usage { cat &lt;&lt;- EOF PlayMusic [OPTION] -s ReCreate the Settings file .. -r [number] Set the number of times a track should be played .. -v View the Settings file .. -u Uninstall the Program .. -d Force download .. -p Force play .. -a -d / -p applies for everything in the list, so everything will be downloaded/played automatically .. -D Turn on double check mode .. --version Show Program Info .. EOF } ############################################### Parsing Arguments ######################## [[ "$1" == '--version' ]] &amp;&amp; { echo 'PlayMusic v1.3, Licence:GPL3' ; exit 0 ; } # giving the version while getopts r:svdupaD opt;do # Getting options case $opt in r ) if IsNum "$OPTARG" &amp;&amp; [[ "$OPTARG" -gt 1 ]];then declare times_to_play="$OPTARG" else echo 'Invalid Number of Times ..' &gt;&amp;2 fi ;; s ) create_settings_file true notify-send "Settings File Recreated Successfully !" exit 0 ;; v ) read -p 'Editor ? ' editor if [[ -z "$editor" ]] || ! which "$editor" &amp;&gt;/dev/null;then editor='nano' fi $editor "$HOME/.config/PlayMusic/PlayMusic.settings" exit 0 ;; u ) IsYes -p 'Are you sure you want to UnInstall ? ' &amp;&amp; UNINSTALL ;; d ) declare just_download=true chosen=true ;; # download without asking p ) declare just_download=false chosen=true ;; # play online without asking a ) declare all=true ;; D ) declare double_check=true ;; # turn on double check mode ( it is an experimantal feature for now .. ) \? ) usage &gt;&amp;2; exit 2;; esac done if $all &amp;&amp; ! $chosen;then echo "All what ? use -d or -p option to specify what to do with each of them .." &gt;&amp;2 ; exit 2 ; fi ############################################### Starting Work ########################## parse_settings clear printf "\033[0;37mLoading (\033[1m${#SITES[@]}\033[0;37m) Sites ..\n" load_sites $all &amp;&amp; EVERYTHING select track in "${!Tracks[@]}";do # interacting with the USER .. [[ -n $track ]] || continue # Continues the loop if choice is empty ( meaning that user's choice wasn't appropriate ) .. printf '\033[0m' clear if $chosen;then # if the user already specified something to do as an option ( -d / -p ) $just_download &amp;&amp; DOWNLOAD true || Play "${Tracks[$track]}" else select opt in "Download then Play" "Just Download" "Play Online" "Play then ask to download";do [[ -n "$opt" ]] || continue case "$opt" in "Play Online") Play "${Tracks[$track]}" ;; "Download then Play") DOWNLOAD true ;; "Just Download") DOWNLOAD false ;; "Play then ask to download") Play "${Tracks[$track]}" IsYes -p 'Do you want to download it ? ' &amp;&amp; DOWNLOAD false ;; esac break done fi done </code></pre>
[ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-05-17T19:21:54.657", "Id": "88040", "Score": "3", "body": "You could consider fixing issues pointed out by [automated tooling](http://www.shellcheck.net) first, and making the code more syntactically consistent (not putting some loops/ifs or multiple statements on single lines, using the same amount of whitespace around keywords, using same capitalization everywhere). This will let human reviewers focus on the important things." } ]
[ { "body": "<p>You completely ignored the first points from <a href=\"https://codereview.stackexchange.com/a/48520/12390\">the review your earlier question</a>, \nand they still apply here:</p>\n\n<blockquote>\n <p>Whitespace is not a precious resource: your code is far too dense for\n my taste</p>\n \n <ul>\n <li>fewer semicolons, more newlines.</li>\n <li>try to limit your line length to 90 chars for readability</li>\n </ul>\n</blockquote>\n\n<p>I would go even further, and recommend to stay within 70 chars. Look at this for example:</p>\n\n<blockquote>\n<pre><code>declare -r settings_file=\"$HOME/.config/PlayMusic/PlayMusic.settings\" log_file=\"$HOME/Desktop/PlayMusic_log.log\" # readonly variables\n</code></pre>\n</blockquote>\n\n<p>This is more than just a matter of taste. The left part of any text is always more readable and less easy to overlook than the far right part. This line should have been written as 3 lines instead:</p>\n\n<blockquote>\n<pre><code># readonly variables\ndeclare -r settings_file=\"$HOME/.config/PlayMusic/PlayMusic.settings\" \ndeclare -r log_file=\"$HOME/Desktop/PlayMusic_log.log\"\n</code></pre>\n</blockquote>\n\n<p>You gain nothing by squeezing this into one hardly readable line.</p>\n\n<p>The same goes for all the other <code>declare</code> statements too.\nJust because you <em>can</em> declare multiple variables on one line doesn't mean you should.\nI think it's a lot more readable if you declare one variable per line in general, with few exceptions.</p>\n\n<p>Since you didn't take this advice from your previous posting,\nlet me quote something from <a href=\"http://www.cc2e.com/Default.aspx\" rel=\"nofollow noreferrer\">Steve McConnell's Code Complete</a>:</p>\n\n<blockquote>\n <p>Favor read-time convenience to write-time convenience.\n Code is read far\n more times than it’s written, even during initial development.\n Favoring a technique that speeds write-time convenience at the expense\n of read- time convenience is a false economy.</p>\n</blockquote>\n\n<p>Some more specific notes about using more spaces:</p>\n\n<ul>\n<li>Put a space after semicolons, for example:\n\n<ul>\n<li>Instead of <code>for ...;do</code> write as <code>for ...; do</code></li>\n<li>Instead of <code>if [[ ... ]];then</code> write as <code>if [[ ... ]]; then</code></li>\n</ul></li>\n<li>Put one or two empty lines before function definitions</li>\n<li>Put one empty line between large logical steps, for example when you have a large <code>while</code> loop followed by a large <code>if</code> followed by another large <code>while</code>, put some empty lines between those blocks of code for visual separation</li>\n</ul>\n\n<h3>Simplifications</h3>\n\n<p>You could simplify the <code>IsNum</code> function:</p>\n\n<blockquote>\n<pre><code>IsNum() {\n return $([[ \"$1\" =~ ^[0-9]+$ ]] &amp;&amp; echo 0 || echo 1)\n}\n</code></pre>\n</blockquote>\n\n<p>You don't need the subshell to return 0 or 1, you could use the exit code of <code>[[ ... ]]</code> itself, and you don't need to quote <code>$1</code> inside it:</p>\n\n<pre><code>IsNum() {\n [[ $1 =~ ^[0-9]+$ ]]\n}\n</code></pre>\n\n<p>At other places, instead of <code>exit 0</code>, you could simply <code>exit</code>, as 0 is the default exit code (success).</p>\n\n<h3>Functions</h3>\n\n<p>According to the <a href=\"http://wiki.bash-hackers.org/scripting/obsolete\" rel=\"nofollow noreferrer\">bash hackers wiki</a>, this writing style of function declarations is not recommended:</p>\n\n<blockquote>\n<pre><code>function Play {\n # ...\n}\n</code></pre>\n</blockquote>\n\n<p>This is the preferred way:</p>\n\n<pre><code>Play() {\n # ...\n}\n</code></pre>\n\n<h3>Suspicious code</h3>\n\n<p>As <a href=\"http://www.shellcheck.net/#\" rel=\"nofollow noreferrer\">shellcheck.net</a> points out, be careful with these kind of expressions:</p>\n\n<blockquote>\n<pre><code>$just_download &amp;&amp; DOWNLOAD false || Play \"${Tracks[$track]}\"\n</code></pre>\n</blockquote>\n\n<p><code>A &amp;&amp; B || C</code> is NOT an if-then-else. <code>C</code> will be executed when:</p>\n\n<ul>\n<li><code>A</code> fails</li>\n<li><code>A</code> succeeds but <code>B</code> fails</li>\n</ul>\n\n<p>It seems that if <code>$just_download</code> is true, you won't want to play. In that case you should rewrite the above with an <code>if</code>:</p>\n\n<pre><code>if $just_download; then DOWNLOAD false; else Play \"${Tracks[$track]}\"; fi\n</code></pre>\n\n<p>Copy-paste your code on shellcheck.net and review the warnings of all the places where you use this pattern. Even if it's an innocent use case (for example when you <em>know</em> for sure that <code>B</code> always succeeds), it's a good practice to rewrite these suspicious cases to make all tests pass.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-09-25T20:57:09.623", "Id": "63904", "ParentId": "49128", "Score": "17" } } ]
{ "AcceptedAnswerId": "63904", "CommentCount": "1", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-05-07T09:30:08.033", "Id": "49128", "Score": "10", "Tags": [ "beginner", "bash", "shell", "audio" ], "Title": "Bash Music Player 2" }
49128
<p>I'm using this function to replace UTF-8 characters representing numbers in text with 'normal' digits.</p> <p>I'm wondering if this is optimized code since this is using two <code>str_replace()</code>s.</p> <pre><code>public static function convertArabicNumbers($string) { //$engish = array(0,1,2,3,4,5,6,7,8,9); $persian = array('۰', '۱', '۲', '۳', '۴', '۵', '۶', '۷', '۸', '۹'); $arabic = array('٠','١','٢','٣','٤','٥','٦','٧','٨','٩'); $num = range(0, 9); return str_replace($arabic, $num, str_replace($persian, $num, $string)); } </code></pre>
[]
[ { "body": "<p>You are right that this is not optimal (performance wise). You may want to consider two things:</p>\n\n<ol>\n<li>static variables (those values in there are constants no need to recreate them every time).</li>\n<li>merging the arrays.</li>\n</ol>\n\n<p>Consider the following code:</p>\n\n<pre><code>public static function convertArabicNumbers($string) {\n //$engish = array(0,1,2,3,4,5,6,7,8,9);\n static $fromchar = array('۰', '۱', '۲', '۳', '۴', '۵', '۶', '۷', '۸', '۹',\n '٠','١','٢','٣','٤','٥','٦','٧','٨','٩');\n static $num = array('0', '1', '2', '3', '4', '5', '6', '7', '8', '9',\n '0', '1', '2', '3', '4', '5', '6', '7', '8', '9')\n return str_replace($fromchar, $num, $string);\n}\n</code></pre>\n\n<p>I am really uncertain about the right-to-left characters.... should they be transformed in the same way as the left-to-right ones? You're the expert on that one.</p>\n\n<p>Still, you get the idea....</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-05-07T11:46:44.363", "Id": "86322", "Score": "1", "body": "thank you I think you are right, btw both languages are left to right in numbers though" } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-05-07T11:26:36.477", "Id": "49139", "ParentId": "49138", "Score": "3" } } ]
{ "AcceptedAnswerId": "49139", "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-05-07T11:08:20.147", "Id": "49138", "Score": "3", "Tags": [ "php", "performance", "strings", "converting", "utf-8" ], "Title": "Replacing Perisan and Arabic digits" }
49138
<p>I have a 'speed problem' with a program I'm currently developing. I already have encountered the methods which costs some time.</p> <pre><code>public void ConvertDataFrameToValueFields() { List&lt;byte[]&gt; items = new List&lt;byte[]&gt;() { new byte[2], new byte[2], new byte[2], new byte[2] }; items[0][0] = this.DataBytes[0]; items[0][1] = this.DataBytes[1]; items[1][0] = this.DataBytes[2]; items[1][1] = this.DataBytes[3]; items[2][0] = this.DataBytes[4]; items[2][1] = this.DataBytes[5]; items[3][0] = this.DataBytes[6]; items[3][1] = this.DataBytes[7]; int i = 0; IEnumerable&lt;PropertyInfo&gt; result = this.determineCanMessageValueFields(); foreach (var prop in result) { if (prop.PropertyType == typeof(MessageStatusValueField)) { prop.SetValue(this, new MessageStatusValueField(BitConverter.ToUInt16(items[i], 0), prop.Name, this.UnitType), null); } else if (prop.PropertyType == typeof(MessageValueField)) { prop.SetValue(this, new MessageValueField(BitConverter.ToUInt16(items[i], 0), prop.Name), null); } else if (prop.PropertyType == typeof(MessageValueFieldInt32)) { prop.SetValue(this, new MessageValueFieldInt32(BitConverter.ToUInt16(items[i], 0), prop.Name), null); } else if (prop.PropertyType.GetCustomAttributes(false).Count(x =&gt; x.GetType() == typeof(BitmaskValueFieldClass)) &gt; 0) { var tempField = new MessageValueField(BitConverter.ToUInt16(items[i], 0), prop.Name); prop.SetValue(this, Convert.ChangeType(tempField, prop.PropertyType), null); } i++; } } private IEnumerable&lt;PropertyInfo&gt; determineCanMessageValueFields() { //Get all properties with the //custom attribute [IsValueField] return this.GetType().GetProperties() .Where(p =&gt; p.GetCustomAttributes(false) .Count(x =&gt; x.GetType() == typeof(IsValueField)) &gt; 0) .OrderBy(x =&gt; ((IsValueField)x.GetCustomAttributes(false)[0]).ValueFieldIndex); } public object ToType(Type conversionType, IFormatProvider provider) { //...only convert if the conversion type is a BitmaskValueFieldClass if (conversionType.GetCustomAttributes(false).Count(x =&gt; x.GetType() == typeof(BitmaskValueFieldClass)) == 0) { throw new NotImplementedException("The conversion is only available for conversion types with the BitmaskValueFieldClass attribute"); } //...create an instance of the conversion type var instance = Activator.CreateInstance(conversionType); //...go thru each property and set the value foreach (var item in instance.GetType().BaseType.GetProperties()) { item.SetValue(instance, this.GetType().GetProperty(item.Name).GetValue(this, null), null); } return instance; } </code></pre> <p>The method <code>ConvertDataFrameToValueFields()</code> is the sticking point. I know it is because of the <code>prop.SetValue()</code> and the <code>ToType() IConvertible</code> method calls. When I am removing the <code>ConvertDataFrameToValueFields()</code> method I gain the missing time I need to fulfill the project. </p> <p>Is there a way to improve the whole thing? Problem is that the idea has to be as it is. In the <code>ConvertDataFrameToValueFields()</code> method I have to map the returning DataFrame, the DataBytes array, to the MessageValueField properties of the specific class. I'm getting all containing messagevaluefields by calling the <code>ConvertDataFrameToValueFields()</code>. </p>
[ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-05-07T18:01:59.667", "Id": "86401", "Score": "1", "body": "Why is speed a problem? Are you calling these methods on the same type many times? If that's the case, you might benefit from using reflection once to generate code for that type and then use that generated code repeatedly." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-05-08T21:14:06.870", "Id": "86629", "Score": "0", "body": "I also wonder what those property setters are doing. If they're not simple value settings, then perhaps the problem is not that your code is slow but that the setters it's invoking are slow. Removing the whole method would not distinguish between those cases." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-07-14T05:39:42.893", "Id": "101597", "Score": "1", "body": "could you post a working sample? may we analyse the root cause." } ]
[ { "body": "<p><strong>Style</strong> </p>\n\n<p>Based on the <a href=\"http://msdn.microsoft.com/en-us/library/xzf533w0%28v=vs.71%29.aspx\" rel=\"nofollow\">naming guidlines</a> method names should use <code>PascalCasing</code> casing. </p>\n\n<p><strong>determineCanMessageValueFields()</strong></p>\n\n<p>Instead of calling <code>Count()</code> and checking if it is greater than <code>0</code> you should call <code>Any()</code>. </p>\n\n<p>So <code>determineCanMessageValueFields()</code> would become </p>\n\n<pre><code>private IEnumerable&lt;PropertyInfo&gt; determineCanMessageValueFields()\n{\n return this.GetType().GetProperties()\n .Where\n (p =&gt; p.GetCustomAttributes(false)\n .Any(x =&gt; x.GetType() == typeof(IsValueField))\n )\n .OrderBy(x =&gt; ((IsValueField)x.GetCustomAttributes(false)[0]).ValueFieldIndex);\n}\n</code></pre>\n\n<p><strong>ConvertDataFrameToValueFields()</strong> </p>\n\n<p>The creation of the <code>List&lt;byte[]&gt;</code> is not needed at all. If you increment the <code>i</code> counter by <code>2</code> you can just use <code>this.DataBytes</code> for the calling <code>BitConverter.ToUInt16(this.DataBytes,i)</code>. </p>\n\n<p>This leads after using <code>Any()</code>instead of <code>Count() &gt; 0</code> to </p>\n\n<pre><code>public void ConvertDataFrameToValueFields()\n{\n\n int i = 0;\n\n foreach (var prop in DetermineCanMessageValueFields())\n {\n ushort value = BitConverter.ToUInt16(this.DataBytes, i);\n\n if (prop.PropertyType == typeof(MessageStatusValueField))\n {\n prop.SetValue(this, new MessageStatusValueField(value, prop.Name, this.UnitType), null);\n }\n else if (prop.PropertyType == typeof(MessageValueField))\n {\n prop.SetValue(this, new MessageValueField(value, prop.Name), null);\n }\n else if (prop.PropertyType == typeof(MessageValueFieldInt32))\n {\n prop.SetValue(this, new MessageValueFieldInt32(value, prop.Name), null);\n }\n else if (prop.PropertyType.GetCustomAttributes(false).Any(x =&gt; x.GetType() == typeof(BitmaskValueFieldClass)))\n {\n var tempField = new MessageValueField(value, prop.Name);\n prop.SetValue(this, Convert.ChangeType(tempField, prop.PropertyType), null);\n }\n\n i += 2;\n }\n}\n</code></pre>\n\n<p>and applying the <code>Any()</code> change to the <code>ToType()</code> method </p>\n\n<pre><code>public object ToType(Type conversionType, IFormatProvider provider)\n{\n\n if (!conversionType.GetCustomAttributes(false).Any(x =&gt; x.GetType() == typeof(BitmaskValueFieldClass)))\n {\n throw new NotImplementedException(\"The conversion is only available for conversion types with the BitmaskValueFieldClass attribute\");\n }\n\n var instance = Activator.CreateInstance(conversionType);\n\n foreach (var item in instance.GetType().BaseType.GetProperties())\n {\n item.SetValue(instance, this.GetType().GetProperty(item.Name).GetValue(this, null), null);\n }\n\n return instance;\n} \n</code></pre>\n\n<p><strong>Comments</strong> </p>\n\n<p>Comments should be used to explain <strong>why</strong> something is done, not <strong>what</strong> is done. The <strong>what</strong> part should be done by the code itself. </p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-11-13T11:48:35.757", "Id": "69723", "ParentId": "49141", "Score": "2" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "3", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-05-07T13:05:06.103", "Id": "49141", "Score": "2", "Tags": [ "c#", "performance", "reflection" ], "Title": "Speed problems with SetValue, ToType and Reflection" }
49141
<p>I'm pretty new to multithreading. The code below is a simple implementation of a single consumer/single producer circular buffer that does not use any locking, that I wrote for fun. </p> <p>The question is, will this kind of container work in actual real world situation or would it crash miserably because of some data race that I have not noticed? </p> <pre><code>#include &lt;array&gt; #include &lt;memory&gt; #include &lt;atomic&gt; #include &lt;stdexcept&gt; #include &lt;iostream&gt; #include &lt;thread&gt; #include &lt;random&gt; template&lt;typename T, int S=5&gt; class CircularBuffer{ public: CircularBuffer():start(0),end(0){ } bool AddElement(std::unique_ptr&lt;T&gt; &amp;&amp; obj,bool block=true){ int end_idx=end.load(); if(block) while(end_idx+1==start.load());//Busy wait until there is place else if(end_idx+1==start.load()) return false; buffer[end_idx++]=std::move(obj); if(end_idx==buffer.size()) end.store(0); else end.store(end_idx); return true; } std::unique_ptr&lt;T&gt; GetElement(bool block=true){ int start_idx=start.load(); if(block) while(end.load()==start_idx); else if(end.load()==start_idx) return std::unique_ptr&lt;T&gt;(); auto ret_obj=std::move(buffer[start_idx]); start_idx++; if(start_idx==buffer.size()) start.store(0); else start.store(start_idx); return ret_obj; } private: std::array&lt;std::unique_ptr&lt;T&gt;,S+1&gt; buffer; std::atomic&lt;int&gt; start; std::atomic&lt;int&gt; end; }; std::random_device rd; std::mt19937 gen(rd()); std::uniform_int_distribution&lt;&gt; dis(0,500); void Producer(CircularBuffer&lt;int&gt; * buffer){ int i=0; while(i&lt;20){ std::this_thread::sleep_for(std::chrono::milliseconds(dis(gen))); auto val=dis(gen); std::cout &lt;&lt; "Adding " &lt;&lt; val &lt;&lt;std::endl; buffer-&gt;AddElement(std::unique_ptr&lt;int&gt;(new int(val))); i++; } } void Consumer(CircularBuffer&lt;int&gt; * buffer){ int i=0; while(i&lt;20){ std::this_thread::sleep_for(std::chrono::milliseconds(dis(gen))); std::cout &lt;&lt; "Got " &lt;&lt; *buffer-&gt;GetElement() &lt;&lt; std::endl; i++; } } int main(){ CircularBuffer&lt;int&gt; buffer; std::thread t[2]; t[0]=std::thread(Producer,&amp;buffer); t[1]=std::thread(Consumer,&amp;buffer); t[0].join(); t[1].join(); } </code></pre>
[ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-05-07T13:55:11.943", "Id": "86339", "Score": "1", "body": "This is actually off-topic cause you ask review of the actual working of your code. We do review on your code as in improve your code writing, sometimes a faster or better solution. For your question, the best is to write some tests and test your code by them." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-05-07T14:20:48.597", "Id": "86343", "Score": "1", "body": "@chillworld On the other hand, their question implies another question which is \"how can I improve my code to be sure that it's thread-safe\". A little reformulation would make the question on-topic :)" } ]
[ { "body": "<p>A few notes, mostly unrelated to the actual lock-free nature of the code:</p>\n\n<ol>\n<li><p>Some of your names are a lot less meaningful than I'd like. A prime example is your template parameter <code>S</code> in: <code>template&lt;typename T, int S=5&gt;</code>. This should probably be renamed to something like <code>Size</code> instead. Although not quite as problematic, I'd say your <code>dis</code> and <code>gen</code> have pretty much the same problem as well. (Note that although <code>T</code> as the type parameter is just as short, it's so common I'd accept it, much like I'd accept <code>i</code> as the index for a loop).</p></li>\n<li><p>Although some people avoid them, I'd at least <em>consider</em> using something like <code>size_t</code> for the types of <code>CircularBuffer::begin</code> and <code>CircularBuffer::end</code>. It appears that neither should ever be negative.</p></li>\n<li><p>You might want to consider using <code>std::atomic_int</code> (or <code>std::atomic_uint</code>) instead of <code>std::atomic&lt;int&gt;</code>. It's unlikely to make <em>much</em> difference, but does give the library design a little extra chance for optimization (i.e., <code>atomic_int</code> might just be a typedef for <code>atomic&lt;int&gt;</code>, but could be a separate type instead, if the library designer sees an advantage in doing so).</p></li>\n<li><p>It may just be a side-effect of some strange tab expansion (or something similar) but at least as posted, your indentation is pretty strange in a few places. For one obvious example:</p>\n\n<pre><code> if(start_idx==buffer.size())\nstart.store(0);\n else\nstart.store(start_idx);\n</code></pre></li>\n<li><p>I'd have to do some looking to be <em>absolutely</em> certain, but I <em>believe</em> your use of a global for the random number generator causes a data race that leads to undefined behavior. Specifically, a pseudo-random number generator has an internal state that's modified when you obtain a random number from it. Doing that modification simultaneously from two or more threads gives undefined behavior.</p></li>\n<li><p>This sequence:</p>\n\n<pre><code> start_idx++;\n if(start_idx==buffer.size())\nstart.store(0);\n else\nstart.store(start_idx);\n</code></pre></li>\n</ol>\n\n<p>Looks to me like it's subject to race conditions. For example, let's assume <code>start_idx</code> starts out equal to <code>buffer_size-1</code>, then we execute the code above from two threads:</p>\n\n<pre><code>thread A: start_idx++; \nthread B: start_idx++;\n\nthread A: if (start_idx == buffer.size())\nthread B: if (start_idx == buffer.size())\n</code></pre>\n\n<p>Both if statements return false--<code>start_idx</code> is now one <em>greater</em> than <code>buffer.size()</code>. We then store <code>start_idx</code> into <code>start</code>.</p>\n\n<p>The next time the function is called, it attempts to use:</p>\n\n<pre><code>auto ret_obj=std::move(buffer[start_idx]);\n</code></pre>\n\n<p>...and <code>start_idx</code> indexes past the end of <code>buffer</code>, giving undefined behavior.</p>\n\n<p>Limiting to single-producer, single-consumer <em>may</em> be enough to prevent this problem from manifesting, but 1) I find that an essentially useless model, and 2) I'm not at all sure it's sufficient even then.</p>\n\n<p>Although it may sound defeatist, let me give one little bit of advice: when you first do multithreaded programming, you're a lot better off sticking to using locks, mutexes, and so on. Getting just that much right will keep you busy for quite a while.</p>\n\n<p>(Only) once you've gotten to the point that it's easy to handle that, <em>then</em> start to move on to working at lock-free programming (but be aware that it's an area where even the very best, brightest and most experienced <em>still</em> get things wrong quite frequently.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-05-08T15:53:19.243", "Id": "86548", "Score": "1", "body": "+10 (If I could) on the using locks comment. People new to threading jump trying a lock free implementation (probably because its cool). But lock free code is extremely hard to get correct and the chance of subtle bugs is huge. Write the versions with locks first. Prove it is correct (and not fast enough) before trying a lock free version." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-05-09T02:31:01.457", "Id": "86667", "Score": "0", "body": "@LokiAstari: ...and then live with the fact that although the lock-free version guarantees forward progress (assuming you've done it correctly), it may not be any faster than the version that uses locking (and could even be slower). Yes, there's a good chance it'll be faster, but certainly no guarantee." } ], "meta_data": { "CommentCount": "2", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-05-08T07:14:44.647", "Id": "49209", "ParentId": "49142", "Score": "7" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "2", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-05-07T13:15:17.177", "Id": "49142", "Score": "5", "Tags": [ "c++", "c++11", "multithreading", "circular-list", "lock-free" ], "Title": "Single consumer and single producer lock-free circular buffer" }
49142
<p>I've created a generic data structure intended for game development entity management. It has some interesting properties:</p> <ul> <li>Entities are stored contiguously in an <code>std::vector</code>.</li> <li>Stored entities can be in one of three states: <em>alive</em>, <em>dead</em>, <em>unused</em>.</li> <li>Upon entity creation, a lightweight <code>Handle</code> object is returned: <ul> <li>The user can check whether the entity is alive or not from the handle.</li> <li>The user can access the entity from the handle.</li> <li>The user can <em>mark the entity as dead</em> from the handle.</li> </ul></li> <li>Every frame (or every time the user desires), calling <code>Manager::refresh()</code> deals with dead entities: <ol> <li>The internal contiguous storage is sorted using entity state as the sorting predicate. <em>Alive</em> entities are placed at the beginning of the storage, <em>dead</em> entities are placed at the end. <em>Unused</em> entities stay in between.</li> <li><em>Dead</em> entities get destroyed and their handles get invalidated.</li> <li>The manager iterates over <em>Alive</em> entities to update their handles (and keep them valid).</li> </ol></li> </ul> <p>Example diagram:</p> <blockquote> <pre class="lang-none prettyprint-override"><code>// Starting situation: we have 6 alive entities Entity storage: | A00 | A01 | A02 | A03 | A04 | A05 | Control storage: | 000 | 001 | 002 | 003 | 004 | 005 | Index storage: | 000 | 001 | 002 | 003 | 004 | 005 | Counter storage: | 000 | 000 | 000 | 000 | 000 | 000 | // Entity #04 is marked as `dead` (handle is still valid) X Entity storage: | A00 | A01 | A02 | A03 | A04 | A05 | Control storage: | 000 | 001 | 002 | 003 | 004 | 005 | Index storage: | 000 | 001 | 002 | 003 | 004 | 005 | Counter storage: | 000 | 000 | 000 | 000 | 000 | 000 | // User calls `refresh()` - at the beginning of the method entities are sorted // along with their control indices X Entity storage: | A00 | A01 | A02 | A03 | A05 | A04 | Control storage: | 000 | 001 | 002 | 003 | 005 | 004 | Index storage: | 000 | 001 | 002 | 003 | 004 | 005 | Counter storage: | 000 | 000 | 000 | 000 | 000 | 000 | // `refresh()` continues - dead entity data is destroyed, and dead entity // counters are incremented to invalidate existing handles // Dead entities become unused entities now U Entity storage: | A00 | A01 | A02 | A03 | A05 | | Control storage: | 000 | 001 | 002 | 003 | 004 | 005 | Index storage: | 000 | 001 | 002 | 003 | 004 | 005 | Counter storage: | 000 | 000 | 000 | 000 | 001 | 000 | // If an user queries an handle with index 004 to check the status of the // entity, the incremented counter will make the user know the entity is now // dead // `refresh()` continues - alive entities update their indices/controllers U Entity storage: | A00 | A01 | A02 | A03 | A05 | | Control storage: | 000 | 001 | 002 | 003 | 005 | 004 | Index storage: | 000 | 001 | 002 | 003 | 004 | 005 | Counter storage: | 000 | 000 | 000 | 000 | 001 | 000 | // Now, accessing an handle pointing to A05 will access the 6th control storage // element, which contains 005, which is the new index of the A05 entity </code></pre> </blockquote> <hr> <pre class="lang-cpp prettyprint-override"><code>#include &lt;SSVUtils/SSVUtils.hpp&gt; using Idx = std::size_t; using Ctr = int; template&lt;typename&gt; class Manager; namespace Internal { template&lt;typename T&gt; class Uncertain { private: ssvu::AlignedStorageBasic&lt;T&gt; storage; public: template&lt;typename... TArgs&gt; inline void init(TArgs&amp;&amp;... mArgs) noexcept(ssvu::isNothrowConstructible&lt;T&gt;()) { new (&amp;storage) T(std::forward&lt;TArgs&gt;(mArgs)...); } inline void deinit() noexcept(ssvu::isNothrowDestructible&lt;T&gt;()) { get().~T(); } inline T&amp; get() noexcept { return reinterpret_cast&lt;T&amp;&gt;(storage); } inline const T&amp; get() const noexcept { return reinterpret_cast&lt;const T&amp;&gt;(storage); } }; template&lt;typename T&gt; class Atom { template&lt;typename&gt; friend class Manager; private: enum class State : int {Alive = 0, Unused = 1, Dead = 2}; Idx ctrlIdx; State state{State::Unused}; Uncertain&lt;T&gt; data; // Initializes the internal data template&lt;typename... TArgs&gt; inline void initData(TArgs&amp;&amp;... mArgs) noexcept(ssvu::isNothrowConstructible&lt;T&gt;()) { SSVU_ASSERT(state == State::Unused); data.init(std::forward&lt;TArgs&gt;(mArgs)...); } // Deinitializes the internal data inline void deinitData() noexcept(ssvu::isNothrowDestructible&lt;T&gt;()) { SSVU_ASSERT(state != State::Unused); data.deinit(); } public: inline Atom() = default; inline Atom(Atom&amp;&amp;) = default; inline Atom&amp; operator=(Atom&amp;&amp;) = default; inline T&amp; getData() noexcept { SSVU_ASSERT(state != State::Unused); return data.get(); } inline const T&amp; getData() const noexcept { SSVU_ASSERT(state != State::Unused); return data.get(); } inline void setDead() noexcept { state = State::Dead; } // Disallow copies inline Atom(const Atom&amp;) = delete; inline Atom&amp; operator=(const Atom&amp;) = delete; }; } template&lt;typename T&gt; class Handle { template&lt;typename&gt; friend class Manager; private: using AtomType = typename Internal::Atom&lt;T&gt;; Manager&lt;T&gt;&amp; manager; Idx ctrlIdx; Ctr ctr; inline Handle(Manager&lt;T&gt;&amp; mManager, Idx mCtrlIdx, Ctr mCtr) noexcept : manager(mManager), ctrlIdx{mCtrlIdx}, ctr{mCtr} { } template&lt;typename TT&gt; inline TT getAtomImpl() noexcept { SSVU_ASSERT(isAlive()); return manager.getAtomFromController(manager.controllers[ctrlIdx]); } public: inline AtomType&amp; getAtom() noexcept { return getAtomImpl&lt;AtomType&amp;&gt;(); } inline const AtomType&amp; getAtom() const noexcept { return getAtomImpl&lt;const AtomType&amp;&gt;(); } inline T&amp; get() noexcept { return getAtom().getData(); } inline const T&amp; get() const noexcept { return getAtom().getData(); } bool isAlive() const noexcept; void destroy() noexcept; }; template&lt;typename T&gt; class Manager { template&lt;typename&gt; friend class Handle; private: struct Controller { Idx idx; Ctr ctr; }; using AtomType = typename Internal::Atom&lt;T&gt;; using AtomState = typename AtomType::State; std::vector&lt;AtomType&gt; atoms; std::vector&lt;Controller&gt; controllers; Idx size{0u}; inline void growStorage(std::size_t mOldSize, std::size_t mNewSize) { SSVU_ASSERT(mNewSize &gt;= 0 &amp;&amp; mNewSize &gt;= mOldSize); atoms.resize(mNewSize); controllers.resize(mNewSize); // Initialize resized storage for(; mOldSize &lt; mNewSize; ++mOldSize) { atoms[mOldSize].ctrlIdx = mOldSize; controllers[mOldSize].idx = mOldSize; } } inline void growIfNeeded() { constexpr std::size_t resizeAmount{10}; // If the first free index is valid, return auto oldSize(atoms.size()); if(oldSize &gt; size) return; // Calculate new size and grow storage growStorage(oldSize, oldSize + resizeAmount); } inline void destroy(Idx mCtrlIdx) noexcept { getAtomFromController(controllers[mCtrlIdx]).setDead(); } inline Controller&amp; getControllerFromAtom(const AtomType&amp; mAtom) { return controllers[mAtom.ctrlIdx]; } inline AtomType&amp; getAtomFromController(const Controller&amp; mController) { return atoms[mController.idx]; } inline void cleanUpMemory() { for(auto&amp; a : atoms) if(a.state != AtomState::Unused) { a.deinitData(); a.state = AtomState::Unused; } } public: inline Manager() = default; inline ~Manager() { cleanUpMemory(); } inline void clear() noexcept { cleanUpMemory(); atoms.clear(); controllers.clear(); size = 0; } inline void reserve(std::size_t mSize) { growStorage(atoms.size(), mSize); } template&lt;typename... TArgs&gt; inline Handle&lt;T&gt; createAtom(TArgs&amp;&amp;... mArgs) { // `size` may be greater than the sizes of the vectors - resize vectors if needed growIfNeeded(); // `size` now is the first empty valid index - we create our atom there atoms[size].initData(std::forward&lt;TArgs&gt;(mArgs)...); atoms[size].state = AtomState::Alive; // Update the controller auto cIdx(atoms[size].ctrlIdx); auto&amp; controller(controllers[cIdx]); controller.idx = size; ++controller.ctr; // Update current size ++size; return {*this, cIdx, controller.ctr}; } inline void refresh() { // C++14: use polymorphic lambda ssvu::sortStable(atoms, [](const AtomType&amp; mA, const AtomType&amp; mB){ return mA.state &lt; mB.state; }); // Starting from the end, update dead entities and their controllers auto i(atoms.size() - 1); for(; i &gt; 0 &amp;&amp; atoms[i].state == AtomState::Dead; --i) { atoms[i].deinitData(); atoms[i].state = AtomState::Unused; ++(getControllerFromAtom(atoms[i]).ctr); } // Starting from the beginning, update alive entities and their controllers for(i = 0u; i &lt;= atoms.size() &amp;&amp; atoms[i].state == AtomState::Alive; ++i) getControllerFromAtom(atoms[i]).idx = i; // Update current size size = i; } template&lt;typename TFunc&gt; inline void forEach(TFunc mFunc) { for(auto i(0u); i &lt; size; ++i) mFunc(atoms[i].getData()); } template&lt;typename TFunc&gt; inline void forEachAtom(TFunc mFunc) { for(auto i(0u); i &lt; size; ++i) mFunc(atoms[i]); } inline AtomType&amp; getAtomAt(Idx mIdx) noexcept { SSVU_ASSERT(mIdx &lt; atoms.size()); return atoms[mIdx]; } inline const AtomType&amp; getAtomAt(Idx mIdx) const noexcept { SSVU_ASSERT(mIdx &lt; atoms.size()); return atoms[mIdx]; } inline T&amp; getDataAt(Idx mIdx) noexcept { return getAtomAt(mIdx).getData(); } inline const T&amp; getDataAt(Idx mIdx) const noexcept { return getAtomAt(mIdx).getData(); } inline std::size_t getSize() const noexcept { return size; } }; template&lt;typename T&gt; inline bool Handle&lt;T&gt;::isAlive() const noexcept { return manager.controllers[ctrlIdx].ctr == ctr; } template&lt;typename T&gt; inline void Handle&lt;T&gt;::destroy() noexcept { return manager.destroy(ctrlIdx); } </code></pre> <hr> <p>Example usage:</p> <pre class="lang-cpp prettyprint-override"><code>Manager&lt;std::string&gt; mgr; assert(mgr.getSize() == 0); auto h0 = mgr.createAtom("hi"); auto h1 = mgr.createAtom("bye"); auto h2 = mgr.createAtom("hello"); auto h3 = mgr.createAtom("goodbye"); assert(mgr.getSize() == 4); h0.get() += " sir"; h1.destroy(); h2.get() += " madam; h3.destroy(); mgr.refresh(); assert(!h1.isAlive()); assert(!h3.isAlive()); assert(h0.get() == "hi sir"); assert(h2.get() == "hello madam"); assert(mgr.getSize() == 2); </code></pre>
[]
[ { "body": "<p>A few minor things I've found:</p>\n\n<ul>\n<li><p>This could be a maintenance issue:</p>\n\n<pre><code>inline void cleanUpMemory()\n{\n for(auto&amp; a : atoms) \n if(a.state != AtomState::Unused) \n {\n a.deinitData();\n a.state = AtomState::Unused;\n } \n}\n</code></pre>\n\n<p>There should still be curly braces with the <code>for</code> loop. You already use them elsewhere, so I don't need to go further into that.</p>\n\n<p>I also don't think this needs to be <code>inline</code>. Even when the keyword is needed, it's primarily done with single-line functionality. If the compiler decides to inline it anyway, then it will.</p></li>\n<li><p>This comment is useless:</p>\n\n<pre><code>// Update current size\n++size;\n</code></pre>\n\n<p><code>size</code> is clearly being updated, or specifically, incremented. Comments should be useful and not state the obvious.</p></li>\n<li><p>It may be a little more readable to have the <code>template</code> statement on a separate line from the class or function statement:</p>\n\n<pre><code>template&lt;typename T&gt;\nclass Uncertain\n</code></pre></li>\n</ul>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-05-08T03:44:52.503", "Id": "49204", "ParentId": "49150", "Score": "6" } }, { "body": "<p>Overall, I like your liberal use of C++11 style. One minor nitpick about the use of <code>inline</code> that occurs all over the place:</p>\n\n<pre><code>class Bla\n{\npublic:\n inline void fun() { /* implementation */ }\n ^^^^^^\n};\n</code></pre>\n\n<p>the use of <code>inline</code> is superfluous here since anything defined in-class is implicitly inline, and furthermore, <code>inline</code> is only a compiler <em>hint</em> for actual inlining (the main use of <code>inline</code> is to prevent ODR violations in header files).</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-05-08T20:52:57.103", "Id": "49266", "ParentId": "49150", "Score": "3" } } ]
{ "AcceptedAnswerId": "49204", "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-05-07T14:42:54.970", "Id": "49150", "Score": "4", "Tags": [ "c++", "c++11", "memory-management" ], "Title": "Handle-based entity manager (that stores entities contiguously)" }
49150
<p>As advised by many, I am using a client pool - specifically the Apache <a href="http://hc.apache.org/httpcomponents-client-4.3.x/httpclient/apidocs/org/apache/http/impl/conn/PoolingHttpClientConnectionManager.html">PoolingHttpClientConnectionManager</a>.</p> <p>For simplicity I wrap it in my own simple singleton class. Sorry about the rather OTT <code>Stop</code> mechanism:</p> <pre><code>public final class HttpClientPool { private static final Logger log = LoggerFactory.getLogger(HttpClientPool.class); // Single-element enum to implement Singleton. private static enum Singleton { // Just one of me so constructor will be called once. Client; // The thread-safe client. private final CloseableHttpClient threadSafeClient; // The pool monitor. private final IdleConnectionMonitorThread monitor; // The constructor creates it - thus late private Singleton() { PoolingHttpClientConnectionManager cm = new PoolingHttpClientConnectionManager(); // Increase max total connection to 200 cm.setMaxTotal(200); // Increase default max connection per route to 20 cm.setDefaultMaxPerRoute(20); // Build the client. threadSafeClient = HttpClients.custom() .setConnectionManager(cm) .build(); // Start up an eviction thread. monitor = new IdleConnectionMonitorThread(cm); // Don't stop quitting. monitor.setDaemon(true); monitor.start(); } public CloseableHttpClient get() { return threadSafeClient; } } public static CloseableHttpClient getClient() { // The thread safe client is held by the singleton. return Singleton.Client.get(); } // Watches for stale connections and evicts them. private static class IdleConnectionMonitorThread extends Thread { // The manager to watch. private final PoolingHttpClientConnectionManager cm; // Use a BlockingQueue to stop everything. private final BlockingQueue&lt;Stop&gt; stopSignal = new ArrayBlockingQueue&lt;Stop&gt;(1); // Pushed up the queue. private static class Stop { // The return queue. private final BlockingQueue&lt;Stop&gt; stop = new ArrayBlockingQueue&lt;Stop&gt;(1); // Called by the process that is being told to stop. public void stopped() { // Push me back up the queue to indicate we are now stopped. stop.add(this); } // Called by the process requesting the stop. public void waitForStopped() throws InterruptedException { // Wait until the callee acknowledges that it has stopped. stop.take(); } } IdleConnectionMonitorThread(PoolingHttpClientConnectionManager cm) { super(); this.cm = cm; } @Override public void run() { try { // Holds the stop request that stopped the process. Stop stopRequest; // Every 5 seconds. while ((stopRequest = stopSignal.poll(5, TimeUnit.SECONDS)) == null) { // Close expired connections cm.closeExpiredConnections(); // Optionally, close connections that have been idle too long. cm.closeIdleConnections(60, TimeUnit.SECONDS); // Look at pool stats. log.trace("Stats: {}", cm.getTotalStats()); } // Acknowledge the stop request. stopRequest.stopped(); } catch (InterruptedException ex) { // terminate } } public void shutdown() throws InterruptedException { log.trace("Shutting down client pool"); // Signal the stop to the thread. Stop stop = new Stop(); stopSignal.add(stop); // Wait for the stop to complete. stop.waitForStopped(); // Close the pool - Added threadSafeClient.close(); // Close the connection manager. cm.close(); log.trace("Client pool shut down"); } } public static void shutdown() throws InterruptedException { // Shutdown the monitor. Singleton.Client.monitor.shutdown(); } } </code></pre> <p>I use it exclusively with JSON requests:</p> <pre><code> // General query of the website. Takes an object of type Q and returns one of class R. public static &lt;Q extends JSONObject, R&gt; R query(String urlBase, String op, Q q, Class&lt;R&gt; r) throws IOException { // The request. final HttpRequestBase request; //postRequest.addHeader("Accept-Encoding", "gzip,deflate"); if (q != null) { // Prepare the post. HttpPost postRequest = new HttpPost(urlBase + op); // Get it all into a JSON string. StringEntity input = new StringEntity(asJSONString(q)); input.setContentType("application/json"); postRequest.setEntity(input); // Use that one. request = postRequest; } else { // Just get. request = new HttpGet(urlBase + op); } log.debug("&gt; " + urlBase + op + (q == null ? "" : " " + q)); // Post it and wait. return readResponse(request, HttpClientPool.getClient().execute(request), r); } public static &lt;R&gt; R readResponse(HttpRequestBase request, CloseableHttpResponse response, Class&lt;R&gt; r) throws IOException { // What was read. R red = null; try { // What happened? if (response.getStatusLine().getStatusCode() == 200) { // Roll out the results HttpEntity entity = response.getEntity(); if (entity != null) { InputStream content = entity.getContent(); try { // Roll it directly from the response stream. JsonParser rsp = getFactory().createJsonParser(content); // Bring back the response. red = rsp.readValueAs(r); } finally { // Always close the content. content.close(); } } } else { // The finally below will clean up. throw new IOException("HTTP Response: " + response.getStatusLine().getStatusCode()); } } finally { // Always close the response. response.close(); } if (red == null) { log.debug("&lt; {null}"); } else { log.debug("&lt; {}", red.getClass().isArray() ? Arrays.toString((Object[]) red) : red.toString()); } return red; } </code></pre> <p>This seems to work fine under normal load - however, a recent high-load period caused everything to fall apart. We even interfered with other hosted apps. Not sure what caused the interference but I want to be sure this side of it is done right.</p> <p>The exceptions I saw were:</p> <pre><code>org.apache.http.NoHttpResponseException: The target server failed to respond java.net.BindException: Address already in use: connect java.net.SocketException: No buffer space available (maximum connections reached?): connect -- Thousands of these per hour!!! </code></pre> <p>So - my questions:</p> <ol> <li><p>Am I using the pool correctly?</p></li> <li><p>Am I closing/not closing at the right time?</p></li> <li><p>Should I reset the request (<code>request.reset()</code>)?</p></li> <li><p>Have I missed something?</p></li> </ol> <hr> <p><strong>Added</strong></p> <p>Spot the <em>deliberate mistake</em> - not closing the <code>threadSafeClient</code> at <code>shutdown</code> time. Not relevant to the issue but important. Fixed!</p> <p>Also - failing to close the stream and checking the entity against null. Fixed!</p>
[ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-05-09T13:26:33.543", "Id": "86736", "Score": "0", "body": "Could you specify the version of the library you're using ?" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-05-09T13:34:00.527", "Id": "86738", "Score": "0", "body": "@Marc-Andre - httpcomponents version 4.3.3 - thank you for your interest." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-05-09T13:47:05.137", "Id": "86741", "Score": "0", "body": "@Marc-Andre - I forgot! The problem occurred while I was using 4.2.5 and a slightly less streamlined close mechanism. I am primarily interested in confirmation that this way is **right**." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-05-09T13:50:08.773", "Id": "86742", "Score": "0", "body": "As I was suspecting the Http Apache changes a lot with each version, so that's why I've ask for the version, I'm glad you resolve your problem. I'll see if I can come up with an answer but everything looks fine so far." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-05-09T13:54:46.340", "Id": "86745", "Score": "0", "body": "@Marc-Andre - May also be significant that I am running under Java 5." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2015-09-17T13:38:42.303", "Id": "192034", "Score": "0", "body": "You know what's funny? We're dealing with http connections not closing themselves and when I looked at the code, well all the advice I gave we're applicable to our code. Code Review is really helpful!" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2016-06-05T14:24:08.487", "Id": "244551", "Score": "0", "body": "@OldCurmudgeon - slightly not related, but may I ask how much load you are able handle with this code? You wrote things started to fall off when the load was increased. Thanks!" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2016-06-06T12:17:32.613", "Id": "244667", "Score": "0", "body": "@jagamot - The instability showed itself under pressure. The various changes I made removed the instability. Not sure of the specific causes but suspect it was failing to close the stream or the upgrade from 4.2.2 to 4.3.3." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2016-06-06T12:30:12.853", "Id": "244668", "Score": "0", "body": "Would you mind sharing the latest you have? And what load is it able to handle currently under what memory configurations?..only if you can share! I am in a similar boat and I see issues under load, like running OOM etc." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2016-06-06T12:37:40.023", "Id": "244672", "Score": "0", "body": "@jagamot - The code as posted matches the live setup in all reasonable respects. I have no metrics for it's stability under load - that is likely to be subjective." } ]
[ { "body": "<p>I'm not an expert in the library or multithreading, so maybe some advises will not be applicable. </p>\n\n<p><strong>TL;DR</strong><br>\nI didn't find anything in your code really wrong. In fact, the more I look at it, the more I can just find only nitpicking things, and I'm really forcing myself. I would find myself quite happy to maintain this code. Everything is clean, the exception managing is excellent and it's quite easy to read.</p>\n\n<p><code>readResponse</code> Looks clean to me. What is important when working with the request is to always \"consume\" the entity and/or close the request. At first, I thought that you had a problem when the request didn't return a <code>200</code>. When the return code is not <code>200</code> you're not consuming the <code>Entity</code> which can normally block the connection, but it seems that you don't need to consume the <code>Entity</code> if you <code>close()</code> the request. In my code, I'm still using <code>EntityUtils.consume()</code>, but it's probably overkill.</p>\n\n<p><code>query</code> seems a bit weird to me. I always see either <code>get</code> or <code>post</code> not both. I find weird that <code>query</code> can do both, since normally it's very two different things. Despite that fact, it still really well handled.</p>\n\n<p>This line is a bit hard to fully grasp at first read IMO : </p>\n\n<blockquote>\n<pre><code>return readResponse(request, HttpClientPool.getClient().execute(request), r);\n</code></pre>\n</blockquote>\n\n<p>I find it hard to see that this it's actually where you're making the request. It could be in it's own line, to better extract it's important role. I find it easier to debug too.</p>\n\n<blockquote>\n<pre><code>final HttpRequestBase request;\n//postRequest.addHeader(\"Accept-Encoding\", \"gzip,deflate\");\n</code></pre>\n</blockquote>\n\n<p>I guess the comment is a dead one. It could be remove since it serve no purpose. In general, I find there is a bit too much comments for my own taste, but this is basically because your code is very clean and comments are just expressing what I understand by just reading your code. (I'm really impress by the quality)</p>\n\n<blockquote>\n<pre><code>// Post it and wait.\n</code></pre>\n</blockquote>\n\n<p>This one is not quite true, because you could be executing a <code>Get</code> request and not a <code>Post</code>. I'm starting to think that those methods were at first working with <code>Post</code> request and evolve into both type of request. (base on the dead comment and this one)</p>\n\n<blockquote>\n<pre><code> if (response.getStatusLine().getStatusCode() == 200)\n</code></pre>\n</blockquote>\n\n<p>Instead of <code>200</code> I would personaly use <code>HttpStatus.OK</code>.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-05-10T14:06:38.150", "Id": "86862", "Score": "1", "body": "Thank you Marc for your helpful comments. You are right in all cases - I will adjust my code accordingly." } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-05-10T01:38:34.250", "Id": "49381", "ParentId": "49151", "Score": "7" } }, { "body": "<p>One small correction here:</p>\n\n<pre><code> // Close the pool - Added\n threadSafeClient.close();\n</code></pre>\n\n<p>Change this to:</p>\n\n<pre><code>// Close the pool - Added\nSingleton.Client.threadSafeClient.close();\n</code></pre>\n\n<p>Explanation:</p>\n\n<p>There is no <code>threadSafeClient</code> field in <code>IdleConnectionMonitorThread</code> class, thus the code fails to compile. Since this field is present in Singleton, the correct way of closing this is:</p>\n\n<pre><code>Singleton.Client.threadSafeClient.close();\n</code></pre>\n\n<p>This fixes the compilation error.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2015-06-11T04:36:29.657", "Id": "93286", "ParentId": "49151", "Score": "3" } }, { "body": "<p>You create only one Connection.\nTry this:</p>\n\n<pre><code>private static enum Singleton {\n // Just one of me so constructor will be called once.\n Client;\n // The pool\n private PoolingHttpClientConnectionManager cm;\n\n // The constructor creates it - thus late\n private Singleton() {\n cm = new PoolingHttpClientConnectionManager();\n // Increase max total connection to 200\n cm.setMaxTotal(200);\n // Increase default max connection per route to 20\n cm.setDefaultMaxPerRoute(20);\n\n }\n\n public CloseableHttpClient get() {\n CloseableHttpClient threadSafeClient = HttpClients.custom()\n .setConnectionManager(cm)\n .build();\n return threadSafeClient;\n }\n\n}\n</code></pre>\n\n<p>`</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2016-06-16T10:44:51.517", "Id": "132168", "ParentId": "49151", "Score": "2" } } ]
{ "AcceptedAnswerId": "49381", "CommentCount": "10", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-05-07T14:44:31.783", "Id": "49151", "Score": "31", "Tags": [ "java", "http", "client" ], "Title": "HTTP Client requests done right" }
49151
<p>I've been writing far too many routines in JavaScript that get a record from a an object or array based off a matching property, much like jQuery does with DOM elements. Since all the good names are taken, I called it <code>Hmm</code>.</p> <p>I went with the philosophy that if I don't need it yet, I wont provide for it. </p> <pre><code>var Hmm = (function() { //A snippet/library to find records in table-like JS arrays function getNamedValue( o , name ) { //Name can have dots, 'car.tire.brand.name' should get the expected var parts = name.split("."); while( parts.length &amp;&amp; o ){ o = o[parts.shift()]; } return o; } function unique( ) { //Assuming `this` is an array, will copy all unique entries of `this` to a returned new array var array = [], map = {}, json; this.forEach( function( value ){ if( value instanceof Object ){ json = JSON.stringify( value ); if( !map[json] ){ array.push( value ); map[json] = true; } } else if( !~array.indexOf( value ) ){ array.push( value ); } }); return array; } function Hmm( data ) { //data could be a string -&gt; treat as JSON, parse it //data could be an object, or a string that got converted to an object -&gt; convert to array //data could be an array ( original or through conversion ) -&gt; leave as is this.data = data instanceof Object ? data : JSON.parse( data ); this.data = this.data instanceof Array ? this.data : [ this.data ]; } Hmm.prototype.index = function( name ) { //Name can have dots, 'car.tire.brand.name' should get the expected //Generates an index object var index = {} , i; this.data.forEach( function( value ) { var key = getNamedValue( value , name ), keys = key instanceof Array ? key : [key]; for( i = 0 ; i &lt; keys.length ; i++ ) { key = keys[i]; index[key] = index[key] || []; index[key].push( value ); } }); return index; }; Hmm.prototype.uniqueIndex = function( name ) { //Create an index, point each index to the first of possible values var index = this.index( name ); Object.keys( index ).forEach( function(key){ index[key] = index[key][0]; }); return index; }; Hmm.prototype.collect = function( name ) { //Collect all the values for a given property name var values = this.data.map( function ( o ) { return getNamedValue( o , name ); }); values.unique = unique; return values; }; Hmm.prototype.toString = function() { //More for jsbin than anything else return JSON.stringify( this.data ); }; return Hmm; }()); //Some tests var foods = [ { name : 'potatoes' , calories : 100 , allergens : [] , storage : 'ambient' }, { name : 'pistachio ice cream' , calories : 1000 , allergens : ['nuts','milk'] , storage : 'frozen' }, { name : 'chocolate ice cream' , calories : 1200 , allergens : ['milk'] , storage : 'frozen' }, { name : '2% fat milk' , calories : 600 , allergens : ['milk'] , storage : 'chilled' } ]; var hmm = new Hmm( foods ); console.log( hmm.collect('name') ); //Collect all names console.log( hmm.collect('allergens') ); // console.log( hmm.collect('allergens').unique() ); console.log( hmm.collect('allergens.0') ); console.log( hmm.collect('allergens.0').unique().sort() ); console.log( hmm.index('name') ); console.log( hmm.index('name').potatoes ); console.log( hmm.index('allergens').milk ); console.log( hmm.uniqueIndex('name') ); console.log( hmm.uniqueIndex('name').potatoes ); console.log( hmm.index('allergens') ); console.log( hmm.index('allergens.0') ); //Index on the first allergy </code></pre>
[]
[ { "body": "<p>It's very nice. What few qualms I have are a result of me looking really hard for things to have qualms about (furrowing my brow and going \"hmm\", basically).</p>\n\n<p>Anyway, some thoughts:</p>\n\n<ul>\n<li><p>Your <code>unique</code> function relies on the assumption that there are no circular references in the object passed to <code>JSON.stringify</code>. It's probably a fair assumption, but an assumption nonetheless. Also, from a specification standpoint, JSON representation of objects doesn't impose or guarantee any ordering of properties. I <em>highly</em> doubt it'll ever be an issue anywhere, but it could mean that identical objects will have different JSON representations, and <code>unique</code> would thus include both those objects.</p></li>\n<li><p>Similarly edge-case'y: Your <code>instanceof</code> usage is vulnerable to <a href=\"https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/instanceof#instanceof_and_multiple_context_%28e.g._frames_or_windows%29\" rel=\"nofollow\">the usual cross-frame pitfalls</a>.</p></li>\n<li><p>The <code>!~array.indexOf( value )</code> trick is a bit arcane. It's neat, but I don't think I've actually seen it used anywhere - except in some other code you posted :)<br>\nA <code>=== -1</code> comparison isn't nearly as cool, but it wouldn't cause me to go \"huh?\". In other words: I like it, but I wouldn't call it obvious or idiomatic.</p></li>\n<li><p>That curly-brace-on-new-line style just rubs me the wrong way, but you know what you're doing, so I'll spare you the \"automatic semi-colon insertion\" speech :)</p></li>\n</ul>\n\n<p>On a more overall note: Like jQuery, it might be useful to always return a <code>Hmm</code>-wrapped array, instead of only adding <code>unique</code> to the array returned by <code>collect</code>. Of course it'd be quite a different API.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-05-16T21:31:15.370", "Id": "50966", "ParentId": "49152", "Score": "6" } }, { "body": "<p>First off, a couple of your function names are slightly misleading/go against naming conventions in other libraries.</p>\n\n<ul>\n<li><code>{hmm}.index</code> seems to be more of a <a href=\"http://underscorejs.org/#groupBy\" rel=\"nofollow noreferrer\"><code>group</code></a> function than a index finder.</li>\n<li><code>{hmm}.collect</code> appears to be a <a href=\"http://laravel.com/api/function-array_pluck.html\" rel=\"nofollow noreferrer\"><code>pluck</code></a> function but I've heard it called <code>collect</code> as well so \\o/</li>\n<li><code>{hmm}.uniqueIndex</code> should, imo, be called <code>groupFirst</code></li>\n</ul>\n\n<hr>\n\n<p>Alright, with that out of the way lets talk implementation</p>\n\n<p>I think it would be useful for <code>Hmm</code> to inherit from <code>Array</code> as a pure wrapper - most of what you can do with an array you can do with an <code>hmm</code> instance (at least in modern browsers see <a href=\"https://stackoverflow.com/q/3261587/1517919\">Subclassing Javascript Arrays.</a>.</p>\n\n<p>This would just involve refactoring your code a little:</p>\n\n<pre><code>var push = Array.prototype.push;\nfunction Hmm( data ) {\n //data could be a string -&gt; treat as JSON, parse it\n //data could be an object, or a string that got converted to an object -&gt; convert to array\n //data could be an array ( original or through conversion ) -&gt; leave as is\n var _data = data instanceof Object ? data : JSON.parse( data );\n _data = _data instanceof Array ? _data : [ _data];\n push.apply(this, _data); //merge with this hmm instance\n}\n\nHmm.prototype = [];\n// ....\n</code></pre>\n\n<p>Disclaimer: this may be too clever and might not work in some environments :)</p>\n\n<p>Next, you can decide if you want to rewrite <code>map</code>, <code>filter</code>, et al to produce a <code>hmm</code> rather than an <code>array</code></p>\n\n<p>Another advantage of doing this is you can define <code>unique</code> on <code>hmm.prototype</code> so</p>\n\n<p><code>Object.keys(hmm.collect('allergens.0')) != [\"0\", \"1\", \"2\", \"3\", \"unique\"]</code> which I would consider a bug.</p>\n\n<hr>\n\n<p>Other stuff</p>\n\n<p>Seeing you seem to be writing for modern environments anyway I would write your constructor logic</p>\n\n<pre><code>var _data = typeof data !== \"string\" ? data : JSON.parse( data );\nthis.data = Array.isArray(_data) ? this.data : [ this.data ];\n</code></pre>\n\n<p>If you want to convert <code>Array-likes</code> (such as a <code>hmm</code> or <code>jQuery</code> instance) to <code>hmms</code> I would use the <code>underscore</code> check <a href=\"https://github.com/jashkenas/underscore/issues/1590\" rel=\"nofollow noreferrer\">see this issue for some discussion</a>:</p>\n\n<pre><code>var _data = typeof data !== \"string\" ? data : JSON.parse( data );\nthis.data = _data &amp;&amp; _data.length === +_data.length ? this.data : [ this.data ];\n</code></pre>\n\n<p>You may also want to consider catching the <code>JSON.parse</code> - if it fails wrap the string in the <code>hmm</code> object, however that may lead to weird edge cases.</p>\n\n<p>I might come back to his later as I need to take off. Last thing as has been mentioned, you're not a hacker -- no need for <code>!~array.indexOf( value )</code>.. <code>array.indexOf( value ) &lt; 0</code> is the same number of bits and faster</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-05-16T23:40:05.267", "Id": "50974", "ParentId": "49152", "Score": "4" } } ]
{ "AcceptedAnswerId": "50966", "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-05-07T14:45:33.037", "Id": "49152", "Score": "15", "Tags": [ "javascript", "search", "query-selector" ], "Title": "Hmm, a thoughtful library" }
49152
<p>I am trying to build something similar to planning poker and am very new to Knockout and was wondering if anyone could help me improve on my very crude start?</p> <p>This is what I have so far:</p> <p>HTML</p> <p>Selected Card</p> <p>CSS </p> <pre><code> .profile { width: 50px; height: 80px; color: #FFF; background: black; border: 1px solid #FFF; float: left; line-height:80px } .highlight { background: yellow !important; border:1px solid #000; color: black; } </code></pre> <p>JavaScript/Knockout </p> <pre><code>function Step(number) { this.active = ko.observable(false); this.name = ko.observable( number); } var model = function () { var items = ko.observableArray([new Step(1), new Step(2), new Step(3), new Step(5),new Step(8),new Step(13),new Step(20),new Step(40),new Step(100)]); var selectedItems = ko.computed(function () { return _.filter(items(), function (item) { return item.active(); }); }) var clicked = function (item) { items().forEach(function(item){ item.active(false) }); item.active(!this.active()); }; var save = function () { alert("sending items \n" + ko.toJSON(selectedItems())); } return { items: items, selectedItems: selectedItems, save: save, clicked: clicked } } ko.applyBindings(model); </code></pre> <p><a href="http://jsfiddle.net/grahamwalsh/63yeD/" rel="nofollow">http://jsfiddle.net/grahamwalsh/63yeD/</a></p>
[ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-05-07T15:06:17.673", "Id": "86357", "Score": "2", "body": "The html part seems to be missing." } ]
[ { "body": "<p>A surprisingly good start, most knockout code looks terrible to me, but I can follow this, it's well laid out, JsHint has nothing to complain about.</p>\n\n<p>Only this bothered me: </p>\n\n<pre><code>var items = ko.observableArray([new Step(1), new Step(2), new Step(3), new Step(5),new Step(8),new Step(13),new Step(20),new Step(40),new Step(100)]);\n</code></pre>\n\n<p>I would have approached that a little differently:</p>\n\n<pre><code>var steps = [1,2,3,5,8,13,20,40,100];\nfor ( var i = 0 ; i &lt; steps.length ; i++ )\n steps[i] = new Step( steps[i] );\nvar items = ko.observableArray( steps )\n</code></pre>\n\n<p>What this does is more clearly show the different steps from 1-> 100, and take out the repetition in your code of calling <code>new Step</code> for every single step.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-05-07T15:09:41.623", "Id": "49156", "ParentId": "49154", "Score": "0" } }, { "body": "<p>I'm only going to focus on this piece of code since I'm not a knockout expert:</p>\n\n<pre><code>var selectedItems = ko.computed(function () {\n return _.filter(items(), function (item) {\n return item.active();\n });\n})\n</code></pre>\n\n<p>First of all I would call this variable <code>selectedItem</code> since you can only have one and not multiple selected items.\nSecondly <code>UnderscoreJS</code> provides you a function called <code>find</code>. It's in my opinion more clear to use this function instead of filter because <code>filter</code> can return multiple results.</p>\n\n<pre><code>var selectedItem = ko.computed(function () {\n return _.find(items(), function (item) {\n return item.active();\n });\n})\n</code></pre>\n\n<p>Another small remark, add semicolons after your statements. Consider the following:</p>\n\n<pre><code>var save = function() {\n\n}\n// Another developer adds an anonymous function after your save function.\n// This will break your code\n(function() {\n\n})();\n</code></pre>\n\n<p>It won't break your code if you add semicolons:</p>\n\n<pre><code>var save = function() {\n\n};\n(function() {\n // This will work\n})();\n</code></pre>\n\n<p>This is not necessary if you define a function as follows:</p>\n\n<pre><code>function save() {\n\n}\n(function() {\n // This will also work\n})(); \n</code></pre>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-05-09T12:43:14.027", "Id": "49328", "ParentId": "49154", "Score": "0" } }, { "body": "<p>You are using function as definition for model and inside that function you are defined an interface to have access to those properties/methods. In complicated cases you would have inflexible usage between definition and public interface. Better solution would be to create definition for the class like this</p>\n\n<pre><code>var Model = function () {\n var self = this;\n self.selectedItems = ko.computed(function () {\n return _.filter(items(), function (item) {\n return item.active();\n });\n })\n}\n</code></pre>\n\n<p>and then create an instance of it</p>\n\n<pre><code>var model = new Model();\n</code></pre>\n\n<p>because a <strong>new</strong> operator you will create new JS object and this object will be send as scope for current <strong>this</strong> content. This is commonly used patterns in order to follow OOJ see link here <a href=\"https://developer.mozilla.org/en-US/docs/Web/JavaScript/Introduction_to_Object-Oriented_JavaScript\" rel=\"nofollow\">https://developer.mozilla.org/en-US/docs/Web/JavaScript/Introduction_to_Object-Oriented_JavaScript</a></p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-05-22T13:26:42.777", "Id": "51405", "ParentId": "49154", "Score": "2" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "1", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-05-07T14:54:30.550", "Id": "49154", "Score": "4", "Tags": [ "javascript", "css", "knockout.js" ], "Title": "Planning Poker Using Knockout" }
49154
<p>I need <code>roomId</code> (an <code>auto_increment</code> primary key) to locate a specific room to update chat info. My way of doing it right now is dumb.</p> <p>In <code>createRoom.js</code>, I use <code>roomName</code> from a form that a user has entered to create a room model and find its <code>roomId</code>, then make <code>roomId</code> a param of a URL:</p> <pre><code>var Room = require('../models/database').Room exports.create = function (req, res) { Room .create({ room_name: req.body.roomName }) .complete(function () { Room .find({where: {room_name: req.body.roomName}}) .success(function (room) { res.redirect('rooms/videochat/' + req.body.roomName + '/' + room.room_id); }) }) }; </code></pre> <p>in <code>routes.js</code>, I grab <code>roomId</code> with <code>req.params.roomId</code> and pass it to a view file jade so it can be displayed on a video chat page:</p> <pre><code>app.get('/rooms/videochat/:roomName/:roomId', function (req, res) { res.render('videochat.jade', {roomName: req.params.roomName, roomId: req.params.roomId}); }); </code></pre> <p>In the client side JavaScript, I use</p> <pre><code>var roomId = $('#roomId span').text(); </code></pre> <p>to get the <code>roomId</code>, then use socket.emit to pass it back to server side:</p> <pre><code>socket.emit('updateStartTime', roomId); </code></pre>
[ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-05-07T15:32:34.340", "Id": "86364", "Score": "1", "body": "It seems like your code does not work as it will not fire `socket.on('disconnect')`, which makes it off-topic for CR." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-05-07T15:55:17.813", "Id": "86375", "Score": "0", "body": "Hi, it will fire when users click close window button." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-05-09T15:49:47.173", "Id": "86777", "Score": "0", "body": "@konijn the code works as it can get roomId successfully. i just want to see if there is a bette way. it does not contain broken code" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-05-09T15:54:57.247", "Id": "86778", "Score": "0", "body": "Voting to re-open now" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-05-09T17:41:08.417", "Id": "86784", "Score": "0", "body": "you have a lot of Empty White Space in that code, you should really get rid of that in your code." } ]
[ { "body": "<p>Interesting question,</p>\n\n<p>my first point is that it is not clear how you wrote the <code>Room</code> module, but ideally, that module should do 2 things:</p>\n\n<ol>\n<li>Provide the created room to <code>complete</code></li>\n<li>Provide a way to deal with failure</li>\n</ol>\n\n<p>Then, I would expect in the top code to see something like this:</p>\n\n<pre><code>var Room = require('../models/database').Room\n\nexports.create = function (req, res) {\n Room.create({\n room_name: req.body.roomName\n })\n .complete(function ( success, room ) {\n if( success )\n res.redirect('rooms/videochat/' + room.roomName + '/' + room.roomId );\n else\n res.redirect('cuteapologetickittenvideo/');\n });\n};\n</code></pre>\n\n<p>You will notice that I also changed <code>req.body.roomName</code> -> room.room_name -> room.roomName which makes more sense to me. On a general note I find it bad practice to require <code>room_name</code> in your call to the constructor, but <code>roomName</code> in the request. I would suggest to stick to 1 convention (The JavaScript One) and use <code>roomName</code> everywhere. Then you could write</p>\n\n<pre><code>var Room = require('../models/database').Room\n\nexports.create = function (req, res) {\n Room.create( req.body ).complete(function roomComplete( success, room ) {\n if( success )\n res.redirect('rooms/videochat/' + room.roomName + '/' + room.roomId );\n else\n res.redirect('cuteapologetickittenvideo/');\n });\n};\n</code></pre>\n\n<p>For the Jade processing, you should be able to get room id and name from the matching on <code>'/rooms/videochat/:roomName/:roomId'</code>.</p>\n\n<p>Same for the client side javascript, I would be more inclined to get this from the URL than from a field in the HTML.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-08-07T21:11:02.887", "Id": "59441", "ParentId": "49157", "Score": "2" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "5", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-05-07T15:13:37.030", "Id": "49157", "Score": "3", "Tags": [ "javascript", "beginner", "jquery", "node.js", "socket" ], "Title": "Getting the current chat room ID" }
49157
<p>I'm writing Stringbuilder to file asynchronously. This code takes control of a file, writes a stream to it and releases it. It deals with requests from asynchronous operations, which may come in at any time.</p> <p>The <code>FilePath</code> is set per class instances (so the lock <code>Object</code> is per instance), but there is potential for conflict since these classes may share <code>FilePath</code>s. That sort of conflict, as well as all other types from outside the class instance, would be dealt with with retries.</p> <p>Is this code suitable for its purpose? Is there a better way to handle this that means less (or no) reliance on the catch and retry mechanic? </p> <p>Also how do I avoid catching exceptions that have occurred for other reasons?</p> <pre><code>public string Filepath { get; set; } private Object locker = new Object(); public async Task WriteToFile(StringBuilder text) { int timeOut = 100; Stopwatch stopwatch = new Stopwatch(); stopwatch.Start(); while (true) { try { //Wait for resource to be free lock (locker) { using (FileStream file = new FileStream(Filepath, FileMode.Append, FileAccess.Write, FileShare.Read)) using (StreamWriter writer = new StreamWriter(file, Encoding.Unicode)) { writer.Write(text.ToString()); } } break; } catch { //File not available, conflict with other class instances or application } if (stopwatch.ElapsedMilliseconds &gt; timeOut) { //Give up. break; } //Wait and Retry await Task.Delay(5); } stopwatch.Stop(); } </code></pre>
[ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-05-07T19:56:53.090", "Id": "86422", "Score": "0", "body": "Can you elaborate on what your *requirements* are? That will make it easier to not over-engineer this." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-05-07T20:31:57.650", "Id": "86442", "Score": "0", "body": "There's a load test going on and every time a unit test is run it is logged. I think every unit test has it's own file so the lock on its own should be sufficient. If that's not the case, come to think of it, this try again method would probably be overwhelm and it would have to be a static lock. I think I'll just make it a simple lock and comment in my assumptions." } ]
[ { "body": "<p><strong>I'm not sure why this is async.</strong></p>\n\n<p>Unless you have a good reason for write to the file asynchronously, this is wasted effort.</p>\n\n<p>If you <code>lock</code> properly, this will work fine. Your <code>locker</code> variable should be marked <code>static</code>. You can then get away with something like this:</p>\n\n<pre><code>using System;\nusing System.IO;\nusing System.Text;\nusing System.Threading;\nusing System.Threading.Tasks;\n\nnamespace test\n{ \n public class Writer\n {\n public string Filepath { get; set; }\n private static object locker = new Object();\n\n public void WriteToFile(StringBuilder text)\n {\n lock (locker)\n {\n using (FileStream file = new FileStream(Filepath, FileMode.Append, FileAccess.Write, FileShare.Read))\n using (StreamWriter writer = new StreamWriter(file, Encoding.Unicode))\n {\n writer.Write(text.ToString());\n }\n }\n\n }\n }\n}\n</code></pre>\n\n<p>This assumes you don't have some other reason for making this async.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-05-07T19:56:20.560", "Id": "86421", "Score": "2", "body": "By making the lock object `static` you lose the capability of writing to several files at once because all instances of `Writer` will have to wait, no matter what file they are writing to." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-05-08T13:29:14.280", "Id": "86513", "Score": "3", "body": "If each instance of `Writer` points to a different file, then correct, you can use an instance locking object. If you have two instances of `Writer` pointing at the same file, the locking will do nothing unless you use the `static` lock." } ], "meta_data": { "CommentCount": "2", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-05-07T16:48:33.777", "Id": "49161", "ParentId": "49158", "Score": "18" } } ]
{ "AcceptedAnswerId": "49161", "CommentCount": "2", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-05-07T15:20:39.193", "Id": "49158", "Score": "10", "Tags": [ "c#", "multithreading", "thread-safety", "file-system" ], "Title": "Writing to file in a thread safe manner" }
49158
<p><strong>Code Objective</strong><br> I need to create a <code>System.Data.DataSet</code> object from an Excel workbook. Each <code>DataTable</code> within the <code>DataSet</code> must correspond to a nonempty worksheet in the workbook. The top row of each sheet will be used as column names for each <code>DataTable</code> and the columns will be populated as the string representation of the worksheet data. The string part here is very important--everything in the final <code>DataSet</code> must be visually identical to what is in the Excel file with no assumptions about data types.</p> <p><strong>The Issue</strong><br> My code is horrendously slow. The workbook I'm using to test my code has one worksheet which uses the Excel columns A through CO and uses rows 1 through 11361, so I don't expect it to be too blazing fast, but I finally stopped it after 20 minutes of letting it run. That's really slow, even for a big workbook.</p> <p><strong>My Goal Here</strong><br> I would love your help in determining the cause of the slowness, or perhaps if there's an altogether more efficient way of going about this. My instinct was to post this to Stack Overflow, but I figured this would be a better place because the code actually works and does what I want it to do, it just does it very slowly.</p> <p><strong>The Code</strong><br> I used Dylan Morley's code <a href="http://www.codeproject.com/Questions/164267/Diificulty-in-releasing-Excel-COM-objects" rel="nofollow noreferrer">here</a> for creating an Excel "wrapper" which aids with orphaned Excel processes and the release of COM objects.</p> <pre><code>namespace Excel.Helpers { internal class ExcelWrapper : IDisposable { private class Window { [DllImport("user32.dll", SetLastError = true)] static extern IntPtr FindWindow(string lpClassName, string lpWindowName); [DllImport("user32.dll")] private static extern IntPtr GetWindowThreadProcessId(IntPtr hWnd, out IntPtr ProcessID); public static IntPtr GetWindowThreadProcessId(IntPtr hWnd) { IntPtr processID; IntPtr returnResult = GetWindowThreadProcessId(hWnd, out processID); return processID; } public static IntPtr FindExcel(string caption) { IntPtr hWnd = FindWindow("XLMAIN", caption); return hWnd; } } private Application excel; private IntPtr windowHandle; private IntPtr processID; private const string ExcelWindowCaption = "MyUniqueExcelCaption"; public ExcelWrapper() { excel = CreateExcelApplication(); windowHandle = Window.FindExcel(ExcelWindowCaption); processID = Window.GetWindowThreadProcessId(windowHandle); } private Application CreateExcelApplication() { Application excel = new Application(); excel.Caption = ExcelWindowCaption; excel.Visible = false; excel.DisplayAlerts = false; excel.AlertBeforeOverwriting = false; excel.AskToUpdateLinks = false; return excel; } public Application Excel { get { return this.excel; } } public int ProcessID { get { return this.processID.ToInt32(); } } public int WindowHandle { get { return this.windowHandle.ToInt32(); } } public void Dispose() { if (excel != null) { excel.Workbooks.Close(); excel.Quit(); Marshal.ReleaseComObject(excel); excel = null; GC.Collect(); GC.WaitForPendingFinalizers(); GC.Collect(); GC.WaitForPendingFinalizers(); try { Process process = Process.GetProcessById(this.ProcessID); if (process != null) { process.Kill(); } } catch { throw; } } } } } </code></pre> <p>Now I make a class that processes the Excel files using <code>Microsoft.Office.Interop.Excel</code> operations.</p> <pre><code>namespace FileProcessing { class FileToProcess { public string File { get; set; } public DataSet GetExcelData() { using (var wrapper = new Excel.Helpers.ExcelWrapper()) { Application oXL = wrapper.Excel; Workbook oWB = oXL.Workbooks.Open(this.File, 0, true); try { DataSet excelData = new DataSet(); foreach (Worksheet oSheet in oWB.Worksheets) { int nColumns = oSheet.UsedRange.Columns.Count; int nRows = oSheet.UsedRange.Rows.Count; if (nColumns &gt; 0) { System.Data.DataTable sheetData = excelData.Tables.Add(oSheet.Name); Range rHeaders = (Range)oSheet.UsedRange.Rows[1]; for (int j = 1; j &lt;= nColumns; j++) { string columnName = rHeaders.Columns[j].Text.ToString(); if (string.IsNullOrEmpty(columnName)) continue; else if (sheetData.Columns.Contains(columnName)) { int i = 1; string c; do { c = columnName + i.ToString(); i += 1; } while (sheetData.Columns.Contains(c)); sheetData.Columns.Add(c, typeof(string)); } else sheetData.Columns.Add(columnName, typeof(string)); } for (int i = 2; i &lt;= nRows; i++) { DataRow sheetRow = sheetData.NewRow(); for (int j = 1; j &lt;= nColumns; j++) { string columnName = rHeaders.Columns[j].Text.ToString(); Range oRange = (Range)oSheet.Cells[i, j]; if (!string.IsNullOrEmpty(columnName)) sheetRow[columnName] = oRange.Text.ToString(); } sheetData.Rows.Add(sheetRow); } } } return excelData; } catch (Exception) { throw; } finally { oWB.Close(); oWB = null; oXL.Quit(); oXL = null; wrapper.Dispose(); } } } } </code></pre> <p>Finally I try to use the class. This is just a testing example where I record the amount of time the code takes to read the file and construct the dataset.</p> <pre><code> class Program { static void Main(string[] args) { Stopwatch sw = Stopwatch.StartNew(); FileToProcess testXLFile = new FileToProcess(); testXLFile.File = @"C:\BigWorkbook.xls"; DataSet ds = testXLFile.GetExcelData(); sw.Stop(); TimeSpan ts = sw.Elapsed; Console.WriteLine("Elapsed Time: {0}ms", ts.Milliseconds); Console.ReadKey(); } } } </code></pre> <p><strong>Closing Remarks</strong><br> My thought here is that reading each cell one at a time is taking forever on huge worksheets. I don't know how else to ensure that each value is properly captured as a string though. I don't want to ever assume that a particular column or cell has a particular data type to avoid conversion issues and preserve data integrity between the Excel file and the <code>DataSet</code>. I saw user3488442's question <a href="https://codereview.stackexchange.com/questions/47227/reading-data-from-excel-sheet-with-exceldatareader">here</a> but I'm not convinced that I could modify it to suit my needs without running into conversion issues. Conversion between dates (which import as <code>DateTime</code> objects in C#) and strings doesn't always preserve the display format in the worksheet. I also saw <a href="https://codereview.stackexchange.com/questions/43290/importing-data-from-an-external-excel-sheet">this question</a> but it uses a VBA macro (and I don't speak German). Any input would be much appreciated.</p>
[ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-05-07T17:05:34.877", "Id": "86385", "Score": "1", "body": "As a short info, I am the OP of the second question you mention. FYI what I use is an Excel Macro (VBA). That would require you to recode your whole program, as vba != vb (!) != c#.... The Macro is executed inside the Excel application itself, and thus has some overhead less, that comes from using COM / interop. You might consider switching to a macro *after* refactoring your current approach" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-05-07T17:10:47.243", "Id": "86387", "Score": "0", "body": "@Vogel612: Thanks for your input. Unfortunately I can't switch to a macro because I will need to apply this approach to a bunch of files. My actual program (which was edited here to include only Excel) includes handling for files other than Excel workbooks as well." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-05-07T17:46:30.073", "Id": "86393", "Score": "0", "body": "What happens if you change your Range oRange = (Range)oSheet.Cells[i, j]; call to the outside loop, selecting multiple rows and all columns and loop through that? (A guess that if that is slow, it may have a fixed overhead)" } ]
[ { "body": "<blockquote>\n <p><em>The workbook I'm using to test my code has one worksheet which uses the Excel columns A through CO and uses rows 1 through 11361, so I don't expect it to be too blazing fast [...]</em></p>\n</blockquote>\n\n<p>Cell CO11361, in R1C1 notation, is R11361C93. You're reading the value of 1,056,573 cells, through COM interop... just to return a <code>DataSet</code>.</p>\n\n<p>Excel Interop wasn't designed for this.</p>\n\n<p>Since you're returning a <code>DataSet</code>, it looks like a safe assumption to make, that the workbook data has the <em>shape</em> of a data table.</p>\n\n<p>I have this code that I've been using on some Excel 97-2003 files, I'm sure it can be tweaked to work with newer versions - basically you write an implementation for this interface:</p>\n\n<pre><code>/// &lt;summary&gt;\n/// An interface exposing functionality required to convert a Microsoft Excel workbook into a &lt;see cref=\"DataTable\"/&gt; object using an &lt;see cref=\"OleDbConnection\"/&gt;.\n/// &lt;/summary&gt;\npublic interface IExcelOleDbReader\n{\n /// &lt;summary&gt;\n /// Converts specified Microsoft Excel workbook into a &lt;see cref=\"DataTable\"/&gt; object.\n /// &lt;/summary&gt;\n /// &lt;param name=\"fileName\"&gt;The name of the file to import.&lt;/param&gt;\n /// &lt;returns&gt;&lt;/returns&gt;\n DataTable ImportExcelFile(string fileName);\n}\n</code></pre>\n\n<hr>\n\n<p>Here's the Excel 8.0 implementation I have:</p>\n\n<pre><code>public class Excel8OleDbReader : IExcelOleDbReader\n{\n /// &lt;summary&gt;\n /// Converts specified Microsoft Excel 97-2003 (8.0) workbook into a &lt;see cref=\"DataTable\"/&gt; object.\n /// &lt;/summary&gt;\n /// &lt;param name=\"fileName\"&gt;Full path and file name of Microsoft Excel 97-2003 (8.0) workbook to connect to.&lt;/param&gt;\n /// &lt;returns&gt;Returns a &lt;see cref=\"DataTable\"/&gt; with the contents of the active worksheet.&lt;/returns&gt;\n public DataTable ImportExcelFile(string fileName)\n {\n if (string.IsNullOrEmpty(fileName)) return null;\n if (!File.Exists(fileName)) return null;\n\n var result = new DataTable();\n using (var connection = GetWorkbookConnection(fileName))\n {\n connection.Open();\n var adapter = new OleDbDataAdapter(\"select * from A1:BA60000\", connection);\n adapter.Fill(result);\n connection.Close();\n }\n\n return result;\n }\n\n private OleDbConnection GetWorkbookConnection(string fileName)\n {\n var connectionString = @\"Provider=Microsoft.Jet.OLEDB.4.0; Data Source=\" + fileName + @\";Extended Properties=\"\"Excel 8.0;HDR=YES;\"\"\";\n return (fileName != string.Empty) \n ? new OleDbConnection(connectionString)\n : null;\n }\n}\n</code></pre>\n\n<hr>\n\n<p>OLEDB should be much faster than COM interop, but it comes with its own problems - if you have two data types in a single column, you might need to do some gymnastics with your worksheet data to get it to work.</p>\n\n<p>You might want to search/ask Stack Overflow about how this might work when you have more than just the active worksheet to read from.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-05-07T17:53:32.243", "Id": "86395", "Score": "0", "body": "Thank you very much for your answer. My original thought had been to go with OLEDB and use `IMEX=1` in my connection string to account for mixed data types, but I had an issue with dates importing as `DateTime` objects and I wasn't able to capture the exact display format used in the worksheet. It's critical that I a.) don't edit the original workbooks in any way, and b.) capture the exact display from the workbook as a string." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-05-07T17:55:20.370", "Id": "86396", "Score": "0", "body": "Handling multiple worksheets in a workbook is no problem. You loop through the entries in the OLEDB schema and process each worksheet individually by name." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-05-07T17:55:32.243", "Id": "86397", "Score": "0", "body": "In that case I'd write a VBA add-in to grab a workbook, format it properly (like, make everything strings / text-formatted), *save it as a temp copy of the original*, and use OLEDB to import the temp copy, which I'd then destroy ;)" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-05-07T17:57:09.110", "Id": "86398", "Score": "0", "body": "Would that really be faster than reading directly in C#? I would just end up looping through all 1,056,573 cells in VBA rather than C#." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-05-07T17:58:22.263", "Id": "86399", "Score": "1", "body": "VBA is \"Excel-native\", C# is managed code \"talking\" to COM, \"talking\" to Excel, there's LOTS of overhead with Excel interop, so yes, looping through 1M cells in VBA is much faster than doing the exact same thing in C# ;)" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-05-07T18:00:55.867", "Id": "86400", "Score": "0", "body": "Wouldn't that require adding a VBA macro to an existing workbook? I can't edit the workbooks in any way. (Forgive me if I sound dense here; it's been 7+ years since I last used VBA.)" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-05-07T18:04:20.597", "Id": "86402", "Score": "0", "body": "You could make a separate workbook with your macro, and open that workbook whenever you need to run the macro - or you can make an Excel add-in and have a button on your ribbon, readily available to run whatever code you want to run.. which way to go depends on your UX preferences and how often you need to run that macro. Make sure you post your VBA code for review here, too - I want a VBA tag badge!! =D" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-05-07T18:22:21.537", "Id": "86405", "Score": "0", "body": "I'll be running the macro a lot. This is part of an overarching project to loop through a HUGE directory and process files by type, and there are a lot of big Excel files. There is no user intervention; the code just goes and will spit out a report of the datasets at the end. There's no need for any nice user features. Opening a workbook that opens a workbook and creates a new workbook will have a lot of Excel processes running, which would also affect performance. Though I'd like to assist in your badge quest, I'm not sold on the VBA approach yet." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-05-08T18:48:29.647", "Id": "86586", "Score": "1", "body": "I figured out how to do it successfully in OLEDB, hence the acceptance of the answer that recommended OLEDB. I really appreciate all of your fantastic input, Mat (and Mug)." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-05-08T18:49:42.943", "Id": "86587", "Score": "0", "body": "Thanks! Out of curiosity, how long does it run for with OLEDB?" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-05-08T18:52:47.490", "Id": "86591", "Score": "1", "body": "I basically adapted my approach from one I use for Access files, so as a disclaimer my OLEDB method is pretty dissimilar from yours. Mine constructs the `DataSet` from the 1,056,573 cell workbook in 432ms. I'd say that's an improvement on 20 minutes. :)" } ], "meta_data": { "CommentCount": "11", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-05-07T17:46:32.040", "Id": "49170", "ParentId": "49162", "Score": "7" } }, { "body": "<p>My other answer proposed a radically different approach. This is more of a <em>code review</em>.</p>\n<hr />\n<h3>Naming</h3>\n<p>The naming isn't following the typical C# naming conventions:</p>\n<blockquote>\n<pre><code> Application oXL = wrapper.Excel;\n\n Workbook oWB = oXL.Workbooks.Open(this.File, 0, true);\n</code></pre>\n</blockquote>\n<p>Would be more readable like this:</p>\n<pre><code> Application app = wrapper.Excel; \n Workbook workbook = app.Workbooks.Open(this.File, 0, true);\n</code></pre>\n<p>Or, with type inference / implicit typing:</p>\n<pre><code> var app = wrapper.Excel; \n var workbook = app.Workbooks.Open(this.File, 0, true);\n</code></pre>\n<p>Avoid arbitrary prefixes:</p>\n<blockquote>\n<pre><code> int nColumns = oSheet.UsedRange.Columns.Count;\n int nRows = oSheet.UsedRange.Rows.Count;\n</code></pre>\n</blockquote>\n<p><code>n</code> means what? <em>number</em>? it's redundant. Just call a cat, a cat:</p>\n<pre><code> var columns = worksheet.UsedRange.Columns.Count;\n var rows = worksheet.UsedRange.Rows.Count;\n</code></pre>\n<p>Same here, the <code>o</code> prefix isn't buying you anything, and only makes the pronounciation of that variable's name sound funny:</p>\n<blockquote>\n<pre><code> int oRange = (Range)oSheet.Cells[i, j];\n</code></pre>\n</blockquote>\n<p>Use <em>meaningful names</em>:</p>\n<blockquote>\n<pre><code> public string File { get; set; }\n</code></pre>\n</blockquote>\n<p><code>File</code>, in .net, usually refers to the <code>System.IO.File</code> class. Given that it's a <code>string</code>, I'd suggest the name <code>FileName</code> for that property instead.</p>\n<hr />\n<h3>Readability</h3>\n<p>This:</p>\n<pre><code>i += 1;\n</code></pre>\n<p>Would more explicitly read as an <em>increment</em> if written like this:</p>\n<pre><code>i++;\n</code></pre>\n<p>Your main loop (inside the <code>try</code> block) is doing 3 things:</p>\n<ul>\n<li>Create a new <code>DataTable</code> for each worksheet.</li>\n<li>Create a new <code>DataColumn</code> for each column on each worksheet.</li>\n<li>Create a new <code>DataRow</code> for each row on each worksheet, and populate each column.</li>\n</ul>\n<p>I'd extract 3 methods out of the main loop, to make it easier to parse:</p>\n<pre><code>var result = new DataSet();\ntry\n{\n foreach (var worksheet in workbook.Worksheets)\n {\n DataTable worksheetData;\n If (ReadWorksheetData(worksheet, out worksheetData))\n {\n result.Tables.Add(worksheetData);\n }\n }\n}\nfinally\n{\n workbook.Close();\n app.Quit();\n}\n</code></pre>\n<p>I dropped the redundant <code>catch</code> clause, and removed the call to <code>wrapper.Dispose()</code>, since the <code>wrapper</code> instance is created in a <code>using</code> scope, which already ensures its proper disposal - you're basically calling <code>Dispose</code> twice on it. Also <code>null</code>ing references that you're not going to reuse, doesn't buy you anything really, so I removed them too.</p>\n<p>The <code>ReadWorksheetData</code> method would look something like this:</p>\n<pre><code>private bool ReadWorksheetData(Worksheet worksheet, out DataTable worksheetData)\n{\n var result = false;\n\n var columns = worksheet.UsedRange.Columns.Count; \n if (columns &gt; 0)\n {\n var data = new DataTable(worksheet.Name);\n worksheetData = data;\n AddWorksheetColumns(worksheet, worksheetData, columns);\n AddWorksheetRows(worksheet, worksheetData); // temporal coupling here...\n\n result = true;\n }\n else\n {\n worksheetData = null;\n }\n\n return result;\n}\n</code></pre>\n<p>This isn't perfect, <code>AddWorksheetColumns</code> <em>must</em> run before <code>AddWorksheetRows</code> and that creates <em>temporal coupling</em> between the two methods, but you get the idea - you break the main loop into multiple, smaller methods that do as little as possible.</p>\n<hr />\n<h3>Would parallelization help?</h3>\n<p>As a <em>possible</em> performance helper, the main loop could then be parallelized:</p>\n<pre><code> Parallel.ForEach(workbook.Worksheets, worksheet =&gt;\n {\n DataTable worksheetData;\n If (ReadWorksheetData(worksheet, out worksheetData))\n {\n result.Tables.Add(worksheetData);\n }\n });\n</code></pre>\n<p>So you'd possibly have multiple worksheets being processed at the same time, depending on number of available CPU cores and some other factors. The overall workload remains the same though.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-05-07T19:46:34.703", "Id": "86417", "Score": "3", "body": "Mat, your mug is so smart and helpful!" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-05-07T19:48:24.283", "Id": "86418", "Score": "0", "body": "Also it's useful to note that _until_ I added the `wrapper.Dispose()` I was getting orphaned Excel processes on exceptions. I don't when I include it though." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-05-07T19:50:37.623", "Id": "86420", "Score": "3", "body": "That's an interesting observation... and mug says thanks! :)" } ], "meta_data": { "CommentCount": "3", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-05-07T19:31:08.083", "Id": "49178", "ParentId": "49162", "Score": "11" } } ]
{ "AcceptedAnswerId": "49170", "CommentCount": "3", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-05-07T16:55:48.300", "Id": "49162", "Score": "11", "Tags": [ "c#", "performance", "excel" ], "Title": "Extract Excel data using Interop.Excel from C#" }
49162
<p>My PHP contact form was recently being used to send spam. Some security measures have since been put in place (please refer to the comments below) and I'm seeking the collective wisdom of others to review the code and to check to make sure it is secure from injection attacks.</p> <pre><code>&lt;?php /* method for validate each input values in case any injection scripts it will ignore */ function test_input($data) { $data = trim($data); $data = stripslashes($data); $data = htmlspecialchars($data); return $data; } /* honeypot - if hidden field is completed discard form content */ if(!isset($_POST['honeypot']) || $_POST['honeypot'] != '') { die("You spammer!\n"); } else { // define variables and set to empty values $subject = $id = $subcategory = $subcategory = $subcategory_email = $to = $descError = $error = $remarks = $response= $message= $name = $from = $phone =""; if(isset($_REQUEST['category']) &amp;&amp; $_REQUEST['category']!="") { //validate each input values for any injection attacks $id = test_input($_REQUEST['category']); $subcategory = test_input($_REQUEST['subcategory']); $emails = array ( array("0",""), array("1","email1@yahoo.com","email2@yahoo.com"), array("2","email1@yahoo.com","email2@yahoo.com"), array("3","email1@yahoo.com","email2@yahoo.com"), array("4","email1@yahoo.com","email2@yahoo.com"), array("5","email1@yahoo.com","email2@yahoo.com") ); $value = explode(",", $subcategory); $subcategory_email = $emails[$id][$value[0]]; $remarks = test_input($_REQUEST['remarks']); $message = '&lt;html&gt;&lt;body&gt;'; $message .= '&lt;table rules="all" style="border-color: #666;" border="1" cellpadding="10"&gt;'; $message .= "&lt;tr style='background-color:#F5F5F5;'&gt;&lt;th width=25%&gt;Heading &lt;/th&gt;&lt;th width=75%&gt;Content&lt;/th&gt;&lt;/tr&gt;"; $message .= "&lt;tr&gt;&lt;td&gt;&lt;b&gt;Category &lt;/b&gt;&lt;/td&gt;&lt;td&gt;".$category[$id-1]."&lt;/td&gt;&lt;/tr&gt;"; $message .= "&lt;tr&gt;&lt;td&gt;&lt;b&gt;SubCategory &lt;/b&gt;&lt;/td&gt;&lt;td&gt;".$value[1]."&lt;/td&gt;&lt;/tr&gt;"; $message .= "&lt;tr&gt;&lt;td&gt;&lt;b&gt;Comments&lt;/b&gt;&lt;/td&gt;&lt;td&gt;&lt;pre&gt;".$remarks."&lt;/pre&gt;&lt;/td&gt;&lt;/tr&gt;"; if($response==0) { $name = test_input($_REQUEST['name']); $from = test_input($_REQUEST['email']); if (!preg_match("/([\w\-]+\@[\w\-]+\.[\w\-]+)/",$from)) { $emailErr = "Invalid email format"; } $phone = test_input($_REQUEST['phone']); $message .= "&lt;tr&gt;&lt;td&gt;&lt;b&gt;Would you like a response? &lt;/b&gt;&lt;/td&gt;&lt;td&gt;Yes&lt;/td&gt;&lt;/tr&gt;"; $message .= "&lt;tr&gt;&lt;td&gt;&lt;b&gt;Name&lt;/b&gt;&lt;/td&gt;&lt;td&gt;".$name."&lt;/td&gt;&lt;/tr&gt;"; $message .= "&lt;tr&gt;&lt;td&gt;&lt;b&gt;E-Mail&lt;/b&gt;&lt;/td&gt;&lt;td&gt;".$from."&lt;/td&gt;&lt;/tr&gt;"; $message .= "&lt;tr&gt;&lt;td&gt;&lt;b&gt;Telephone&lt;/b&gt;&lt;/td&gt;&lt;td&gt;".$phone."&lt;/td&gt;&lt;/tr&gt;"; } else { $from = "noreply@test.com"; $message .= "&lt;tr&gt;&lt;td&gt;&lt;b&gt;Would you like a response? &lt;/b&gt;&lt;/td&gt;&lt;td&gt;No&lt;/td&gt;&lt;/tr&gt;"; } $subject = "SubCategory ".$value[1]; //Normal headers $headers = "From: " . strip_tags($from) . "\r\n"; $headers .= "Reply-To: ". strip_tags($subcategory_email) . "\r\n"; $headers .= "MIME-Version: 1.0\r\n"; $headers .= "Content-Type: text/html; charset=ISO-8859-1\r\n"; $message .= "&lt;/table&gt;"; if(mail($subcategory_email, $subject, $message, $headers)) { include("thanks.php"); $error=6; } else { echo "mail not sent"; } } else { echo "&lt;br/&gt;"; $subject = "Sub Category"; $to = "Email1@yahoo.com"; if(empty($_REQUEST['remarks'])) { $descError = "Enter Description"; $error = 5; } else { $remarks = test_input($_REQUEST['remarks']); } if(test_input($_REQUEST['response'])=="0") { $yesDIV = "checked"; $response = "Yes"; if(empty($_REQUEST['name'])) { $nameError = "Name Required"; $error = 5; } else { $name = test_input($_REQUEST['name']); } $from = $_REQUEST['email']; if(empty($_REQUEST['email'])) { $emailError = "Email Required"; $error = 5; } else if (!filter_var($from, FILTER_VALIDATE_EMAIL)) { $emailError = "Valid Email Required"; $error = 5; } } else { $noDIV = "checked"; $response = "No"; $bodyDIV = "style='display:none;'"; } if($error!=5) { $phone = test_input($_REQUEST['phone']); $message = '&lt;html&gt;&lt;body&gt;'; $message .= '&lt;table rules="all" style="border-color: #666;" border="1" cellpadding="10"&gt;'; $message .= "&lt;tr style='background-color:#F5F5F5;'&gt;&lt;th width=25%&gt;Heading &lt;/th&gt;&lt;th width=75%&gt;Content&lt;/th&gt;&lt;/tr&gt;"; $message .= "&lt;tr&gt;&lt;td&gt;&lt;b&gt; Comments&lt;/b&gt;&lt;/td&gt;&lt;td &gt;&lt;pre&gt;".$remarks."&lt;/pre&gt;&lt;/td&gt;&lt;/tr&gt;"; $message .= "&lt;tr&gt;&lt;td&gt;&lt;b&gt;Would you like a response? &lt;/b&gt;&lt;/td&gt;&lt;td&gt;".$response."&lt;/td&gt;&lt;/tr&gt;"; $message .= "&lt;tr&gt;&lt;td&gt;&lt;b&gt;Name&lt;/b&gt;&lt;/td&gt;&lt;td&gt;".$name."&lt;/td&gt;&lt;/tr&gt;"; $message .= "&lt;tr&gt;&lt;td&gt;&lt;b&gt;E-Mail&lt;/b&gt;&lt;/td&gt;&lt;td&gt;".$from."&lt;/td&gt;&lt;/tr&gt;"; $message .= "&lt;tr&gt;&lt;td&gt;&lt;b&gt;Telephone&lt;/b&gt;&lt;/td&gt;&lt;td&gt;".$phone."&lt;/td&gt;&lt;/tr&gt;"; $message .= "&lt;/table&gt;"; //Normal headers $headers = "From: noreply@test.com \r\n"; $headers .= "Reply-To: ". strip_tags($from) . "\r\n"; $headers .= "MIME-Version: 1.0\r\n"; $headers .= "Content-Type: text/html; charset=ISO-8859-1\r\n"; if(mail($to, $subject, $message, $headers)) { include("thanks.php"); $error=6; } else { echo "mail not sent"; } } } } ?&gt; </code></pre>
[ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-05-07T17:15:45.023", "Id": "86388", "Score": "0", "body": "doing a security audit of this code is a bit difficult, as it features inconsistent formatting and a high cyclomatic complexity. Consider improving the formatting, and splitting the code into multiple helper functions that can be reviewed for security independently. It would be also good to use some naming convention to mark which values have not yet been validated and sanitized." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-05-07T17:25:07.313", "Id": "86390", "Score": "0", "body": "@amon I'm just looking to get a general sense. i.e. Does anything \"pop out\" at you?" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-05-08T01:27:41.303", "Id": "86487", "Score": "1", "body": "The problem is, the code is too messy *for* anything to \"pop out\". Issues that might be obvious in cleaner code are hidden in the spaghetti." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-05-09T19:34:35.040", "Id": "86809", "Score": "0", "body": "Unless you're implementing this for learning purposes, I'd suggest [swiftmailer](http://swiftmailer.org/) or another such open-source library. It has already been fine tuned and looked over for security holes. No need to reinvent the wheel!" } ]
[ { "body": "<p>Some things I've noticed:</p>\n\n<ul>\n<li><code>subcategory_email</code> might be empty if a user would supply an index out of the array bounds.</li>\n<li>Why use <code>$_REQUEST</code>? It's almost always better to use <code>$_GET</code> or <code>$_POST</code> if you know what to expect (<code>POST</code> would probably be best for a 'committing' action).</li>\n<li>I think it's weird to have a function called <code>test</code> not return <code>true</code> or <code>false</code>, but modify the value. I would call <code>test_input</code>, <code>cleanup_value</code> or something like that instead.</li>\n<li><code>strip_tags($from)</code> seems a bit excessive as you've already validated it.</li>\n<li><a href=\"https://codereview.stackexchange.com/questions/42313/preventing-email-injection?rq=1#comment72787_42313\">You don't have to validate email address yourself. PHP has a built in function <code>filter_var($email, FILTER_VALIDATE_EMAIL);</code></a></li>\n<li>The operations in <code>test_input</code> seem a bit excessive, </li>\n</ul>\n\n<p>I did not look at code style, etcetera, but you should make an effort to clean it up a bit. It makes problems in general a lot easier to spot. I also did not look at HTML code.</p>\n\n<p>You're also spoofing the <code>from</code> address in some cases, this might make your email end up in the spam folder or even not get delivered at all if the user has strict <a href=\"https://en.wikipedia.org/wiki/DMARC\" rel=\"nofollow\">DMARC</a> checks on their email domain. It might be better to set <code>from</code> to your email address, but instead set <code>Reply-To</code> to the user's address.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-05-07T20:15:41.777", "Id": "49181", "ParentId": "49163", "Score": "1" } } ]
{ "AcceptedAnswerId": "49181", "CommentCount": "4", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-05-07T17:05:08.913", "Id": "49163", "Score": "1", "Tags": [ "php", "security", "email" ], "Title": "Is this PHP mailer file secure from injection attacks?" }
49163
<pre><code>#include&lt;iostream&gt; using namespace std; int partition(int arr[],int first,int last,int pivot) { int tmparr[100]; int left=first,right=last; for(int i=first;i&lt;=last;i++) { if(arr[i]&lt;pivot) tmparr[left++]=arr[i]; else if(arr[i]&gt;pivot) tmparr[right--]=arr[i]; } //for the case when pivot is duplicated for(int i=left;i&lt;=right;i++) tmparr[i]=pivot; for(int i=first;i&lt;=last;i++) arr[i]=tmparr[i]; return left; } void quicksort(int arr[],int first,int last) { if(first&lt;last) { int pivotindex = partition(arr,first,last,arr[first]); quicksort(arr,first,pivotindex-1); quicksort(arr,pivotindex+1,last); } } int main() { int arr[6]={6,6,9,5,3,7}; int n=6; quicksort(arr,0,n-1); for(int i=0;i&lt;n;i++) cout&lt;&lt;arr[i]; } </code></pre> <ul> <li><p>How do I avoid the copying to <code>tmparr</code>? </p></li> <li><p>How does the current method of copying to <code>tmparr</code> and back affect my time efficiency as opposed to an in-place swap?</p></li> <li><p>Am I missing anything in this code? It looks much simpler than implementations I could find online.</p></li> </ul>
[ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-05-07T17:38:49.897", "Id": "86391", "Score": "0", "body": "\"I am aware of issues around it being limited to 5 elements instead of dynamic, and some variables not named properly\" then you should fix that first." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-05-07T17:42:17.480", "Id": "86392", "Score": "0", "body": "@AJMansfield Fixed most of the names, essentially need feedback on the algo implementation" } ]
[ { "body": "<p>I know you haven't mentioned anything about this, but I think it should still be addressed.</p>\n\n<p>You should not be passing around C arrays in C++. The entire array is <em>not</em> passed; it merely decays to a pointer to the array.</p>\n\n<p>Instead, use a storage container such as an <a href=\"http://en.cppreference.com/w/cpp/container/vector\" rel=\"nofollow\"><code>std::vector</code></a>. These will <em>not</em> decay to pointers, and using such containers is more idiomatic C++. If you have C++, you can use an <a href=\"http://en.cppreference.com/w/cpp/container/array\" rel=\"nofollow\"><code>std::array</code></a> instead.</p>\n\n<p>Declare and push back the elements:</p>\n\n<pre><code>std::vector&lt;int&gt; values;\n\nvalues.push_back(6);\nvalues.push_back(6);\n// ...\n</code></pre>\n\n<p>If you have C++11, initialize an <code>std::array</code> instead:</p>\n\n<pre><code>std::array&lt;int, 6&gt; values = { 6, 6, 9, 5, 3, 7 };\n</code></pre>\n\n<p>Pass either one to a function:</p>\n\n<pre><code>void func(std::vector&lt;int&gt;&amp; values) {}\n</code></pre>\n\n<p></p>\n\n<pre><code>void func(std::array&lt;int, 6&gt;&amp; values) {}\n</code></pre>\n\n<p>You will also no longer need <code>n</code>; storage containers know their sizes. You can access this value with <code>values.size()</code>, which is of the return type <code>std::size_type</code>. This is also safer because the returned value will be updated as the container changes size.</p>\n\n<p>If you don't have C++11, display the container with (const) iterators:</p>\n\n<pre><code>std::vector&lt;int&gt;::const_iterator iter;\n// OR\nstd::array&lt;int, 6&gt;::const_iterator iter;\n\nfor (iter = values.cbegin(); iter != values.cend(); iter++)\n{\n std::cout &lt;&lt; *iter;\n}\n</code></pre>\n\n<p>If you do have C++11, use a <a href=\"http://en.cppreference.com/w/cpp/language/range-for\" rel=\"nofollow\">range-based <code>for</code>-loop</a>:</p>\n\n<pre><code>for (auto&amp; iter : values)\n{\n std::cout &lt;&lt; iter;\n}\n</code></pre>\n\n<p>You can use <a href=\"http://en.cppreference.com/w/cpp/language/auto\" rel=\"nofollow\"><code>auto</code></a> here to give you the correct container type automatically.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-05-07T18:47:31.357", "Id": "86410", "Score": "0", "body": "Thanks, but the fact that an array is passed as a pointer is what I am using in my partition and sort functions. Passing it by value would not have allowed me to sort the values without having a return. Still, the vector functions are new to me. Thanks" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-05-07T18:49:18.597", "Id": "86411", "Score": "1", "body": "@Akash: You could still pass them by reference, and I've just added it to this answer." } ], "meta_data": { "CommentCount": "2", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-05-07T18:44:10.553", "Id": "49175", "ParentId": "49166", "Score": "3" } }, { "body": "<blockquote>\n <p>How do I avoid the copying to <code>tmparr</code>?</p>\n</blockquote>\n\n<p>Use in-place swaps.</p>\n\n<blockquote>\n <p>How does the current method of copying to <code>tmparr</code> and back affect my time efficiency as opposed to an in-place swap?</p>\n</blockquote>\n\n<p>The effort of moving data is approximately the same. I don't see any performance gain or impact, other than that your approach is less cache-friendly.</p>\n\n<blockquote>\n <p>Am I missing anything in this code? It looks much simpler than implementations I could find online.</p>\n</blockquote>\n\n<p>Mostly the fact that you can't deal with large datasets, and that stack consumption is significantly larger. Properly implemented (that is, not limited to 100 elements), your algorithm would require \\$O(n)\\$ space vs \\$O(log n)\\$ for a real <code>quicksort</code>.</p>\n\n<p>PS: As usual, I can't help noticing that two last loops in <code>partition</code> represent important algorithms (namely, <code>fill</code> and <code>copy</code>), and shall be factored out into functions of their own.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-05-09T03:32:11.353", "Id": "86671", "Score": "0", "body": "Will the larger stack consumption be resolved if I used `malloc(last-first)` and a corresponding `free()` instead of the statically allocated `tmparr`?" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-05-09T03:44:42.863", "Id": "86673", "Score": "0", "body": "Unfortunately, no. Extra memory is extra memory, no matter where it comes from." } ], "meta_data": { "CommentCount": "2", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-05-07T21:50:46.650", "Id": "49190", "ParentId": "49166", "Score": "3" } } ]
{ "AcceptedAnswerId": "49190", "CommentCount": "2", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-05-07T17:36:28.713", "Id": "49166", "Score": "2", "Tags": [ "c++", "algorithm", "beginner", "sorting", "quick-sort" ], "Title": "Is this reimplemented quicksort correct?" }
49166
<p>I have a complex directory structure on my web server that includes .tar files for download; I'm trying to create a report on the size distribution of these files (e.g. 10 are less than 1MB, two are 1-2MB, three are 2-3MB...)</p> <p>Is there a better way to organize this code? I started it as a console application, writing directly in the Main() function. Now I'm taking a step back and thinking about improvements.</p> <pre><code>public class MyClass { private static int counter = 0; private static Dictionary&lt;int, int&gt; sizeMap = new Dictionary&lt;int, int&gt;() { {0, 0} , {1, 0} , {2, 0} , {3, 0} , {4, 0} , {5, 0} , {6, 0} , {7, 0} , {8, 0} , {9, 0} , {10, 0} , {20, 0} , {30, 0} , {40, 0} , {50, 0} , {75, 0} , {100, 0} , {999, 0} }; static void Main(string[] args) { DirectoryInfo cloud1 = new DirectoryInfo("C:\\brian"); IEnumerable&lt;DirectoryInfo&gt; cloud1Dirs = cloud1.EnumerateDirectories(); foreach (var dir in cloud1Dirs) { ParseDir(dir); } Console.WriteLine("=================================================="); foreach (int i in sizeMap.Keys) { Console.WriteLine(i + "M\t" + sizeMap[i]); } Console.WriteLine("Press any key to exit"); Console.ReadKey(); } private static void ParseDir(DirectoryInfo currentDir) { if (counter++ &gt; 1000) { return; } IEnumerable&lt;FileInfo&gt; tarFiles = currentDir.EnumerateFiles("*.tar"); if (tarFiles.Count() &gt; 0) { foreach (FileInfo tarFile in tarFiles) { int megLength = (int)(tarFile.Length / 1048576); int key = MakeDictionaryKey(megLength); sizeMap[key]++; Console.WriteLine(tarFile.Name + "\t" + megLength + "M"); } } else { foreach (var dir in currentDir.EnumerateDirectories()) { ParseDir(dir); } } } private static int MakeDictionaryKey(int n) { if (n &lt;= 10) { return n; } else if (n &lt;= 50) { return (int) Math.Ceiling(n / 10.0) * 10; } else if (n &lt;= 75) { return 75; } else if (n &lt;= 100) { return 100; } else { //Really large file! return 999; } } } </code></pre>
[ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-05-07T18:35:03.050", "Id": "86406", "Score": "1", "body": "Is `Foo` the actual name of the method?" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-05-07T18:37:48.850", "Id": "86407", "Score": "0", "body": "Oops! It started that way, but I changed it to `ParseDir`." } ]
[ { "body": "<p>The biggest complaint I would have with this code is that you're essentially defining your size map twice. Imagine if you decide you don't want to report on files between 50 and 75MB - you remove the \"75\" entry from the dictionary, but forget to remove it from the MakeDictionaryKey method, and your program will occasionally fail at runtime.</p>\n\n<p>First, I'd consider modifying your dictionary so instead of using \"999\" as a synonym for \"really big file\", you use int.MaxValue:</p>\n\n<pre><code> , {100, 0}\n , {int.MaxValue, 0}\n</code></pre>\n\n<p>In your MakeDictionaryKey method, you're then looking for the smallest key value where the key value is greater than the file size you've provided to it. With a bit of LINQ, that simply becomes:</p>\n\n<pre><code>private static int MakeDictionaryKey(int n)\n{\n return sizeMap.Keys.Where(x =&gt; x &lt;= n).Min();\n}\n</code></pre>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-05-08T14:51:17.407", "Id": "49228", "ParentId": "49174", "Score": "2" } } ]
{ "AcceptedAnswerId": "49228", "CommentCount": "2", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-05-07T18:27:52.943", "Id": "49174", "Score": "1", "Tags": [ "c#", "file-system" ], "Title": "Search a directory structure for tar files and report on their size" }
49174
<p>I have read several articles using Google, but I somehow do not really get what they do, and when it is needed. Below I'll give 2 pieces of code, in one using get/set and in the other without, and they both work (at least in this example).</p> <p>Example 1</p> <pre><code>public class Example { public int number; } class Program { static void Main(string[] args) { Example example = new Example(); example.number = 5; Console.WriteLine(example.number); Console.ReadKey(); } } </code></pre> <p>Example 2</p> <pre><code>public class Example { private int number; public int Number { get { return number; } set { number = value; } } } class Program { static void Main(string[] args) { Example example = new Example(); example.Number = 5; Console.WriteLine(example.Number); Console.ReadKey(); } } </code></pre> <p>I've added a piece of real code below so it may be improved and perhaps shown examples on these accessors.</p> <pre><code>// Main public class Asteroid { Random random = new Random(); public Texture2D texture; public Vector2 position, origin; public float rotationAngle; public int speed; public Rectangle boundingBox; public bool isVisible; public float randomX, randomY; // Constructor public Asteroid(Texture2D newTexture, Vector2 newPosition) { position = newPosition; texture = newTexture; speed = 4; randomX = random.Next(0, 750); randomY = random.Next(-600, -50); isVisible = true; } // Load Content public void LoadContent(ContentManager Content) { } // Draw public void Draw(SpriteBatch spriteBatch) { if (isVisible) // spriteBatch.Draw(texture, position, Color.White); spriteBatch.Draw(texture, position, null, Color.White, rotationAngle, origin, 1.0f, SpriteEffects.None, 0f); } // Update public void Update(GameTime gameTime) { // Set bounding box for collision boundingBox = new Rectangle((int)position.X - (texture.Width / 2), (int)position.Y - (texture.Height / 2), texture.Width, texture.Height); origin.X = texture.Width / 2; origin.Y = texture.Height / 2; // Update Movement position.Y = position.Y + speed; if (position.Y &gt;= 950) { isVisible = false; } // Rotating Asteroid float elapsed = (float)gameTime.ElapsedGameTime.TotalSeconds; rotationAngle += elapsed; float circle = MathHelper.Pi * 2; rotationAngle = rotationAngle % circle; } } </code></pre>
[]
[ { "body": "<p>First of all, I'd make the texture and position fields private. They're set from the outside, and the outside doesn't need to change them.</p>\n\n<p>Then I'd extend that. Anything your class needs to be given, add to the constructor. If <code>Asteroid</code> makes it itself, make it private. If something needs to look at it, make a get only property to access it. If it needs to be modified, make it an autoproperty.</p>\n\n<p>The only thing that seems like a good candidate for a property to me is your Origin. Something may want to sort <code>Asteroid</code>s by Origin.</p>\n\n<p>If, following my advice, you reach more than 4 parameters, you should make a new class to either use as the parameter or deal with those values in the <code>Asteroid</code>.</p>\n\n<p>If your teachers have been telling you to make everything a public field, ignore them. They're wrong. Maybe follow their advice on assignments for the sake of credits, but never in production code.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-05-07T20:54:17.133", "Id": "49183", "ParentId": "49179", "Score": "3" } }, { "body": "<p>Example 2 could also be written like this using autoproperties</p>\n\n<pre><code>public int Number { get; set; }\n</code></pre>\n\n<p>It would be good to recognize that you can set access modifiers on these</p>\n\n<pre><code>private int number;\npublic int Number\n{\n get { return number; }\n private set { number = value; }\n}\n</code></pre>\n\n<p>which could also be written as</p>\n\n<pre><code>public int Number { get; private set; }\n</code></pre>\n\n<p>In your specific example you will use getters and setters simply when something is public instead of private. You can however have private properties with getters and setters. Getter and Setters are methods which are used in the setting and getting of data. They are very useful when you need to do some calculation when getting or setting data. \nExample: getting calculation</p>\n\n<pre><code>DateTime Birthday { get; set;}\nTimeSpan Age { get { return DateTime.Now Birthday; } }\n</code></pre>\n\n<p>Example: MVVM OnProperty Changed, notifies the UI when something in the backend has changed and updates accordingly</p>\n\n<pre><code>public string ContactName\n{\n get { return _contactName; }\n set\n {\n if (_contactName == value) return;\n _contactName = value;\n OnPropertyChanged(\"ContactName\");\n }\n}\n</code></pre>\n\n<hr>\n\n<p>As I said above, C# convention is to make anything that is publicly accessible to be a property. So this is your chance to look at your class members and decide what really needs to be seen and/or modified by outside sources.</p>\n\n<p>What if you decided to allow addons to your game, and lets say its a multiplayer game, so you don't want people cheating. But now anyone who can get the memory address of your asteroid object could easily change its position, visibility, or its texture. Even if this is some small project for yourself, data should only be exposed as much as absolutely necessary, and only those who need to change that data should be able to. Also, anything that is public needs to be <code>PascalCase</code>, not <code>camelCase</code> ie. start with a capital letter.</p>\n\n<p>From a quick look... this is how I would do it.</p>\n\n<pre><code>public Texture2D Texture {get; private set;}\npublic Vector2 Origin {get; private set;}\npublic float RotationAngle {get; private set;}\npublic Rectangle BoundingBox {get; private set;}\npublic bool Visible {get; private set;}\n\nprivate Random _random = new Random();\nprivate Vector2 _position;\nprivate int _speed;\nprivate float _randomX, _randomY;\n</code></pre>\n\n<h2>Edit:</h2>\n\n<p>It is important to note: that depending on the datatype making a private set does not stop the object from being modified. You could still be pointing to the same object as before, but some malicious code could have changed properties of that code. In this case, you could have the <code>public get</code> get a cloned version of a privately backed object.</p>\n\n<pre><code>private Person _customer;\npublic Person Customer {get { return _customer.Clone(); }}\n</code></pre>\n\n<p>Now the only customer that the public gets to toy with is a customer they can modify, but it wont affect the customer you have though.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-05-07T21:23:26.873", "Id": "86453", "Score": "2", "body": "+1 especially for the last paragraph. Clear, applicable justification for a concept beginners often find obscure." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-05-07T21:24:34.840", "Id": "86456", "Score": "1", "body": "Last paragraph really helped me understand why it is important not to leave fields public." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-05-08T01:25:35.120", "Id": "86486", "Score": "1", "body": "Anyone who has the memory address of your variables will use memory editing software which bypasses all and any language-level private modifiers. Please don't treat private modifiers as offering any security." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-05-08T11:54:08.483", "Id": "86506", "Score": "0", "body": "@LieRyan I'm talking about pointers. If you can get a reference to an object you shouldn't, you would be allowed to change it to you're hearts content. Imagine that you are connecting to an online service, you cant use your memory hacking software to find and change a value on the server, BUT if they leave it public, then yes you can." } ], "meta_data": { "CommentCount": "4", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-05-07T21:16:09.480", "Id": "49184", "ParentId": "49179", "Score": "3" } }, { "body": "<p>I'd probably go one farther - if this class has an immutable state in that <code>number</code> (I don't know the use case for your actual class), make it immutable as such:</p>\n\n<pre><code>public sealed class Example\n{\n private readonly int number;\n public Example(int number)\n {\n this.number = number;\n }\n public int Number\n {\n get { return this.number; }\n }\n}\n\nclass Program\n{\n static void Main(string[] args)\n {\n Example example = new Example(5);\n\n Console.WriteLine(example.Number);\n Console.ReadKey();\n }\n}\n</code></pre>\n\n<p>If it is a simple value that can change, make it mutable and add the property setter. If there is some other action that happens when the number changes, make a method <code>SetNumberForPinballInitialization(int number)</code> or some such.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-05-07T21:24:13.287", "Id": "49185", "ParentId": "49179", "Score": "2" } }, { "body": "<p>The answer to this is more subtle than most would admit. Whether or not to use getter/setter is highly dependant on the features of the language you're using and most importantly the intent of the class.</p>\n\n<p>In languages like Java and C++, exposing public fields is considered bad practice, because it allows external code to modify internal mechanism of the object and invalidate the object's contracts and invariants. In these languages, getter and setter are an unavoidable way of life, as their syntaxes limits their possible options.</p>\n\n<p>In languages like Python, exposing attributes as public is considered OK, because attribute access in Python is actually a method call to the attribute's descriptor; in simpler words, in these languages, you can easily override an attribute assignments to maintain the class' contracts and invariants. In languages that allows transparent transition between attributes and properties like Python, it is common that the language doesn't even need/have private attributes.</p>\n\n<p>Like Python, C# allows overriding attribute assignment; unlike Python, in C#, changing attribute to property and vice versa breaks binary compatibility. Thus, if you ever wanted to make the attribute public in C#, you should do it as autoproperty instead of as public attribute. There are also <a href=\"http://csharpindepth.com/Articles/Chapter8/PropertiesMatter.aspx\" rel=\"nofollow\">more subtle differences</a> between changing attributes to properties, so starting with property is generally a good idea.</p>\n\n<p>Immutability is a different beast. Immutable classes are easier to reason with than mutable classes and can be safely passed around without the need for copying so immutable classes are generally very desirable. In many softwares, it is a good idea to have a certain set of classes (i.e. value-type classes) to be immutable. Value-type classes are essentially a bundle of data that needs to go together with zero behaviour in itself, in other words, a struct. Examples of value-type classes are classes that represents Numbers, Vectors/Coordinates, Matrices, Colours, etc. Strictly speaking, there is really not much of a real issue in exposing publicly attributes of a bundle of data with zero behaviours. For value-type objects, most people advocates the use of autoproperties for consistency and a \"just-in-case\" attitude, and because properties are very cheap anyway; while some people advocates to just <a href=\"http://blogs.msdn.com/b/ricom/archive/2006/09/07/745085.aspx\" rel=\"nofollow\">do away with properties</a> under this very limited circumstances. I'd say, if you're ever in doubt, just use property.</p>\n\n<p>Having said that. Most non-value-type classes should never expose attributes whether it's as properties, getter/setters, or public attributes. Classes that are not value-type classes should expose behaviours rather than attributes and it is these behaviours that you should emphasize. Instead of <code>public int X { get; set }</code> and <code>public int Y { get; set }</code>, expose <code>.Move(coordinate)</code>; instead of <code>.GetImage()</code>, expose <code>.Draw(canvas)</code>; etc. If you have lots of accessors for every fields in the class, then you're most likely doing something wrong, you're not encapsulating the data.</p>\n\n<p>In summary, you are asking the wrong question. Your question should not be whether to use getter/setter vs attributes nor should it be getter/setter vs property. Your question should be whether these accessors should exist in the first place; more often than not, having accessors produce <a href=\"http://www.martinfowler.com/bliki/AnemicDomainModel.html\" rel=\"nofollow\">anemic domain model</a> anti-patterns.</p>\n\n<p>This is how I might do the Asteroid class, no accessors should be needed as Asteroid should be a class with rich behaviors:</p>\n\n<pre><code>public class Asteroid\n{\n private Texture2D texture;\n private Vector2 position, origin;\n private float rotationAngle;\n private int speed;\n private Rectangle boundingBox;\n private bool isVisible;\n private float randomX, randomY;\n\n // Constructor\n public Asteroid(Texture2D newTexture, Vector2 newPosition)\n {\n position = newPosition;\n texture = newTexture;\n speed = 4;\n randomX = random.Next(0, 750);\n randomY = random.Next(-600, -50);\n isVisible = true;\n }\n\n public void Show(bool show=true) { ... }\n public void Hide() { ... }\n\n public void Draw( ... ) { ... }\n\n public void Update( ... ) { ... } \n public void CollidesWith( Collideable ) { ... }\n\n\n}\n</code></pre>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-05-08T01:52:35.007", "Id": "49200", "ParentId": "49179", "Score": "3" } } ]
{ "AcceptedAnswerId": "49183", "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-05-07T20:04:14.453", "Id": "49179", "Score": "4", "Tags": [ "c#" ], "Title": "How to know when I need to use get/set and when not?" }
49179
<p>Working my way through <a href="http://rads.stackoverflow.com/amzn/click/032157351X">Algorithms, Fourth edition by Robert Sedgewick &amp; Kevin Wayne</a>. I implemented a generic version of the Quick-Union algorithm and added Path Compression (not described in the book) to it.</p> <p>Mainly I'm looking for feedback on these two aspects and whether I might have overlooked a side effect.</p> <pre><code>public class WeightedQuickUnionWithPathCompression&lt;T&gt; { private final Map&lt;T, T&gt; components = new HashMap&lt;&gt;(); private final Map&lt;T, Integer&gt; treeSizes = new HashMap&lt;&gt;(); public WeightedQuickUnionWithPathCompression(T[] components) { for (T component : components) { this.components.put(component, component); this.treeSizes.put(component, 1); } } public void connect(T leftComponent, T rightComponent) { Objects.requireNonNull(leftComponent); Objects.requireNonNull(rightComponent); if (areConnected(leftComponent, rightComponent)) { return; } T leftComponentTree = find(leftComponent); T rightComponentTree = find(rightComponent); int leftTreeSize = getTreeSize(leftComponentTree); int rightTreeSize = getTreeSize(rightComponentTree); if (leftTreeSize &lt; rightTreeSize) { components.put(leftComponentTree, rightComponentTree); treeSizes.put(rightComponentTree, leftTreeSize + rightTreeSize); } else { components.put(rightComponentTree, leftComponentTree); treeSizes.put(leftComponentTree, leftTreeSize + rightTreeSize); } } private T find(T component) { while (!component.equals(components.get(component))) { components.put(component, components.get(components.get(component))); // Path compression component = components.get(component); } return component; } private int getTreeSize(T component) { return treeSizes.get(component); } public boolean areConnected(T leftComponent, T rightComponent) { Objects.requireNonNull(leftComponent); Objects.requireNonNull(rightComponent); return find(leftComponent).equals(find(rightComponent)); } } </code></pre>
[]
[ { "body": "<p>In <code>find()</code> and <code>areConnected()</code>, you should be able to use <code>==</code> rather than <code>.equals()</code> since you are comparing references, not contents.</p>\n\n<hr>\n\n<p>Your <code>find()</code> loop is a bit inefficient:</p>\n\n<ul>\n<li>You do <code>components.get(component)</code> once during the <code>while</code> condition test, and again during path compression.</li>\n<li>You do <code>components.put(component, …)</code> during path compression, then immediately lookup <code>components.get(component)</code> to advance the loop.</li>\n</ul>\n\n<p>The remedy is to introduce two temporary variables, which I call <code>parent</code> and <code>grandparent</code>.</p>\n\n<p>I've chosen to write it as a <code>for</code> loop with side-effect assignments, but of course you can choose to use a <code>while</code> loop without side-effect assignments.</p>\n\n<pre><code>private T find(T c) {\n // Lookup with path compression\n for (T parent, grandparent; (parent = components.get(c)) != c; c = grandparent) {\n components.put(c, grandparent = components.get(parent));\n }\n return c;\n}\n</code></pre>\n\n<hr>\n\n<p><code>connect()</code> calls <code>areConnected()</code>, which performs redundant work. I suggest…</p>\n\n<pre><code>public void connect(T leftComponent, T rightComponent) {\n Objects.requireNonNull(leftComponent);\n Objects.requireNonNull(rightComponent);\n\n T leftComponentTree = find(leftComponent);\n T rightComponentTree = find(rightComponent);\n\n if (leftComponentTree == rightComponentTree) {\n return; // Already connected\n }\n\n …\n}\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-05-08T01:11:24.347", "Id": "86484", "Score": "0", "body": "Invaluable remarks, much appreciated! I've stuck with a `while` loop inside `find(T)` because it stays more true to the original algorithm, but the intermediate assignments definitely were an eye-opener." } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-05-08T00:19:34.917", "Id": "49197", "ParentId": "49186", "Score": "2" } }, { "body": "<p>While I applaud your effort to keep methods short by refactoring, I question the benefit of replacing</p>\n\n<pre><code>treeSizes.get(component)\n</code></pre>\n\n<p>with a private method call that saves two characters without abstracting or encapsulating anything:</p>\n\n<pre><code>getTreeSize(component)\n</code></pre>\n\n<p>I'd be curious to see if introducing a private static class to combine the result of <code>find</code> and <code>getTreeSize</code> could simplify <code>connect</code>.</p>\n\n<p>Finally, why bother with the null checks when null values will immediately throw NPE anyway? It would make sense if the check included a message denoting the problem, but all you get here is a line number--no more than without them. Not that this isn't a good habit in general.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-05-08T15:53:50.690", "Id": "86549", "Score": "0", "body": "You're right about the simplicity of the method. On one hand I like the level of abstraction it brings but at the same time it's not something I expected to change so I'll remove the intermediate method. Could you clarify what you mean with the private class? Good point about the parameter checking as well, I've used the overload instead." } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-05-08T02:27:07.167", "Id": "49203", "ParentId": "49186", "Score": "1" } } ]
{ "AcceptedAnswerId": "49197", "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-05-07T21:34:11.583", "Id": "49186", "Score": "5", "Tags": [ "java", "algorithm" ], "Title": "Generic implementation of the Quick-Union algorithm with Path Compression" }
49186
<p>After changing all variables in <a href="https://codereview.stackexchange.com/questions/49179/how-to-know-when-i-need-to-use-get-set-and-when-not">this code</a> from <code>public</code> to <code>private</code> and adding <code>get</code>/<code>set</code> according to the need to get modified and/or read in another class, I'd like to know if this was done correctly.</p> <pre><code>// Main public class Asteroid { Random random = new Random(); private Rectangle boundingBox; public Rectangle BoundingBox { get { return boundingBox; } } private Vector2 position; public Vector2 Position { get { return position; } } private bool isVisible; public bool IsVisible { get; set; } private Vector2 origin; private float rotationAngle; private int speed; private Texture2D texture; private float randomX, randomY; // Constructor public Asteroid(Texture2D newTexture, Vector2 newPosition) { position = newPosition; texture = newTexture; speed = 4; randomX = random.Next(0, 750); randomY = random.Next(-600, -50); isVisible = true; } // Load Content public void LoadContent(ContentManager Content) { } // Draw public void Draw(SpriteBatch spriteBatch) { if (isVisible) // spriteBatch.Draw(texture, position, Color.White); spriteBatch.Draw(texture, position, null, Color.White, rotationAngle, origin, 1.0f, SpriteEffects.None, 0f); } // Update public void Update(GameTime gameTime) { // Set bounding box for collision boundingBox = new Rectangle((int)position.X - (texture.Width / 2), (int)position.Y - (texture.Height / 2), texture.Width, texture.Height); origin.X = texture.Width / 2; origin.Y = texture.Height / 2; // Update Movement position.Y = position.Y + speed; if (position.Y &gt;= 950) { isVisible = false; } // Rotating Asteroid float elapsed = (float)gameTime.ElapsedGameTime.TotalSeconds; rotationAngle += elapsed; float circle = MathHelper.Pi * 2; rotationAngle = rotationAngle % circle; } } </code></pre>
[ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-05-07T21:49:04.907", "Id": "86466", "Score": "0", "body": "You may not have noticed, but you can remove the isVisible field. It isn't used. Or you could connect it to the IsVisible property." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-05-07T21:51:55.510", "Id": "86467", "Score": "0", "body": "isVisible is being used as it removes all object where isVisble = false (happens in Game1.cs), and it's also being used in the Draw method, `if (isVisible)`?" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-05-07T21:53:48.357", "Id": "86468", "Score": "0", "body": "I know, but my point is that you could be using the property there. Currently, the property does nothing. One or the other should go, and if it's the field, the property should do what it was doing." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-05-07T21:55:48.780", "Id": "86469", "Score": "0", "body": "// If any asteroid is invisible, remove it.\n for (int i = 0; i < asteroidList.Count; i++)\n {\n if (!asteroidList[i].`IsVisible`)\n {\n asteroidList.RemoveAt(i);\n i--;\n }\n }\n\nThe property gets used here, I believe? (Sorry, getting a bit confused. isVisible is the FIELD, and IsVisible is the PROPERY, am I right?)" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-05-07T22:01:41.603", "Id": "86471", "Score": "1", "body": "You are correct, but my point is that you have two things with names that differ only in case which are totally unrelated. Presumably the property should return and assign the field? As it is, it is only confusing." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-05-07T22:04:05.747", "Id": "86473", "Score": "0", "body": "@Magus Write that out in more detail as an answer and you will get an up vote." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-05-07T22:05:26.310", "Id": "86474", "Score": "0", "body": "So it should be get `return isVisible`, and `set isVisible = value`? Sorry if I'm sounding really dumb.." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-05-08T15:28:37.397", "Id": "86535", "Score": "0", "body": "I think I went through this tutorial, I should look at what I have for the code when I get home. I will have to fire up an old box though because I don't have it set up with MonoGame yet" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-05-08T16:33:07.997", "Id": "86559", "Score": "0", "body": "It wasn't made in MonoGame, though ;) Visual Studio XNA" } ]
[ { "body": "<h1>Fields vs Properties</h1>\n\n<p>As discussed in the comments above, there's a problem with <code>IsVisible</code>:</p>\n\n<blockquote>\n<pre><code>private bool isVisible;\npublic bool IsVisible { get; set; }\n</code></pre>\n</blockquote>\n\n<p>When this code compiles, you'll basically get something like this \"under the hood\":</p>\n\n<pre><code>private bool isVisible;\n\nprivate bool IsVisible;\npublic bool get_IsVisible() { return this.IsVisible; }\npublic void set_IsVisible(bool value) { this.IsVisible = value; }\n</code></pre>\n\n<p><strong>BUG!</strong>\nYou're using <code>isVisible</code> all over your code, but the setter for <code>IsVisible</code>, <code>set_IsVisible</code>, is never called. Hence your <em>clients</em> will not see the right value... literally: the public getter will always return <code>default(bool)</code>... <code>false</code>!</p>\n\n<hr>\n\n<h2>You really have two options.</h2>\n\n<p>Either you <em>expose</em> data, or you <em>encapsulate</em> data.</p>\n\n<p>Think of what a class really is: it's a <em>definition</em> for a <em>type</em>. A type <em>can</em> be a <code>class</code>, but in C# you can also have an <code>enum</code>, a <code>struct</code>, an <code>interface</code>... types can also be <em>abstract</em> (like an <code>interface</code>, or an <code>abstract class</code>).</p>\n\n<p>When you <em>instantiate</em> a class, you create an <em>object</em> of the <em>type</em> defined by the <em>class</em>. An <em>object</em> has an <em>interface</em> (do not confuse with <code>interface</code>) that <em>exposes</em> everything that's publicly available. The <em>client code</em> doesn't \"see\" anything that's <code>private</code> or <code>protected</code> (or <code>internal</code> if the client code is in another <em>assembly</em>). And that's exactly where <em>encapsulation</em> is: it's <em>hidden</em>, <em>encapsulated</em> inside the inner workings, the <em>implementation details</em> of the type - the interface doesn't expose it because client code <em>does not need to know</em> what the implementation details are.</p>\n\n<p>Fields are <em>implementation details</em>. They don't <em>need</em> to be exposed, and doing so breaks <em>encapsulation</em>.</p>\n\n<h3>Option One</h3>\n\n<p>You could make <code>IsVisible</code> an auto-property:</p>\n\n<pre><code>public bool IsVisible { get; set; }\n</code></pre>\n\n<p>Or, for a <em>get-only</em> auto-property:</p>\n\n<pre><code>public bool IsVisible { get; private set; }\n</code></pre>\n\n<p>Remember that <em>under the hood, there is a private field for that auto-property</em> (see \"When this code compiles...\" above).</p>\n\n<h3>Option Two</h3>\n\n<p>You could make <code>IsVisible</code> a property that uses a <code>_isVisible</code> private backing field:</p>\n\n<pre><code>private bool _isVisible;\n\npublic bool IsVisible\n{\n get { return _isVisible; }\n set { _isVisible = value; }\n}\n</code></pre>\n\n<p>The <em>get-only</em> version simply omits the setter.</p>\n\n<p>You'll notice I'm using a naming convention that makes it a no-brainer to tell a field (<code>_isVisible</code>) from a parameter (<code>value</code> - implicit parameter in a property setter).</p>\n\n<p>If you don't like having an underscore prefix on your private fields (it really comes down to personal preference.. or to the naming conventions your team is using), you could alternatively do it like this:</p>\n\n<pre><code>private bool isVisible;\n\npublic bool IsVisible\n{\n get { return this.isVisible; }\n set { this.isVisible = value; }\n}\n</code></pre>\n\n<p>The <code>this</code> qualifier isn't really needed (it's actually redundant in this case), but then if you had a method like this:</p>\n\n<pre><code>private void DoSomething(bool isVisible)\n{\n // \"isVisible\" in this scope refers to the parameter.\n // use \"this.isVisible\" to refer to the private field.\n}\n</code></pre>\n\n<p>And this is why I prefer the underscore prefix.</p>\n\n<hr>\n\n<h2>Bottom line: Properties win.</h2>\n\n<p>Some useful references:</p>\n\n<h3><a href=\"http://msdn.microsoft.com/en-us/library/ms229057%28v=vs.110%29.aspx\" rel=\"nofollow\">Member Design Guidelines (Field Design) on MSDN</a>:</h3>\n\n<blockquote>\n <p>We exclude constant and static read-only fields from this strict restriction, because such fields, almost by definition, are never required to change. </p>\n \n <ul>\n <li><strong>X DO NOT</strong> provide instance fields that are public or protected. You should provide properties for accessing fields instead of making them public or protected. </li>\n <li><strong>√ DO</strong> use constant fields for constants that will never change. The compiler burns the values of const fields directly into calling code. Therefore, const values can\n never be changed without the risk of breaking compatibility. </li>\n <li><strong>√ DO</strong> use public static readonly fields for predefined object instances. If there are predefined instances of the type, declare them as public read-only static fields of the type itself. </li>\n <li><strong>X DO NOT</strong> assign instances of mutable types to readonly fields.</li>\n </ul>\n</blockquote>\n\n<p>Note that in <a href=\"/questions/tagged/oop\" class=\"post-tag\" title=\"show questions tagged &#39;oop&#39;\" rel=\"tag\">oop</a>, <em>static, predefined instance</em> is generally just bad wording for <strong>don't do that!!</strong> </p>\n\n<p>Also while <a href=\"http://ericlippert.com/2008/05/14/mutating-readonly-structs/\" rel=\"nofollow\">you certainly don't want a mutable readonly struc</a>, but <code>readonly</code> in front of a reference type only means that the <em>reference</em> cannot be reassigned. These are <em>guidelines</em> after all ;)</p>\n\n<h3><a href=\"http://msdn.microsoft.com/en-us/library/ms229006%28v=vs.110%29.aspx\" rel=\"nofollow\">Member Design Guidelines (Property Design) on MSDN</a>:</h3>\n\n<blockquote>\n <ul>\n <li><strong>√ DO</strong> create get-only properties if the caller should not be able to change the value of the property. Keep in mind that if the type of the property is a mutable reference type, the property value can be changed even if the property is get-only. </li>\n <li><strong>X DO NOT</strong> provide set-only properties or properties with the setter having broader accessibility than the getter. For example, do not use properties with a public setter and a protected getter. If the property getter cannot be provided, implement the functionality as a method instead. Consider starting the method name with Set and follow with what you would have named the property. For example, AppDomain has a method called SetCachePath instead of having a set-only property called CachePath.</li>\n <li><strong>√ DO</strong> provide sensible default values for all properties, ensuring that the defaults do not result in a security hole or terribly inefficient code. </li>\n <li><strong>√ DO</strong> allow properties to be set in any order even if this results in a temporary invalid state of the object. It is common for two or more properties to be interrelated to a point where some values of one property might be invalid given the values of other properties on the same object. In such cases, exceptions resulting from the invalid state should be postponed until the interrelated properties are actually used together by the object. </li>\n <li><strong>√ DO</strong> preserve the previous value if a property setter throws an exception. </li>\n <li><strong>X AVOID</strong> throwing exceptions from property getters.</li>\n </ul>\n</blockquote>\n\n<hr>\n\n<h1>Abstraction</h1>\n\n<p>If I look at the <em>interface</em> of an <code>Asteroid</code>, I see these members:</p>\n\n<pre><code>Asteroid(Texture2D newTexture, Vector2 newPosition);\n\nRectangle BoundingBox { get; }\nVector2 Position { get; }\nbool IsVisible { get; set; }\n\nvoid LoadContent(ContentManager content);\nvoid Draw(SpriteBatch spriteBatch);\nvoid Update(GameTime gameTime);\n</code></pre>\n\n<p>I would think pretty much everything that's drawable in your game has a very similar interface, if not an identical one.</p>\n\n<p>If you defined an <em>abstraction</em> for the methods this interface exposes...</p>\n\n<pre><code>public interface IDrawableContent\n{\n void LoadContent(ContentManager Content);\n void Draw(SpriteBatch spriteBatch);\n void Update(GameTime gameTime);\n}\n</code></pre>\n\n<p>Then you could have every drawable game component <em>implement</em> that interface, like this:</p>\n\n<pre><code>public class Asteroid : IDrawableContent\n</code></pre>\n\n<p>And since your <code>GameScreen</code> (I'm making this up) also has these methods with the same signature, why not do this as well:</p>\n\n<pre><code>public class GameScreen : IDrawableContent\n</code></pre>\n\n<p>Your <code>AsteroidZapperGame</code> class (or whatever it's called) also has similar methods (defined by the XNA <code>Game</code> class), but it's pretty much your top-level object, so you don't need it to implement the interface.</p>\n\n<hr>\n\n<h2>What gives?</h2>\n\n<p>The <code>GameScreen</code> class might roughly look like this (over-simplified):</p>\n\n<pre><code>public class GameScreen : IDrawableContent\n{\n // _items is readonly. \n // its reference may only be assigned in a constructor.\n // items may still be added or removed from the list any time.\n private readonly IList&lt;IDrawableContent&gt; _items;\n\n public GameScreen(IList&lt;IDrawableContent&gt; items)\n {\n _items = items;\n }\n\n public void LoadContent(ContentManager content)\n {\n foreach (var item in _items)\n {\n item.LoadContent(content);\n }\n }\n\n public void Draw(SpriteBatch spriteBatch)\n {\n foreach (var item in _items)\n {\n item.Draw(spriteBatch);\n }\n }\n\n public void Update(GameTime gameTime)\n {\n foreach (var item in _items)\n {\n item.Update(gameTime);\n }\n }\n}\n</code></pre>\n\n<p>This class <em>has no clue that you're making it draw asteroids</em>. In fact, it could just as well be drawing bubbles in a soda can, or a bunch of zombies hunting the player down. That's what <em>abstractions</em> do: they <em>abstract</em> away the implementation details, and that makes code easier to read, extend, and maintain.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-05-08T02:12:19.467", "Id": "49202", "ParentId": "49188", "Score": "15" } }, { "body": "<p>This is a slippery slope here</p>\n\n<pre><code>public void Draw(SpriteBatch spriteBatch)\n{\n if (isVisible)\n // spriteBatch.Draw(texture, position, Color.White);\n spriteBatch.Draw(texture, position, null, Color.White, rotationAngle, origin, 1.0f, SpriteEffects.None, 0f);\n}\n</code></pre>\n\n<p>Especially when in the next method you write the if statement like this</p>\n\n<pre><code>if (position.Y &gt;= 950)\n{\n isVisible = false;\n}\n</code></pre>\n\n<p>in the first example it is unclear whether the statement is actually enclosed inside of the if statement because there is a commented out line of code there, I know it will compile, but you should do one of these things (or two)</p>\n\n<ul>\n<li>Delete the comment (write yourself notes somewhere other than in the code, so you know what you changed)</li>\n<li>Don't one line the isVisible if statement</li>\n<li>One line all of your if statements</li>\n</ul>\n\n<hr>\n\n<p>I would write it like this personally</p>\n\n<pre><code>public void Draw(SpriteBatch spriteBatch)\n{\n if (isVisible)\n {\n spriteBatch.Draw(texture, position, null, Color.White, rotationAngle, origin, 1.0f, SpriteEffects.None, 0f);\n }\n}\n</code></pre>\n\n<p>This is very clear what your intent is and doesn't clutter with Comments that hide code that could confuse you when you maintain the code later.</p>\n\n<p>Always be consistent in the way that you code if statements and other blocks of code, because it will make it much easier to maintain later.</p>\n\n<hr>\n\n<hr>\n\n<p>you probably should look at disposing the asteroid once it goes off-screen rather than holding the variable while it is not visible, it will make it easier for when you want to expand the game to include more objects. </p>\n\n<p>right now I have an issue of too many shots from my ship not being disposed fast enough, but that is because I created a world map where I use a viewport to travel the world and I wanted my shots to kill things off screen (still a lot of things that need to be changed like viewport size and stuff lol)</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-05-08T15:35:18.310", "Id": "86540", "Score": "1", "body": "I had forget that comment, I was using that as a non rotating asteroid before I got the rotation working, my bad :-)" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-05-08T15:36:42.007", "Id": "86541", "Score": "0", "body": "still if you one line without brackets and then one line with brackets, it can be confusing. I prefer to always use brackets. but there is another way....." } ], "meta_data": { "CommentCount": "2", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-05-08T15:32:40.153", "Id": "49232", "ParentId": "49188", "Score": "5" } } ]
{ "AcceptedAnswerId": "49202", "CommentCount": "9", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-05-07T21:43:56.423", "Id": "49188", "Score": "7", "Tags": [ "c#", "game", "xna" ], "Title": "Encapsulation, fields and properties for Asteroid class" }
49188
<p>This is the controller I created for my MVC framework, and I think I finally got it right.</p> <p>Anything I can do to make the code more efficient?</p> <p>Is this how a MVC controller is supposed to look like?</p> <pre><code>abstract class Controller { protected $requestHandler; public function __construct(RequestHandler $rh, $action) { $this-&gt;requestHandler = $rh; $this-&gt;$action(); } protected abstract function index(); } class SignUpController extends Controller { protected function index() { $headerData = array( 'title' =&gt; 'Sign up', 'stylesheets' =&gt; ['/stylesheets/signup.css'], 'scripts' =&gt; array( '//ajax.googleapis.com/ajax/libs/jquery/1.11.0/jquery.min.js', '/javascripts/misc.js' ) ); View::render('Header', $headerData); if ($this-&gt;requestHandler-&gt;getMethod() === 'POST') { $v = new Validator(); $v-&gt;addRule(1, ['required', 'max' =&gt; 35]); $v-&gt;addRule(2, ['required', 'between' =&gt; [5, 255], 'email']); $v-&gt;addRule(3, ['required', 'min' =&gt; 6]); $v-&gt;addRule(4, ['required']); $firstname = $v-&gt;validate(1, (isset($_POST['firstname'])) ? trim($_POST['firstname']) : false); $lastname = $v-&gt;validate(1, (isset($_POST['lastname'])) ? trim($_POST['lastname']) : false); $email = $v-&gt;validate(2, (isset($_POST['email'])) ? trim($_POST['email']) : false); $emailConfirm = $v-&gt;validate(2, (isset($_POST['emailConfirm'])) ? trim($_POST['emailConfirm']) : false); $password = $v-&gt;validate(3, (isset($_POST['password'])) ? $_POST['password'] : false); $terms = $v-&gt;validate(4, isset($_POST['terms'])); if ($emailConfirm === true &amp;&amp; trim($_POST['email']) !== trim($_POST['emailConfirm'])) { $emailConfirm = $v-&gt;setError('match'); } if (!$v-&gt;errors()) { //user sign up logic here View::render('SignUpSuccess', ['email' =&gt; trim($_POST['email'])]); } else { $signUpData = array( 'firstname' =&gt; $firstname, 'fnVal' =&gt; (isset($_POST['firstname'])) ? $_POST['firstname'] : false, 'lastname' =&gt; $lastname, 'lnVal' =&gt; (isset($_POST['lastname'])) ? $_POST['lastname'] : false, 'email' =&gt; $email, 'emVal' =&gt; (isset($_POST['email'])) ? $_POST['email'] : false, 'emailConfirm' =&gt; $emailConfirm, 'emConfVal' =&gt; (isset($_POST['emailConfirm'])) ? $_POST['emailConfirm'] : false, 'password' =&gt; $password, 'pwVal' =&gt; (isset($_POST['password'])) ? $_POST['password'] : false, 'terms' =&gt; $terms, 'termsVal' =&gt; isset($_POST['terms']) ); View::render('SignUp', $signUpData); } } else { View::render('SignUp'); } View::render('Footer'); } } </code></pre>
[]
[ { "body": "<p>The biggest thing that bugs me about this is that <code>Controller::__construct</code> is basically handling the whole request. A constructor should be doing as little work as possible -- ideally <em>only</em> getting the object ready to use.</p>\n\n<p>The problem is that otherwise, your request is never really handled. That can be resolved by simply renaming the constructor. (It's really a dispatcher, so a good name would mention that.)</p>\n\n<p>Also, the action method in <code>SignUpController</code> is a bit too familiar with how the page is laid out. Your view should generally be handling the rendering of the header and footer.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-05-07T21:58:43.033", "Id": "86470", "Score": "0", "body": "So the controller constructor should only get/set the dependency injected objects? Also, isn't the controller supposed to \"control\" what happens, which view is rendered where in the page layout? So aside from rendering the main content view in the controller, I should render the header and footer inside my view templates and not the controller?" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-05-07T22:26:31.633", "Id": "86475", "Score": "0", "body": "@KidDiamond: The controller coordinates the flow of messages. In web-style \"MVC\" (really more akin to front-controller), it might decide which view and/or model is appropriate. Ideally, though, it does little to nothing else, and doesn't care (much less dictate) what the view does. If you're separating your concerns properly, then the view and controller are near-totally independent -- you could rearrange everything on the page without the controller having to change at all." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-05-07T22:40:49.520", "Id": "86477", "Score": "0", "body": "In truth, i'm kinda thinking the constructor shouldn't exist here (or if it does, it should take no params and do no work). If you pass it the request info and then say `$controller->handleRequest();` or the like, all you're really doing is turning methods into half-procedures...separating the passing of params from the procedure that actually uses them. I'd rather see a `public function dispatchRequest($request, $action)`, personally...or possibly even do away with that, and have your action methods take `$rh` as a parameter, if you really need it, and leave request routing to a router." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-05-07T23:18:03.993", "Id": "86480", "Score": "0", "body": "I already am using my request handler with my router. And my router routes to the correct controller and action. The reason I'm using the request handler in my controller is that the request handler knows the request method (GET, POST, etc) so I can do things based on the condition. Why would I sent the $rh object as a parameter in the action? Every action is going to need it as a parameter, while in the constructor I can actually set it once and use that in every action." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-05-08T00:51:04.397", "Id": "86482", "Score": "0", "body": "@KidDiamond: You can...and in many cases, it makes sense. But it is only worthwhile if `$rh` may be unknown when the request is being handled (which can not possibly be the case here, since the request ends up responded to before you even finish *constructing* your controller). If you do it unnecessarily, you're just splitting `$controller->$action($rh)` in two for the sake of doing so, which gains you nothing but obscurity." } ], "meta_data": { "CommentCount": "5", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-05-07T21:52:55.560", "Id": "49191", "ParentId": "49189", "Score": "0" } }, { "body": "<p><a href=\"https://en.wikipedia.org/wiki/Model%E2%80%93view%E2%80%93controller\" rel=\"nofollow noreferrer\">MVC has a strict definition</a>. However, frameworks don't actually follow MVC (yet they call themselves such). It's like a free-for-all on framework design, approaches can differ.</p>\n\n<p>Enough of that theory, let's do code.</p>\n\n<p>One issue here is the constructor. If the class is subclassed, but doesn't call the parent when the constructor is overridden, then nothing will run. I suggest you separate a router logic from the controller. The order should be like</p>\n\n<p>Also, I think it's best you place all request data (parameters, headers) into an object, like a <code>$request</code> parameter handed into the function that's called in the controller by the router (pre-cleaned and pre-formatted). Also, throw in getters to normalize the data, so that you won't be doing 'isset` all the time. Something like:</p>\n\n<pre><code>$pass = $req-&gt;post('password'); // Gets the password param from a post request, else false\n</code></pre>\n\n<p>Don't render by parts, like header, content, footer in the controller. It's best you invest in having a templating system. The template has the fully formed HTML, and all your render does is fill in the blanks. <a href=\"https://github.com/bobthecow/mustache.php\" rel=\"nofollow noreferrer\">See mustache templates</a>, you might like it.</p>\n\n<p>So the order is:</p>\n\n<ol>\n<li><p>Receive request (in CodeIgniter, that's the <code>index.php</code>)</p></li>\n<li><p><code>index.php</code> loads core libraries and dependencies (like routers, url parsers, db driver, XSS prevention, stuff like that).</p></li>\n<li><p>Parse the request and simplify where needed. What you could do is </p>\n\n<ul>\n<li>Sanitize all inputs from XSS and SQL injections.</li>\n<li>Normalize input by placing encapsulating them in an object. Throw in a getter, so that you only need to call something like <code>$request-&gt;post('password')</code> to get the password from a POST request.</li>\n</ul></li>\n<li><p>Then the router determines the route from the request, includes that class, creates an instance, and executes the appropriate method. Something like <code>$classInstance-&gt;theAction($normalizedRequestData)</code></p></li>\n<li><p>Now we are in the controller. Controller then talks to the model, do something here and there, gets the data, and renders the view with the data from the DB.</p>\n\n<pre><code>$this-&gt;render('VIEW_NAME',$dataFromDB);\n</code></pre></li>\n<li><p>Template parser kicks in, renders the data and generates the HTML which then gets send back to browser.</p></li>\n</ol>\n\n<p>If you're a visual guy like I am, I'd prefer to look at a diagram rather than a wall of text. Luckily, <a href=\"http://ellislab.com/codeigniter/user-guide/overview/appflow.html\" rel=\"nofollow noreferrer\">CodeIgniter drew their data flow</a>, which got me sold. It's pretty handy diagram, which can be used as basis for framework design.</p>\n\n<p><img src=\"https://i.stack.imgur.com/jbYO6.gif\" alt=\"enter image description here\"></p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-05-08T06:31:27.717", "Id": "49208", "ParentId": "49189", "Score": "3" } } ]
{ "AcceptedAnswerId": "49208", "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-05-07T21:44:04.300", "Id": "49189", "Score": "2", "Tags": [ "php", "mvc" ], "Title": "Is this how an MVC controller supposed to be?" }
49189
<p>I just finished <a href="http://projecteuler.net/problem=37" rel="nofollow">Project Euler 37</a> after a bit of debugging and can't figure out how to make it faster. Whenever I add extra tests that I want to speed the program up, it ends up just slowing it down. My primes test is from <a href="http://en.wikipedia.org/wiki/Primality_test#Python_implementation" rel="nofollow">here</a>. Please help me optimize!</p> <pre><code>from primes import test as is_prime from itertools import product from timeit import default_timer as timer def is_trunc(list_num): num = ''.join(map(str, list_num)) # turn (1, 2, 3) into 123 if is_prime(int(num)): for k in range(1, len(num)): if not is_prime(int(num[k:])) or not is_prime(int(num[:k])): return False return True return False start = timer() data = {"count": 0, "length": 2, "sum": 0} while data["count"] &lt; 11: for combo in product([1, 2, 3, 5, 7, 9], repeat = data["length"]): if is_trunc(combo): data["count"] += 1 data["sum"] += int(''.join(map(str, list(combo)))) data["length"] += 1 ans = data["sum"] elapsed_time = (timer() - start) * 1000 # s --&gt; ms print "Found %d in %r ms." % (ans, elapsed_time) </code></pre>
[ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-05-08T01:12:16.253", "Id": "86485", "Score": "1", "body": "Go to the Project Euler forum for that problem, page 8, a post by Cthuloid on April 16th, 2014 has Python code that finds the solution in 0.2 sec." } ]
[ { "body": "<p>There's no need to convert lists to ints every time. Truncation from the right is an integer division by 10. Truncation from the left is modulo certain power of ten; you can keep track of the modulo as the loop progresses.</p>\n\n<p>There's no need to run a very expensive primality every time. Keep track of the primes you already found.</p>\n\n<p>PS: The biggest hint in the problem is that there's only 11 numbers of interest. There must be a way to prove that fact, and the proof is most likely constructive.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-05-08T01:14:47.297", "Id": "49199", "ParentId": "49195", "Score": "3" } } ]
{ "AcceptedAnswerId": "49199", "CommentCount": "1", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-05-07T23:30:04.277", "Id": "49195", "Score": "3", "Tags": [ "python", "optimization", "programming-challenge" ], "Title": "Truncatable Primes -- Project Euler 37?" }
49195
<p>I have two IEnumerable objects called <code>items</code> and <code>newItems</code>. I need to update the <code>Did</code> and <code>KeyDid</code> property of each element in <code>items</code> with the matching <code>Did</code> and <code>KeyDid</code> from <code>newItems</code>. I can't just call <code>items = newItems;</code> since other things have a reference to <code>items</code>. Here's my code:</p> <pre><code>T[] arrItems = items as T[] ?? items.ToArray(); if (arrItems.Length != newItems.Count()) throw new Exception("Item counts do not match."); //Copy Did and KeyDid from old items to newItems int i = 0; foreach (T newItem in newItems) { T oldItem = arrItems[i++]; oldItem.Did = newItem.Did; oldItem.KeyDid = newItem.KeyDid; } </code></pre> <p>I'm interested in a more concise way to do this, perhaps using a single LINQ expression. Any ideas how to improve this code in terms of readability, clearness, conciseness, or overall coolness?</p>
[ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-05-08T00:58:04.393", "Id": "86483", "Score": "0", "body": "Not sure about the only enumerate once comment. You are possible already enumerating twice by doing the .Count() call earlier???" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-05-08T01:57:25.063", "Id": "86489", "Score": "0", "body": "@dreza - Good call. The `.Count()` call should be moved to after the `.ToArray()` - I'll update the code." } ]
[ { "body": "<pre><code> if (arrItems.Length != newItems.Count())\n // --&gt; BAD throw new Exception(\"Item counts do not match.\");\n // Do not throw the Exception base here look for the real exception for example ArgumentException(if the arr come from arguments) or your custom exception:\n throw new ArgumentException();\n\n //Copy Did and KeyDid from old items to newItems\n for (var index = 0; index &lt; newItems.Length; index++)\n {\n arrItems[index].Did = newItems[index].Did;\n arrItems[index].KeyDid = newItems[index].KeyDid;\n }\n</code></pre>\n\n<p>I do not think LINQ will give you a better solution than what you have above; you can use group by or select to create a new element in the linq query and than put it back to object! \"For\" in this case is very fast and it solve the problem.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-05-08T17:12:26.383", "Id": "86570", "Score": "0", "body": "Thanks! Yea looks like just looping through the list is the way to go. The `Exception` was just for demonstration purposes; we have our own exception classes in our *actual* code." } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-05-08T08:58:14.237", "Id": "49213", "ParentId": "49196", "Score": "2" } }, { "body": "<p>How about this - </p>\n\n<pre><code>if (arrItems.Length == newItems.Count())\n{\n newItems = newItems.Zip(arrItems, (newItem, arrItem) =&gt;\n {\n newItem.KeyDid = arrItem.KeyDid;\n newItem.Did = arrItem.Did;\n return newItem;\n }); \n}\n</code></pre>\n\n<p>The Zip method basically merges two enumerables by invoking the specified delegate and passing the items of the two arrays as parameters. Makes for concise code.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-05-08T17:11:11.943", "Id": "86569", "Score": "0", "body": "Looks like you're copying from `arrItems` to `newItems` which is the opposite of what I want. Either way, this approach won't work. You're creating a new list, which is then lost when the function exits. Plus, the code would never be run unless you materialized the list. This approach seems hacky to me." } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-05-08T10:24:46.627", "Id": "49217", "ParentId": "49196", "Score": "1" } } ]
{ "AcceptedAnswerId": "49213", "CommentCount": "2", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-05-07T23:51:38.540", "Id": "49196", "Score": "3", "Tags": [ "c#", ".net", "linq" ], "Title": "Copy two properties from one array item to matching index in another array" }
49196
<p>I'm trying to get my progress bar animated. I'd like it to smoothly transition in between the starting and destination values, but only be initiated by clicking the continue button.</p> <p>The code I currently have works great, but when clicking forward or backward, it brings you directly to the values:</p> <pre><code>//PROGRESS BAR $("#progress").progressbar( { value: 0 }) //UPDATING PROGRESS BAR WHEN CONTINUE BUTTON CLICKED var currValue=0,toValue=0; $("#cont").button().click(function() { currValue = $("#progress").progressbar("value"); if(currValue+25 &lt;= 100) { toValue=currValue+25; animateProgress(); } }); //DECREASING PROGRESS BAR WHEN GO BACK BUTTON CLICKED $("#back").button().click(function() { currValue = $("#progress").progressbar("value"); if(currValue-25 &gt; 0) { toValue=currValue-25; animateProgress(); } }); }); function animateProgress() { if (currValue &lt; toValue) { $("#progress").progressbar("value", currValue+1); currValue = $("#progress").progressbar("value"); setTimeout(animateProgress, 4); } else if (currValue &gt; toValue) { $("#progress").progressbar("value", currValue-1); currValue = $("#progress").progressbar("value"); setTimeout(animateProgress, 4); } } </code></pre> <p>I've seen a couple examples of animated progressbars, but none by clicking and stopping when a certain value was reached. </p> <p>Think of it more like 4 individual "slides" and the progress bar showing you which slide you're on.</p> <p><strong>EDIT:</strong> here's the working fiddle...<a href="http://jsfiddle.net/ryanhagz/8u76B/20/" rel="nofollow">http://jsfiddle.net/ryanhagz/8u76B/20/</a></p> <p>Anyone tried something similar?</p>
[ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-05-08T06:07:38.250", "Id": "86491", "Score": "0", "body": "It would be better if you set up a demo in JSFiddle or JSBin so we can verify." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-05-08T21:39:24.110", "Id": "86634", "Score": "0", "body": "I added the fiddle @JosephtheDreamer , it works perfectly in the fiddle which is why i don't understand why it doesn't work in my local version...?" } ]
[ { "body": "<p>Not sure if it is helpful, but since we are on codereview, allow me to give it a shot.</p>\n\n<ul>\n<li>there is a <strong>progress</strong> element available in HTML5 that works very easily and is fairly well supported (<a href=\"http://caniuse.com/progressmeter\" rel=\"nofollow\">http://caniuse.com/progressmeter</a>), except for in IE off course. I would suggest using this in stead of the (heavy) jquery-ui you use now. </li>\n<li>When writing js code, <strong>avoid global variables</strong> at all cost. They take up resources, and some day they will come and haunt you when you accidentally overwrite a variable that you forgot about. Keep your variables in function scope whenever possible.</li>\n<li>when you see yourself writing the <strong>same code more then once</strong>, with just a minor difference in one of the values, try to think of a way to reuse your code. It will decrease the number of bytes, make your code better maintainable, and almost certainly improve the quality of your code. </li>\n<li>Be <strong>careful with setTimeout</strong>. It can be a very useful and powerful tool, but it costs quite some resources. When working with jQuery, try to use their functions in stead. They have been used and tested millions of times, and you are a lot less likely to mess things up when you use them.</li>\n</ul>\n\n<p>With those tips in mind, I tried to rewrite your code.The full version is in the <a href=\"http://jsfiddle.net/8u76B/21/\" rel=\"nofollow\">updated fiddle</a>, and the javascript is here:</p>\n\n<pre><code>// changing progressbar when button is clicked\n$(\".button\").click(function () {\n animateProgress(parseInt($(this).data('diff')));\n});\n\n// animate progress by a step indicated by diff\nfunction animateProgress(diff) {\n var currValue = $(\"#progress\").val();\n var toValue = currValue + diff;\n\n toValue = toValue &lt; 0 ? 0 : toValue;\n toValue = toValue &gt; 100 ? 100 : toValue;\n\n $(\"#progress\").animate({'value': toValue}, 500);\n}\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-05-09T02:14:45.303", "Id": "86665", "Score": "0", "body": "You're the man, Peter!" } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-05-08T22:35:09.330", "Id": "49277", "ParentId": "49201", "Score": "4" } } ]
{ "AcceptedAnswerId": "49277", "CommentCount": "2", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-05-08T02:06:05.210", "Id": "49201", "Score": "3", "Tags": [ "javascript", "jquery", "jquery-ui", "animation" ], "Title": "Updating a jquery progressbar via button clicks" }
49201
<p>Following code is supposed to identify a shift and then it should identify whether the shift is a night or a day shift. The method will take 'in time' and 'out time' as two parameters.</p> <p>These are the rules:</p> <ol> <li>Day shift - From 7AM to 7PM</li> <li>Night shift - From 7PM to 7AM (on the next day)</li> <li>The employee should report before 8AM for a day shift, otherwise the shift will not be taken into account.</li> <li>The employee should report before 8PM for a night shift, otherwise the shift will not be taken into account.</li> <li>If an employee leaves before the regular off time of a shift, that shift will not be taken into account.</li> </ol> <p>This code gives the intended result. Please let me know is the way I've done this acceptable? Do you have any better idea to achieve the same?</p> <pre><code>public string IdentifyShift(DateTime inTime, DateTime OutTime) { var compareInTimeToOutTIme = inTime.CompareTo(OutTime); //Two random dates used to assign value '1 day' to timespan "aDay" DateTime from= Convert.ToDateTime("05/01/2014 12:00:00"); DateTime to=Convert.ToDateTime("05/02/2014 12:00:00"); TimeSpan aDay = (to - from).Duration(); //If OutTime is less than the InTime that means the OutTime is on the next day if (compareInTimeToOutTIme &gt; 0) { OutTime = OutTime.Add(aDay); } TimeSpan shift = (OutTime - inTime).Duration(); var compareInTimeTo8AM =inTime.CompareTo(Convert.ToDateTime( inTime .ToShortDateString() +" 08:00:00")); //InTime of a day shift should be before 08AM var compareOutTimeTo7PM = OutTime.CompareTo(Convert.ToDateTime(inTime .ToShortDateString ()+" 19:00:00")); //OutTime of a day shift should be after or equal to 07PM var compareInTimeTo8PM =inTime.CompareTo(Convert.ToDateTime(inTime.ToShortDateString ()+" 20:00:00")); //InTime of a night shift should be before 08AM string DayOfnightShiftOutTime= inTime.Add(aDay).ToShortDateString(); var compareOutTimeTo7AM =OutTime.CompareTo(Convert.ToDateTime(DayOfnightShiftOutTime+" 07:00:00")); //OutTime of a night shift should be after or equal to 07AM on the next day if (shift.TotalHours &gt;= 11) { if ((compareInTimeTo8AM &lt; 0) &amp; (compareOutTimeTo7PM &gt;= 0)) { return "Day Shift"; } else if ((compareInTimeTo8PM &lt; 0) &amp; (compareOutTimeTo7AM &gt;= 0)) { return "Night Shift"; } else { return "Not a Shift"; } } else { return "Not a Shift"; } } </code></pre>
[]
[ { "body": "<p>First Things first:</p>\n\n<h3>Method Signature:</h3>\n\n<blockquote>\n<pre><code>public string IdentifyShift(DateTime inTime, DateTime OutTime)\n</code></pre>\n</blockquote>\n\n<p>C# conventions state, that public methods should be <code>PascalCased</code> (check), and local variables, as well as private fields, should be <code>camelCased</code> (partly). Furthermore your calculations are not depending on anything, but the method itself, they don't access class fields. You can, could and <strong>should</strong> make it static.</p>\n\n<pre><code>public static string IdentifyShift(DateTime inTime, DateTime outTime)\n</code></pre>\n\n<h3>TimeSpan, one Day:</h3>\n\n<blockquote>\n<pre><code>DateTime from= Convert.ToDateTime(\"05/01/2014 12:00:00\");\nDateTime to=Convert.ToDateTime(\"05/02/2014 12:00:00\");\n\nTimeSpan aDay = (to - from).Duration();\n</code></pre>\n</blockquote>\n\n<p>Have you read up on the <a href=\"http://msdn.microsoft.com/de-de/library/system.timespan%28v=vs.110%29.aspx\">Constructors of TimeSpan?</a> There is one, where you can do the following:</p>\n\n<pre><code>TimeSpan aDay = new TimeSpan(1,0,0,0);\n</code></pre>\n\n<h3>Returning Strings:</h3>\n\n<p>Returning strings is.. well It can be horrendous. In your case it's not a good idea: you have 3 Predefined States: <code>DayShift, NightShift, InvalidShift</code>. These can be extracted to an enum structure. This would change your Method signature to the Following:</p>\n\n<pre><code>public static Shift IdentifyShift(DateTime inTime, DateTime outTime)\n</code></pre>\n\n<p>Given the case you introduce an enum like this:</p>\n\n<pre><code>enum Shift\n{\n DayShift, NightShift, InvalidShift\n}\n</code></pre>\n\n<h3>Conditions in itself:</h3>\n\n<blockquote>\n <ol>\n <li><p>Day shift - From 7AM to 7PM</p></li>\n <li><p>Night shift - From 7PM to 7AM (on the next day)</p></li>\n <li><p>The employee should report before 8AM for a day shift, otherwise the shift will not be taken into account.</p></li>\n <li>The employee should report before 8PM for a night shift, otherwise the shift will not be taken into account.</li>\n <li>If an employee leaves before the regular off time of a shift, that shift will not be taken into account.</li>\n </ol>\n</blockquote>\n\n<p>This gives following conditions, assuming inTime is before outTime (and they are not more than one Day apart):</p>\n\n<pre><code>DayShift: if(7AM &lt;= inTime(hour) &lt; 8AM AND 7PM &lt; outTime(hour)) \nNightShift: if(7PM &lt;= inTime(hour) &lt; 8PM AND 7AM &lt; outTime(hour)) \nInvalidShift: all else\n</code></pre>\n\n<p><strong>Keep in mind, that as soon as the clock shows <code>08:00:00 / 20:00:00</code> respectively, that marks the shift as invalid.</strong></p>\n\n<h3>Extracting Magic Numbers</h3>\n\n<p>You can further clarify the intentions of your Code, if you extract the magic numbers (7AM, 7PM, and so on) to named constants:</p>\n\n<pre><code>const int DAY_SHIFT_START = 7;\nconst int DAY_SHIFT_DEADLINE = 8;\nconst int NIGHT_SHIFT_START = 19;\nconst int NIGHT_SHIFT_DEADLINE = 20;\n</code></pre>\n\n<p>You can thus simplify your code to the following: </p>\n\n<pre><code>public static Shift IdentifyShift(DateTime inTime, DateTime outTime)\n{\n if (inTime &gt;= outTime)\n {\n throw new ArgumentException(\"inTime is not before outTime\");\n }\n if ((outTime - inTime).Duration() &gt; new TimeSpan(1, 0, 0, 0))\n {\n throw new ArgumentException(\"outTime is more than 24 hours after inTime\");\n }\n\n int inHour = inTime.Hour;\n int outHour = outTime.Hour;\n if (inHour &gt;= DAY_SHIFT_START &amp;&amp; \n inHour &lt; DAY_SHIFT_DEADLINE &amp;&amp; outHour &gt; NIGHT_SHIFT_START)\n {\n return Shift.DayShift;\n }\n else if (inHour &gt;= NIGHT_SHIFT_START &amp;&amp;\n inHour &lt; NIGHT_SHIFT_DEADLINE &amp;&amp; outHour &gt; DAY_SHIFT_START)\n {\n return Shift.NightShift;\n }\n else\n {\n return Shift.InvalidShift;\n }\n}\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-05-08T15:10:18.413", "Id": "86531", "Score": "0", "body": "+1, but I think creating a 1-day `TimeSpan` is much more readable with the static `FromDays` factory method: `var aDay = TimeSpan.FromDays(1);`, than the constructor `TimeSpan(1,0,0,0);`." } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-05-08T07:20:19.820", "Id": "49211", "ParentId": "49205", "Score": "4" } } ]
{ "AcceptedAnswerId": "49211", "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-05-08T04:58:39.707", "Id": "49205", "Score": "3", "Tags": [ "c#", "optimization", "algorithm", ".net", "datetime" ], "Title": "Algorithm to identify a shift and its type based on on and off times" }
49205
<p>Below are two functions.</p> <p>The first is to set a cookie. This function is called on any product page on my website.</p> <pre><code>function setcookie() { $entry_id = $this-&gt;EE-&gt;TMPL-&gt;fetch_param('entry_id'); if (isset($_COOKIE['recently_viewed'])) { $currentSession = unserialize($_COOKIE['recently_viewed']); if (!in_array($entry_id, $currentSession)) { if (count($currentSession) &gt; 5) { unset($currentSession[0]); } $currentSession[] = $entry_id; } else {} $currentSession = serialize($currentSession); setcookie('recently_viewed', $currentSession, pow(2,31)-1, '/', ''); } else { $recently_viewed[] = $entry_id; $currentSession = serialize($recently_viewed); setcookie('recently_viewed', $currentSession, pow(2,31)-1, '/', ''); } } </code></pre> <p>The second function retrieves the IDs in the cookie array and outputs them.</p> <pre><code>function recently_viewed() { $tagdata = $this-&gt;EE-&gt;TMPL-&gt;tagdata; if ( array_key_exists('recently_viewed', $_COOKIE) ) { $recent = unserialize($_COOKIE['recently_viewed']); } else { $recent = NULL; } if ($recent) { $entry_ids = implode('|', $recent); } else { $entry_ids = NULL; } $data['entry_ids'] = $entry_ids; $variables = array(); $variables[] = $data; return $this-&gt;EE-&gt;TMPL-&gt;parse_variables($tagdata, $variables); } </code></pre> <p>The code is built for the content management system Expression Engine. If you don't know 'codeigniter' code, just ignore those bits and take a look at the straight PHP if possible.</p> <p>Can anyone tell me if there is any way to speed the functions up?</p> <p>The first function, <code>setcookie</code>, is basically checking to see if a cookie exists. If it does, it checks if the current <code>entry id</code> is in the array already. If it's not, then it checks if there are more than 5 items in the array. If there is, it deletes the first one and adds the new <code>entry id</code>. If no cookie exists, it creates a new cookie and adds the <code>entry id</code>.</p> <p>The second function (recently viewed) is checks the cookie, converts it to a string with pipelines between <code>entry ids</code>, then outputs this string.</p>
[ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-05-08T21:09:19.707", "Id": "86627", "Score": "0", "body": "Why do you use cookies instead of sessions to store this data?" } ]
[ { "body": "<p>First of all, let me tell you that I have zero experience with Codeigniter, but I suppose it is an MVC / OOP based framework, and I have plenty of experience with those. I am not trying to declare myself an expert or anything, just trying to be helpful and constructive. So here we go...</p>\n\n<p>A few general words of advice:<br>\n - try to avoid nesting control structures. <strong>Work with early returns</strong> in stead. You hardly ever need to nest an if inside an if, or even use an else. If you realy do, you are probably not <strong>following the principles of single responsibility</strong><br>\n - <strong>don't waste resources</strong> by storing stuff in variables and only using them once immediately after you stored them. Use the value you wanted to store directly.<br>\n - <strong>Put comments inside your code</strong>. A lot of them! It may take a little bit longer now, but it will safe you time when you ever have to debug or alter your code!</p>\n\n<p>With those hints in mind, I would write your first function as follows:</p>\n\n<pre><code>function setcookie() { \n // prepare the entry id\n $entry_id = $this-&gt;EE-&gt;TMPL-&gt;fetch_param('entry_id');\n\n // if cookie has not been set before\n if (! isset($_COOKIE['recently_viewed'])) {\n // write the current entry id to a cookie\n setcookie('recently_viewed', serialize(array($entry_id)), pow(2,31)-1, '/', '');\n // and we are done (return self for chaining)\n return $this;\n }\n\n // convert the cookie to an array\n $currentSession = unserialize($_COOKIE['recently_viewed']);\n\n // if the current entry id is already in the cookie\n if (in_array($entry_id, $currentSession)) {\n // we are done (return self for chaining)\n return $this;\n }\n\n // if there are already 5 entries\n if (count($currentSession) &gt; 5) {\n // shift of the first entry \n // don't use an index here, cause there is no garantee the first element actualy has index 0\n array_shift($currentSession);\n }\n\n // push the current id onto the list\n $currentSession[] = $entry_id;\n // write it to a cookie\n setcookie('recently_viewed',serialize($currentSession), pow(2,31)-1, '/', '');\n}\n</code></pre>\n\n<p>And the second function:</p>\n\n<pre><code>function recently_viewed() {\n // prepare the tagdata\n $tagdata = $this-&gt;EE-&gt;TMPL-&gt;tagdata;\n\n // if no recently_viewed cookie is present\n // (isset is supposed to be a little better in performance then array_key_exists)\n if (! isset($_COOKIE['recently_viewed']) ) {\n // do something and return the result\n return $this-&gt;EE-&gt;TMPL-&gt;parse_variables(\n $tagdata, \n array(\n array('entry_ids' =&gt; null)\n )\n );\n } \n\n // convert the recently viewed ids to a piped string\n // do something with it and return the result\n return $this-&gt;EE-&gt;TMPL-&gt;parse_variables(\n $tagdata, \n array(\n array(\n 'entry_ids' =&gt; implode('|', unserialize($_COOKIE['recently_viewed']))\n )\n )\n );\n}\n</code></pre>\n\n<p>You could even put that function into a single 'line' of code, which should be a bit more performant, but a lot less readable. And imo you should always take readable code over performant code when the difference is small. Just as an example though:</p>\n\n<pre><code>function recently_viewed() {\n return $this-&gt;EE-&gt;TMPL-&gt;parse_variables(\n $this-&gt;EE-&gt;TMPL-&gt;tagdata,\n array(\n array(\n 'entry_ids' =&gt; \n isset($_COOKIE['recently_viewed']) \n ? implode('|', unserialize($_COOKIE['recently_viewed'])) \n : null\n )\n )\n );\n}\n</code></pre>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-05-08T21:39:42.570", "Id": "49269", "ParentId": "49214", "Score": "2" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "1", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-05-08T09:22:28.600", "Id": "49214", "Score": "2", "Tags": [ "php" ], "Title": "Functions for setting cookies and outputting their IDs" }
49214
<p>I've just finished creating this form validation but I want to make it public for beginner 'contact us forms'.</p> <p>I was wondering if I can have some peoples' input on if they can understand/read my JavaScript. Although I know my JS works, it's better to be safe than to have 20 people asking what this does. It's just input feedback. </p> <p>What I'm trying to achieve in my code is making fields required with JavaScript.</p> <p>The following fields are REQUIRED:</p> <ul> <li>First Name</li> <li>Last Name</li> <li>Email</li> <li>Phone</li> </ul> <p>Most of the functions such as <code>alphaNumeric</code> only allows numbers and <code>onlyAlphameric</code> only allows letters. </p> <p>E.g for each function or what not, add a comment saying what it does.</p> <p>For example, adding a comment:</p> <p>This function does this and triggers that and so on.</p> <p>JavaScript:</p> <pre><code>function elem(id) { return document.getElementById(id); }; window.onload = function () { document.querySelector("#RadioGroup1_0").click(); var form = document.getElementById('form'); form.onsubmit = function (e) { var rules = [ ['first-name', elem('first-name').value.length &gt; 0], ['last-name', elem('last-name').value.length &gt; 0], ['email', elem('email').value.length &gt; 0 &amp;&amp; /^([a-zA-Z0-9_\.\-])+\@(([a-zA-Z0-9\-])+\.)+([a-zA-Z0-9]{2,4})+$/.test(elem('email').value)], ['phone', elem('phone').value.length &gt; 7 &amp;&amp; elem('phone').value.length &lt; 11 &amp;&amp; /^(\+\d{1,2})?[\d ()-]+$/.test(elem('phone').value)] ]; function myFunction() { document.getElementById("myForm").reset(); } function alpha(e) { var k; document.all ? k = e.keyCode : k = e.which; return ((k &gt; 64 &amp;&amp; k &lt; 91) || (k &gt; 96 &amp;&amp; k &lt; 123) || k == 8); } var valid = true; var firstFocus = null; for (var i = 0; i &lt; rules.length; i++) { var parent = elem(rules[i][0]).parentNode; if (!rules[i][1]) { valid = false; parent.children[2].style.display = "inline"; if (firstFocus == null) firstFocus = parent.children[1]; } else { parent.children[2].style.display = "none"; } } if (!valid) { firstFocus.focus(); return false; } return true; }; }; function onlyAlphabets(e, t) { try { if (window.event) { var charCode = window.event.keyCode; } else if (e) { var charCode = e.which; } else { return true; } if ((charCode &gt; 64 &amp;&amp; charCode &lt; 91) || (charCode &gt; 96 &amp;&amp; charCode &lt; 123) || (charCode === 8)) return true; else return false; } catch (err) { alert(err.Description); } } var specialKeys = new Array(); specialKeys.push(8); //Backspace function IsNumeric(e) { var keyCode = e.which ? e.which : e.keyCode var ret = ((keyCode &gt;= 48 &amp;&amp; keyCode &lt;= 57) || specialKeys.indexOf(keyCode) != -1); //document.getElementById("phone").style.display = ret ? "none" : "inline"; return ret; } </code></pre>
[ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-05-08T11:27:55.123", "Id": "86501", "Score": "1", "body": "Welcome to Code Review! Asking *us* to provide the comments about what your code does makes me wonder: Do **you** know what your code does? We'd gladly review the readability of your code, but we do assume that you understand your own code. Because, this *is* **your** code, right?" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-05-08T11:29:54.600", "Id": "86502", "Score": "0", "body": "To make life easier for reviewers, please add sufficient context to your question. The more you tell us about what your code does and what the purpose of doing that is, the easier it will be for reviewers to help you. See also [this meta question](http://meta.codereview.stackexchange.com/questions/1226/code-should-include-a-description-of-what-the-code-does)" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-05-08T11:30:01.630", "Id": "86503", "Score": "0", "body": "@SimonAndréForsberg Hi there, yes this is my code that I wrote, I originally posted it at another section of StackOverflow so they just redirected me here and I had to create a new account, or 'Post as a guest'." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-05-08T11:42:03.030", "Id": "86504", "Score": "0", "body": "Good. Thanks for editing your question and providing a short description. Again, Welcome to Code Review!" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-05-08T11:43:17.707", "Id": "86505", "Score": "0", "body": "@SimonAndréForsberg Thanks for the helping had bud, if you have time do you reckon you could go over my code? Cheers" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-05-08T13:17:15.260", "Id": "86512", "Score": "0", "body": "For what it's worth, I would not do this type of validation within JavaScript. It is by far simpler to use HTML5 form properties (see: http://dev.opera.com/articles/new-form-features-in-html5/) and write a good polyfill for older browsers." } ]
[ { "body": "<p>Take care that I can read JavaScript but it was a whole time ago that I effectively wrote in that.</p>\n\n<ol>\n<li><p>I see you've created your own <code>isNumeric</code> function.</p>\n\n<p>Maybe you can use the <code>isNaN</code>. <a href=\"http://www.w3schools.com/jsref/jsref_isnan.asp\" rel=\"nofollow\">Documentation over here.</a></p></li>\n<li><p>You use this twice:</p>\n\n<pre><code>((k &gt; 64 &amp;&amp; k &lt; 91) || (k &gt; 96 &amp;&amp; k &lt; 123) || k == 8);\n</code></pre>\n\n<p>If you use such a statement more than once, you should consider refactoring to a method.</p></li>\n<li><p>What is the meaning of <code>t</code>? (you don't use it)</p>\n\n<pre><code>function onlyAlphabets(e, t) {\n try {\n if (window.event) {\n var charCode = window.event.keyCode;\n } else if (e) {\n var charCode = e.which;\n } else {\n return true;\n }\n if ((charCode &gt; 64 &amp;&amp; charCode &lt; 91) || (charCode &gt; 96 &amp;&amp; charCode &lt; 123) || (charCode === 8)) return true;\n else return false;\n } catch (err) {\n alert(err.Description);\n }\n}\n</code></pre></li>\n<li><p>Very bad naming of method:</p>\n\n<pre><code>function alpha(e) {\n var k;\n document.all ? k = e.keyCode : k = e.which;\n return ((k &gt; 64 &amp;&amp; k &lt; 91) || (k &gt; 96 &amp;&amp; k &lt; 123) || k == 8);\n}\n</code></pre>\n\n<p>Don't you do it almost the same as the function mentioned in the third issue?</p></li>\n</ol>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-05-08T15:45:57.230", "Id": "86547", "Score": "0", "body": "I would add on the third point that the `if(expression) return true else return false` beginner code should be changed to `return (expression)`. In this case, `expression` should probably be a function call...that's a long (somewhat) complicated expression." } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-05-08T12:07:44.437", "Id": "49221", "ParentId": "49218", "Score": "10" } }, { "body": "<blockquote>\n <p>Can people understand my code?</p>\n</blockquote>\n\n<p>Its certainly not bad code - but I believe there are some things you can do which will improve the speed with which people like me can grasp what it is doing (and why).</p>\n\n<h2>Comments</h2>\n\n<p>Some people think well-written code needs no comments. I don't fall into that camp. Looking at your code I see the following:</p>\n\n<p>Total number of comments is 2</p>\n\n<p>Total number of helpful comments is 1</p>\n\n<p>Total number of comments describing goal of sections of code is 0</p>\n\n<p>Languages like Java have JavaDoc, which are comments in the code from which you can automatically produce documentation. If you've ever tried to re-use code that has no documentation you'll know how useful it is. If you've ever had to maintain documentation that is separate from code you'll know what a pain that is. Innaccurate documentation is worse than none.</p>\n\n<p>So I believe it is best to put documentation into code. Ideally in a form from which documentation can be produced. </p>\n\n<p>I like to treat every function/method I write as if it were one I would put into a library and re-use. To me this means it needs comments that document its purpose, interface and any quirks.</p>\n\n<h2>Magic Numbers</h2>\n\n<p>You have a lot of <a href=\"http://en.wikipedia.org/wiki/Magic_number_(programming)\" rel=\"nofollow noreferrer\">magic numbers</a>, e.g. 48 and 57. These should be either</p>\n\n<ul>\n<li>explained in comments</li>\n<li>replaced by constants with meaningful names (e.g. ASCII_0, DIGIT_0 ...)</li>\n<li>replaced by functions</li>\n</ul>\n\n<p>The latter may be best, especially if you (or anyone else) want this code to work with character sets other than ASCII.</p>\n\n<h2>Meaningful names</h2>\n\n<pre><code> function myFunction()\n</code></pre>\n\n<p>I feel you may be underestimating the usefulness of meaningful names as an aid to other's understanding. I'd try to find a more helpful name that helps others understand the purpose of the the function and what it returns.</p>\n\n<h2>Writing for comprehension</h2>\n\n<p>You use the <a href=\"https://stackoverflow.com/questions/2595392/what-does-the-question-mark-and-the-colon-ternary-operator-mean-in-objectiv\">ternary operator</a>. Often this is used for assignment. If you use if for assignment but in an unusual way you may momentarily confuse readers.</p>\n\n<p>Unless you need conciseness, it can sometimes be clearer to use a conventional if-then-else form instead.</p>\n\n<p>Wouldn't</p>\n\n<pre><code>document.all ? k = e.keyCode : k = e.which;\n</code></pre>\n\n<p>be clearer as</p>\n\n<pre><code>k = document.all ? e.keyCode : e.which;\n</code></pre>\n\n<p>Because the main purpose seems to be to assign a value to k. The earlier style is one I might use if the main point is to call a function and, as an afterthought, evaluate its's success or failure. I think in this case it moves the reader's focus to the wrong place.</p>\n\n<h2>Writing portable code and avoiding browser-sniffing</h2>\n\n<p>The above use of the ternary operator can probably be avoided entirely. I suspect you may be interested in <a href=\"http://jquery.com/\" rel=\"nofollow noreferrer\">jQuery</a> and replace it with</p>\n\n<pre><code>keyPressed = e.which\n</code></pre>\n\n<p>Which I find easier to read and which can be understood more rapidly.</p>\n\n<p>I would at least factor out browser-dependent and/or repeated stuff into my own functions/methods and/or carefully document in comments what it is doing and why it needs to be done.</p>\n\n<hr>\n\n<h2>Documenting purpose</h2>\n\n<blockquote>\n <p>What I'm trying to achieve in my code is ...</p>\n</blockquote>\n\n<p>As I mentioned above, I believe it is very useful to have this described in comments in the code itself (others may disagree). From it's inclusion in your question you evidently believe this helps readers understand the following code. Therefore I'd put it into the code as a comment.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-05-08T14:59:21.297", "Id": "86528", "Score": "0", "body": "Welcome to CodeReview, feel free to drop by in our [chat]" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-05-08T16:06:43.827", "Id": "86550", "Score": "2", "body": "`Some people think well-written code needs no comments.` I think this. Self-documenting code is the way to go. Every now and then you run into situation where you have to do something a little unclear, which is where you leave comments. If there's too many comments in code, it's as good as none, I don't know which ones are useful so read none. If you code DEPENDING on comments to explain it, then there's definitely something wrong." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-05-08T16:18:52.860", "Id": "86553", "Score": "0", "body": "@Cruncher: I agree with most of that. But not all :-). However the subject deserves it's own question and answers - for example [this](http://codereview.stackexchange.com/q/38963/42109). So I'll leave it at that for now." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-05-08T16:32:07.560", "Id": "86558", "Score": "0", "body": "I disagree... some coders are better than others. What an excellent experienced coder might see simple and straightforward and lesser experienced coder might struggle with.\n\nObviously never add pages and pages of code comments but I always find something in relation to comments is better than none at all." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-05-08T21:03:06.740", "Id": "86626", "Score": "0", "body": "While I prefer the \"well written code needs no comments\" approach, I would add that a good comment explains _why_ the code works rather than how and what the _intended_ result is. If the code is incorrect the comment shouldn't make it _worse_ by reiterating what the code is doing. A good comment shouldn't need to be edited when you fix a bug. You would either delete it, add to it, or replace it entirely." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-05-08T22:35:50.297", "Id": "86640", "Score": "1", "body": "To comment or not to comment — that has been [debated on Programmers](http://programmers.stackexchange.com/q/51307/51698) to the point where the question had to be locked, so it's not going to get resolved in this comment thread." } ], "meta_data": { "CommentCount": "6", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-05-08T14:24:29.013", "Id": "49226", "ParentId": "49218", "Score": "15" } }, { "body": "<p>In my eyes, any function called <code>myFunction</code> is not a good function.</p>\n\n<p>This applies to <code>foo()</code> and <code>helloWorld()</code> too.</p>\n\n<p>Having another look at the code, I can see that it involves a form and resetting values.</p>\n\n<p>Maybe a function as follows would be better:</p>\n\n<pre><code>function formReset() { }\n</code></pre>\n\n<p>In an nutshell a function name in my view should be</p>\n\n<ol>\n<li>relatively short</li>\n<li>straight to the point</li>\n</ol>\n\n<p>For instance:</p>\n\n<pre><code>function addOrder() {}\n</code></pre>\n\n<p>looks much better in my view than </p>\n\n<pre><code>function addOrderToShoppingCart()\n</code></pre>\n\n<p>Both are pretty obvious, one just takes a little bit longer to read.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-05-08T16:53:44.543", "Id": "86565", "Score": "2", "body": "`addOrder` is named with a verb-noun scheme, so naming `formReset` with a noun-verb scheme would be inconsistent." } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-05-08T14:42:59.993", "Id": "49227", "ParentId": "49218", "Score": "6" } }, { "body": "<p>I will try not to repeat items that others have mentioned, since I agree with all of them.</p>\n\n<p>Here is what I have found:</p>\n\n<ol>\n<li><p><strong>Not using helper code that you have written</strong></p>\n\n<p>At the top you define a function:</p>\n\n<pre><code>function elem(id) {\n return document.getElementById(id);\n};\n</code></pre>\n\n<p>but then in two other places, I see these:</p>\n\n<pre><code>var form = document.getElementById('form');\n</code></pre>\n\n<p>and</p>\n\n<pre><code>function myFunction()\n{\n document.getElementById(\"myForm\").reset();\n}\n</code></pre>\n\n<p>Why not use your <code>elem</code> function since you appear to have created it as a short form, so you could use it as:</p>\n\n<pre><code>var form = elem('form');\n</code></pre>\n\n<p>for the first example above and </p>\n\n<pre><code>function myFunction()\n{\n elem('myForm').reset();\n}\n</code></pre>\n\n<p><strong>Note:</strong> I agree with the above posters about poor choice of naming functions.</p></li>\n<li><p><strong>Standardize on quotes</strong></p>\n\n<p>Try pick a standard set of quotes to use, either single quotes everywhere, or double quotes everywhere and stick to one of those styles.</p></li>\n<li><p><strong>Dangers of chaining</strong></p>\n\n<p>Again on the topic of <code>document.getElementById()</code>, I always try to check if the value returned is a <code>null</code> prior to assuming that properties exist on that object.</p>\n\n<p>e.g. </p>\n\n<pre><code>var myTextBox = document.getElementById('my-textbox');\nif (myTextBox) {\n return myTextBox.value.length;\n}\n</code></pre>\n\n<p>rather than:</p>\n\n<pre><code>return document.getElementById('my-textbox').value.length;\n</code></pre></li>\n</ol>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-05-08T18:22:15.403", "Id": "49246", "ParentId": "49218", "Score": "4" } }, { "body": "<p>Your email checker is broken. You fail to allow various characters that are legal in the local part (such as <code>+</code>) and you fail to allow TLDs longer than four characters, of which there are now many.</p>\n\n<p>Also, you <code>myFunction</code>, <code>alpha</code>, <code>onlyAlphabets</code>, and <code>IsNumeric</code> functions are never called. It would help to see how these are being used to determine if they are being used correctly.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-05-08T21:41:42.563", "Id": "49270", "ParentId": "49218", "Score": "3" } }, { "body": "<p>You should read more about how JavaScript works, especially <a href=\"http://www.w3schools.com/js/js_hoisting.asp\" rel=\"nofollow\" title=\"Hoisting\">variable hoisting</a>.</p>\n\n<pre><code>if (window.event) {\n var charCode = window.event.keyCode;\n} else if (e) {\n var charCode = e.which;\n}\n</code></pre>\n\n<p>Here you are declaring two variables with the name <code>charCode</code>. But you want to declare it only once and then initialize it in your <code>if</code>-block.</p>\n\n<pre><code>var charCode;\nif (window.event) {\n charCode = window.event.keyCode;\n} else if (e) {\n charCode = e.which;\n}\n</code></pre>\n\n<p>Generally put all your var statements directly beneath your function keyword</p>\n\n<pre><code>function calculateSomething() {\n var a, b, c;\n ...\n}\n</code></pre>\n\n<p>Also read about the <a href=\"http://bonsaiden.github.io/JavaScript-Garden/#types.equality\" rel=\"nofollow\">comparison operator</a> and use the strict <code>===</code> instead of <code>==</code> (and <code>!==</code> instead of <code>!=</code> resp.)</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-05-09T06:44:39.343", "Id": "86688", "Score": "0", "body": "Keep in mind, that changing the comparison operation will affect the behaviour. For a validator the strict comparison may be better, but in other cases I wouldn't recommend it ;) Either way, nice answer and welcome to [Codereview.se]. Maybe you want to check out our [chat] too ;)" } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-05-09T06:21:29.930", "Id": "49300", "ParentId": "49218", "Score": "3" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "6", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-05-08T11:17:08.140", "Id": "49218", "Score": "10", "Tags": [ "javascript", "form", "validation" ], "Title": "Can people understand my form validation code?" }
49218
<p>I wrote the following groovy function for taking a string of multiple lines (or any other character for splitting the code into parts), and bringing each line/part to a specified number of characters, cutting too long lines and filling up too short lines with a fill character:</p> <pre><code>static final String adjustLineLength(Integer length, String filler, String token, String source) { source .tokenize(token) .collect{ String line -&gt; if(line.size() &gt; length) line.substring(0, length) else if(line.size() &lt; length) line + (filler * (length - line.size())) else line } .join(token) } </code></pre> <p>Is that a good approach? Any suggestions how this code can be improved in concerns of making it more easy to understand and maybe (but that has not priority over beeing easy to understand) improving performance?</p>
[]
[ { "body": "<p>I think your approach is fine, and it's easy to understand. I have just a few improvement ideas:</p>\n\n<ul>\n<li>A more natural ordering of the method parameters might be: source, token, length, filler</li>\n<li>Instead of <code>Integer</code>, <code>int</code> should be enough and shorter</li>\n<li>Move the closure in <code>collect</code> to its own method</li>\n<li>Do you really need the <code>static final String</code> declaration? Why not use simply <code>def</code>?</li>\n<li>Do you really need the type declarations in the signature? You could omit them, and it will be still quite clear</li>\n<li><p>The brackets around the multiplication are unnecessary in</p>\n\n<pre><code>line + (filler * (length - line.size()))\n</code></pre></li>\n</ul>\n\n<h3>Suggested implementation</h3>\n\n<p>Putting the above suggestions together:</p>\n\n<pre><code>def adjustLineLength = { line, length, filler -&gt;\n if (line.size() &gt; length) {\n line.substring(0, length)\n } else if (line.size() &lt; length) {\n line + filler * (length - line.size())\n } else {\n line\n }\n}\n\ndef adjustTextLength = { source, token, length, filler -&gt;\n source\n .tokenize(token)\n .collect { adjustLineLength(it, length, filler) }\n .join(token)\n}\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-05-08T20:15:09.940", "Id": "86618", "Score": "0", "body": "Hi, the reason why I used this \"odd\" ordering is because of currying. I want to use curry and if I order it like you posted (what I would do when not having to curry it) then I have to use ncurry and that is a little ugly. Any suggestions what to do in this case? Regarding the \"verbose\" syntax: I want it to be more familiar for java developers. But thx for the other points, they are really helpfull for me. =)" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-05-08T21:00:41.883", "Id": "86624", "Score": "0", "body": "I don't actually get your point about currying, but that doesn't mean anything, because I don't know groovy well at all (and so I cannot comment about the ugliness and ncurry). As for making it more java-developer-friendly, I would boldly go and embrace groovy, but that may be subjective ;-)" } ], "meta_data": { "CommentCount": "2", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-05-08T16:03:34.250", "Id": "49234", "ParentId": "49219", "Score": "3" } } ]
{ "AcceptedAnswerId": "49234", "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-05-08T11:35:46.223", "Id": "49219", "Score": "4", "Tags": [ "strings", "formatting", "groovy" ], "Title": "Code for adjusting linelength" }
49219
<p>I am trying to learn Clojure for some time. In my experience, it has been rather too easy to produce write-only code.</p> <p>Here is a solution to <a href="http://code.google.com/codejam/contest/2974486/dashboard#s=p1" rel="nofollow">a simple problem</a> with very little essential complexity. Input and output formats are extremely simple, too. Which means all complexity in it must be accidental. How to improve its legibility, intelligibility?</p> <ul> <li>Is the decomposition of the problem into functions all right?</li> </ul> <p>Also other specific problems:</p> <ul> <li><p>How to input/output numbers? Is there any benefit to use <code>read-string</code> instead of <code>Double/parseDouble</code>? How to format floating point numbers to fixed precision without messing with the default locale?</p></li> <li><p>How to avoid the explicit <code>loop</code>/<code>recur</code>, which is currently a translation of a while loop?</p></li> <li><p>Are there definitions that should/shouldn't have bee private/dynamic?</p></li> </ul> <blockquote> <p><strong>Problem</strong></p> <p>You start with 0 cookies. You gain cookies at a rate of 2 cookies per second [...]. Any time you have at least <strong>C</strong> cookies, you can buy a cookie farm. Every time you buy a cookie farm, it costs you <strong>C</strong> cookies and gives you an extra <strong>F</strong> cookies per second.</p> <p>Once you have <strong>X</strong> cookies that you haven't spent on farms, you win! Figure out how long it will take you to win if you use the best possible strategy.</p> </blockquote> <pre><code>(ns cookie-clicker (:use [clojure.string :only [split]]) (:require [clojure.java.io :as io] [clojure.test :refer :all])) ;;See http://code.google.com/codejam/contest/2974486/dashboard#s=p1 (defn parse-double [s] (java.lang.Double/parseDouble s)) (defn parse-row [line] (map parse-double (split line #"\s+"))) (defn parse-test-cases [rdr] (-&gt;&gt; rdr line-seq rest (map parse-row))) (def initial-rate 2.0) (defn min-time [c f x] (loop [n 0 ; no of factories used tc 0 ; time cost of factories built r initial-rate ; cookie production rate t (/ x r)] ; total time (let [n2 (inc n) tc2 (+ tc (/ c r)) r2 (+ r f) t2 (+ tc2 (/ x r2))] (if (&gt; t2 t) t (recur n2 tc2 r2 t2))))) (java.util.Locale/setDefault (java.util.Locale/US)) (defn ans [n t] (str "Case #" n ": " (format "%.7f" t))) (defn answers [test-cases] (map #(ans %1 (apply min-time %2)) (rest (range)) test-cases)) (defn spit-answers [in-file] (with-open [rdr (io/reader in-file)] (doseq [answer (answers (parse-test-cases rdr))] (println answer)))) (defn solve [in-file out-file] (with-open [w (io/writer out-file :append false)] (binding [*out* w] (spit-answers in-file)))) (def ^:dynamic *tolerance* 1e-6) (defn- within-tolerance [expected actual] (&lt; (java.lang.Math/abs (- expected actual)) *tolerance*)) (deftest case-3 (is (within-tolerance 63.9680013 (min-time 30.50000 3.14159 1999.19990)))) (defn -main [] (solve "resources/cookie_clicker/B-large-practice.in" "resources/cookie_clicker/B-large-practice.out")) </code></pre>
[]
[ { "body": "<p>I have to admit, the actual \"solving the problem\" component of this is a little over my head. But, I thought I'd try to answer your questions and give you some style/structure feedback, for what it's worth :)</p>\n\n<p>You can simplify your <code>ns</code> declaration like this:</p>\n\n<pre><code>(ns cookie-clicker\n (:require [clojure.string :refer (split)]\n [clojure.java.io :as io]\n [clojure.test :refer :all]))\n</code></pre>\n\n<p>(<code>:require foo :refer (bar)</code> does the same thing as <code>:use foo :only (bar)</code>, and is generally considered preferable, especially as an alternative to having both <code>:use</code> and <code>:require</code> in your <code>ns</code> declaration)</p>\n\n<p>I think <code>Double/parseDouble</code> is a good approach to parsing doubles in string form. <code>Integer/parseInt</code> is usually my go-to for doing the same with integers in string form. This is just a hypothesis, but <code>Double/parseDouble</code> might be faster and/or more accurate than <code>read-string</code> because it's optimized for doubles.</p>\n\n<p>FYI, you can leave out the <code>java.lang.</code> and just call it as <code>Double/parseDouble</code> in your code. In light of that, you might consider getting rid of your <code>parse-double</code> function altogether and just using <code>Double/parseDouble</code> whenever you need it. The only thing is that Java methods aren't first-class in Clojure, so you would need to do things like this if you go that route:</p>\n\n<pre><code>(defn parse-row [line]\n (map #(Double/parseDouble %) (split line #\"\\s+\")))\n</code></pre>\n\n<p>(Personally, I still like that better, but you might prefer to keep it wrapped in a function <code>parse-double</code> like you have it. It's up to you!)</p>\n\n<p>I think needing to mess with the locale might be a locale-specific problem... I tried playing around with <code>(format \"%.7f\" ...</code> without changing my locale and it worked as expected. Granted, I'm in the US :)</p>\n\n<p>I think the legibility issues you're seeing might be related to having too many functions. You might consider condensing and renaming things and see if you like that better. I would re-structure your program so that you parse the data into the data structure at the top, something like this:</p>\n\n<pre><code>(defn parse-test-cases [in-file]\n (with-open [rdr (io/reader in-file)]\n (let [rows (rest (line-seq rdr))]\n (map (fn [row] \n (map #(Double/parseDouble %) (split row #\"\\s+\")))\n rows))))\n</code></pre>\n\n<p>(I condensed your functions <code>parse-row</code>, <code>parse-test-cases</code> and half of <code>spit-answers</code> into the function above)</p>\n\n<p>Then define the functions that \"do all the work\" like <code>min-time</code>, and then, at the end:</p>\n\n<pre><code>(defn spit-answers [answers out-file]\n (with-open [w (io/writer out-file :append false)]\n (.write w (clojure.string/join \"\\n\" answers)))\n\n(def -main []\n (let [in \"resources/cookie_clicker/B-large-practice.in\"\n out \"resources/cookie_clicker/B-large-practice.out\"\n test-cases (parse-test-cases in)\n answers (map-indexed (fn [i [c f x]]\n (format \"Case #%d: %.7f\" (inc i) (min-time c f x)))\n test-cases)]\n (spit-answers answers out)))\n</code></pre>\n\n<p>I came up with a few ideas above:</p>\n\n<ol>\n<li><p>In your <code>answers</code> function you use <code>(map ... (rest (range)) (test-cases))</code> in order to number each case, starting from 1. A simpler way to do this is with <code>map-indexed</code>. I used <code>(inc i) for the case numbers</code>, since the index numbering starts at 0.</p></li>\n<li><p>I condensed <code>(str \"Case #\" n \": \" (format \"%.7f\" t)))</code> into a single call to <code>format</code>.</p></li>\n<li><p>I used destructuring over the arguments to the <code>map-indexed</code> function to represent each case as <code>c f x</code> -- that way it's clearer that each test case consists of those three values, and you can represent the calculation as <code>(min-time c f x)</code> instead of <code>(apply min-time test-case)</code>.</p></li>\n</ol>\n\n<p>As for your <code>min-time</code> function, I don't think <code>loop</code>/<code>recur</code> is necessarily a bad thing, and I often tend to rely on it in complicated situations where you're doing more involved work on each iteration, checking conditions, etc. I think it's OK to use it here. But if you want to go a more functional route, you could consider writing a <code>step</code> function and creating a lazy sequence of game states using <code>iterate</code>, like so:</p>\n\n<p>(note: I'm writing <code>step</code> as a <code>letfn</code> binding so that it can use arbitrary values of <code>c</code>, <code>f</code> and <code>x</code> that you feed into a higher-order function that I'm calling <code>step-seq</code> -- this HOF takes values for <code>c</code>, <code>f</code> and <code>x</code> and generates a lazy sequence of game states or \"steps.\")</p>\n\n<pre><code>(defn step-seq [c f x]\n (letfn [(step [{:keys [factories time-cost cookie-rate total-time result]}]\n (let [new-time-cost (+ time-cost (/ c cookie-rate))\n new-cookie-rate (+ cookie-rate f)\n new-total-time (+ new-time-cost (/ x new-cookie-rate))]\n {:factories (inc factories)\n :time-cost new-time-cost\n :cookie-rate new-cookie-rate\n :total-time new-total-time\n :result (when (&gt; new-total-time total-time) total-time)}))]\n (iterate step {:factories 0, :time-cost 0, :cookie-rate 2.0, \n :total-time (/ x 2.0), :result nil})))\n</code></pre>\n\n<p>Now, finding the solution is as simple as grabbing the <code>:result</code> value from the first step that has one:</p>\n\n<pre><code>(defn min-step [c f x]\n (some :result (step-seq c f x)))\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-05-13T10:45:30.333", "Id": "87254", "Score": "0", "body": "Thanks for the answer. As for `spit-answers`, I'd thought writing answers of test cases one by one would reduce memory requirement, but after reading your answer I realize the memory burden of the `join` would probably would be on the order of KBs for the majority of cases (and possibly having multiple disk seeks could hurt performance more)." } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-05-09T23:46:05.047", "Id": "49377", "ParentId": "49220", "Score": "3" } } ]
{ "AcceptedAnswerId": "49377", "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-05-08T12:07:21.493", "Id": "49220", "Score": "2", "Tags": [ "clojure" ], "Title": "\"Cookie Clicker Alpha\" solution" }
49220
<p>I have to generate a lot of tables from different JSON files (up to 20 tables per page). Because it's a lot of data, I really want to keep loading speed in mind. I know it's better to use a non jQuery solution, but native is not in my skillset right now.</p> <pre><code>$(document).ready(function(){ (function getPersonData(){ $.getJSON('path/to/json', function(data){ (function addPersonsTable1(personsData){ var elementContainer = ''; $.each(personsData.persons, function(key, person){ elementContainer = elementContainer + '&lt;tr&gt;' + '&lt;td&gt;' + person.value1 + '&lt;/td&gt;' + '&lt;td&gt;' + person.value2 + '&lt;/td&gt;' + '&lt;td&gt;' + person.value3 + '&lt;/td&gt;' + '&lt;td&gt;' + person.value4 + '&lt;/td&gt;' + '&lt;td&gt;' + person.value5 + '&lt;/td&gt;' + '&lt;/tr&gt;'; }); $('.persons-table-1').append(elementContainer); }(data)); (function addPersonsTable2(personsData){ var elementContainer = ''; $.each(personsData.persons, function(key, person){ elementContainer = elementContainer + '&lt;tr&gt;' + '&lt;td&gt;' + person.value1 + '&lt;/td&gt;' + '&lt;td&gt;' + person.value2 + '&lt;/td&gt;' + '&lt;td&gt;' + person.value3 + '&lt;/td&gt;' + '&lt;td&gt;' + person.value4 + '&lt;/td&gt;' + '&lt;td&gt;' + person.value5 + '&lt;/td&gt;' + '&lt;/tr&gt;'; }); $('.persons-table-2').append(elementContainer); }(data)); /* * * * * * &lt;..... And many more tables * * * * */ }).done(function(){ loadedAnimation(); }); }); </code></pre>
[]
[ { "body": "<p>Use <code>detach</code> to remove the elements from the DOM, append the tables to the detached nodes, then add them back to to DOM:</p>\n\n<pre><code>var table = $( \"#myTable\" );\nvar parent = table.parent();\n\ntable.detach();\n\n // ... add lots and lots of rows to table\n\nparent.append( table );\n</code></pre>\n\n<p><strong>References</strong></p>\n\n<ul>\n<li><p><a href=\"https://learn.jquery.com/performance/detach-elements-before-work-with-them/\" rel=\"nofollow noreferrer\">Detach Elements to Work with Them</a></p></li>\n<li><p><a href=\"http://api.jquery.com/detach/\" rel=\"nofollow noreferrer\">jQuery API: detach</a></p></li>\n</ul>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2018-03-18T15:53:05.280", "Id": "189880", "ParentId": "49223", "Score": "1" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-05-08T12:30:56.020", "Id": "49223", "Score": "2", "Tags": [ "javascript", "jquery", "html", "json" ], "Title": "Generate HTML from JSON" }
49223
<p>Assume I have the following list (<code>List&lt;string&gt;</code>)</p> <p>G<br> G<br> M<br> T</p> <p>I'd like this to be in an order where the same letter will not occur twice, such as</p> <p>G<br> M<br> G<br> T</p> <p>(I appreciate other variations would also suffice)</p> <p>Please note, if I had the following</p> <p>G<br> G<br> G<br> G<br> G<br> M<br> T </p> <p>Then of course some values will have to occur concurrently. The position within the List where this concurrency occurs is not relevant. What I'm after is to stop this repetition where possible to most evenly spread the letters.</p> <p>The C# console application code I share works</p> <pre><code>using System; using System.Collections.Generic; using System.Linq; using System.Text; namespace resorting { class Program { static void Main(string[] args) { List&lt;string&gt; list = new List&lt;string&gt; { "G", "G", "G", "G", "M", "M", "T", "T", "T", "T", "T", "T", "T", "T", "G", "G", "G", "G", "M", "M", "T", "T", "T", "T", "T", "T", "T", "T" }; list.UpdateList(); } } public static class extension { public static void UpdateList(this List&lt;string&gt; list) { GetList(list); list.Reverse(); // DO I HAVE TO REVERSE GetList(list); // AND THEN CALL THE METHOD AGAIN } private static void GetList(List&lt;string&gt; list) { int total = list.Count; int inc = 2; for (int i = 0; i &lt; total; i++) { if (total &lt;= i + 2) break; if (total &lt;= i + inc) continue; if (list[i] == list[i + 1]) { var val = list[i]; list.RemoveAt(i); list.Insert(i + inc, val); i = i - 1; inc++; continue; } inc = 2; } } } } </code></pre> <p>As you can see, I have to call this function twice. I reverse the order and then reapply the same logic. Whilst it works, and based upon the amount of data I will be using, I don't <em>need</em> the function to be more efficient my question is still about efficiency (if worth while against the amount of work required). </p> <p>Can I update the code to not need to reverse the list to avoid calling the code twice? </p>
[ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-05-08T13:38:40.543", "Id": "86515", "Score": "6", "body": "This is an interesting problem in *unsorting*..." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-05-08T14:20:39.980", "Id": "86519", "Score": "0", "body": "It's not an unsorting problem because the list is not sorted in first place. Repeated elements may appear in any guiven position." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-05-08T14:22:38.303", "Id": "86520", "Score": "0", "body": "@BrunoCosta, Even if the original list was sorted alphabetically, the problem remains the same (and I will *guess* so does the solution)" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-05-08T14:23:39.673", "Id": "86521", "Score": "0", "body": "The problem would be the same but could be solved easier if the array was sorted. Well maybe not easier but faster for sure." } ]
[ { "body": "<p>Here's an alternate way to do it. It doesn't involve modifying and reversing the existing list. Instead, it first groups and counts the items, then yields the one that wasn't printed last time and still needs to be yielded the most times. I'm not sure about actual runtime for large lists, but as long as the number of distinct items in the list is small, the reorderings and searches should run very fast.</p>\n\n<pre><code>public static IEnumerable&lt;T&gt; WithoutDupes&lt;T&gt;(this IEnumerable&lt;T&gt; source) where T : IEquatable&lt;T&gt;\n{\n var sourceGroups = source.GroupBy(x =&gt; x).Select(x =&gt; new GroupCount&lt;T&gt;(x)).ToList();\n T last = default(T);\n bool hasLast = false;\n while (sourceGroups.Count &gt; 0)\n {\n sourceGroups = sourceGroups.OrderByDescending(x =&gt; x.Count - x.CountOutputted).ToList();\n var group = (hasLast ? sourceGroups.FirstOrDefault(x =&gt; !last.Equals(x.Value)) : null) ?? sourceGroups[0];\n\n yield return group.Value;\n group.CountOutputted++;\n if (group.CountOutputted == group.Count)\n {\n sourceGroups.Remove(group);\n }\n last = group.Value;\n hasLast = true;\n }\n}\nprivate class GroupCount&lt;T&gt;\n{\n public T Value { get; private set; }\n public int Count { get; private set; }\n public int CountOutputted { get; set; }\n public GroupCount(IGrouping&lt;T, T&gt; grouping)\n {\n this.Value = grouping.Key;\n this.Count = grouping.Count();\n }\n}\n</code></pre>\n\n<p>As example output, with your input, it produces this list (note how it handles the impossible case: puts the extra T's at the end)</p>\n\n<pre><code>T, G, T, G, T, G, T, G, T, G, T, M, T, M, T, G, T, G, T, M, T, M, T, G, T, T, T, T\n</code></pre>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-05-08T14:57:05.363", "Id": "49230", "ParentId": "49225", "Score": "10" } }, { "body": "<p>@Tim gave a great solution of his own, so I won't talk about your algorithm, but about your code:</p>\n\n<p><strong>Naming Conventions</strong><br>\nClass and namespace names in C# should be in PascalCase: </p>\n\n<pre><code>namespace Resorting\n{\n public static class Extension\n {\n ....\n }\n}\n</code></pre>\n\n<p><strong>Meaningful Names</strong><br>\nA class named <code>Extension</code> does not tell me anything about what it does. This goes twice for a method called <code>UpdateList</code>, and <code>GetList</code> is simply misleading. Give the method a name which actually explains what it does:</p>\n\n<pre><code>public static class ReorderListExtension\n{\n public static void ReorderForNoSequentialRepeats(this List&lt;string&gt; list)\n {\n }\n\n private static void ReorderForNoSequentialRepeatsIteration(this List&lt;string&gt; list)\n {\n }\n}\n</code></pre>\n\n<p>It might be longer, but it is meaningful...</p>\n\n<p><strong>Don't break the flow</strong><br>\nYour use of the <code>continue</code> keyword inside the last <code>if</code> block is easy to miss, and may confuse a code reader.<br>\nWhen all the <code>if</code> block does it <code>break;</code>, <code>continue;</code> or <code>return;</code> using these keywords is fine (this is called <a href=\"http://en.wikipedia.org/wiki/Guard_%28computer_science%29\">guard conditions</a>).<br>\nBut if the block contains a lot of code before changing the flow, the keyword is easily missed.</p>\n\n<p>Simply put the last line in </p>\n\n<pre><code>if (list[i] == list[i + 1])\n{\n var val = list[i];\n list.RemoveAt(i);\n list.Insert(i + inc, val);\n i = i - 1;\n inc++;\n} else\n{\n inc = 2;\n}\n</code></pre>\n\n<p><strong>Why not generalize?</strong><br>\nYour new API accepts <code>List&lt;string&gt;</code>, but it actually never uses the fact that the values are strings.<br>\nWhy not simply accept <code>List&lt;T&gt;</code>? It costs you nothing, and extends your code considerably...<br>\nI would even take it a step further, and change the signature to accept <code>IList&lt;T&gt;</code>.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-05-08T17:04:39.117", "Id": "49240", "ParentId": "49225", "Score": "7" } }, { "body": "<p>Another approach:</p>\n\n<pre><code>public static List&lt;T&gt; Reorder&lt;T&gt;(List&lt;T&gt; input)\n{\n var workingList = new List&lt;T&gt;(input);\n var output = new List&lt;T&gt;();\n\n while(workingList.Count() != 0)\n {\n var skipped = new List&lt;T&gt;();\n bool anyAdded = false;\n\n foreach(T item in workingList)\n {\n if(item.Equals(output.LastOrDefault()))\n {\n skipped.Add(item);\n continue;\n }\n output.Add(item);\n anyAdded = true;\n }\n if(!anyAdded)\n {\n output.AddRange(workingList);\n break;\n }\n workingList = skipped;\n }\n return output;\n}\n</code></pre>\n\n<p>Then for, e.g., input: <code>\"A\", \"A\", \"B\", \"B\", \"B\", \"A\", \"A\", \"C\", \"C\", \"B\", \"A\"</code> you get output: <code>\"A\",\"B\",\"A\",\"C\",\"B\",\"A\",\"B\",\"A\",\"C\",\"A\",\"B\"</code></p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-05-08T18:32:45.040", "Id": "49248", "ParentId": "49225", "Score": "3" } }, { "body": "<p>I turned this problem to an unsorting problem and I had so much pleasure doing so. To make that obviously you have to sort the list first. We all know that sorting takes it's time but I tried to reduce the complexity of the algorithm. If it was guaranteed that the collection was already sorted then we could discard the sorting time and thus this solution would be a clever solution (maybe). My solution assumes that there are at least three distinct values however it could be adapted to consider two or one (with probably a decreasing degree of complexity).</p>\n\n<pre><code>//find first and last index of elem\npublic static Tuple&lt;int, int&gt; BinarySearch&lt;T&gt;(List&lt;T&gt; list, T elem)where T:IComparable{\n return BinarySearch(list, elem, 0, list.Count-1);\n}\n\npublic static Tuple&lt;int, int&gt; BinarySearch&lt;T&gt;(List&lt;T&gt; list, T elem, int left, int right)where T:IComparable{\n int idxFirst = -1;\n int auxRight = right;\n int auxLeft = -1;\n while(left &lt;= right){\n int mid = left + (right - left) / 2;\n if(list[mid].CompareTo(elem) &gt; 0){\n right = mid - 1;\n }else if(list[mid].CompareTo(elem) &lt; 0){\n left = mid + 1;\n }else{\n if(list[right].CompareTo(elem) &gt; 0){\n auxRight = right+1;\n }\n right = mid - 1;\n idxFirst = mid;\n auxLeft = auxLeft &lt; 0 ? mid : auxLeft;\n }\n }\n int idxLast = BinarySearchLast(list, elem, auxLeft, auxRight);\n return Tuple.Create(idxFirst, idxLast);\n}\n\nprivate static int BinarySearchLast&lt;T&gt;(List&lt;T&gt; list, T elem, int left, int right)where T:IComparable{\n int idxLast = - 1;\n while(left &lt;= right){\n int mid = left + (right - left) / 2;\n if(list[mid].CompareTo(elem) &gt; 0){\n right = mid - 1;\n }else if(list[mid].CompareTo(elem) &lt; 0){\n left = mid + 1;\n }else{\n left = mid + 1;\n idxLast = mid;\n }\n }\n return idxLast;\n}\n//get's the 3 maximum elements\nprivate static K[] ThreeMax&lt;K, V&gt;(Dictionary&lt;K, V&gt; map)where V:IComparable{\n K[] keys = new K[3];\n Dictionary&lt;K, V&gt; aux = new Dictionary&lt;K, V&gt;(map);\n for(int i = 0; i &lt; keys.Length; ++i){\n KeyValuePair&lt;K, V&gt; pair = aux.First();\n foreach(var entry in aux){\n if(entry.Value.CompareTo(pair.Value) &gt; 0){\n pair = entry;\n }\n }\n keys[i] = pair.Key;\n aux.Remove(pair.Key);\n }\n return keys;\n}\n\npublic static IEnumerable&lt;T&gt; InterLeaveValues&lt;T&gt;(List&lt;T&gt; list)where T:IComparable{\n List&lt;T&gt; aux = new List&lt;T&gt;(list);\n aux.Sort(); //O(n) (I think it performs a quicksort)\n int idx = 0;\n //get all different values and put them on map O(number of different elements * lg n)\n Dictionary&lt;T, int&gt; map = new Dictionary&lt;T, int&gt;();\n while(idx &lt; aux.Count){\n T elem = aux[idx];\n Tuple&lt;int, int&gt; range = BinarySearch(aux, elem, idx, aux.Count-1);\n //add to set the value and number of occurrences of the value\n map.Add(elem, range.Item2 - range.Item1 + 1);\n idx = range.Item2 + 1;\n }\n int idxMax = 0;\n int[] maxs;\n T[] keysMax;\n do{\n //find the 3 elements that occurr most time O(number of different elements)\n keysMax = ThreeMax(map);\n maxs = new int[keysMax.Length];\n for(int i = 0; i &lt; keysMax.Length; ++i){\n maxs[i] = map[keysMax[i]];\n }\n int times = maxs[idxMax +1] - maxs[idxMax+2] + 1;\n //return the two elements with most occurrences interleaved\n for(int i = 0; i &lt; times; ++i){\n yield return keysMax[0];\n yield return keysMax[1];\n }\n map[keysMax[0]] -= times;\n map[keysMax[1]] -= times;\n }while(maxs[1] &gt; 0);\n for(int i = 0; i &lt; maxs[0] ; ++i){\n yield return keysMax[0];\n }\n}\n</code></pre>\n\n<p><strong>EDIT</strong> Here lies all my remaining madness. I removed the ThreeMax method. I think this is the best as it can get maybe, I'm going to measure it againinst Tim S. solution.</p>\n\n<pre><code>public class DelegatedComparer&lt;T&gt; : IComparer&lt;T&gt;\n{\n private readonly Func&lt;T, T, int&gt; compare;\n public DelegatedComparer(Func&lt;T, T, int&gt; compare)\n {\n this.compare = compare;\n } \n\n public int Compare(T x, T y)\n {\n return compare(x, y);\n }\n}\n\npublic class ItemAndCount&lt;T&gt;{\n public T Item{get;set;}\n public int Count{get;set;}\n}\n\nprivate static IEnumerable&lt;T&gt; InterleaveValues&lt;T&gt;(List&lt;ItemAndCount&lt;T&gt;&gt; distinctList)\n{\n //yield all elements until distinctList[1] .. distinctList[n] is same\n for (int nElems = 2; nElems &lt; distinctList.Count; ++nElems)\n {\n int nextCount = distinctList[nElems].Count;\n int times = distinctList[nElems - 1].Count - nextCount;\n for (int i = 0; i &lt; nElems; ++i)\n {\n distinctList[i].Count -= times;\n }\n while (times &gt; 0)\n {\n for (int i = 0; i &lt; nElems; ++i)\n {\n yield return distinctList[i].Item;\n }\n --times;\n }\n }\n\n\n if (distinctList.Count &gt;= 2)\n {\n int idxCurr = 1;\n int countFirst = distinctList[0].Count;\n int times = 0;\n while (countFirst &gt;= distinctList[idxCurr].Count)\n {\n\n //yield first interleaved with the current Element, so first occurrs more times\n yield return distinctList[0].Item;\n yield return distinctList[idxCurr].Item;\n --countFirst;\n distinctList[idxCurr].Count -= 1;\n idxCurr = (idxCurr + 1) == distinctList.Count ? 1 : (idxCurr + 1);\n ++times;\n }\n distinctList[0].Count -= times;\n for (; idxCurr &lt; distinctList.Count; ++idxCurr)\n {\n yield return distinctList[idxCurr].Item;\n }\n distinctList[distinctList.Count - 1].Count -= 1;\n }\n\n //here the list has only one element or all elements have the same amount of ocurrences\n int count = distinctList[distinctList.Count - 1].Count;\n distinctList[0].Count -= count;\n while (count &gt; 0)\n {\n for (int i = 0; i &lt; distinctList.Count; ++i)\n {\n distinctList[i].Count -= 1;\n yield return distinctList[i].Item;\n }\n --count;\n }\n\n for (int i = distinctList[0].Count; i &gt; 0; --i)\n {\n yield return distinctList[i].Item;\n }\n}\n\n\npublic static IEnumerable&lt;T&gt; InterleaveValues&lt;T&gt;(List&lt;T&gt; list)where T:IComparable{\n List&lt;T&gt; aux = new List&lt;T&gt;(list);\n aux.Sort(); //O(n) (I think it performs a quicksort)\n int idx = 0;\n //get all different values and put them on a sorted set set O(number of different elements * lg n)\n ICollection&lt;ItemAndCount&lt;T&gt;&gt; distinct = new SortedSet&lt;ItemAndCount&lt;T&gt;&gt;(new DelegatedComparer&lt;ItemAndCount&lt;T&gt;&gt;(\n //put those who occurr most in the beggining\n (t1, t2) =&gt; t2.Count - t1.Count\n ));\n while(idx &lt; aux.Count){\n T elem = aux[idx];\n Tuple&lt;int, int&gt; range = BinarySearch(aux, elem, idx, aux.Count-1);\n //add the value and number of occurrences of the value\n distinct.Add(new ItemAndCount&lt;T&gt;(){Item = elem, Count = range.Item2 - range.Item1 + 1});\n idx = range.Item2 + 1;\n }\n return InterleaveValues(distinct.ToList());\n}\n</code></pre>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-05-09T09:14:27.543", "Id": "49311", "ParentId": "49225", "Score": "2" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "4", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-05-08T13:25:08.440", "Id": "49225", "Score": "18", "Tags": [ "c#" ], "Title": "List with no sequential repeats (where possible)" }
49225
<p>I'm currently working on a Scala HTTP library, <a href="https://github.com/nrinaudo/fetch" rel="nofollow">fetch</a>, mostly because I have yet to find one that suits all my needs.</p> <p>As part of this library, I need a generic key / value store, which I intend to use both for request / response headers and URL query parameters. This store uses type classes for value parsing and formatting, which makes it both type-safe and convenient to use: ETags, for example, can be manipulated through an <code>ETag</code> class, but I do not need the key / value store to be aware that etags even exist.</p> <p>This is what I have come up with:</p> <pre><code>trait ValueReader[S, T] { def read(value: S): Try[T] } trait ValueWriter[S, T] { def write(value: S): Option[T] } class KeyValueStore[T](val values: Map[String, T] = Map()) { def apply[S](name: String)(implicit reader: ValueReader[T, S]): S = reader.read(values(name)).get def getOpt[S](name: String)(implicit reader: ValueReader[T, S]): Option[S] = for { raw &lt;- values.get(name) parsed &lt;- reader.read(raw).toOption } yield parsed def get[S](name: String)(implicit reader: ValueReader[T, S]): Option[Try[S]] = values.get(name) map reader.read def set[S](name: String, value: S)(implicit writer: ValueWriter[S, T]): KeyValueStore[T] = writer.write(value).fold(this)(set(name, _)) def set(name: String, value: T): KeyValueStore[T] = new KeyValueStore(values + (name -&gt; value)) def setIfEmpty[S](name: String, value: S)(implicit writer: ValueWriter[S, T]): KeyValueStore[T] = if(contains(name)) this else set(name, value) def remove(name: String): KeyValueStore[T] = if(contains(name)) new KeyValueStore[T](values - name) else this def contains(name: String): Boolean = values.contains(name) } </code></pre> <p>See <a href="https://github.com/nrinaudo/fetch/blob/9926e26693ff4da7150dabce44f9b8c858ac33a7/core/src/main/scala/com/nrinaudo/fetch/ValueFormat.scala" rel="nofollow">this class</a> for sample implementations of readers and writers.</p> <p>I'd be very happy for this code to be criticised and improvements to be suggested, especially in the following areas:</p> <ul> <li>variance: I will probably end up making this covariant in <code>T</code>. Is there any reason not to do so?</li> <li>I've included three "accessor" methods: <code>apply</code> (which throws), <code>getOpt</code> (safe but doesn't let the caller know what went wrong) and <code>get</code> (safe, granular, but heavier). Is there a standard pattern for this, or is what I'm doing considered acceptable / idiomatic?</li> <li>I'm pretty sure I'm not the first person to need this kind of class, are there standard methods that are expected and I'm not providing?</li> <li>what's the general consensus on "operator-like" methods, such as <code>-</code> for <code>remove</code> or <code>+</code> for add?</li> </ul>
[ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-05-28T21:03:53.197", "Id": "89892", "Score": "0", "body": "That link for your implementation class gets a 404." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-05-28T21:17:34.740", "Id": "89894", "Score": "0", "body": "Sorry, my fault, I'd failed to pin the link to a specific git commit. It might be less than useful though, as I experimented quite a bit with this design since I initially asked the question..." } ]
[ { "body": "<p>I don't see how to understand the <code>KeyValueStore</code> without understanding the <code>ValueFormat</code> implementation you reference. You don't have <strong>any</strong> substantial comments in either implementation, including \"why\". Their mutual dependency makes it very difficult to review either of them.</p>\n\n<p>Readability issues:</p>\n\n<ol>\n<li>You use <code>ValueReader[S,T]</code> in the <code>KeyValueStore</code> and <code>ValueReader[T]</code> in the <code>ValueFormat</code> -- this caused many minutes of confusion and blind paths.</li>\n<li>Similarly, you define <code>trait ValueReader[S,T]</code> and then you immediately turn around and use <code>ValueReader[T,S]</code> in the body of <code>KeyValueStore</code>. Swapping the parameters causes more confusion.</li>\n</ol>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-05-29T19:00:34.017", "Id": "52036", "ParentId": "49229", "Score": "2" } } ]
{ "AcceptedAnswerId": "52036", "CommentCount": "2", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-05-08T14:55:59.227", "Id": "49229", "Score": "4", "Tags": [ "scala" ], "Title": "Key / Value store with type classes for formatting / parsing" }
49229
<p>I'm not very good at JavaScript, so it would be great if somebody could review my jQuery Upvote plugin, and point out mistakes, bad practices, or anything suspicious.</p> <p>The repository is on <a href="https://github.com/janosgyerik/jquery-upvote">GitHub</a>. Here's a <a href="http://janosgyerik.github.io/jquery-upvote/">live demo</a>, and <a href="http://janosgyerik.github.io/jquery-upvote/tests/test1.html">qunit tests</a>, if you're interested, but I'm not asking for a review of those.</p> <p>Here's the code, with the header omitted (<a href="https://github.com/janosgyerik/jquery-upvote/blob/master/lib/jquery.upvote.js">full version here</a>):</p> <pre><code>;(function($) { "use strict"; var namespace = 'upvote'; var dot_namespace = '.' + namespace; var upvote_css = 'upvote'; var dot_upvote_css = '.' + upvote_css; var upvoted_css = 'upvote-on'; var dot_upvoted_css = '.' + upvoted_css; var downvote_css = 'downvote'; var dot_downvote_css = '.' + downvote_css; var downvoted_css = 'downvote-on'; var dot_downvoted_css = '.' + downvoted_css; var star_css = 'star'; var dot_star_css = '.' + star_css; var starred_css = 'star-on'; var dot_starred_css = '.' + starred_css; var count_css = 'count'; var dot_count_css = '.' + count_css; var enabled_css = 'upvote-enabled'; function init(options) { return this.each(function() { methods.destroy.call(this); var count = parseInt($(this).find(dot_count_css).text()); count = isNaN(count) ? 0 : count; var initial = { id: $(this).attr('data-id'), count: count, upvoted: $(this).find(dot_upvoted_css).size(), downvoted: $(this).find(dot_downvoted_css).size(), starred: $(this).find(dot_starred_css).size(), callback: function() {} }; var data = $.extend(initial, options); if (data.upvoted &amp;&amp; data.downvoted) { data.downvoted = false; } var that = $(this); that.data(namespace, data); render(that); setupUI(that); }); } function setupUI(that) { that.find(dot_upvote_css).addClass(enabled_css); that.find(dot_downvote_css).addClass(enabled_css); that.find(dot_star_css).addClass(enabled_css); that.find(dot_upvote_css).on('click.' + namespace, function() { that.upvote('upvote'); }); that.find('.downvote').on('click.' + namespace, function() { that.upvote('downvote'); }); that.find('.star').on('click.' + namespace, function() { that.upvote('star'); }); } function _click_upvote() { this.find(dot_upvote_css).click(); } function _click_downvote() { this.find(dot_downvote_css).click(); } function _click_star() { this.find(dot_star_css).click(); } function render(that) { var data = that.data(namespace); that.find(dot_count_css).text(data.count); if (data.upvoted) { that.find(dot_upvote_css).addClass(upvoted_css); that.find(dot_downvote_css).removeClass(downvoted_css); } else if (data.downvoted) { that.find(dot_upvote_css).removeClass(upvoted_css); that.find(dot_downvote_css).addClass(downvoted_css); } else { that.find(dot_upvote_css).removeClass(upvoted_css); that.find(dot_downvote_css).removeClass(downvoted_css); } if (data.starred) { that.find(dot_star_css).addClass(starred_css); } else { that.find(dot_star_css).removeClass(starred_css); } } function callback(that) { var data = that.data(namespace); data.callback(data); } function upvote() { var data = this.data(namespace); if (data.upvoted) { data.upvoted = false; --data.count; } else { data.upvoted = true; ++data.count; if (data.downvoted) { data.downvoted = false; ++data.count; } } render(this); callback(this); return this; } function downvote() { var data = this.data(namespace); if (data.downvoted) { data.downvoted = false; ++data.count; } else { data.downvoted = true; --data.count; if (data.upvoted) { data.upvoted = false; --data.count; } } render(this); callback(this); return this; } function star() { var data = this.data(namespace); data.starred = ! data.starred; render(this); callback(this); return this; } function count() { return this.data(namespace).count; } function upvoted() { return this.data(namespace).upvoted; } function downvoted() { return this.data(namespace).downvoted; } function starred() { return this.data(namespace).starred; } var methods = { init: init, count: count, upvote: upvote, upvoted: upvoted, downvote: downvote, downvoted: downvoted, starred: starred, star: star, _click_upvote: _click_upvote, _click_downvote: _click_downvote, _click_star: _click_star, destroy: destroy }; function destroy() { return $(this).each(function() { $(window).unbind(dot_namespace); $(this).removeClass(enabled_css); $(this).removeData(namespace); }); } $.fn.upvote = function(method) { if (methods[method]) { return methods[method].apply(this, Array.prototype.slice.call(arguments, 1)); } if (typeof method === 'object' || ! method) { return methods.init.apply(this, arguments); } $.error('Method ' + method + ' does not exist on jQuery.upvote'); }; })(jQuery); </code></pre> <p>I pasted the code into jshint.com, and it gives 21 warnings: "Possible strict violation", for most but not all places where I use <code>this</code>. What does that mean, and how to improve it?</p>
[]
[ { "body": "<h2>This in JSHint</h2>\n\n<p>JSHint says \"Possible strict violation\" because you are using <code>this</code> inside something that, as far as it can tell, is not a method.</p>\n\n<p>In non-strict mode, calling <code>_click_downvote(5)</code> would bind <code>this</code> to the global object (<code>window</code> in the browser). In strict mode, <code>this</code> would be <code>undefined</code>, and you would get in trouble. Binding it as a listener in jQuery would make <code>this</code> the target of the event.</p>\n\n<p>If that's how you intend to implement, you can ignore JSHint, as you will not generate any errors. But, it is telling you that your code is unclear to anyone reading it, because using <code>this</code> inside of something that is not obviously a method is quite confusing. It would be better to simply pass the object as a parameter.</p>\n\n<p>See the explanation in <a href=\"https://stackoverflow.com/questions/7688765/why-is-jshint-complaining-that-this-is-a-strict-violation/7688882#7688882\">this SO Answer</a>.</p>\n\n<p>Also your missing a <a href=\"https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/parseInt\" rel=\"nofollow noreferrer\">radix parameter</a> in parseInt in line 25 presumably you want the number in base 10, so the line should be:</p>\n\n<pre><code> var count = parseInt($(this).find(dot_count_css).text(),10);\n</code></pre>\n\n<p>It'll work fine either way, but you said <code>'use strict'</code>. :)</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-05-09T14:00:40.617", "Id": "49336", "ParentId": "49231", "Score": "6" } }, { "body": "<p>I like your code, I wish I could write code like that in languages <em>I'm not very good at</em> ;)</p>\n\n<p>The <em>Possible strict violation</em> stems from the fact that your function could easily be called without setting <code>this</code> and then <code>this</code> would point to <code>window</code> and basically you could then be setting global variables without using <code>var</code> which is a strict violation.</p>\n\n<p>You could solve this by either placing your functions within an object with Literal Notation or by provide <code>this</code> as a a parameter. I would go for Literal Notation. <a href=\"https://developer.mozilla.org/en-US/docs/Web/JavaScript/Guide/Working_with_Objects#Using_object_initializers\" rel=\"nofollow\">Some bedtime reading</a>.</p>\n\n<p>Some minor items;</p>\n\n<ul>\n<li><code>var that = $(this);</code> -> I would go for <code>var $this = $(this);</code>, <code>that</code> is usually indicating that you are going to use a closure.</li>\n</ul>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-05-09T14:07:12.997", "Id": "49337", "ParentId": "49231", "Score": "3" } }, { "body": "<p>The answers helped:</p>\n\n<ul>\n<li>I fixed the <code>parseInt</code> call to use a radix</li>\n<li>I <em>understood</em> that <code>var that = $(this);</code> is NOT a good name</li>\n<li>I <em>understood</em> that I'm using <code>this</code> incorrectly</li>\n</ul>\n\n<p>From conversations with <a href=\"https://codereview.stackexchange.com/users/9520/dagg\">@Dagg</a> I also understood that:</p>\n\n<ul>\n<li><code>$this</code> is not a good name either, as <code>this</code> itself is already unclear what it is, and sticking a <code>$</code> which effectively makes it look like a Hungarian notation for \"jQuery this\", which makes no sense at all</li>\n<li>I understood that I don't understand sqat about <code>this</code>, and what kind of values it takes on in the code above</li>\n<li>I understood that I should avoid using <code>this</code> as much as possible</li>\n</ul>\n\n<p>Although I understood many things that were wrong, the solution was still far from clear. So I dug deeper. The most important piece was really understandig what value <code>this</code> will take in the method calls where JSHint was reporting a warning. And the fix is to NOT use <code>this</code> at those places, but to pass in an object, to make it perfectly clear what the method is working with.</p>\n\n<p>As for the naming of <code>var something = $(this)</code>, I went with <code>jqdom</code>, though I realize it's not great.</p>\n\n<p>I rewrote it like this, solving all JSHint warnings:</p>\n\n<pre><code>function init(dom, options) {\n return dom.each(function() {\n var jqdom = $(this);\n methods.destroy(jqdom);\n\n var count = parseInt(jqdom.find(dot_count_css).text(), 10);\n count = isNaN(count) ? 0 : count;\n var initial = {\n id: jqdom.attr('data-id'),\n count: count,\n upvoted: jqdom.find(dot_upvoted_css).size(),\n downvoted: jqdom.find(dot_downvoted_css).size(),\n starred: jqdom.find(dot_starred_css).size(),\n callback: function() {}\n };\n\n var data = $.extend(initial, options);\n if (data.upvoted &amp;&amp; data.downvoted) {\n data.downvoted = false;\n }\n\n jqdom.data(namespace, data);\n render(jqdom);\n setupUI(jqdom);\n });\n}\n\nfunction setupUI(jqdom) {\n jqdom.find(dot_upvote_css).addClass(enabled_css);\n jqdom.find(dot_downvote_css).addClass(enabled_css);\n jqdom.find(dot_star_css).addClass(enabled_css);\n jqdom.find(dot_upvote_css).on('click.' + namespace, function() {\n jqdom.upvote('upvote');\n });\n jqdom.find('.downvote').on('click.' + namespace, function() {\n jqdom.upvote('downvote');\n });\n jqdom.find('.star').on('click.' + namespace, function() {\n jqdom.upvote('star');\n });\n}\n\nfunction _click_upvote(jqdom) {\n jqdom.find(dot_upvote_css).click();\n}\n\nfunction _click_downvote(jqdom) {\n jqdom.find(dot_downvote_css).click();\n}\n\nfunction _click_star(jqdom) {\n jqdom.find(dot_star_css).click();\n}\n\nfunction render(jqdom) {\n var data = jqdom.data(namespace);\n jqdom.find(dot_count_css).text(data.count);\n if (data.upvoted) {\n jqdom.find(dot_upvote_css).addClass(upvoted_css);\n jqdom.find(dot_downvote_css).removeClass(downvoted_css);\n } else if (data.downvoted) {\n jqdom.find(dot_upvote_css).removeClass(upvoted_css);\n jqdom.find(dot_downvote_css).addClass(downvoted_css);\n } else {\n jqdom.find(dot_upvote_css).removeClass(upvoted_css);\n jqdom.find(dot_downvote_css).removeClass(downvoted_css);\n }\n if (data.starred) {\n jqdom.find(dot_star_css).addClass(starred_css);\n } else {\n jqdom.find(dot_star_css).removeClass(starred_css);\n }\n}\n\nfunction callback(jqdom) {\n var data = jqdom.data(namespace);\n data.callback(data);\n}\n\nfunction upvote(jqdom) {\n var data = jqdom.data(namespace);\n if (data.upvoted) {\n data.upvoted = false;\n --data.count;\n } else {\n data.upvoted = true;\n ++data.count;\n if (data.downvoted) {\n data.downvoted = false;\n ++data.count;\n }\n }\n render(jqdom);\n callback(jqdom);\n return jqdom;\n}\n\nfunction downvote(jqdom) {\n var data = jqdom.data(namespace);\n if (data.downvoted) {\n data.downvoted = false;\n ++data.count;\n } else {\n data.downvoted = true;\n --data.count;\n if (data.upvoted) {\n data.upvoted = false;\n --data.count;\n }\n }\n render(jqdom);\n callback(jqdom);\n return jqdom;\n}\n\nfunction star(jqdom) {\n var data = jqdom.data(namespace);\n data.starred = ! data.starred;\n render(jqdom);\n callback(jqdom);\n return jqdom;\n}\n\nfunction count(jqdom) {\n return jqdom.data(namespace).count;\n}\n\nfunction upvoted(jqdom) {\n return jqdom.data(namespace).upvoted;\n}\n\nfunction downvoted(jqdom) {\n return jqdom.data(namespace).downvoted;\n}\n\nfunction starred(jqdom) {\n return jqdom.data(namespace).starred;\n}\n\nvar methods = {\n init: init,\n count: count,\n upvote: upvote,\n upvoted: upvoted,\n downvote: downvote,\n downvoted: downvoted,\n starred: starred,\n star: star,\n _click_upvote: _click_upvote,\n _click_downvote: _click_downvote,\n _click_star: _click_star,\n destroy: destroy\n};\n\nfunction destroy(jqdom) {\n return jqdom.each(function() {\n $(window).unbind(dot_namespace);\n $(this).removeClass(enabled_css);\n $(this).removeData(namespace);\n });\n}\n\n$.fn.upvote = function(method) { \n var args;\n if (methods[method]) {\n args = Array.prototype.slice.call(arguments, 1);\n args.unshift(this);\n return methods[method].apply(this, args);\n }\n if (typeof method === 'object' || ! method) {\n args = Array.prototype.slice.call(arguments);\n args.unshift(this);\n return methods.init.apply(this, args);\n }\n $.error('Method ' + method + ' does not exist on jQuery.upvote');\n}; \n</code></pre>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-08-10T18:44:24.060", "Id": "59642", "ParentId": "49231", "Score": "2" } } ]
{ "AcceptedAnswerId": "49336", "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-05-08T15:23:22.910", "Id": "49231", "Score": "8", "Tags": [ "javascript", "jquery", "stackexchange" ], "Title": "jQuery Upvote, a simple Stack Exchange style voting plugin" }
49231
<p>I would like to find out if my current solution to the problem described below is &quot;<em>good enough</em>&quot; or if there is an alternative way of achieving it. All I care about is the length (no. of lines) of the code and its efficiency. I am trying to follow the &quot;DRY&quot; principle and come up with something that when seen by another developer in the future will be considered a &quot;good practice&quot;.</p> <p>I am forced<sup>[1]</sup> to enter a few formulas into spreadsheet cells via <a href="/questions/tagged/vba" class="post-tag" title="show questions tagged &#39;vba&#39;" rel="tag">vba</a>. The formula is for a calculation of an inflation (say labour rate) on volume/year. It has some constants and some variants but the tricky bit is a variable inflation rate added each year. In my real life example this is far more complicated but I have shortened it and came up with an SSCCE.</p> <h1>SSCCE</h1> <p>You can view the example <a href="https://docs.google.com/spreadsheets/d/1NuDo2T2HsRSe43gOou_2tiTFfbekHdzUvQjETtecUtE/edit?usp=sharing" rel="noreferrer">as a spreadsheet on Google Docs</a>, or have a quick look through below:</p> <p><img src="https://i.stack.imgur.com/0NzZv.png" alt="enter image description here" /></p> <p>The formulas are:</p> <pre><code>D6 = -$B$12*D4*(D8+1) E6 = -$B$12*E4*(D8+1)*(E8+1) F6 = -$B$12*F4*(D8+1)*(E8+1)*(F8+1) G6 = -$B$12*G4*(D8+1)*(E8+1)*(F8+1)*(G8+1) H6 = -$B$12*H4*(D8+1)*(E8+1)*(F8+1)*(G8+1)*(H8+1) I6 = -$B$12*I4*(D8+1)*(E8+1)*(F8+1)*(G8+1)*(H8+1)*(I8+1) J6 = -$B$12*J4*(D8+1)*(E8+1)*(F8+1)*(G8+1)*(H8+1)*(I8+1)*(J8+1) K6 = -$B$12*K4*(D8+1)*(E8+1)*(F8+1)*(G8+1)*(H8+1)*(I8+1)*(J8+1)*(K8+1) L6 = -$B$12*L4*(D8+1)*(E8+1)*(F8+1)*(G8+1)*(H8+1)*(I8+1)*(J8+1)*(K8+1)*(L8+1) </code></pre> <p>I tried it but didn't like it. There are 9 really long and ugly lines (remember, in my real life example there are many more variables).</p> <pre><code>Range(&quot;D6&quot;).Formula = &quot;-$B$12*D4*(D8+1)&quot; Range(&quot;E6&quot;).Formula = &quot;-$B$12*E4*(D8+1)*(E8+1)&quot; Range(&quot;F6&quot;).Formula = &quot;-$B$12*F4*(D8+1)*(E8+1)*(F8+1)&quot; Range(&quot;G6&quot;).Formula = &quot;-$B$12*G4*(D8+1)*(E8+1)*(F8+1)*(G8+1)&quot; Range(&quot;H6&quot;).Formula = &quot;-$B$12*H4*(D8+1)*(E8+1)*(F8+1)*(G8+1)*(H8+1)&quot; Range(&quot;I6&quot;).Formula = &quot;-$B$12*I4*(D8+1)*(E8+1)*(F8+1)*(G8+1)*(H8+1)*(I8+1)&quot; Range(&quot;J6&quot;).Formula = &quot;-$B$12*J4*(D8+1)*(E8+1)*(F8+1)*(G8+1)*(H8+1)*(I8+1)*(J8+1)&quot; Range(&quot;K6&quot;).Formula = &quot;-$B$12*K4*(D8+1)*(E8+1)*(F8+1)*(G8+1)*(H8+1)*(I8+1)*(J8+1)*(K8+1)&quot; Range(&quot;L6&quot;).Formula = &quot;-$B$12*L4*(D8+1)*(E8+1)*(F8+1)*(G8+1)*(H8+1)*(I8+1)*(J8+1)*(K8+1)*(L8+1)&quot; </code></pre> <p>Or <code>Cells</code>:</p> <pre><code>Cells(6, 4).Formula = &quot;-$B$12*D4*(D8+1)&quot; Cells(6, 5).Formula = &quot;-$B$12*E4*(D8+1)*(E8+1)&quot; Cells(6, 6).Formula = &quot;-$B$12*F4*(D8+1)*(E8+1)*(F8+1)&quot; Cells(6, 7).Formula = &quot;-$B$12*G4*(D8+1)*(E8+1)*(F8+1)*(G8+1)&quot; Cells(6, 8).Formula = &quot;-$B$12*H4*(D8+1)*(E8+1)*(F8+1)*(G8+1)*(H8+1)&quot; Cells(6, 9).Formula = &quot;-$B$12*I4*(D8+1)*(E8+1)*(F8+1)*(G8+1)*(H8+1)*(I8+1)&quot; Cells(6, 10).Formula = &quot;-$B$12*J4*(D8+1)*(E8+1)*(F8+1)*(G8+1)*(H8+1)*(I8+1)*(J8+1)&quot; Cells(6, 11).Formula = &quot;-$B$12*K4*(D8+1)*(E8+1)*(F8+1)*(G8+1)*(H8+1)*(I8+1)*(J8+1)*(K8+1)&quot; Cells(6, 12).Formula = &quot;-$B$12*L4*(D8+1)*(E8+1)*(F8+1)*(G8+1)*(H8+1)*(I8+1)*(J8+1)*(K8+1)*(L8+1)&quot; </code></pre> <p>But try to play with the right hand side of the statement. I see so much potential** in terms of optimising it, but the best I could have come up with in <a href="/questions/tagged/vba" class="post-tag" title="show questions tagged &#39;vba&#39;" rel="tag">vba</a> is:</p> <pre><code>Sub Main() Dim i As Long Dim s As String For i = 4 To 12 s = s + &quot;*(&quot; + Cells(8, i).Address + &quot;+1)&quot; Cells(6, i).Formula = &quot;=-$B$12*&quot; + Cells(4, i).Address + s Next i End Sub </code></pre> <p>I realize that I am concatenating <code>String</code>s to achieve my goal. The code is working fine in this SSCCE and in my real life problem. It's not slow but I am purely curious if there is any other approach or if my current one can be optimized any further.</p> <h1>Questions</h1> <ol> <li>Can this be optimized any further?</li> <li>Would you do this differently? If so, how? Why would your solution be any better than my current one?</li> </ol> <hr> <p><sup>[1]</sup> Forced because the real life example pulls its values from multiple places like another closed workbook, database, website, user input etc. For example, <code>INDIRECT()</code> does not work with closed workbooks so I can't rely on pure built-in functions.</p>
[]
[ { "body": "<p>Since you need to multiply by another interest rate every year, why not precalculate this interest rate using a temp variable? You precalculate the interest in row 10 and then refer to the relevant field in the calculation column.</p>\n\n<p>It might also be worth to check out the default Excel formulas involving financial calculations: <a href=\"http://office.microsoft.com/en-001/excel-help/financial-functions-reference-HP010342519.aspx\" rel=\"nofollow\">http://office.microsoft.com/en-001/excel-help/financial-functions-reference-HP010342519.aspx</a></p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-05-12T11:30:30.273", "Id": "87084", "Score": "1", "body": "I am sorry but this is a very generalized answer. I am doing this for a financial/commercial team and because of its complexity I can't use any/many built-in functions -> btw. name one function that I could use here....I am not sure what you mean by using a `temp variable`, precalculate interest in row 10 and refer to the relevant field? Can you demonstrate that somehow because those 2 sentences do not make a lot of sense to me. Why would this approach be any better than current one and how would it reduce/optimize code? Thanks" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-05-12T13:18:28.330", "Id": "87103", "Score": "0", "body": "about the temp variable: in D10, write =(D8+1). in E10, write =(D8+1)*(E8+1). repeat this for all other cells. then you can just write in D6 = $B%12*D4*D10 and copy this code to the entire 6th row. Those Excel formulas are a set of formulas to calculate, among other things, compound interest, monthly payments (both capital and interest), interest rates and eventual payments. There might be a formula that's suitable for calculating those separate numbers based on the acumulated inflation." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-05-12T13:32:47.780", "Id": "87104", "Score": "1", "body": "thanks I get it now but I am sorry can't see how this is any more optimized in terms of VBA? It would require more code than I currently have and another temp variable..maybe I am still missing something here so do you want to demo a sample?" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-05-12T13:43:16.970", "Id": "87110", "Score": "0", "body": "My remark was meant to imply that you don't exactly require VBA to generate this, at least in this situation. I don't know how your complete situation is with the entire spreadsheet and how much more complicated it is, so it's entirely possible that the complete setup would not be feasible without VBA." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-05-12T13:44:15.260", "Id": "87111", "Score": "0", "body": "I thought I was clear in the first sentence of the second paragraph in my original post. Thanks for your effort. I can't use pure formulas because the components/elements which build it come from all around the house, ( some come from another excel file, some from a DB, some from an email etc, like indirect() doesn't work with closed excel files etc it just comes down to efficiency now). Hope it's clear now" } ], "meta_data": { "CommentCount": "5", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-05-12T11:07:04.590", "Id": "49509", "ParentId": "49235", "Score": "2" } }, { "body": "<p>Here is what I would do if I were you:</p>\n\n<pre><code>Sub Main()\n Dim b12_value As Double\n Dim inflation As Double\n\n 'Seed the inflation variable and store the static B12 value\n inflation = 1\n b12_value = Range(\"$B$12\").value\n\n 'Loop through each cell in D6:L6 and calculate its value.\n For Each cell In Range(\"D6:L6\")\n inflation = inflation * (Cells(8, cell.Column).Value + 1)\n cell.Value = -b12_value * Cells(4, cell.Column).Value * inflation\n Next\n\nEnd Sub\n</code></pre>\n\n<p>Since you are concerned about number of lines, I chose not to store the volume for each calulation in its own variable (which I would prefer to do as it makes for more readable code).</p>\n\n<p>The solution is only 1 line longer than your original solution and it does not rely on string concatenation (which is slow). It also simply does the formula work itself instead of setting the cell's value instead of setting the formula then having Excel calculate the value from said formula.</p>\n\n<p><strong>NOTE:</strong> If you wanted the formula visible in Excel (instead of just its value), I would think your original solution (with a couple tweaks) is sufficient for you needs:</p>\n\n<pre><code>Sub Main()\n 'Use a more descriptive variable name than \"s\". Descriptive names improve\n 'readability and better facilitates user understanding.\n Dim inflation_string as String\n\n 'Using the for each syntax creates more readable code. Plus, as a bonus,\n 'it removed the use of the index variable i. \n For Each cell In Range(\"D6:L6\")\n inflation_string = inflation_string + \"*(\" + Cells(8, cell.Column).Address + \"+1)\"\n cell.Formula = \"=-$B$12*\" + Cells(4, cell.Column).Address + inflation_string\n Next\n\nEnd Sub\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-05-12T15:10:27.467", "Id": "87137", "Score": "1", "body": "ya man that's what I am talking about ( the `s` is used just in this example but it's worth mentioning for any future readers definitely), I like the for each syntax and actually haven't realized that Range(\"\") also has a hidden _NewEnum so for each is more efficient in this case. Just trying to adopt your tips to my real life example so far so good so thanks a lot for your input. I can't award the bounty for another 17 hours but I will do tomorrow." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-05-12T16:38:09.830", "Id": "87147", "Score": "0", "body": "Glad I could help! :D" } ], "meta_data": { "CommentCount": "2", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-05-12T14:33:42.793", "Id": "49534", "ParentId": "49235", "Score": "8" } } ]
{ "AcceptedAnswerId": "49534", "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-05-08T16:26:57.727", "Id": "49235", "Score": "12", "Tags": [ "performance", "algorithm", "vba", "excel", "finance" ], "Title": "Calculation of an inflation on volume/year" }
49235
<p>I am working with currencies, and so have been using the decimal module to rule out any floating point weirdness in the following maths.</p> <p>I have to add together a number of decimal amounts, find an average of them, add ten percent, and then round it to the nearest round £. I then need to do more decimal maths with the output, so it'll need to be a decimal (or an integer) so I can play with it. Adding the decimals has been fairly straightforward, but doing the rest of the maths has left me with this line:</p> <pre><code>result = decimal.Decimal(round((sum_of_items / count_of_items) * decimal.Decimal(1.1), 0)) </code></pre> <p>It strikes me that this isn't particularly elegant, as I'm converting the decimal average+10% to a float just to round it off, and then turning the result back into a decimal.</p> <p>Am I risking any floating point weirdness with that brief conversion back to floating point? And is there any way to achieve the same effect as round using the decimal module so I don't have to go decimal->float->decimal?</p>
[ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-05-08T22:00:27.747", "Id": "86637", "Score": "1", "body": "Don't use `decimal.Decimal(1.1)`. Always initialize decimal constants with strings, to avoid rounding error: `decimal.Decimal('1.1')`" } ]
[ { "body": "<p>I was actually unaware of the decimal module -- I've +1 your question just for that. </p>\n\n<p>Taking a quick look at the <a href=\"https://docs.python.org/2/library/decimal.html\" rel=\"nofollow\">docs</a>, Decimal is specifically designed to avoid artifacts of binary floats and work like \"people\" math. Because of that I would be suspicious of the conversion to float, no matter how brief. Can you use the <code>quantize()</code> function instead of <code>round()</code>? The quantize method \"rounds a number to a fixed exponent. This method is useful for monetary applications that often round results to a fixed number of places\" and sounds well suited to your application. </p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-05-08T17:03:41.197", "Id": "49238", "ParentId": "49236", "Score": "4" } }, { "body": "<p>I thin you should rely more on the Decimal object to do the right thing; rather than rounding, set your precision with, for instance:\n<code>getcontext().prec=6</code> and then just do <code>Decimal(sum_of_items) / Decimal(count_of_items) * Decimal(1.1)</code></p>\n\n<p>Alternately, just do all your multiplies before you do your divides, to keep the most precision.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-05-08T17:04:10.287", "Id": "49239", "ParentId": "49236", "Score": "1" } } ]
{ "AcceptedAnswerId": "49238", "CommentCount": "1", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-05-08T16:33:03.370", "Id": "49236", "Score": "6", "Tags": [ "python", "python-2.x" ], "Title": "More elegant way to round decimals in Python?" }
49236
<p>The following piece of code will act as a single access to all social networks. It aims to connect different social networks to get a broader picture of the social life of a user. I have just committed the code for Twitter access, but similar access will be provided to Facebook and Github.</p> <p>The code is available <a href="https://github.com/P-Raj/SocNet" rel="nofollow">here</a>.</p> <p>I'd appreciate any and all comments-- correctness, style, best practices, logging, error handling.</p> <pre><code>import tweepy import TwitterConfig as config_twitter class Twitter : def __init__(self): self.CONSUMER_KEY = config_twitter.get_consumer_key() self.CONSUMER_SECRET = config_twitter.get_consumer_secret() self.oauth_token = None self.oauth_verifier = None self.api = None def get_auth_url(self): self.auth = tweepy.OAuthHandler(self.CONSUMER_KEY, self.CONSUMER_SECRET) return self.auth.get_authorization_url() def get_request_token(self): return (self.auth.request_token.key,self.auth.request_token.secret) def set_token(self,token): self.oauth_token = token def set_verifier(self,verifier): self.oauth_verifier = verifier def set_request_token (self,ReqToken): self.request_token = ReqToken def get_access_token (self): self.auth = tweepy.OAuthHandler(self.CONSUMER_KEY, self.CONSUMER_SECRET) token = self.request_token #session.delete('request_token') self.auth.set_request_token(token[0],token[1]) self.auth.get_access_token(self.oauth_verifier) def authorize (self): key = self.auth.access_token.key secret = self.auth.access_token.secret self.auth = tweepy.OAuthHandler(self.CONSUMER_KEY, self.CONSUMER_SECRET) self.auth.set_access_token(key, secret) self.api = tweepy.API(self.auth) def update_status(self,status): if self.oauth_token == None or self.oauth_verifier == None or self.api == None : return "Verification Problem" self.api.update_status (status) return "Done" def user_information (self): # returns information of the authenticate user if self.oauth_token == None or self.oauth_verifier == None or self.api == None : return "Verification Problem" return self.api.me() def get_friends (self): if self.oauth_token == None or self.oauth_verifier == None or self.api == None : return ["Verification Problem"] return self.api.GetFriends(self.user_information().name) def get_followers (self): if self.oauth_token == None or self.oauth_verifier == None or self.api == None : return ["Verification Problem"] return self.api.GetFollowers() def get_followers_id (self): if self.oauth_token == None or self.oauth_verifier == None or self.api == None : return "Verification Problem" return self.api.followers_ids() def get_friends_ids (self): # returns ids of the friends if self.oauth_token == None or self.oauth_verifier == None or self.api == None : return "Verification Problem" return self.api.friends_ids() def get_rate_limit_status (self): #returns the rate limit status of the authenticated user return self.api.rate_limit_status() def get_tweets(self): if self.oauth_token == None or self.oauth_verifier == None or self.api == None : return ["Verification Problem"] me = self.user_information() statuses = self.api.GetUseerTimeline(me.name) return statuses def get_messages(self): if self.oauth_token == None or self.oauth_verifier == None or self.api == None : return ["Verification Problem"] return self.api.GetDirectMessages() </code></pre>
[]
[ { "body": "<p>You are inconsistent in naming. Some of your methods are in camelCase and some are in under_score format. Pick one.</p>\n\n<p>Where is the consistent API for the various social networks?? From your write up I expect to be able to write something like the following:</p>\n\n<pre><code>my_friends = []\nfor soc in my_social_networks:\n my_friends.append(soc.get_friends())\nshow(my_friends)\n</code></pre>\n\n<p>or:</p>\n\n<pre><code>my_messages = []\nfor soc in my_social_networks:\n my_messages.append(soc.get_current_messages())\nshow(my_messages)\n</code></pre>\n\n<p>Instead I see <code>get_tweets</code> or <code>get_wall</code>. That means I have to pay attention to whether I have a Twitter object or a Facebook object. So all of my code needs to have a long if/else for each new type of social network I want to support in my program.</p>\n\n<p>Double underscores are not meant for code outside of Python. Use a single underscore.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-05-12T23:34:03.130", "Id": "49581", "ParentId": "49241", "Score": "1" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-05-08T17:17:38.440", "Id": "49241", "Score": "1", "Tags": [ "python" ], "Title": "Module for providing users easy access to all social networking websites" }
49241
<p>This works, but it's huge.</p> <p>We need to repeat each table column on each <code>UNION SELECT</code>, as well as the <code>WHERE</code> clause for <code>DATE</code> comparison.</p> <pre><code>( SELECT GROUP_CONCAT(APA_T.district), t.name FROM tbl_activity AS t INNER JOIN tbl_activity_package AS ap ON t.id = ap.activity_id INNER JOIN ( SELECT DISTINCT apa.district AS district, ( SELECT s1.activity_package_id FROM tbl_activity_package_address s1 WHERE apa.district = s1.district ORDER BY s1.id DESC LIMIT 1 ) AS idActivityPackage FROM tbl_activity_package_address apa ORDER BY apa.district ) AS APA_T ON ap.id = APA_T.idActivityPackage WHERE (ap.publication_date &lt;= CURDATE()) AND (DATE_ADD(ap.publication_date, INTERVAL ap.publication_duration_in_days DAY) &gt;= CURDATE()) GROUP BY t.name ORDER BY APA_T.district ) UNION DISTINCT ( SELECT GROUP_CONCAT(DISTINCT apa2.district ORDER BY apa2.district), t2.name FROM tbl_activity AS t2 INNER JOIN tbl_activity_package AS ap2 ON t2.id = ap2.activity_id INNER JOIN tbl_activity_package_address AS apa2 ON ap2.id = apa2.activity_package_id WHERE (ap2.publication_date &lt;= CURDATE()) AND (DATE_ADD(ap2.publication_date, INTERVAL ap2.publication_duration_in_days DAY) &gt;= CURDATE()) GROUP BY t2.name ORDER BY apa2.district ) LIMIT 6, 6 </code></pre> <p>I have removed the WHERE CLAUSE for DATE comparisons, because I can't have it on this fiddle structure, but, the repetition is still an issue. I've been told about INTERSECT but found nothing about that on MySQL.</p> <p><a href="http://sqlfiddle.com/#!2/37dd94/51" rel="nofollow">http://sqlfiddle.com/#!2/37dd94/51</a></p>
[]
[ { "body": "<p>The nesting is incomprehensible without indentation. For your benefit and for the benefit of anyone attempting to review this code, I've reformatted the code, changing nothing but whitespace.</p>\n\n<pre><code>(\n SELECT GROUP_CONCAT(APA_T.district), t.name\n FROM tbl_activity AS t\n INNER JOIN tbl_activity_package AS ap\n ON t.id = ap.activity_id\n INNER JOIN (\n SELECT DISTINCT apa.district AS district,\n (SELECT s1.activity_package_id\n FROM tbl_activity_package_address s1\n WHERE apa.district = s1.district\n ORDER BY s1.id DESC\n LIMIT 1\n ) AS idActivityPackage\n FROM tbl_activity_package_address apa \n ORDER BY apa.district\n ) AS APA_T\n ON ap.id = APA_T.idActivityPackage\n WHERE (ap.publication_date &lt;= CURDATE())\n AND (DATE_ADD(ap.publication_date, INTERVAL ap.publication_duration_in_days DAY) &gt;= CURDATE())\n GROUP BY t.name\n ORDER BY APA_T.district\n)\nUNION DISTINCT\n(\n SELECT GROUP_CONCAT(DISTINCT apa2.district ORDER BY apa2.district), t2.name\n FROM tbl_activity AS t2\n INNER JOIN tbl_activity_package AS ap2\n ON t2.id = ap2.activity_id\n INNER JOIN tbl_activity_package_address AS apa2\n ON ap2.id = apa2.activity_package_id\n WHERE (ap2.publication_date &lt;= CURDATE())\n AND (DATE_ADD(ap2.publication_date, INTERVAL ap2.publication_duration_in_days DAY) &gt;= CURDATE())\n GROUP BY t2.name\n ORDER BY apa2.district\n)\nLIMIT 6, 6\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-05-08T18:50:01.030", "Id": "86588", "Score": "0", "body": "I have edit my question with your indentation work. Thanks." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-05-08T18:51:59.963", "Id": "86590", "Score": "0", "body": "Edit rolled back. [Code in a question must be preserved](http://meta.codereview.stackexchange.com/a/1816/9357), so as not to invalidate answers." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-05-08T18:53:45.447", "Id": "86592", "Score": "0", "body": "It was preserved. Changing spaces will do nothing, but clarification. :) You suggest a edit, and I've done it. :) No? I believe your answer serves more an edit to the OP question. But that's my 2 cents. :) No issues either way." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-05-08T18:55:52.510", "Id": "86595", "Score": "0", "body": "No. As mentioned in the meta post that I linked to, all facets of the code are subject to review, _including whitespace_." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-05-08T18:59:45.307", "Id": "86597", "Score": "1", "body": "I understand. Even if, the answer doesn't answer all, it answers some parts of it, by reviewing some parts of the code. It makes sense on a \"code review\" stackexchange. :)" } ], "meta_data": { "CommentCount": "5", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-05-08T18:38:20.273", "Id": "49249", "ParentId": "49243", "Score": "2" } }, { "body": "<p>Your SQL Fiddle and the question have inconsistent column names: the fiddle has <code>id_activity_package</code>, while the code in this question has <code>activity_package_id</code>. I'll consider the fiddle as supplementary information, and treat the code in the question as authoritative.</p>\n\n<hr>\n\n<p>The two halves of the <code>UNION</code> are nearly identical, with the exception of the second <code>INNER JOIN</code>. Let's analyze it one step at a time.</p>\n\n<ol>\n<li><p>In the first half of the <code>UNION</code>, you join with <code>APA_T</code>, which is…</p>\n\n<pre><code>SELECT DISTINCT apa.district AS district,\n (SELECT s1.activity_package_id\n FROM tbl_activity_package_address s1\n WHERE apa.district = s1.district\n ORDER BY s1.id DESC\n LIMIT 1\n ) AS idActivityPackage\n FROM tbl_activity_package_address apa \n ORDER BY apa.district\n</code></pre>\n\n<p>The <code>DISTINCT</code> there is superfluous, since the innermost <code>SELECT</code> is guaranteed to return at most one row per <code>district</code>.</p>\n\n<p>As I read it, <code>APA_T</code> is a subquery that lists the most recently added <code>activity_package_id</code> for each <code>district</code>. I think it's worth creating a view for clarity.</p>\n\n<pre><code>CREATE VIEW latest_activity_package_address AS\nSELECT *\n FROM tbl_activity_package_address\n WHERE id IN (\n SELECT MAX(id)\n FROM tbl_activity_package_address AS latest_apa\n GROUP BY district\n );\n</code></pre>\n\n<p>Then, the first half of the <code>UNION</code> becomes:</p>\n\n<pre><code>SELECT GROUP_CONCAT(district ORDER BY district), t.name\n FROM tbl_activity AS t\n INNER JOIN tbl_activity_package AS ap\n ON t.id = ap.activity_id\n INNER JOIN latest_activity_package_address AS apa\n ON ap.id = apa.activity_package_id\n WHERE (ap.publication_date &lt;= CURDATE())\n AND (DATE_ADD(ap.publication_date, INTERVAL ap.publication_duration_in_days DAY) &gt;= CURDATE())\n GROUP BY t.name\n ORDER BY apa.district\n</code></pre>\n\n<p>I've copied the <code>ORDER BY</code> clause into the <code>GROUP_CONCAT()</code>, where I think it belongs.</p></li>\n<li><p>Next, I'd like to point out that <code>LIMIT 6,6</code> will produce non-deterministic results, since there is no <code>ORDER BY</code> clause on the <code>UNION</code> query. You've put an <code>ORDER BY</code> on each half of the <code>UNION</code>, but <a href=\"https://stackoverflow.com/a/3473427/1157100\">that doesn't guarantee that the result will be ordered the same way</a>.</p></li>\n<li><p>Surprisingly, I haven't found a way to reduce duplication between the two halves of the <code>UNION</code>. However, there is now a nice parallelism which may be more aesthetically pleasing. You don't need to select new table aliases for the second half; they aren't in the same scope as the first half.</p>\n\n<pre><code>SELECT GROUP_CONCAT(district ORDER BY district), t.name\n FROM tbl_activity AS t\n INNER JOIN tbl_activity_package AS ap\n ON t.id = ap.activity_id\n INNER JOIN latest_activity_package_address AS apa\n ON ap.id = apa.activity_package_id\n WHERE (ap.publication_date &lt;= CURDATE())\n AND (DATE_ADD(ap.publication_date, INTERVAL ap.publication_duration_in_days DAY) &gt;= CURDATE())\n GROUP BY t.name\n ORDER BY apa.district\nUNION DISTINCT\nSELECT GROUP_CONCAT(district ORDER BY district), t.name\n FROM tbl_activity AS t\n INNER JOIN tbl_activity_package AS ap\n ON t.id = ap.activity_id\n INNER JOIN tbl_activity_package_address AS apa\n ON ap.id = apa.activity_package_id\n WHERE (ap.publication_date &lt;= CURDATE())\n AND (DATE_ADD(ap.publication_date, INTERVAL ap.publication_duration_in_days DAY) &gt;= CURDATE())\n GROUP BY t.name\n ORDER BY apa.district\n</code></pre></li>\n</ol>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-05-10T21:53:53.353", "Id": "86911", "Score": "1", "body": "Thanks a lot for taking your time analysing the code. Please allow me some time to study." } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-05-08T21:51:48.477", "Id": "49272", "ParentId": "49243", "Score": "4" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-05-08T17:36:59.143", "Id": "49243", "Score": "5", "Tags": [ "mysql", "sql" ], "Title": "Long SQL query with much duplication between two halves of a UNION" }
49243
<p>I have developed a few web applications according to my own coding style similar to MVC architecture. I'm a self learner. But there is no controller class or model class. In my way, I don't split the URL. I have mentioned below an example URL. Now I'm familiar with this process, but I know this is not a professional level coding, so I tried to move to MVC. Now I can easily manage any javascript, ajax call. I don't know how to use JavaScript and Ajax in MVC. </p> <p>Basically my question is: Shall I continue in this way?</p> <p>My project file structure.</p> <p>Below example based on <a href="http://www.www.mysite.com/index.php?view=user/index&amp;uid=234" rel="nofollow">this URL</a></p> <pre><code>/root -/images -/include ---database.php ---user.php ---course.php -/layout ---/user ---/course ---index.php -index.php -config.php </code></pre> <p><strong>Cofig.php</strong></p> <pre><code>require("include/database.php"); require("include/user.php"); require("include/course.php"); $db = Database::getInstance(); $user = new user(); $course = new course(); </code></pre> <p><strong>index.php</strong></p> <pre><code>&lt;?php include('config.php'); //get view page using url $view_page = isset($_GET['view']) ? $_GET['view']: 'home'; ?&gt; &lt;html&gt; &lt;body&gt; &lt;div id='header'&gt;&lt;/div&gt; &lt;div id='content'&gt; &lt;?php include('layout/index.php'); ?&gt; &lt;/div&gt; &lt;/body&gt; &lt;/html&gt; </code></pre> <p><strong>layout/index.php</strong></p> <pre><code>&lt;?php include($_SERVER['DOCUMENT_ROOT'].'/layout/'.$view_page.'.php'); ?&gt; </code></pre> <p><strong>layout/user/index.php</strong></p> <pre><code>//this page will be displayed : www.mysite.com/index.php?view=user/index&amp;uid=234 // user/index = (folder/page) or (view/action) // these details will be dispalyed with &lt;div id='content'&gt;&lt;/div&gt; &lt;?php $userDetails = $user-&gt;getUserDetails($_GET['uid']); echo $userDetails['username']; echo $userDetails['email']; ?&gt; </code></pre>
[ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-05-08T19:02:57.213", "Id": "86599", "Score": "0", "body": "Regarding the last (removed) note: even if you get downvoted (which I doubt), you won't be blocked from asking questions as that system is not enabled on this site." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-05-27T12:40:15.410", "Id": "89606", "Score": "0", "body": "I can't see how this is MVC. Please have a look at [this user's](http://stackoverflow.com/users/727208/teresko) top answers on [so]." } ]
[ { "body": "<h2>Code Review:</h2>\n\n<ul>\n<li><strong>Naming Convention</strong>: <code>$variableNames</code> and <code>functionNames()</code> should be in camelCase, <code>ClassNames</code> should be in CamelCaps. Keep this convention to make your code more readable!</li>\n<li><strong>Use an autoloader</strong>: To stop you from being worried about loading classes, use an autoloader. See <strong><a href=\"http://il1.php.net/manual/en/function.spl-autoload-register.php\" rel=\"nofollow\"><code>spl_autoload_register()</code></a></strong> for registering an autoloading function.</li>\n<li><strong>Don't use Singletons</strong>: Do <strong><em>not</em></strong> use Singletons. Singletons are global, they introduce hidden dependencies to your code and make it unpredictable and untestable.</li>\n<li><p><strong>No explicit dependncies in sight</strong>: What does your <code>user</code> object need in order to work? I'm guessing a database connection, maybe even a user_id? Why are you not passing those to the <code>user</code>'s constructor?</p>\n\n<pre><code>$user = new User($db, $_SESSION[\"user_id\"]); // For example\n</code></pre></li>\n</ul>\n\n<h2>How to improve</h2>\n\n<p>This code, contrary to popular belief, is <strong>not MVC</strong>. MVC stems from good OOP practices, and the separation of concerns. The idea is to separate your application into three major <strong>layers</strong>:</p>\n\n<ul>\n<li>The <strong>Input</strong>: The Controller layer.</li>\n<li>The <strong>Output</strong>: The View layer.</li>\n<li>The <strong>Processing and Logic</strong>: The Model layer.</li>\n</ul>\n\n<p>Where each has its own job and responsibilities, its own set of objects, and its own role in the application.</p>\n\n<p>I propose you start with learning about OOP, avoid PHP frameworks, and once you grasp OOP, start looking at MVC.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-06-10T07:39:07.080", "Id": "53861", "ParentId": "49250", "Score": "2" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "2", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-05-08T18:51:54.027", "Id": "49250", "Score": "3", "Tags": [ "php", "design-patterns", "mvc" ], "Title": "MVC architecture in PHP" }
49250
<p>Morris Inorder traversal - an algorithm for in-order traversal, of a tree, without recursion of extra memory. Looking for code review, optimizations and best practices.</p> <pre><code>public class MorrisInOrder&lt;T&gt; { TreeNode&lt;T&gt; root; /** * Takes in a BFS representation of a tree, and converts it into a tree. * here the left and right children of nodes are the (2*i + 1) and (2*i + 2)nd * positions respectively. * * @param items The items to be node values. */ public MorrisInOrder(List&lt;? extends T&gt; items) { create(items); } private void create (List&lt;? extends T&gt; items) { root = new TreeNode&lt;T&gt;(null, items.get(0), null); final Queue&lt;TreeNode&lt;T&gt;&gt; queue = new LinkedList&lt;TreeNode&lt;T&gt;&gt;(); queue.add(root); final int half = items.size() / 2; for (int i = 0; i &lt; half; i++) { if (items.get(i) != null) { final TreeNode&lt;T&gt; current = queue.poll(); final int left = 2 * i + 1; final int right = 2 * i + 2; if (items.get(left) != null) { current.left = new TreeNode&lt;T&gt;(null, items.get(left), null); queue.add(current.left); } if (right &lt; items.size() &amp;&amp; items.get(right) != null) { current.right = new TreeNode&lt;T&gt;(null, items.get(right), null); queue.add(current.right); } } } } private static class TreeNode&lt;T&gt; { TreeNode&lt;T&gt; left; T item; TreeNode&lt;T&gt; right; TreeNode(TreeNode&lt;T&gt; left, T item, TreeNode&lt;T&gt; right) { this.left = left; this.item = item; this.right = right; } } /** * Returns the inorder traversal of the tree. * * @return list containing inorder traversal of elements * @throws NoSuchAlgorithmException */ public List&lt;T&gt; inOrder() throws NoSuchAlgorithmException { if (root == null) throw new NoSuchAlgorithmException("The root is null."); final List&lt;T&gt; list = new ArrayList&lt;T&gt;(); TreeNode&lt;T&gt; current = root; while (current != null) { if (current.left == null) { list.add(current.item); current = current.right; } else { TreeNode&lt;T&gt; predecessor = current.left; /* * found the in-order predecessor. */ while (predecessor.right != null &amp;&amp; predecessor.right != current) { predecessor = predecessor.right; } if (predecessor.right == null) { // hook it up. predecessor.right = current; current = current.left; } else { list.add(current.item); predecessor.right = null; current = current.right; } } } return list; } } public class MorrisInOrderTest { @Test public void testBalancedTree() throws NoSuchAlgorithmException { final MorrisInOrder&lt;Integer&gt; morrisInOrder1 = new MorrisInOrder&lt;Integer&gt;(Arrays.asList(1, 2, 3, 4, 5, 6, 7)); assertEquals(Arrays.asList(4, 2, 5, 1, 6, 3, 7), morrisInOrder1.inOrder()); } @Test public void testUnBalancedTree() throws NoSuchAlgorithmException { final MorrisInOrder&lt;Integer&gt; morrisInOrder2 = new MorrisInOrder&lt;Integer&gt;(Arrays.asList(1, 2, 3, 4, 5, null, null)); assertEquals(Arrays.asList(4, 2, 5, 1, 3), morrisInOrder2.inOrder()); } } </code></pre>
[]
[ { "body": "<pre><code>private void create (List&lt;? extends T&gt; items) {\n root = new TreeNode&lt;T&gt;(null, items.get(0), null);\n</code></pre>\n\n<p>This crashes if an empty list is passed in. And since you have this function...</p>\n\n<pre><code>public MorrisInOrder(List&lt;? extends T&gt; items) {\n create(items);\n}\n</code></pre>\n\n<p>It's entirely possible for such a thing to happen.</p>\n\n<hr>\n\n<pre><code>final int left = 2 * i + 1;\nfinal int right = 2 * i + 2;\n</code></pre>\n\n<p><code>right</code> can be set to <code>left + 1</code> instead.</p>\n\n<hr>\n\n<pre><code>current = current.right;\n</code></pre>\n\n<p>and </p>\n\n<pre><code>TreeNode&lt;T&gt; current = root;\n</code></pre>\n\n<p>There's an extra space in here.</p>\n\n<hr>\n\n<pre><code> /*\n * found the in-order predecessor.\n */\n while (predecessor.right != null &amp;&amp; predecessor.right != current) {\n predecessor = predecessor.right;\n }\n</code></pre>\n\n<p>You're using a block-style comment for single line comment. Why?</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-08-08T07:48:37.980", "Id": "59482", "ParentId": "49252", "Score": "3" } }, { "body": "<p>In addition to Pimgd's remarks I want to throw in:</p>\n<h3>Program against high Interfaces, not low ones:</h3>\n<p>Currently your methods all take a <code>List&lt;? extends T&gt;</code>. That in itself is quite nice already. Now a traversal of existing elements does not necessarily have to be done on an ordered Collection only.</p>\n<p>I suggest you explore the possiblities of passing int <code>Collection&lt;? extends T&gt;</code> or even higher: <code>Iterable&lt;? extends T&gt;</code></p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-08-08T08:26:00.950", "Id": "59485", "ParentId": "49252", "Score": "2" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-05-08T19:11:04.653", "Id": "49252", "Score": "4", "Tags": [ "java", "algorithm", "tree" ], "Title": "Morris inorder traversal" }
49252
<p>In a large project of mine, I've run into a situation where a client might need to run evaluated JavaScript code. I know, it makes me cringe too. One option is to manually parse it, but for future flexibility, I would like to evaluate the code safely.</p> <p>Everything I've seen and researched says, NO. Ah, the nay-sayers.</p> <p>This is my attempt to sandbox the eval:</p> <p><a href="http://jsfiddle.net/senica/Pd6Nu/">jsFiddle</a></p> <p>Can you shoot holes in it and try and break it? I should wrap it in a try so it doesn't throw ugly errors, but beyond that, tell me where I have gone awry.</p> <pre><code>/*************************************** * Senica Gonzalez (senica@gmail.com) * This is an attempt to sandbox an eval * in javascript using an iframe. * Test it and let me know if you * can break it. ***************************************/ window.addEventListener("message", function(event){ $('#result').text(event.data.eval); console.log(event.data.scope1); console.log(event.data.scope2); }, false); test = 'do I exist in the window?'; var input = $('[name=toeval]'); input.on('change', function(){ var val = $(this).val(); var code = btoa('&lt;html&gt;\ &lt;head&gt;&lt;\/head&gt;\ &lt;body&gt;\ &lt;' + 'script&gt;\ var party_size = 10;\ window.parent.postMessage({\ eval: eval('+val+'),\ }, "*");\ &lt;\/script' + '&gt;\ &lt;\/body&gt;\ &lt;\/html&gt;'); var frame = $('&lt;iframe sandbox="allow-scripts" src="data:text/html;base64,'+code+'"&gt;&lt;/iframe&gt;'); var sandbox = $('#sandbox'); sandbox.html(frame); }); </code></pre> <p>I have been unsuccessful at accessing the parent document variables, or being able to do anything obnoxious other than to my self within the sandbox.</p>
[ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-05-01T00:28:17.950", "Id": "86604", "Score": "0", "body": "The character sequence `\"</script>\"` should be escaped using `\"<\\/script>\"` (and so should all other closing tags in string literals), the way you have it does nothing useful." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-05-01T03:28:11.200", "Id": "86605", "Score": "0", "body": "You didn't run it. It works as is. If you escape them, then it won't run as a script, which it needs to." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-05-01T11:32:53.110", "Id": "86606", "Score": "0", "body": "`allow-same-origin` is all the security hole you need, isn't it? Also what about browsers that don't understand the `sandbox` attribute?" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-05-01T13:28:36.163", "Id": "86607", "Score": "0", "body": "@SenicaGonzalez—it runs because browsers ignore the script tag that should close the element (test it in an [*HTML validator*](http://validator.w3.org/)). Quoting the closing `/` as suggested certainly does not stop the inserted script from running. See [*Why split the <script> tag when writing it with document.write()?*](http://stackoverflow.com/questions/236073/why-split-the-script-tag-when-writing-it-with-document-write)." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-05-01T14:31:47.397", "Id": "86608", "Score": "0", "body": "@Bergi it runs without the allow-same-origin method. Yes, browsers that do not recognize sandbox is certainly an issue." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-05-01T14:43:29.690", "Id": "86609", "Score": "2", "body": "Read - http://stackoverflow.com/questions/16681460/making-a-same-domain-iframe-secure , also related http://stackoverflow.com/questions/10653809/making-webworkers-a-safe-environment and of course - check out \"Secure ECMAScript\"" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-05-01T15:45:30.830", "Id": "86610", "Score": "0", "body": "@Bergi Yes, that's true. That combined with `allow-scripts` would make it pretty easy to just reach out and remove the `sandbox` attribute. The fiddle has only `allow-scripts` and not `allow-same-origin`." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-05-01T16:33:17.657", "Id": "86611", "Score": "0", "body": "Are you storing what they enter and serving it to others? If not, and they're only executing the code they enter, then it poses no threat to anyone but themselves." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-05-02T13:58:03.197", "Id": "86612", "Score": "0", "body": "By the way, why do you need base64 there? I guess you can do something like data:text/html,(html-code). Just escape it." } ]
[ { "body": "<p>Yes, I can poke a few holes in this.</p>\n\n<p>Firstly, your <code>eval()</code> isn't actually doing much of anything here. From the perspective of the parser running the script, that line looks like this:</p>\n\n<pre><code>eval(party_size &lt; 5)\n</code></pre>\n\n<p>This means that <code>party_size &lt; 5</code> is evaluated to <code>false</code> <em>before</em> it is passed to the <code>eval()</code> function. <code>eval()</code> then just spits this value right back out.</p>\n\n<p>Some consequences of this:</p>\n\n<ul>\n<li>It will fail to act as expected if the expression evaluates to a string value. For example, if you put <code>\"a\" + \"b\"</code> into your textbox, this will fail with the error <code>ReferenceError: ab is not defined</code>, because the JS engine will be trying to evaluate <code>eval(\"ab\")</code>.</li>\n<li>It will fail if the code is anything other than a single expression. So entering this into the textbox: <code>var a = 2; a;</code> fails with a syntax error, even though this is a perfectly legitimate thing to pass to <code>eval()</code>.</li>\n</ul>\n\n<p><br/>\nSo let's assume that was just a silly oversight and you meant to do this:</p>\n\n<pre><code>eval: eval(\"'+val+'\"),\\\n</code></pre>\n\n<p>Well, this will succeed in actually executing chunks of code, until that code contains a quotation mark:</p>\n\n<pre><code>eval(\"var a = \"a\"; a + \"b\"\");\n</code></pre>\n\n<p>at which point it will be broken again.\n<br/>\n<br/>\n<br/>\nNow let's imagine you decided to get around this by changing this line to:</p>\n\n<pre><code>eval: eval(\"' + val.replace(/\"/g, '\\\\\"') + '\"),\\\n</code></pre>\n\n<p>Now you can be pretty confident that the code will run (in most cases) and that all you need to worry about at this point is malicious code (haha).</p>\n\n<p>In terms of malicious code, the attacker could execute something resource intensive that hogs the CPU and RAM:</p>\n\n<pre><code>var a = []; while(true) { a.push(new Date()); console.log(\"gotcha!\"); }\n</code></pre>\n\n<p>Or they might choose to carry out a <a href=\"http://en.wikipedia.org/wiki/Cross-site_request_forgery\" rel=\"noreferrer\">CSRF</a>-like attack:</p>\n\n<pre><code>var x = new XMLHttpRequest();\nx.open(\"post\", \"https://www.mybank.com/transferMoney\");\nx.send(\"amount=10000&amp;toAccount=34567890\");\n</code></pre>\n\n<p>So keeping the host DOM safe is really not the only thing to worry about. There are any other number of malicious things an attacker can carry out if they're able to run code on someone's machine.</p>\n\n<p>Given the above, I would stick with the assertion that <code>eval</code> is evil, and it's not going to be easy to find a \"safe\" way to execute untrusted code.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-03-10T22:38:00.003", "Id": "507524", "Score": "0", "body": "This is incorrect. You cannot make that XMLHttpRequest unless you add allow-same-origin to the sandbox attribute. https://stackoverflow.com/questions/14486461/iframe-sandbox-attribute-is-blocking-ajax-calls" } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-05-02T16:08:36.877", "Id": "49254", "ParentId": "49253", "Score": "13" } }, { "body": "<p>A possible solution for Node.js and the browser is:</p>\n\n<pre><code>var globalScope = global ? global : window // node.js and browser\nvar globals = Object.getOwnPropertyNames(globalScope)\n\nmodule.exports = function makeSafeEval (include) {\n var clearGlobals = ''\n for (var i = 0, len = globals.length; i &lt; len; i++) {\n if (include &amp;&amp; include.indexOf(globals[i]) === -1 || !include) {\n clearGlobals += 'var ' + globals[i] + ' = undefined;'\n }\n }\n return function (operation) {\n var globals = undefined // out of scope for operation\n return eval('(function () {' + clearGlobals + ';return ' + operation.replace('this', '_this') + '})()')\n }\n}\n\nvar safeEval = makeSafeEval()\nsafeEval('this') // undefined\nsafeEval('window') // undefined\n</code></pre>\n\n<p>This not prevents you from malicius code that consumes the memory and CPU. This protection would be achieved by executing the above code in a worker and send messages in an interval, if blocked you can terminate it. On browser you can use a Webworker and in node a Cluster Worker. The above code is avalaible as npm module as cross-safe-eval and the code in my <a href=\"https://github.com/carloslfu/cross-safe-eval\" rel=\"nofollow noreferrer\">Github</a>, hope it helps someone.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2017-10-19T19:22:57.010", "Id": "338516", "Score": "3", "body": "This is NOT a safe solution!! It's possible to prevent the function which clears globals from running (in a mysql-injection-like fashion). If `operation` is set to: `0; }); (function() { console.log('Now I can do anything!!'); var thiis = eval('th' + 'is');` then a malicious user can run any code they like, and even get a reference to `this`. This is because the global-clearing code is parsed into a function which is never called." } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2017-02-25T15:09:10.597", "Id": "156298", "ParentId": "49253", "Score": "0" } }, { "body": "<p>There is a safe and sandboxed way to execute JavaScript code without using eval, is to have a JavaScript interpreter written in JavaScript itself. There is an implementation by Neil Fraser at Google called JS-Interpreter, I am using it and it is a good and simple solution, this is the <a href=\"https://github.com/NeilFraser/JS-Interpreter\" rel=\"noreferrer\">repo in Github</a>. Hope it helps.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2017-03-06T02:20:37.597", "Id": "157014", "ParentId": "49253", "Score": "6" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "9", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-05-01T00:11:55.347", "Id": "49253", "Score": "29", "Tags": [ "javascript", "security", "sandbox" ], "Title": "Sandbox or safely execute eval" }
49253
<pre><code>// Check horizontals for (int y = 0; y &lt; sGridHeight; y++) { Shape* groupShape = nullptr; int groupSize = 0; for (int x = 0; x &lt; sGridWidth; x++) { GridItem* gridItem = GetItem(x, y); Shape* shape = gridItem-&gt;GetShape(); if (shape == groupShape) { groupSize++; if (groupSize == m_MatchSize) { g_Audio-&gt;PlaySound(m_GemDestroyedSound.c_str()); m_Score += shape-&gt;GetScore(); for (int tx = x - m_MatchSize + 1; tx &lt;= x; tx++) { RANDOMIZE(GetItem(tx, y)) } return; } } else { groupSize = 1; groupShape = shape; } } } // Check verticals for (int x = 0; x &lt; sGridWidth; x++) { Shape* groupShape = nullptr; int groupSize = 0; for (int y = 0; y &lt; sGridHeight; y++) { GridItem* gridItem = GetItem(x, y); Shape* shape = gridItem-&gt;GetShape(); if (shape == groupShape) { groupSize++; if (groupSize == m_MatchSize) { g_Audio-&gt;PlaySound(m_GemDestroyedSound.c_str()); m_Score += shape-&gt;GetScore(); for (int ty = y - m_MatchSize + 1; ty &lt;= y; ty++) { RANDOMIZE(GetItem(x, ty)) } return; } } else { groupSize = 1; groupShape = shape; } } } </code></pre> <p>Is there an easy way to clean this up? It seems like a lot of code duplication.</p> <p>I have no qualms about using <code>#define</code>s, and I cannot use C++11.</p>
[ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-05-08T19:25:18.637", "Id": "86613", "Score": "1", "body": "*I cannot use C++11* - [`nullptr` is in C++11](http://stackoverflow.com/questions/1282295/what-exactly-is-nullptr)." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-05-08T20:57:16.173", "Id": "86623", "Score": "0", "body": "Good point, I was unclear - I can use C++11, but not the C++11 standard library." } ]
[ { "body": "<p>Consider replacing:</p>\n\n<pre><code> groupSize++;\n if (groupSize == m_MatchSize)\n {\n g_Audio-&gt;PlaySound(m_GemDestroyedSound.c_str());\n m_Score += shape-&gt;GetScore();\n for (int tx = x - m_MatchSize + 1; tx &lt;= x; tx++)\n {\n RANDOMIZE(GetItem(tx, y))\n }\n return;\n }\n</code></pre>\n\n<p>With something more like:</p>\n\n<pre><code>groupVector.push_back(gridItem);\nif(groupVector.size() == m_MatchSize)\n{\n DestroyGroup(groupVector);\n return;\n}\n\n// where DestroyGroup looks like:\nvoid MyClass::DestroyGroup(const std::vector&lt;GridItem*&gt; &amp; groupVector)\n{\n g_Audio-&gt;PlaySound(m_GemDestroyedSound.c_str());\n m_Score += shape-&gt;GetScore();\n for(std::vector&lt;GridItem*&gt;::iterator itemIter = groupVector.begin();\n itemIter != groupVector.end();\n ++itemIter)\n {\n RANDOMIZE(*itemIter)\n }\n return;\n}\n</code></pre>\n\n<p>I leave optimizing the code above and finding more appropriate function and variable names as an exercise for the original poster. But basically, if you maintain some kind of list of items that you've already traversed you should be able to more easily remove the code duplication that exists between the horizontal and vertical versions of your grid traversal.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-05-08T20:24:22.340", "Id": "86619", "Score": "0", "body": "Since the `DestroyGroup` function doesn't care about the positions of any of the `GridItems` it can be used in future algorithms that locate `GridItems` in patterns that aren't vertical or horizontal, such as diagonal, or X-shaped patterns of items." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-05-08T21:29:36.680", "Id": "86632", "Score": "1", "body": "And if, in the future, the code starts to use C++11 and eliminate those pointers, the `for` loop gets even cleaner: `for (auto &item : groupvector) RANDOMIZE(item);`" } ], "meta_data": { "CommentCount": "2", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-05-08T20:00:52.417", "Id": "49261", "ParentId": "49255", "Score": "1" } }, { "body": "<p>The most straightforward way to do this is to introduce a new boolean variable <code>horz</code> that is true in the case that you wish to check horizontals. With that simple addition, both routines now can be expressed as one:</p>\n\n<pre><code>// if (horz) is true, check horizontals, else check verticals\naLimit = horz ? sGridHeight : sGridWidth;\nbLimit = horz ? sGridWidth : sGridHeight;\nfor (int a = 0; a &lt; aLimit; a++) \n{\n Shape* groupShape = nullptr;\n int groupSize = 0;\n for (int b = 0; b &lt; bLimit; b++) \n {\n GridItem* gridItem = (horz ? GetItem(b, a) : GetItem(a, b));\n Shape* shape = gridItem-&gt;GetShape(); \n if (shape == groupShape)\n {\n groupSize++;\n if (groupSize == m_MatchSize)\n {\n g_Audio-&gt;PlaySound(m_GemDestroyedSound.c_str());\n m_Score += shape-&gt;GetScore();\n for (int tb = b - m_MatchSize + 1; tb &lt;= b; tb++) \n {\n RANDOMIZE(horz ? GetItem(tb, a) : GetItem(a, tb));\n }\n return;\n }\n }\n else\n {\n groupSize = 1;\n groupShape = shape;\n }\n }\n}\n</code></pre>\n\n<p>However, there are a number of things that suggest opportunities for further improvement. In particular, the use of pointers is probably not a good idea. For example, these two lines:</p>\n\n<pre><code> GridItem* gridItem = (horz ? GetItem(b, a) : GetItem(a, b));\n Shape* shape = gridItem-&gt;GetShape(); \n</code></pre>\n\n<p>Are the only place that the <code>gridItem</code> pointer is used, and it's not checked for <code>nullptr</code> before it's dereferenced. So either that's a bug if <code>GetItem()</code> could possibly return a <code>nullptr</code> or it should instead be written as a reference. Even better, it could be combined into a single line and the variable eliminated completely.</p>\n\n<p>Using this modified code is OK, but it's still a little unwieldy, so I would suggest that the <code>GetItem()</code> function should take a third argument which is the bool <code>horz</code>. That would make those same two lines of code look like this:</p>\n\n<pre><code> Shape* shape = GetItem(a, b, horz).GetShape(); \n</code></pre>\n\n<p>Much nicer, but again, I'd turn this pointer into a reference (or better yet, a <code>const</code> reference if possible).</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-05-08T20:01:35.830", "Id": "49262", "ParentId": "49255", "Score": "3" } } ]
{ "AcceptedAnswerId": "49262", "CommentCount": "2", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-05-08T19:23:32.533", "Id": "49255", "Score": "4", "Tags": [ "c++" ], "Title": "Removing duplication in horizontal and vertical checks" }
49255
<p>Web Browsers such as Chrome and Firefox using varying sandboxing techniques, to protect the users from malicious code infecting the system.</p> <p>Operating systems and language runtimes may also use sandboxing as a security measure. Examples include iOS and the Java Virtual Machine.</p>
[]
[]
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-05-08T19:25:06.680", "Id": "49257", "Score": "0", "Tags": null, "Title": null }
49257
Sandbox is a security mechanism for containing untrusted programs. Such programs could contain malicious code, which would harm the user's system.
[]
[]
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-05-08T19:25:06.680", "Id": "49258", "Score": "0", "Tags": null, "Title": null }
49258
<p><strong>Summary:</strong></p> <p>I need to hide several (pre-determined) divs based on a child element's ID.</p> <hr> <p><strong>Caviats:</strong></p> <p>I can't alter the HTML directly in any way (by modifying the literal .html file). The IDs of the child elements for which the parents are to be hidden are known and not likely to change often (or even at all).</p> <p>I can't add CSS that will be available to the HTML page.</p> <hr> <p><a href="http://jsfiddle.net/YtY9b/" rel="nofollow">Here is the solution that I came up with</a></p> <p><strong>JavaScript</strong></p> <pre><code>var toHide = $("#item2, #item3, #item6"); toHide.parent().hide(); </code></pre> <p><strong>HTML</strong></p> <pre><code>&lt;div id="container"&gt; &lt;div&gt; &lt;div id="item1"&gt; &lt;p&gt;item 1&lt;/p&gt; &lt;/div&gt; &lt;div&gt;related item stuff&lt;/div&gt; &lt;/div&gt; &lt;div&gt; &lt;div id="item2"&gt; &lt;p&gt;item 2&lt;/p&gt; &lt;/div&gt; &lt;div&gt;related item stuff&lt;/div&gt; &lt;/div&gt; &lt;div&gt; &lt;div id="item3"&gt; &lt;p&gt;item 3&lt;/p&gt; &lt;/div&gt; &lt;div&gt;related item stuff&lt;/div&gt; &lt;/div&gt; &lt;div&gt; &lt;div id="item4"&gt; &lt;p&gt;item 4&lt;/p&gt; &lt;/div&gt; &lt;div&gt;related item stuff&lt;/div&gt; &lt;/div&gt; &lt;div&gt; &lt;div id="item5"&gt; &lt;p&gt;item 5&lt;/p&gt; &lt;/div&gt; &lt;div&gt;related item stuff&lt;/div&gt; &lt;/div&gt; &lt;div&gt; &lt;div id="item6"&gt; &lt;p&gt;item 6&lt;/p&gt; &lt;/div&gt; &lt;div&gt;related item stuff&lt;/div&gt; &lt;/div&gt; &lt;div&gt; &lt;div id="item7"&gt; &lt;p&gt;item 7&lt;/p&gt; &lt;/div&gt; &lt;div&gt;related item stuff&lt;/div&gt; &lt;/div&gt; &lt;/div&gt; </code></pre> <p>Is there a better way to select these multiple elements than by using <code>$("#item2, #item3, #item6")</code>?</p> <p>Are there any options I'm missing?</p>
[]
[ { "body": "<p>That is pretty close to the optimal way of doing it.</p>\n\n<p>Personally I would go for</p>\n\n<pre><code>//Hide items\n$(\"#item2, #item3, #item6\").parent().hide();\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-05-08T21:28:14.067", "Id": "86631", "Score": "0", "body": "Thanks, @konijn. The only reason I separated my id selection from the `.parent().hide()` is because the actual `id`s are long and I wanted to preserve some readability." } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-05-08T20:28:09.930", "Id": "49264", "ParentId": "49259", "Score": "2" } } ]
{ "AcceptedAnswerId": "49264", "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-05-08T19:40:17.997", "Id": "49259", "Score": "4", "Tags": [ "javascript", "jquery" ], "Title": "Hiding multiple elements' parent container (by child element id)" }
49259
<p>I've wrote some simple code to load a JSON file from the Twitter Streaming API, parse the data, and create relationships between users based on who mentions or retweets who. My ultimate goal is to have a file that I can load into a network analysis program to analyze.</p> <p>I wrote the code to first look for a retweet, and if present, create a relationship between the author and the user retweeted. Then look for any mentions, and if present, create a relationship between the author and any users mentioned. This part can have multiple relationships for a single tweet, as you can mention multiple people in one tweet. Then if neither a retweet or a mention is present, print the author and the tweet. </p> <p>End goal of this is to simple parse a JSON file and return a CSV file that I can then analyze. I will not be loading this into any type of database.</p> <pre><code>import json import sys import time def main(): for line in sys.stdin: line = line.strip() data = [] try: data.append(json.loads(line)) except ValueError as detail: continue for tweet in data: ## deletes any rate limited data if tweet.has_key('limit'): pass else: tweet_time = time.strftime('%Y-%m-%d %H:%M:%S', time.strptime(tweet['created_at'],'%a %b %d %H:%M:%S +0000 %Y')) ## if the key 'retweeted_status' is in the dict, print if tweet.has_key('retweeted_status'): print "\t".join([ tweet_time, tweet['id_str'], tweet['user']['screen_name'], tweet['retweeted_status']['user']['screen_name'], "RETWEET", tweet['text'] ]).encode('utf8') ## if there is a mention in the dict, print elif 'entities' in tweet and len(tweet['entities']['user_mentions']) &gt; 0: for u2 in tweet['entities']['user_mentions']: print "\t".join([ tweet_time, tweet['id_str'], tweet['user']['screen_name'], u2['screen_name'], "MENTION", tweet['text'] ]).encode('utf8') ## if there is no retweet and no mention, print else: print "\t".join([ tweet_time, tweet['id_str'], tweet['user']['screen_name'], "\t", "TWEET", tweet['text'] ]).encode('utf8') if __name__ == '__main__': main() </code></pre>
[]
[ { "body": "<p>I would suggest to create following new classes:</p>\n\n<ol>\n<li>User, which stores information about user, like user_id, user_location</li>\n<li>Text, which stores the tweet text, the language of the tweet, may be the keywords</li>\n<li>Tweet, which contains objects of User ,Text and some other information about the tweet</li>\n</ol>\n\n<p>I am assuming that you will be storing all this data into a database and the above mentioned structure (with some mild changes, based on your requirement) can be used to create a 3-NF database.</p>\n\n<p>Another suggestion is \"not\" using stdin. Create a new file \"Twitter.py\" having function <em>readTweet</em> which will return tweet. This makes it easier to change the source of the tweet in the later part of the development. Suppose you want to directly take tweet from twitter API, then you just need to change the function </p>\n\n<p>Your main function will look like following:</p>\n\n<pre><code>def main():\n\n for tweet in Twitter.getTweets():\n\n tweet_time = tweet.getTime() \n\n if tweet.isRetweeted:\n print \"do something 0\"\n elif tweet.hasEntities and len(tweet.Usermentions) &gt; 0:\n for mention in tweet.userMentions:\n print \"do something 1\"\n else:\n print \"do something 2\"\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-05-09T16:27:39.233", "Id": "86782", "Score": "0", "body": "This looks like a good approach. However, I haven't learned about classes yet, so I will need to study up on this area." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-05-09T16:30:47.497", "Id": "86783", "Score": "0", "body": "The following link contains a nice tutorial for python classes: http://www.tutorialspoint.com/python/python_classes_objects.htm . WARNING: If you are Java programmer then you might have to leave many 'useless' OOPS concepts behind." } ], "meta_data": { "CommentCount": "2", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-05-09T06:48:19.110", "Id": "49303", "ParentId": "49263", "Score": "2" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-05-08T20:10:57.830", "Id": "49263", "Score": "2", "Tags": [ "python", "twitter" ], "Title": "Print Tweets/Mentions/Retweets" }
49263
<p>I am using Merton default model with complex iterative approach.</p> <p>I have already prepared my R codes but as I am quite new in R, they seem very inefficient, in sense that they runs almost 7 hours. My main problem is my for loop part.</p> <p>I kindly ask you review my R codes and give any corrections which could make my R code more efficient i.e. they run less time.</p> <p>I downloaded all data and R code <a href="https://www.dropbox.com/sh/jlqvao40e5nvkev/AACpPdAdG67juhX9HoHPpiC1a" rel="nofollow">here</a>.</p> <pre><code>library(plyr) library(nleqslv) library(data.table) library(zoo) library(TTR) df5&lt;-read.table(file="df5final.txt", sep="\t", header=T) df5&lt;-df5[,-8] NONA &lt;- function(data, columns) { completeVec &lt;- complete.cases(data[, columns]) return(data[completeVec, ]) } head(df5) df5&lt;-NONA(df5,9) nrow(df5) freq&lt;-ddply(df5, .(id,BSheetyearlag), "nrow") df5&lt;-join(df5, freq, by=c("id","BSheetyearlag")) nrow(df5) df5&lt;-subset(df5, !nrow &lt; 250) df5&lt;-subset(df5 , !nrow &gt; 260) unique(df5$nrow) nrow(df5) df5$logret&lt;-log(1+df5$ret) df5&lt;-as.data.table(df5) head(df5, n=25) df5$year&lt;-format(as.Date(df5$date, "%d-%b-%y"), "%Y") df5$year&lt;-as.numeric(df5$year) ####annual risk free rate df5$convert&lt;-as.Date(paste("1",df5$BSheetyearlag,sep=""), format="%d %b %Y") df5$year&lt;-format(df5$convert, "%Y") rfabsolyear&lt;-read.table(file="riskfreeannual.txt", sep="\t", header=T) head(rfabsolyear) tail(df5,n=2) rfabsolyear&lt;-rfabsolyear[,-2] library(plyr) df5&lt;-join(df5, rfabsolyear, by=c("year")) sp500&lt;-read.table(file="spdata.txt", sep="\t", header=T) colnames(sp500)&lt;-c("date", "price", "retsp") sp500&lt;-na.omit(sp500) sp500$date&lt;-format(as.Date(sp500$date, "%d-%b-%y"), "%d-%b-%y") head(df5,n=20) sp500&lt;-na.omit(sp500) df5&lt;-join(df5, sp500, by=c("date")) head(df5) blackscholes &lt;- function(S, X, rf, h, sigma) { d1 &lt;- (log(S/X)+(rf+sigma^2/2)*h)/sigma*sqrt(h) } df5&lt;-subset(df5, ! LTD %in% NA ) df5&lt;-subset(df5, ! STD %in% NA ) df5&lt;-subset(df5, ! LTD %in% 0 ) df5&lt;-subset(df5, ! cap %in% 0 ) df5&lt;-subset(df5, ! STD %in% -882 ) df5$cap&lt;-df5$cap/1000 df5&lt;-within(df5, LTD05&lt;-df5$STD+0.5*df5$LTD) nrow(df5) df5&lt;-within(df5, iterK&lt;-df5$LTD05+df5$cap) df5$logiterK&lt;-log(df5$iterK) df5&lt;-as.data.table(df5) df5[,rollsd:=rollapply(logret, 250, sd, fill = NA, align='right')*sqrt(250), by=c("id", "BSheetyearlag")] df5[,assetreturn:=c(NA,diff(logiterK)),by=c("id", "BSheetyearlag")] df5[,rollsdasset:=rollapply(assetreturn, 249, sd, fill=NA, align='right')*sqrt(250), by=c("id", "BSheetyearlag")] df5[,iterK1:=(cap+LTD05*exp(-rfabsol)*pnorm(blackscholes(iterK,LTD05,rfabsol, 1,rollsdasset[250]))-rollsdasset[250])/pnorm(blackscholes(iterK,LTD05,rfabsol, 1,rollsdasset[250])),by=c("id", "BSheetyearlag")] head(df5, n=254) errors&lt;-ddply( df5, .(id, BSheetyearlag), function(x) sum((x$iterK-x$iterK1)^2)) head(errors) df5&lt;-as.data.frame(df5) nrow(df5) head(df5) df5&lt;-join(df5, errors, by=c("id", "BSheetyearlag")) df5&lt;-as.data.table(df5) for ( i in 1:nrow(errors)){ while(errors$V1[i] &gt;= 10^(-10)) { df5&lt;-as.data.table(df5) df5[,iterK:= iterK1,by=c("id", "BSheetyearlag")] df5[,assetreturn:=c(NA,diff(log(iterK))),by=c("id", "BSheetyearlag")] df5[,rollsdasset:=rollapply(assetreturn, 249, sd, fill=NA, align='right')*sqrt(250), by=c("id", "BSheetyearlag")] df5[,iterK1:=(cap+LTD05*exp(-rfabsol)*pnorm(blackscholes(iterK,LTD05,rfabsol, 1,rollsdasset[250]))-rollsdasset[250])/pnorm(blackscholes(iterK,LTD05,rfabsol, 1,rollsdasset[250])),by=c("id", "BSheetyearlag")] df5&lt;-as.data.frame(df5) errors$V1[i]&lt;-sum((df5[df5$V1 %in% errors$V1[i],"iterK"]-df5[df5$V1 %in% errors$V1[i],"iterK1"])^2) } } </code></pre>
[ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-05-10T11:41:22.693", "Id": "86855", "Score": "0", "body": "duplicate of http://codereview.stackexchange.com/questions/49276/replace-for-loop-while-with-apply-family-function-in-r?" } ]
[]
{ "AcceptedAnswerId": null, "CommentCount": "1", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-05-08T20:34:21.077", "Id": "49265", "Score": "2", "Tags": [ "r" ], "Title": "Merton default model with complex iterative approach" }
49265
<p>I am working on a class for encryption to use on my site. I have read through many examples of these functions and would just like to clarify a few points I have read and check if this code is worthy. It is for storing sensitive information in a database. I am aware that making this method secure does not mean that the information is 100% secure, I simply need an appraisal of the code.</p> <pre><code>&lt;?php class Encryption { private $eMethod = MCRYPT_RIJNDAEL_128; private $siteKey = "01234567890123456789012345678901"; # strlen = 32 private $ivSize; private $iv; public function __construct() { $this-&gt;ivSize = mcrypt_get_iv_size( $this-&gt;eMethod, MCRYPT_MODE_CBC ); $this-&gt;iv = mcrypt_create_iv( $this-&gt;ivSize, MCRYPT_RAND ); } public function encrypt( $data, $salt ) { $encryptedMessage = mcrypt_encrypt( $this-&gt;eMethod, $this-&gt;siteKey, $data, MCRYPT_MODE_CBC, $this-&gt;iv ); $encryptedSalt = mcrypt_encrypt( $this-&gt;eMethod, $this-&gt;siteKey, $salt, MCRYPT_MODE_CBC, $this-&gt;iv ); $saltIdentifier = str_pad( strlen($encryptedSalt), 6, '0', STR_PAD_LEFT ); $newData = $encryptedSalt.($this-&gt;iv).$encryptedMessage.$saltIdentifier; return($newData); } public function decrypt( $data ) { $thisSaltID = substr( $data, -6 ); $saltID = ltrim($thisSaltID,'0'); $thisSalt = substr( $data, 0, $saltID ); $goTo = $saltID + ($this-&gt;ivSize); $thisIv = substr( $data, $saltID, ($this-&gt;ivSize) ); $thisHash = substr( $data, $goTo, -6 ); $decryptedMessage = mcrypt_decrypt( $this-&gt;eMethod, $this-&gt;siteKey, $thisHash, MCRYPT_MODE_CBC, $thisIv ); return($decryptedMessage); } } ?&gt; </code></pre> <hr> <p>When encrypting, it takes the data and a salt, encrypts both and then combines them with the iv and the padded <code>strlen</code> of the salt as per this line:</p> <pre><code>$newData = $encryptedSalt.($this-&gt;iv).$encryptedMessage.$saltIdentifier; </code></pre> <p>Then I know which order things appear and can pull it apart accordingly.</p> <ol> <li><p>Is this salt unnecessary or poorly implemented?</p></li> <li><p>When creating an object and encrypting a string, I pad the string to a length of multiple 16, and generate a random alphanumeric string of length 16 for the salt. Is it unnecessary to make sure the inputs are formatted in this way?</p></li> <li><p>Should the site key be random every time (or static as it is now)? And are there advisements on its length?</p></li> <li><p>Is using <code>RIJNDAEL_128</code> with a 256-bit key the equivalent of using <code>AES-256</code>?</p></li> <li><p>Is this code okay to use?/area of criticism</p></li> </ol>
[]
[ { "body": "<p>I'm no security expert, however I think answering this would be fun!</p>\n\n<p>I'll start off by doing my best answering your four questions:</p>\n\n<ol>\n<li><p>The salt is unnecessary.</p>\n\n<blockquote>\n <p>a salt is random data that is used as an additional input to a one-way\n function... The primary function of salts is to defend against\n <a href=\"http://en.wikipedia.org/wiki/Dictionary_attacks\" rel=\"nofollow noreferrer\">dictionary attacks</a> versus a list of password hashes and against\n pre-computed rainbow table attacks.</p>\n</blockquote>\n\n<p>These first few lines from the <a href=\"http://en.wikipedia.org/wiki/Salt_(cryptography)\" rel=\"nofollow noreferrer\">Wikipedia page for salts</a>\nbasically sum it up. Because we're working with <em>encryption</em>\n(opposed to say, <em>hashing</em>), the private key and the IV are our protection, not a salt. <a href=\"https://security.stackexchange.com/a/53244/38125\">Reiterated over here</a> on our Security Stack Exchange site.</p>\n\n<p><a href=\"http://en.wikipedia.org/wiki/Salt_(cryptography)#Web_application_implementations\" rel=\"nofollow noreferrer\">This section</a> elaborates on why it's necessary for <em>hashing</em> to\nhave salts:</p>\n\n<blockquote>\n <p>Without a salt, a successful SQL injection attack may yield easily\n crackable passwords.</p>\n</blockquote></li>\n<li>Well, we just found out that having a salt infused really isn't very\nbeneficial. So if we eliminate the salt, then all we have left in\nthe encrypted output is the actual encryption, and the IV. Because\nthe IV size won't be changing in this example, it's A-OK to strip\nthe IV from the string using the IV size, and then the left over is\nthe message encrypted.</li>\n<li><p>No, it cannot be unique. How would you decrypt it later on if the data left the class?</p>\n\n<p>I'm not sure how you're creating the key, but I suggest something\nsuch as to get a truly random one:</p>\n\n<pre><code>pack(\"H*\", bin2hex(openssl_random_pseudo_bytes(32)));\n</code></pre></li>\n<li><p>Yes. Rijndael has three members in it's family: Rijndael-128,\nRijndael-192, and Rijndael-256 (there're more, but only these three are AES standard). However, each has a block size of\n128 bits. So therefore Rijndael-256 with a (the only option) block\nsize of 128 would be the same as saying AES-256.</p>\n\n<blockquote>\n <p>The AES algorithm is capable of using cryptographic keys of 128, 192,\n and 256 bits to encrypt and decrypt data in blocks of 128 bits.</p>\n</blockquote>\n\n<p>Via <a href=\"http://csrc.nist.gov/publications/fips/fips197/fips-197.pdf\" rel=\"nofollow noreferrer\">NIST</a></p></li>\n<li><p>Depends. Where do you want to use it? In production, I'd say pick up a framework which already has this topic highly covered and critiqued. It also depends on what you're encrypting. </p></li>\n</ol>\n\n<hr>\n\n<p><strong>Other comments</strong></p>\n\n<blockquote>\n<pre><code>private $eMethod = MCRYPT_RIJNDAEL_128;\n</code></pre>\n</blockquote>\n\n<p>never changes, so you could turn this into a constant.</p>\n\n<blockquote>\n<pre><code>return($newData);\n</code></pre>\n</blockquote>\n\n<p>It's up to you, but it's more common to leave the parentheses off.</p>\n\n<p>Your whitespace and vertical alignment can have negative effects on readability. Of course, it's up to you, but you may want to check out some other coding styles.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-07-08T05:58:40.777", "Id": "56408", "ParentId": "49267", "Score": "5" } } ]
{ "AcceptedAnswerId": "56408", "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-05-08T21:24:39.850", "Id": "49267", "Score": "6", "Tags": [ "php", "security", "cryptography" ], "Title": "MCRYPT - are there any flaws or areas for improvement in this class?" }
49267
<p>I have created a function which returns the number that corresponds to the given row and column from the pascal triangle. I have used the formula for this:</p> <blockquote> <p>n! / r! * (r-n)!</p> </blockquote> <p>The code:</p> <pre><code>def pascal(c: Int, r: Int): Int = { def factorial(number: Int): Int = { def loop(adder: Int, num: Int): Int = { if( num == 0) adder else loop(adder * num, num - 1) } loop(1,number) } factorial(r) / (factorial(c) * factorial(r-c)); } </code></pre> <p>I received 180 points out of 190 for this function because it returns an arithmetic exception for a given case (they don't give me the case). How could I improve this code and how can I make it better? Most importantly, how can I spot the bug? </p>
[ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-05-09T05:12:06.397", "Id": "86675", "Score": "2", "body": "I'm voting against closure cause his code is working(one small case not), and asking for improvement. (also how to spot the bug but not asking to fix the bug)." } ]
[ { "body": "<p>There is a simpler solution. Consider this logic:</p>\n\n<ul>\n<li>if it's the first column, the value is always 1</li>\n<li>if it's the last column, the value is always 1. (You can check this based on the row!)</li>\n<li>otherwise, it's the sum of the value in the previous row previous column + previous row same column</li>\n</ul>\n\n<p>Spoiler alert:</p>\n\n<blockquote class=\"spoiler\">\n <p> <code>def pascal(c: Int, r: Int): Int = {\n require(!(c &lt; 0 || r &lt; 0 || c > r), \"c, r must be both positive and c &lt;= r\")\n if (c == 0) 1\n else if (c == r) 1\n else pascal(c - 1, r - 1) + pascal(c, r - 1)\n}</code></p>\n</blockquote>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-05-08T21:52:22.687", "Id": "49273", "ParentId": "49268", "Score": "3" } }, { "body": "<p>The code appears to be correct, though the explanatory formula you posted is wrong.</p>\n\n<p>Your factorial function is more complex than it needs to be. Furthermore, <code>adder</code> is a poor variable name, since the result is multiplicative rather than additive. The traditional recursive definition is:</p>\n\n<pre><code>def factorial(n: Int): Int = {\n if (n == 0) 1\n else n * factorial(n - 1)\n}\n</code></pre>\n\n<p>The main problem with your approach is that you work with large numbers in both the numerator and the denominator. If your program is generally working, then your problem is probably arithmetic overflow. An <code>Int</code> would only handle values up to 2<sup>31</sup> - 1 correctly.</p>\n\n<p>Therefore, your best bet is to use an entirely different way to construct <a href=\"http://en.wikipedia.org/wiki/Pascal%27s_triangle\" rel=\"nofollow\">Pascal's Triangle</a>, as suggested by @janos.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-05-09T15:08:05.500", "Id": "86768", "Score": "0", "body": "you are right. If I insert large numbers division by 0 occurs. Now implementing a whole new algorithm I guess would do the trick. However couldn't I just work with long? and then return an int?" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-05-29T14:49:11.087", "Id": "89989", "Score": "1", "body": "OP's `factorial` version has an advantage of being a little bit faster (it's tail-recursive )" } ], "meta_data": { "CommentCount": "2", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-05-08T22:18:15.020", "Id": "49274", "ParentId": "49268", "Score": "4" } } ]
{ "AcceptedAnswerId": "49274", "CommentCount": "1", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-05-08T21:34:25.567", "Id": "49268", "Score": "3", "Tags": [ "recursion", "homework", "scala" ], "Title": "Pascal triangle algorithm is good but fails" }
49268
<p>I'm having trouble testing some code. It's laid out in such a way that the business logic relies on the persistence layer.</p> <p>Some classes require that an object be saved to a database. Some classes re-read the object they were working to get the "original" version of it. All of this tends to happen in what's been labeled the business logic layer. </p> <p>This a WCF application where the business logic layer manipulates objects from the DAL</p> <p>Code sample below.</p> <pre><code>public class WCFService : IWCFService { public OrderHeader GetOrder(int id) { var om = new OrderManager(); return om.Read(id); } } </code></pre> <pre><code>[DataContract] public class OrderHeader { [DataMember] public int id { get; set; } public OrderHeader Read(int id) { // ADO.NET calls return new OrderHeader(); } public void CreateUpdate() { // ADO.NET calls this.id = GetSqlOutputParam(); } private int GetSqlOutputParam() { // get the identity supplied by the executed stored proc } } </code></pre> <pre><code>public class OrderManager { public OrderHeader Read(int id) { OrderHeader oh = new OrderHeader(); return oh.Read(id); } public bool SaveOrder(OrderHeader order) { // do lots of complex stuff order.CreateUpdate(); // update here because some other class is going to want to do a fresh read // instantiate other "manager" classes order = order.Read(order.id); // make sure we get the latest record from the database in case other manager classes changed my order // do more complex stuff order.CreateUpdate(); return true; } } </code></pre> <p>Firstly and unfortunately, there isn't an immediate plan to replace the entity specific ADO.NET with an ORM. </p> <p>I would like to start by making the code a little more testable by removing all persistence calls from the business logic layer, or separating the actual logic away from these calls while keeping them in the same layer. Instead of update() and read() littered throughout those manager classes, the object would be passed around as much as needed. </p> <p>To give some context, the code suffers from a lot of persistence related bugs. I feel like removing persistence from the equation would make matters easier to deal with.</p> <p><strong>Edit</strong>: I miscommunicated the intent of the GetSqlOutputParam() method. It's not just returning a const, it is pulling it from an executed SqlCommand.</p>
[ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-05-08T23:28:44.253", "Id": "86647", "Score": "0", "body": "The ADO.NET calls could very well be worth reviewing as well, feel free to edit them in! :)" } ]
[ { "body": "<blockquote>\n <p><em>Firstly and unfortunately, there isn't an immediate plan to replace the entity specific ADO.NET with an ORM.</em></p>\n</blockquote>\n\n<p>That's fine.</p>\n\n<p>This is more questionable:</p>\n\n<blockquote>\n<pre><code>private int GetSqlOutputParam() { return 1; }\n</code></pre>\n</blockquote>\n\n<p>It would be much clearer to declare this as a descriptively named constant near the top of the class (being class-level scoped):</p>\n\n<pre><code>private const int defaultEntityId = 1;\n</code></pre>\n\n<hr>\n\n<p>But that's far from being what's making that code hard to test.</p>\n\n<blockquote>\n <p><em>I would like to start by making the code a little more testable by\n removing all persistence calls from the business logic layer, or\n separating the actual logic away from these calls while keeping them\n in the same layer. Instead of update() and read() littered throughout\n those manager classes, the object would be passed around as much as\n needed.</em></p>\n</blockquote>\n\n<p>A class such as an <code>OrderHeader</code> exists to hold data. Nothing less, but also <em>and more importantly</em> nothing more. It's a <em>Plain Old CLR Object</em>, a POCO. You hit the nail on the head, that's exactly what you need to do. Move the ADO.NET code into its own class.</p>\n\n<p>As much as I dislike this pattern <em>when it's used on top of Entity Framework</em>, if I had to refactor some ADO.NET code into its own class, I'd probably write something like a <em>repository</em>:</p>\n\n<blockquote>\n <p><a href=\"http://moleseyhill.com/blog/2009/08/11/dependency-inversion-repository-pattern/\" rel=\"nofollow noreferrer\"><img src=\"https://i.stack.imgur.com/Iq485.png\" alt=\"DI and repository pattern\"></a></p>\n \n <p>This blog post (click the diagram) explains how <em>dependency inversion</em> enables testing.</p>\n \n <p><sub>(I am not the author of the blog this link points to, it's pure coincidence that this guy's name is Mat. I'm not <em>this Mat</em>'s Mug.)</sub></p>\n</blockquote>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-05-09T09:06:08.993", "Id": "86704", "Score": "0", "body": "Thank you very much for the response! The repository pattern seems to be a good possibility to consider. I have to say I miscommunicated the intent of that GetSqlOutputParam() method. It's not just returning 1 const, it is pulling it from an executed stored procedure" } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-05-09T03:39:14.470", "Id": "49291", "ParentId": "49271", "Score": "3" } } ]
{ "AcceptedAnswerId": "49291", "CommentCount": "1", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-05-08T21:49:49.400", "Id": "49271", "Score": "5", "Tags": [ "c#", "object-oriented", ".net", "unit-testing", "ado.net" ], "Title": "Hard-to-test 3 Tier Architecture" }
49271
<p>I've made a prime number generator (for Project Euler). It uses Euler's Sieve (a modified Sieve of Eratosthenes), with a mod 30 step. I'd like to reduce the memory consumption to 4/15 what it currently is by keeping a boolean array only for the possibly prime remainders of 30. I can't get it to work and also fear that this will slow down the program.</p> <p>I've used</p> <pre><code>n[f/30*8+[zeroes, except 1,2,3,4,5,6,7 at 7,11,13,17,19,23,29][f%30]] </code></pre> <p>which seemed to not filter out any composite numbers. How can I make this work and what other optimizations (aside from increasing the mod) can you suggest? I need the primes up to about two billion.</p> <pre><code>#include &lt;vector&gt; #include &lt;algorithm&gt; #ifndef _pes30_cxx_ #define _pes30_cxx_ typedef unsigned long long big; const int ofs[]={6,4,2,4,2,4,6,2}; void sievePrimes(big m,std::vector&lt;big&gt; &amp;p){ big f; bool n[m]; p={2,3,5}; for(big i=0;i&lt;m;++i)n[i]=true; for(big i=7,s=1;i&lt;=m;i+=ofs[s],++s==8?s=0:0){ if(!n[i])continue; p.push_back(i); for(big j=i,t=s;j&lt;=m/i;j+=ofs[t],++t==8?t=0:0){ if(!n[j])continue; f=j*i; do{ n[f]=false; }while((f*=j)&lt;=m); } } } inline bool isPrime(big n,std::vector&lt;big&gt; p){ return std::binary_search(p.begin(),p.end(),n); } #endif </code></pre>
[ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-05-09T01:23:15.907", "Id": "86658", "Score": "0", "body": "[Follow-up question](http://codereview.stackexchange.com/questions/49284/reduce-prime-sieve-memory-consumption-2)" } ]
[ { "body": "<ul>\n<li><p>The <code>typedef</code> name <code>big</code> makes little sense, especially in regards to integer size. If <code>big</code> can resemble 64-bit, then I suppose <code>bigger</code> can resemble 128-bit.</p>\n\n<p>However, instead of having your own <code>typedef</code> for <code>unsigned long long</code>, use <code>std::uint64_t</code> from <a href=\"http://en.cppreference.com/w/cpp/types/integer\" rel=\"nofollow noreferrer\"><code>&lt;cstdint&gt;</code></a>, which is guaranteed to be 64 bits on supported implementations. It is preferred to use such integer types from this library. Some additional info about that can be found <a href=\"https://stackoverflow.com/a/5836380\">here</a>.</p></li>\n<li><p>There's no practical need for <code>inline</code>, nor will it automatically improve performance. It only serves as a hint to the compiler, and it is still free to ignore it if inlining is unnecessary.</p></li>\n<li><p>This code greatly lacks indentation and whitespace. Here are some tips on this:</p>\n\n<ul>\n<li>Different sections, such as constants and functions, should be separated.</li>\n<li>Although there are no standards in C++ regarding amount of indentation, four spaces is very common and is also quite readable.</li>\n<li><p>There should be whitespace between operators and operands to help with readability.</p>\n\n<p>Here's an example using one of your statements:</p>\n\n<pre><code>for (big i = 0; i &lt; m; ++i ) n[i] = true;\n</code></pre></li>\n</ul></li>\n</ul>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-05-08T22:38:58.903", "Id": "49279", "ParentId": "49275", "Score": "2" } }, { "body": "<p>I consider this to be obfuscated code. Consider:</p>\n\n<ul>\n<li>There are no comments: no guidance on how to call the function, and no explanation of how it works internally.</li>\n<li>All variables have one-character names, as if you had filtered the code through a minifier. The sole exception is <code>ofs</code> — which is still cryptic and meaningless to me.</li>\n<li><p>You have used nearly the minimum amount of whitespace possible:</p>\n\n<p><kbd>Space</kbd><kbd>Space</kbd><code>for(big i=0;i&lt;m;++i)n[i]=true;</code></p>\n\n<p>The code would be more readable with deeper indentation than two spaces per level. It would be easier to see the individual parts of the loop header if you put spaces after each semicolon. The loop body would be easier to see if it didn't immediately follow the closing parenthesis.</p>\n\n<pre><code> for (big i = 0; i &lt; m; ++i) {\n n[i] = true;\n }\n</code></pre>\n\n<p>All these changes cost you nothing, and have tangible benefits.</p></li>\n<li><p>This loop header is trying to accomplish way too much!</p>\n\n<pre><code>for(big j=i,t=s;j&lt;=m/i;j+=ofs[t],++t==8?t=0:0)\n</code></pre></li>\n</ul>\n\n<p>Also, why is the code guarded by <code>#ifndef _pes30_cxx_</code>? Is this code living inside a header file? If so, move it out to a <code>.cpp</code> file where it belongs.</p>\n\n<p>Given the serious stylistic issues with the code, I doubt that anyone would voluntarily reverse-engineer it and review its substance. I suggest that you work on expressing yourself clearly, then post a follow-up question asking about memory or other performance concerns.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-05-08T23:00:01.713", "Id": "86641", "Score": "0", "body": "This is how my code would normally look, but I really should have cleaned it up if I wanted help, so I've done some of that." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-05-08T23:02:54.353", "Id": "86642", "Score": "6", "body": "Umm... it's a filthy habit to code like that normally. You should aim to write clearly _all_ the time, not just when you expect scrutiny." } ], "meta_data": { "CommentCount": "2", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-05-08T22:58:26.570", "Id": "49280", "ParentId": "49275", "Score": "4" } } ]
{ "AcceptedAnswerId": "49280", "CommentCount": "1", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-05-08T22:23:47.847", "Id": "49275", "Score": "3", "Tags": [ "c++", "array", "primes" ], "Title": "Reduce Prime Sieve Memory Consumption" }
49275
<p>I have trouble with for loop, my code runs very slowly. The thing I want to do is to use function from <code>apply</code> family to make my codes run faster (instead of using <code>for loop</code>and <code>while</code>). Here is an example and my loop:</p> <pre><code>require(data.table) require(zoo) K&lt;-seq(1,1000, by=1) b&lt;-c(rep(2,250), rep(3, 250), rep(4, 250), rep(5,250)) a&lt;-c(rep(6,250), rep(7,250), rep(8,250), rep(9,250)) rf&lt;-rep(0.05, 1000) L&lt;-rep(10,1000) cap&lt;-rep(20,1000) df&lt;-data.frame(K, rf, L, cap, a,b) blackscholes &lt;- function(S, X, rf, h, sigma) { d1 &lt;- (log(S/X)+(rf+sigma^2/2)*h)/sigma*sqrt(h) } df$logiterK&lt;-log(df$K) df&lt;-as.data.table(df) df[,rollsd:=rollapply(logret, 250, sd, fill = NA, align='right')*sqrt(250), by=c("a", "b")] df[,assetreturn:=c(NA,diff(logiterK)),by=c("a", "b")] df[,rollsdasset:=rollapply(assetreturn, 249, sd, fill=NA, align='right')*sqrt(250), by=c("a", "b")] df[,K1:=(cap+L*exp(-rf)*pnorm(blackscholes(K,L,rf, 1,rollsdasset[250]))-rollsdasset[250])/pnorm(blackscholes(K,L,rf, 1,rollsdasset[250])),by=c("a","b")] errors&lt;-ddply( df, .(a,b), function(x) sum((x$K-x$K1)^2)) df&lt;-as.data.frame(df) df&lt;-join(df, errors, by=c("a", "b")) for ( i in 1:nrow(errors)){ while(errors$V1[i] &gt;= 10^(-10)) { df&lt;-as.data.table(df) df[,K:= K1,by=c("a", "b")] df[,assetreturn:=c(NA,diff(log(K))),by=c("a", "b")] df[,rollsdasset:=rollapply(assetreturn, 249, sd, fill=NA, align='right')*sqrt(250), by=c("a", "b")] df[,iterK1:=(cap+L*exp(-rf)*pnorm(blackscholes(K,L,rf, 1,rollsdasset[250]))-rollsdasset[250])/pnorm(blackscholes(K,L,rf, 1,rollsdasset[250])) ,by=c("a", "b")] df&lt;-as.data.frame(df) errors$V1[i]&lt;-sum((df[df$V1 %in% errors$V1[i],"K"]-df[df$V1 %in% errors$V1[i],"K1"])^2) } } </code></pre> <p>Any help would be appreciated.</p>
[ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-05-09T05:15:22.777", "Id": "86676", "Score": "0", "body": "I am unable to run the code because an object `logret` is not found. Is it a function? Could you please specify the package at the beginning? I have added loading of `data.table` and `zoo`." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-05-10T11:27:54.280", "Id": "86853", "Score": "1", "body": "The `apply`family of functions all implement a `for` loop. They are not faster, just give you more ways to write `for` loops in a concise manner." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-05-10T11:39:19.240", "Id": "86854", "Score": "2", "body": "The constant switching from data.frame to data.table might be where you waste a lot of time. Try converting to a data.table once and for all and stick to it." } ]
[ { "body": "<p>You <em>could</em> replace the <code>for</code> loop with a function + <code>sapply</code> like this:</p>\n\n<pre><code>reduce.errors &lt;- function(err) {\n while (err &gt;= 10^(-10)) {\n df&lt;-as.data.table(df)\n df[,K:= K1,by=c(\"a\", \"b\")] \n df[,assetreturn:=c(NA,diff(log(K))),by=c(\"a\", \"b\")] \n df[,rollsdasset:=rollapply(assetreturn, 249, sd, fill=NA, align='right')*sqrt(250), by=c(\"a\", \"b\")]\n df[,iterK1:=(cap+L*exp(-rf)*pnorm(blackscholes(K,L,rf, 1,rollsdasset[250]))-rollsdasset[250])/pnorm(blackscholes(K,L,rf, 1,rollsdasset[250])) ,by=c(\"a\", \"b\")]\n df&lt;-as.data.frame(df)\n err &lt;- sum((df[df$V1 %in% err,\"K\"]-df[df$V1 %in% err,\"K1\"])^2)\n } \n}\nsapply(errors$V1, reduce.errors)\n</code></pre>\n\n<p>But I don't think this will make it faster at all. If I understand correctly you need the <code>while</code> loop there to reduce the error below a threshold, and so you need the iteration and this cannot be replaced with the \"apply\" functions easily.</p>\n\n<p>If you want to improve the speed, I think you'll need to rethink come up with a different approach, if it's even possible.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-05-08T23:03:25.353", "Id": "49281", "ParentId": "49276", "Score": "2" } } ]
{ "AcceptedAnswerId": "49281", "CommentCount": "3", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-05-08T22:31:48.820", "Id": "49276", "Score": "3", "Tags": [ "r" ], "Title": "Replace for loop while with apply family function in R" }
49276
<p>I need feedback on this code regarding security issues.</p> <pre><code>&lt;?php if(!isset($_POST['submit'])) { //This page should not be accessed directly. Need to submit the form. echo "error; you need to submit the form!"; } $name = $_POST['name']; $visitor_email = $_POST['email']; $message = $_POST['message']; //Validate first if(empty($name)||empty($visitor_email)) { echo "Name and email are mandatory!"; exit; } if(IsInjected($visitor_email)) { echo "Bad email value!"; exit; } $email_from = 'someemail@some.com';//&lt;== update the email address $email_subject = "New Form submission"; $email_body = "You have received a new message from the user $name.\n". "Here is the message:\n $message". $to = "someemail@some.com";//&lt;== update the email address $headers = "From: $email_from \r\n"; $headers .= "Reply-To: $visitor_email \r\n"; //Send the email! mail($to,$email_subject,$email_body,$headers); //done. redirect to thank-you page. header('Location: thank-you.html'); </code></pre> <p>I'm using this <code>IsInjected($str)</code> function to validate email addresses:</p> <pre><code>// Function to validate against any email injection attempts function IsInjected($str) { $injections = array('(\n+)', '(\r+)', '(\t+)', '(%0A+)', '(%0D+)', '(%08+)', '(%09+)' ); $inject = join('|', $injections); $inject = "/$inject/i"; if(preg_match($inject,$str)) { return true; } else { return false; } } ?&gt; </code></pre>
[]
[ { "body": "<p>In your first validation, I think you forgot to exit, you probably meant:</p>\n\n<pre><code>if(!isset($_POST['submit']))\n{\n //This page should not be accessed directly. Need to submit the form.\n echo \"error; you need to submit the form!\";\n exit;\n}\n</code></pre>\n\n<p>To validate email addresses, you can use the <code>filter_var</code> method, like this:</p>\n\n<pre><code>function is_valid_email($str) {\n return filter_var($str, FILTER_VALIDATE_EMAIL);\n}\n</code></pre>\n\n<p>For example:</p>\n\n<pre><code>function check_email($email) {\n printf(\"checking '%s': %s\\n\", $email, is_valid_email($email) ? 'OK' : 'INVALID');\n}\ncheck_email('joe@example.com');\ncheck_email('bogus');\n</code></pre>\n\n<p>will output:</p>\n\n<pre><code>checking 'joe@example.com': OK\nchecking 'bogus': INVALID\n</code></pre>\n\n<p>For more details and (caveats!), <a href=\"http://www.php.net/manual/en/function.filter-var.php\" rel=\"nofollow\">see the docs</a>. Also <a href=\"http://www.php.net/manual/en/filter.examples.validation.php\" rel=\"nofollow\">some more examples here</a>.</p>\n\n<p>Your original <code>IsInjected</code> method might still be useful for other purposes, that's why I created a new method for validating emails. If you keep it I would rename it to <code>hasInjectedChars</code> or <code>has_injected_chars</code>. And these lines can be improved:</p>\n\n<blockquote>\n<pre><code> if(preg_match($inject,$str))\n {\n return true;\n }\n else\n {\n return false;\n }\n</code></pre>\n</blockquote>\n\n<p>you could write simply:</p>\n\n<pre><code>return preg_match($inject, $str);\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-05-09T01:29:22.680", "Id": "86659", "Score": "0", "body": "should I get rid of this: `// Function to validate against any email injection attempts\nfunction IsInjected($str)\n{\n $injections = array('(\\n+)',\n '(\\r+)',\n '(\\t+)',\n '(%0A+)',\n '(%0D+)',\n '(%08+)',\n '(%09+)'\n );\n $inject = join('|', $injections);\n $inject = \"/$inject/i\";\n if(preg_match($inject,$str))\n {\n return true;\n }\n else\n {\n return false;\n }\n}` and replace it with this: `function is_valid_email($str) {\n return filter_var($str, FILTER_VALIDATE_EMAIL);\n}`" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-05-09T03:46:42.337", "Id": "86674", "Score": "0", "body": "I inserted the filter_var method as you suggested and tested it. It seems I can write anything in the form email input box and it will submit it and goes through. I wonder why that happens?" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-05-09T05:32:14.307", "Id": "86681", "Score": "0", "body": "I updated my post with more examples and explanation. I don't see how it's possible that `is_valid_email` would not work. I tested and works for me (see the example in my post). Btw `filter_var` was introduced in PHP 5.2.0, make sure your PHP is recent enough." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-05-09T06:20:38.887", "Id": "86685", "Score": "0", "body": "thanks again. Just want to make sure I am doing this right, pls advise: 1, I add this to the script: function is_valid_email($str) {\n return filter_var($str, FILTER_VALIDATE_EMAIL);\n} right above the line: function IsInjected($str) 2, I keep the isInjected method but rename it: has_injected_chars Is this what I have to do? if so, then I just test it by typing something into the form email box and submit it. If this works, what should happen after I submit, how do I know it worked exactly?" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-05-09T06:26:47.260", "Id": "86686", "Score": "0", "body": "And change `if(IsInjected($visitor_email))` to: `if(!is_valid_email($visitor_email))`. Notice the `!` there, so that you will exit if the email is NOT valid. After this, invalid emails shouldn't work." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-05-09T07:13:35.103", "Id": "86690", "Score": "0", "body": "now it doesnt work even with a valid email address, nothing happens, no error msg just a blank page after I submit" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-05-09T07:16:11.860", "Id": "86691", "Score": "0", "body": "I guess I should post the the full code again and the html form as well but I can not do that in the comment section here, this is my first time posting here so I am still not sure how it works" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-05-09T07:25:22.507", "Id": "86692", "Score": "0", "body": "@JoeRay keep in mind that Code Review is about advising on working code, not troubleshooting. If your code doesn't work and you don't know why, Stack Overflow is the place, not here." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-05-09T09:05:05.247", "Id": "86703", "Score": "0", "body": "@janosn thanks again, the original code I posted works, I just wanted to get a review on the code security" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-05-09T09:34:27.640", "Id": "86706", "Score": "0", "body": "If the original code works, I don't see how these changes could break it. The end result should be the same, but with less and cleaner code ;-) No?" } ], "meta_data": { "CommentCount": "10", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-05-08T23:26:07.923", "Id": "49283", "ParentId": "49282", "Score": "3" } }, { "body": "<p>Just a short answer, because I've already posted a number of detailed reviews that deal with mail injection.</p>\n\n<p>To validate an email address, all you really need to do is this:</p>\n\n<pre><code>if (!filter_var($email, FILTER_VALIDATE_EMAIL))\n throw new RuntimeException('invalid email address');\n</code></pre>\n\n<p>Optionally sanitizing that same email address first, to remove some, possibly harmful characters:</p>\n\n<pre><code>$email = filter_var($email, FILTER_SANITIZE_EMAIL);\n</code></pre>\n\n<p>That said, checking the email for dangerous characters is all very well, but don't forget about the rest of the user input. I'm not going to repeat myself here, just a couple of links to previous answers that deal with mail injection in detail:</p>\n\n<ul>\n<li><a href=\"https://codereview.stackexchange.com/questions/41129/php-form-review/41318#41318\">PHP form with bot deterrent</a></li>\n<li><a href=\"https://codereview.stackexchange.com/questions/40766/security-of-a-contact-us-form/40834#40834\">Security of a &quot;contact us&quot; form</a></li>\n<li><a href=\"https://codereview.stackexchange.com/questions/36330/critique-sanitized-user-email-php-script/36354#36354\">Critique sanitized user email PHP Script</a></li>\n</ul>\n\n<p>And a fairly detailed article on this topic <a href=\"http://www.codeproject.com/Articles/428076/PHP-Mail-Injection-Protection-and-E-Mail-Validatio\" rel=\"nofollow noreferrer\">can be found here</a>. It discusses libs and tools that are already out there, free for you to use. It shows their features and, more importantly, the caveats.</p>\n\n<p>On your code:</p>\n\n<pre><code>if (!isset($_POST['submit']))\n echo '';\n</code></pre>\n\n<p>This basically checks if the form was submitted, but if it wasn't your code still is executed as if the form <em>was</em> posted. Don't do that. Either redirect, throw an exception or <code>exit</code>.<br>\n<code>isset</code> is indeed the best way to check if a post parameter exists, which is why it's odd to see that you don't check the other paremeters:</p>\n\n<pre><code>$name = $_POST['name'];\n</code></pre>\n\n<p>Should be:</p>\n\n<pre><code>$name = !isset($_POST['name']) ? null : $_POST['name'];\n</code></pre>\n\n<p>and so on. If you don't put that <code>isset</code> language construct (not a function, constructs are faster), then your code might emit notices:</p>\n\n<pre><code>$foo = array();\necho $foo['nonExistantIndex'];\n</code></pre>\n\n<p>Will issue a notice, because you're trying to access a non-existing index. to see the notices, set your ini file to the only correct development settings:</p>\n\n<pre><code>display_errors=1\nerror_reporting=E_STRICT | E_ALL\n</code></pre>\n\n<p>that way, any problem that exists in your code will be visible to you. This enables you to develop better code. Good practice should be the default/norm, not the goal.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-05-09T11:46:31.910", "Id": "49327", "ParentId": "49282", "Score": "1" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-05-08T23:18:26.417", "Id": "49282", "Score": "5", "Tags": [ "php", "security", "form", "validation", "email" ], "Title": "Possible security issues in email validation" }
49282
<p>I've made a prime number generator (for Project Euler). It uses Euler's Sieve (a modified Sieve of Eratosthenes), with a mod 30 step. I'd like to reduce the memory consumption to 4/15 what it currently is by keeping a boolean array only for the possibly prime remainders of 30. I can't get it to work and also fear that this will slow down the program.</p> <p>I've used</p> <pre><code>n[f/30*8+[zeroes, except 1,2,3,4,5,6,7 at 7,11,13,17,19,23,29][f%30]] </code></pre> <p>which seemed to not filter out any composite numbers. How can I make this work and what other optimizations (aside from increasing the mod) can you suggest? I need the primes up to about two billion.</p> <pre><code>//pes30.cxx #include &lt;vector&gt; #include &lt;algorithm&gt; #ifndef _pes30_cxx_ #define _pes30_cxx_ typedef unsigned long long big; const int offsets[]={6,4,2,4,2,4,6,2}; //fill a given vector with all primes under some value: void sievePrimes(big max, std::vector&lt;big&gt; &amp;p){ big multiple; bool n[max];//array of whether or not each number is prime (30/8 too big!) p={2,3,5};//because the sieve skips all multiples of 2,3, and 5, start with them. for(big i=0; i&lt;max; ++i)//initialize the array n[i]=true; //for every number marked prime less than max, mark its multiples with // every number still marked prime over it as composite. for(big i=7, step=1; i&lt;=max; i+=offsets[step], ++step==8?step=0:0){ if(!n[i])//if i is not prime continue; p.push_back(i);//add i to the list of primes //finds every multiple of i and a (still marked) prime greater than i for(big j=i, step2=step; j&lt;=max/i; j+=offsets[step2], ++step2==8?step2=0:0){ if(!n[j])//skip nonprimes continue; multiple=j*i;//begin at i^2 do{ n[multiple]=false; }while((multiple*=j) &lt;= max); } } } //test if a number is prime by searching a given list of primes for it: inline bool isPrime(big n, std::vector&lt;big&gt; p){ return std::binary_search(p.begin(), p.end(), n); } #endif </code></pre> <p>Note that this is a re-post with ... proper formatting, and while I appreciate critiques of my coding style, I would also appreciate some advice about improving the array as well (storing only numbers n with n mod 30 prime or 1, but not 2, 3, or 5).</p>
[]
[ { "body": "<p>You've posted some code, which shows what you told the computer to do.\nAnd it even has some comments.\nHonestly, that's a lot better than the average question.</p>\n\n<p>Then you realize that we aren't going to understand this blob of code, so you use phrases like \"I made\" and \"It uses Euler's Sieve\" and \"I need the primes up to about two billion\".\nLook, that's super-useful information, and I'm glad you told me that, but I'm going to suggest that in the future you put information about who wrote the program, the name of the algorithm you use, etc.\ninto comments embedded in the program:</p>\n\n<pre><code>// pes30.cxx\n// prime number generator for Project Euler\n// Print all the primes up to 2x10^9.\n// 2014-05-08: started by hacatu\n// implementation of Euler's sieve (a modified Sieve of Eratosthenes)\n// http://en.wikipedia.org/wiki/Euler%27s_sieve\n// using wheel factorization with a wheel of size 30 to reduce memory requirements\n// http://en.wikipedia.org/wiki/wheel_factorization\n</code></pre>\n\n<p>So is there some reason not to use <a href=\"http://primesieve.org/\" rel=\"nofollow\">http://primesieve.org/</a> ?\nHave you gotten it working without the <a href=\"http://en.wikipedia.org/wiki/wheel_factorization\" rel=\"nofollow\">wheel factorization</a> optimization?\nHave you tried looking at only odd prime candidates (wheel of size 2) or a small wheel of size 6 or 12 ?</p>\n\n<p>I am mystified by the 3 lines</p>\n\n<pre><code>bool n[max];//array of whether or not each number is prime (30/8 too big!)\nfor(big i=0; i&lt;max; ++i)//initialize the array\n n[i]=true;\n</code></pre>\n\n<p>The \"max\" is the largest number you want to check for possibly being prime during this run of the program, right?\nSo that line eats a bunch of memory -- one bool per each number from 0 to max, perhaps 2 million bool values.</p>\n\n<p>I thought you were going to use wheel factorization to reduce memory requirements?</p>\n\n<p>I think you want to replace those 3 lines with something more like the following 2 lines of code:</p>\n\n<pre><code>big blocks_of_30_values = (max/30)+1;\n// For example, when max is 38, max/30 gives 1, but we need 2 blocks: 0..29 and 30..59.\n// In each block of 30 values under consideration\n// (i.e, the block 30..59, the block 60..89, the block 90..119, etc.),\n// after using the wheel factorization to eliminate multiples of 2 and 3 and 5,\n// there are only 8 potential candidates left in each block.\n// So store each block in a single unsigned char:\n// and initialize the array to all 1 bits (1=candidate prime, 0=definitely composite)\nstd::vector&lt;unsigned char&gt; candidatePrime( blocks_of_30_values, 0xFF );\n</code></pre>\n\n<p>So when max is 2 billion, we only allocate (max/30) = under 70 million chars, or roughly 533 million bits.</p>\n\n<p>It might make your program easier to read if you have named functions for converting a bit in the array to the integer value it represents and vice versa:</p>\n\n<pre><code>// the bit at the n'th bit of the m'th byte of the candidatePrime array\n// represents what value?\nbig the_value( big block_number, int bit_number ){\n const int offset[] = { 1, 7, 11, 13, 17, 19, 23, 29 };\n int this_offset = offset[bit_number];\n return( (30*block_number) + this_offset );\n}\n// the given integer value n corresponds to\n// what (block_number, bit_number) of the candidatePrime array?\n// assumes that n is *not* a multiple of 2, 3, or 5.\nbig block_number( big integer_value ){\n return (integer_value/30);\n}\nint bit_number( big integer_value ){\n // as long as the integer_value is not a multiple of 2, 3, or 5,\n // this function should never return '9'.\n // translate a value 0..29 into the corresponding bit number 0..7\n const int bit_offset[] = {\n 9, 0, 9, 9, 9, 9,\n 9, 1, 9, 9, 9, 2,\n 9, 3, 9, 9, 9, 4,\n 9, 5, 9, 9, 9, 6\n 9, 7, 9, 9, 9, 7\n };\n return bit_offset[ integer_value % 30 ];\n}\n</code></pre>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-05-09T06:46:26.643", "Id": "49302", "ParentId": "49284", "Score": "4" } }, { "body": "<p>I have fixed the vector to use one thirtieth the memory by using offsets and also by using a <code>vector&lt;boolean&gt;</code>, which is optimized to use every bit. This caused a 50% slowdown, but it is worth it for high max values (because the max value can now be 30 times as great), and I'm sure I can reduce this.</p>\n\n<p>I did not use the primesieve.org because I did not know about it. It is far better than my program. It generates the primes under 1 billion in 0.169s, my program takes 18.539s.</p>\n\n<p>Here is my updated program, now with a sensibly sized vector (and even more overworked for loop increments):</p>\n\n<pre><code>// pes30.cxx\n// prime number generator for Project Euler\n// Print all the primes up to 2x10^9.\n// 2014-05-08: started by hacatu\n// implementation of Euler's sieve (a modified Sieve of Eratosthenes)\n// http://en.wikipedia.org/wiki/Euler%27s_sieve\n// using wheel factorization with a wheel of size 30 to reduce memory requirements\n// http://en.wikipedia.org/wiki/wheel_factorization\n#include &lt;vector&gt;\n#include &lt;algorithm&gt;\n#include &lt;cstdint&gt;\n#include &lt;cmath&gt;\n#ifndef _pes30_cxx_\n#define _pes30_cxx_\nusing namespace std;\nconst int offsets[]={6,4,2,4,2,4,6,2};//steps in the wheel 1,7,11,13,17,19,23,29,1...\nconst int bool_offsets[]={//used to find a number's spot on the wheel, for accessing its primality in the vector\n9, 0, 9, 9, 9, 9,//the nines should never be accessed\n9, 1, 9, 9, 9, 2,\n9, 3, 9, 9, 9, 4,\n9, 5, 9, 9, 9, 6,\n9, 9, 9, 9, 9, 7\n};\n//create a vector with all primes under some value:\ninline vector&lt;uint64_t&gt; sievePrimes(uint64_t max){\n uint64_t multiple;\n vector&lt;bool&gt; n(max/30*8+8, true);//vector of whether every number relatively prime to 30 is still a candidate prime.\n //8 bits are needed for every 30 numbers (since 8 are relatively prime with 30), so max/30*8, plus 8 because max/30 rounds down.\n vector&lt;uint64_t&gt; primes={2,3,5};//because the sieve skips all multiples of 2,3, and 5, start with them.\n //for every number marked prime less than max, mark its multiples with\n //every number still marked prime over it as composite.\n int r=sqrt(max);\n for(uint64_t i=1, p=7, step=1; p &lt;= max; ++i, p += offsets[step], ++step == 8 ? step=0:0){\n if(!n[i])//if p is not prime (using i for the index holding the primality of p, to avoid computing the index for every number)\n continue;\n primes.push_back(p);//add p to the list of primes\n //finds every multiple of i and a (still marked) prime greater than i\n for(uint64_t j=i, p2=p, step2=step; p2 &lt;= max/p; ++j, p2 += offsets[step2], ++step2 == 8 ? step2=0:0){\n if(!n[j])//skip nonprimes\n continue;\n multiple=p*p2;\n do{\n n[multiple/30*8 + bool_offsets[ multiple%30 ]]=false;\n }while((multiple*=p) &lt;= max);\n }\n }\n return primes;\n}\n//test if a number is prime by searching a given list of primes for it:\ninline bool isPrime(uint64_t n, vector&lt;uint64_t&gt; primes){\n return std::binary_search(primes.begin(), primes.end(), n);\n}\n#endif\n</code></pre>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-05-29T01:01:50.660", "Id": "51959", "ParentId": "49284", "Score": "2" } } ]
{ "AcceptedAnswerId": "49302", "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-05-08T23:27:44.347", "Id": "49284", "Score": "5", "Tags": [ "c++", "array", "primes", "sieve-of-eratosthenes" ], "Title": "Reduce Prime Sieve Memory Consumption 2" }
49284
<p>When I had to create a fixed header on scroll, I found a few examples on Stack Overflow but they were terrible in the sense that they relied on a fixed page height. Have a look at what I created which does not rely on a wrapper around the header and the content. </p> <p><strong>Default</strong></p> <p><img src="https://i.stack.imgur.com/W01rQ.png" alt="default"></p> <p><strong>On Scroll</strong></p> <p><img src="https://i.stack.imgur.com/AAguI.png" alt="enter image description here"></p> <p>Demo on <a href="http://codepen.io/JGallardo/pen/lJoyk" rel="nofollow noreferrer">CodePen</a>.</p> <hr> <p><strong>HTML</strong></p> <pre class="lang-html prettyprint-override"><code>&lt;header&gt; &lt;div class="header-banner"&gt; &lt;a href="/" class="logo"&gt;&lt;/a&gt; &lt;h1&gt;Art in Finland&lt;/h1&gt; &lt;/div&gt; &lt;nav&gt; &lt;ul&gt; &lt;li&gt;&lt;a href="/archive"&gt;Archive&lt;/a&gt;&lt;/li&gt; &lt;li&gt;&lt;a href="/events"&gt;Events&lt;/a&gt;&lt;/li&gt; &lt;li&gt;&lt;a href="/contact"&gt;Contact&lt;/a&gt;&lt;/li&gt; &lt;ul&gt; &lt;/nav&gt; &lt;/header&gt; </code></pre> <p><strong>CSS</strong></p> <pre class="lang-css prettyprint-override"><code>header { height:360px; z-index:10; } .header-banner { background-color: #333; background-image: url('http://37.media.tumblr.com/8b4969985e84b2aa1ac8d3449475f1af/tumblr_n3iftvUesn1snvqtdo1_1280.jpg'); background-position: center -300px; background-repeat: no-repeat; background-size: cover; width: 100%; height: 300px; } header .logo { background-color: transparent; background-image: url('http://www.futhead.com/static//img/14/clubs/1887.png'); background-position: center top; background-repeat: no-repeat; position: absolute; top: 72px; height: 256px; width: 256px; } header h1 { position: absolute; top: 72px; left: 240px; color: #fff; } .fixed-header { position: fixed; top:0; left:0; width: 100%; } nav { width:100%; height:60px; background: #292f36; postion:fixed; z-index:10; } nav ul { list-style-type: none; margin: 0 auto; padding-left:0; text-align:right; width: 960px; } nav ul li { display: inline-block; line-height: 60px; margin-left: 10px; } nav ul li a { text-decoration: none; color: #a9abae; } /* demo */ .content{ width: 960px; max-width: 100%; margin:0 auto; padding-top: 60px; } article { width: 720px; float: left; } article p:first-of-type { margin-top: 0; } aside { width: 120px; float: right; } aside img { max-width: 100%; } body { color: #292f36; font-family: helvetica; line-height: 1.6; } </code></pre> <p><strong>jQuery</strong></p> <pre class="lang-js prettyprint-override"><code>$(window).scroll(function(){ if ($(window).scrollTop() &gt;= 300) { $('nav').addClass('fixed-header'); } else { $('nav').removeClass('fixed-header'); } }); </code></pre>
[]
[ { "body": "<h1>HTML</h1>\n\n<p>You might want to <code>id</code> that <code>nav</code>. It's because it might not be the only <code>nav</code> on the page, and the JS will pick it up and add <code>.fixed-header</code> to it. Something like:</p>\n\n<pre><code>&lt;nav id=\"main-navigation\"&gt;\n</code></pre>\n\n<h1>CSS</h1>\n\n<p>On the CSS part, if only the <code>nav</code> gets a the <code>.fixed-header</code> class, you might want to consider declaring the CSS for <code>.fixed-header</code> like:</p>\n\n<pre><code>nav.fixed-header{...}\n</code></pre>\n\n<p>That way, it only applies to <code>nav</code> with that class. Scenario: You have another header that wants to be fixed at a certain position. It's logical to name it <code>.fixed-header</code> but it's not a <code>nav</code>. If you didn't do it this way, this style will also apply to the sidebar.</p>\n\n<h1>JS</h1>\n\n<p>It would be better if you cached the value of jQuery DOM pickups, rather than re-fetching them every time the scroll event fires. Additionally, as mentioned in the HTML section, it's better to identify that <code>&lt;nav&gt;</code>. This time, it's for performance.</p>\n\n<p>When you do <code>$('nav')</code>, what jQuery does is pick up all <code>&lt;nav&gt;</code> in the page, and stores them in an array. When you call functions on it, jQuery loops through each one of them, and applies the function. You would want to avoid that looping, and so, you must limit what is being looped by being more specific with your query. Querying an <code>id</code> would be best since <code>id</code> should only happen once on the page.</p>\n\n<pre><code>var $window = $(window);\nvar nav = $('#main-navigation');\n$window.scroll(function(){\n if ($window.scrollTop() &gt;= 300) {\n nav.addClass('fixed-header');\n }\n else {\n nav.removeClass('fixed-header');\n }\n});\n</code></pre>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-05-09T19:35:53.563", "Id": "49367", "ParentId": "49285", "Score": "12" } } ]
{ "AcceptedAnswerId": "49367", "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-05-08T23:39:51.717", "Id": "49285", "Score": "7", "Tags": [ "jquery", "html", "css", "html5" ], "Title": "CSS and HTML5 for this fixed header on scroll" }
49285
<p>I took a little time and wrote the following code to produce enigma encryption. I don't normally write code in C so I would like to get feedback on the way it has been structured and any issues a more experienced C programmer might spot in the way I used structs, command line parsing, and the indexing around the strings to replicate the turning of rotors.</p> <p>I did not create a separate header file since the code is so short I thought it would be best to just have a single file.</p> <pre><code>#include &lt;ctype.h&gt; #include &lt;stdlib.h&gt; #include &lt;stdio.h&gt; #include &lt;string.h&gt; #define ROTATE 26 const char *alpha = "ABCDEFGHIJKLMNOPQRSTUVWXYZ"; const char *rotor_ciphers[] = { "EKMFLGDQVZNTOWYHXUSPAIBRCJ", "AJDKSIRUXBLHWTMCQGZNPYFVOE", "BDFHJLCPRTXVZNYEIWGAKMUSQO", "ESOVPZJAYQUIRHXLNFTGKDCMWB", "VZBRGITYUPSDNHLXAWMJQOFECK", "JPGVOUMFYQBENHZRDKASXLICTW", "NZJHGRCXMYSWBOUFAIVLPEKQDT", "FKQHTLXOCBJSPDZRAMEWNIUYGV" }; const char *rotor_notches[] = {"Q", "E", "V", "J", "Z", "ZM", "ZM", "ZM"}; const char *rotor_turnovers[] = {"R", "F", "W", "K", "A", "AN", "AN", "AN"}; const char *reflectors[] = { "EJMZALYXVBWFCRQUONTSPIKHGD", "YRUHQSLDPXNGOKMIEBFZCWVJAT", "FVPJIAOYEDRZXWGCTKUQSBNMHL" }; struct Rotor { int offset; int turnnext; const char* cipher; const char* turnover; const char* notch; }; struct Enigma { int numrotors; const char* reflector; struct Rotor rotors[8]; }; /* * Produce a rotor object * Setup the correct offset, cipher set and turn overs. */ struct Rotor new_rotor(struct Enigma *machine, int rotornumber, int offset) { struct Rotor r; r.offset = offset; r.turnnext = 0; r.cipher = rotor_ciphers[rotornumber - 1]; r.turnover = rotor_turnovers[rotornumber - 1]; r.notch = rotor_notches[rotornumber - 1]; machine-&gt;numrotors++; return r; } /* * Return the index position of a character inside a string * if not found then -1 **/ int str_index(const char * str, int character) { char * pos; int index; pos = strchr(str, character); // pointer arithmetic if (pos){ index = (int) (pos - str); } else { index = -1; } return index; } /* * Cycle a rotor's offset but keep it in the array. */ void rotor_cycle(struct Rotor *rotor) { rotor-&gt;offset++; rotor-&gt;offset = rotor-&gt;offset % ROTATE; // Check if the notch is active, if so trigger the turnnext if(str_index(rotor-&gt;turnover, alpha[rotor-&gt;offset]) &gt;= 0) { rotor-&gt;turnnext = 1; } } /* * Pass through a rotor, right to left, cipher to alpha. * returns the exit index location. */ int rotor_forward(struct Rotor *rotor, int index) { // In the cipher side, out the alpha side index = (index + rotor-&gt;offset) % ROTATE; index = str_index(alpha, rotor-&gt;cipher[index]); index = (ROTATE + index - rotor-&gt;offset) % ROTATE; return index; } /* * Pass through a rotor, left to right, alpha to cipher. * returns the exit index location. */ int rotor_reverse(struct Rotor *rotor, int index) { // In the cipher side, out the alpha side index = (index + rotor-&gt;offset) % ROTATE; index = str_index(rotor-&gt;cipher, alpha[index]); index = (ROTATE + index - rotor-&gt;offset) % ROTATE; return index; } /* * Run the enigma machine **/ int main(int argc, char* argv[]) { struct Enigma machine = {}; // initialized to defaults int i, character, index; // Command line options int opt_debug = 0; int opt_r1 = 3; int opt_r2 = 2; int opt_r3 = 1; int opt_o1 = 0; int opt_o2 = 0; int opt_o3 = 0; // Command Parsing for (i = 1; i &lt; argc; i++){ if (strcmp(argv[i], "-d") == 0) opt_debug = 1; if (strcmp(argv[i], "-r") == 0) { opt_r1 = atoi(&amp;argv[i+1][0])/100; opt_r2 = atoi(&amp;argv[i+1][1])/10; opt_r3 = atoi(&amp;argv[i+1][2]); i++; } if (strcmp(argv[i], "-o") == 0) { opt_o1 = atoi(&amp;argv[i+1][0])/100; opt_o2 = atoi(&amp;argv[i+1][1])/10; opt_o3 = atoi(&amp;argv[i+1][2]); i++; } } if(opt_debug) { printf("Rotors set to : %d %d %d \n", opt_r3, opt_r2, opt_r1); printf("Offsets set to: %d %d %d \n", opt_o3, opt_o2, opt_o1); } // Configure an enigma machine machine.reflector = reflectors[1]; machine.rotors[0] = new_rotor(&amp;machine, opt_r1, opt_o1); machine.rotors[1] = new_rotor(&amp;machine, opt_r2, opt_o2); machine.rotors[2] = new_rotor(&amp;machine, opt_r3, opt_o3); while((character = getchar())!=EOF) { if (!isalpha(character)) { printf("%c", character); continue; } character = toupper(character); // Plugboard index = str_index(alpha, character); if(opt_debug) { printf("Input character ******** %c \n", character); } // Cycle first rotor before pushing through, rotor_cycle(&amp;machine.rotors[0]); // Double step the rotor if(str_index(machine.rotors[1].notch, alpha[machine.rotors[1].offset]) &gt;= 0 ) { rotor_cycle(&amp;machine.rotors[1]); } // Stepping the rotors for(i=0; i &lt; machine.numrotors - 1; i++) { character = alpha[machine.rotors[i].offset]; if(machine.rotors[i].turnnext) { machine.rotors[i].turnnext = 0; rotor_cycle(&amp;machine.rotors[i+1]); if(opt_debug) { printf("Cycling rotor :%d \n", i+1); printf("Turnover rotor :%d \n", i); printf("Character is :%c \n", character); } } } // Pass through all the rotors forward for(i=0; i &lt; machine.numrotors; i++) { index = rotor_forward(&amp;machine.rotors[i], index); } // Pass through the reflector if(opt_debug) { printf("Into reflector %c\n", alpha[index]); printf("Out of reflector %c\n", machine.reflector[index]); } // Inbound character = machine.reflector[index]; // Outbound index = str_index(alpha, character); if(opt_debug) { printf("Index out of reflector %i\n", index); printf("-&gt;Reflected character %c \n", character); } // Pass back through the rotors in reverse for(i = machine.numrotors - 1; i &gt;= 0; i--) { index = rotor_reverse(&amp;machine.rotors[i], index); } // Pass through Plugboard character = alpha[index]; if(opt_debug) { printf("Plugboard index %d \n", index); printf("Output character ******** "); } putchar(character); if(opt_debug) printf("\n\n"); } return 0; } </code></pre>
[]
[ { "body": "<p>During the command line parsing I would suggest using <code>else</code></p>\n\n<p>This</p>\n\n<pre><code> if (strcmp(argv[i], \"-d\") == 0) opt_debug = 1;\n if (strcmp(argv[i], \"-r\") == 0) {\n</code></pre>\n\n<p>Would be better written as</p>\n\n<pre><code> if (strcmp(argv[i], \"-d\") == 0) opt_debug = 1;\n else if (strcmp(argv[i], \"-r\") == 0) {\n ....\n</code></pre>\n\n<p>To avoid unnecessary checks. (If it is -d then it cannot also be -r so why check?).</p>\n\n<p>I would suggest you remove the <code>i++</code> in the middle of the loop. This is a problem because if someone only enters -r as a single command line argument then this line will access invalid memory. <code>if (strcmp(argv[i], \"-o\")...</code></p>\n\n<pre><code>/* argc = 2, argv[1] = \"-r\" */\nfor (i = 1; i &lt; argc; i++){\n if (strcmp(argv[i], \"-d\") == 0) opt_debug = 1;\n if (strcmp(argv[i], \"-r\") == 0) {\n opt_r1 = atoi(&amp;argv[i+1][0])/100;\n opt_r2 = atoi(&amp;argv[i+1][1])/10;\n opt_r3 = atoi(&amp;argv[i+1][2]);\n i++; /* i = 2 */\n }\n /* There is no argv[2]! */\n if (strcmp(argv[i], \"-o\") == 0) {\n</code></pre>\n\n<p>It makes your code simpler if you leave the loop mechanics to the loop declaration <code>for (...)</code> and not mess around with the loop counter inside the loop.</p>\n\n<p>If you're expecting an argument after -r you should explicitly check that it exists.</p>\n\n<pre><code> /* Is i+1 &lt; argc at this point? */\n opt_r1 = atoi(&amp;argv[i+1][0])/100;\n opt_r2 = atoi(&amp;argv[i+1][1])/10;\n opt_r3 = atoi(&amp;argv[i+1][2]);\n</code></pre>\n\n<p>And the same goes for the length of these arguments. If argv[i+1] exists but is only 1 character long then you will be accessing invalid memory on the third atoi line. Use strlen to make sure the argument is as long as you expect it or check for the end of string '\\0' character before each atoi.</p>\n\n<p>On a style note, as someone reading your code I would ask that you not alternate between <code>char* c</code>, <code>char * c</code> and <code>char *c</code>. Like everything related to code style there is no \"right\" way or \"wrong\" way but it will help your readers if you pick a style and stick to it.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-05-09T13:06:39.113", "Id": "86731", "Score": "0", "body": "If argv[i] is \"-d\" then why should we check if it is also \"-r\"? I feel like I've explained my logic quite extensively. Could you please expand on \"it's wrong\"?" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-05-09T14:15:58.320", "Id": "86749", "Score": "0", "body": "Adjusting the loop counter is so that I can get the number following the flag and then go past it.. the command would look like this `enigma -r123 -o123` where r is the rotor and o is the offset to start with. I will look into it more." } ], "meta_data": { "CommentCount": "2", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-05-09T09:25:42.127", "Id": "49313", "ParentId": "49288", "Score": "3" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-05-09T00:39:30.333", "Id": "49288", "Score": "3", "Tags": [ "performance", "c", "cryptography", "enigma-machine" ], "Title": "Structure and style of Enigma Machine" }
49288