body
stringlengths
25
86.7k
comments
list
answers
list
meta_data
dict
question_id
stringlengths
1
6
<p>I'm trying to learn C++ with Eigen. Here's my attempt at computing <a href="http://stat.ethz.ch/R-manual/R-patched/library/stats/html/mahalanobis.html" rel="nofollow">Mahalanobis</a> distances of a set of points <code>x</code> with respect to a sub-matrix <code>xs</code>.</p> <p>The aim of the project is to turn an R code describing a statistical procedure in C++ (and in the process to learn a bit about numerical computing in c++). Some of these functions will have to be called literally 10,000 of times so the efficiency part is a bit important.</p> <p>Is this an efficient implementation of what I'm trying to do in Eigen (the code does what I want)? Can it be improved? What are the beginner's mistake that I'm doing? (in the application I have in mind, <code>x</code> is an imported matrix, so 30 and 3 are only known at runtime)</p> <pre><code>#include &lt;iostream&gt; #include &lt;Eigen/Dense&gt; #include &lt;fstream&gt; #include &lt;Eigen/Cholesky&gt; using namespace Eigen; using namespace std; VectorXd mah(MatrixXd&amp; x, MatrixXd&amp; xs){ int ps = xs.cols(), ns=xs.rows(); RowVectorXd xs_mean=xs.colwise().sum()/ns; MatrixXd xs_cen = (xs.rowwise()-xs_mean); MatrixXd x_cen = (x.rowwise()-xs_mean); MatrixXd w = xs_cen.transpose()*xs_cen/(ns-1); MatrixXd b = MatrixXd::Identity(ps,ps); w.ldlt().solveInPlace(b); x_cen = (x_cen*b).cwiseProduct(x_cen); return x_cen.rowwise().sum(); } MatrixXd sub(MatrixXd&amp; x, VectorXi&amp; s){ int p = x.cols(); MatrixXd xs(p+1,p); for(int i=0;i&lt;s.size();i++){ xs.row(i)=x.row(s(i)); } return xs; } int main(){ MatrixXd x = MatrixXd::Random(30,3); VectorXi s = (VectorXd::Random(p+1)*n).cast&lt;int&gt;(); MatrixXd xs = sub(x,s); ofstream file("test1.txt"); if (file.is_open()){ file &lt;&lt; x &lt;&lt; '\n'; } cout &lt;&lt; "m" &lt;&lt; endl &lt;&lt; mah(x,xs) &lt;&lt; endl; cout &lt;&lt; "s" &lt;&lt; endl &lt;&lt; s &lt;&lt; endl; return 0; } </code></pre>
[]
[ { "body": "<h3>Is it effecient</h3>\n\n<p>Imposable to tell as we have no idea how stuff in Eigen is implemented.</p>\n\n<h3>Comments on code:</h3>\n\n<p>There should be some logic in the ordering of includes. So you can easily find ones that have been included or spot missing ones (or know where to put knew ones).</p>\n\n<pre><code>#include &lt;iostream&gt;\n#include &lt;Eigen/Dense&gt;\n#include &lt;fstream&gt;\n#include &lt;Eigen/Cholesky&gt;\n</code></pre>\n\n<p>This set seems to be completely random. Personally (though the exact orders does not matter and you can pick your own scheme) I put them in groups (so in this case there would be an Eigen group and a standard lib group). Then I order the groups most specific to most general. Within the groups I am less pedantic but usually it is alphabetical unless there is some good reason to use another scheme.</p>\n\n<pre><code>#include &lt;Eigen/Cholesky&gt;\n#include &lt;Eigen/Dense&gt;\n\n#include &lt;iostream&gt;\n#include &lt;fstream&gt; // I usually group all the stream stuff together\n // Then all containers then all the others in the standard lib.\n // \n</code></pre>\n\n<p>Avoid the using-directive. In non trivial programs it causes more problems than it is worth. For short programs the extra cost of prefixing objects (in terms of typing) is negligible so prefix your types and objects (don't be lazy). (I always use std::cout not cout). If you feel this is too much work then selectively bring types/objects into the current namespace with a using statement.</p>\n\n<pre><code>using namespace Eigen;\nusing namespace std;\n</code></pre>\n\n<ol>\n<li>Prefer to prefix types/objects with their namespace</li>\n<li><p>If you must selectively bring types/objects into current namespace</p>\n\n<p><code>using std::cout;\nusing std::endl;</code></p>\n\n<ul>\n<li>If you must do this then scope the <code>using</code> to minimize polution.</li>\n</ul></li>\n<li>Try to not use <code>using namespace X;</code></li>\n</ol>\n\n<p>Does <code>x</code> change in the following code? If not then pass by const reference to indicate that it is not modified.</p>\n\n<pre><code>VectorXd mah(MatrixXd&amp; x){\n</code></pre>\n\n<p>One variable per line:</p>\n\n<pre><code> int p = x.cols(), n=x.rows();\n</code></pre>\n\n<p>This is a nasty trick to temporarily comment out blocks.</p>\n\n<pre><code>/* ofstream file(\"test1.txt\");\n if (file.is_open()){\n file &lt;&lt; m &lt;&lt; '\\n';\n }\n/**/\n</code></pre>\n\n<p>It is so easily broken that I would avoid it.<br>\nIf you want to comment out a block then use #if 0</p>\n\n<pre><code>// To uncomment block just replace 0 with 1.\n#if 0\n ofstream file(\"test1.txt\");\n if (file.is_open()){\n file &lt;&lt; m &lt;&lt; '\\n';\n }\n#endif\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-02-29T14:28:46.627", "Id": "15075", "Score": "0", "body": "thank you! One question: to declar x as constant, i just do: 'const MatrixXd x = MatrixXd::Random(30,3);' or should i also modify something in the function? Best" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-02-29T14:31:43.347", "Id": "15076", "Score": "1", "body": "No. In the method do this: `VectorXd mah(MatrixXd const& x){` Here you are telling people that `mah()` will not alter x." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-02-29T14:34:31.970", "Id": "15078", "Score": "0", "body": "thanks it was not initially clear. By the way: for clarity i'm leaving the code above unchanged...but i'm following your guidelines in the version of the code on my computer. Thanks again for taking the time." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-02-29T15:45:37.097", "Id": "15085", "Score": "0", "body": "+1, but `using namespace X;` is a using-directive, not a using-declaration." } ], "meta_data": { "CommentCount": "4", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-02-29T14:19:48.213", "Id": "9556", "ParentId": "9554", "Score": "4" } }, { "body": "<h3>Efficiency</h3>\n<p>Seem fine ! It's a good idea to compute all input samples at once.</p>\n<p>If covariance matrix remains small (dim &lt;= 4), you may use <strong>inverse()</strong>.</p>\n<p>I was wondering whether the inverse is needed at all with your approach. I've tried to replace :</p>\n<pre><code>MatrixXd b = MatrixXd::Identity(ps,ps); \nw.ldlt().solveInPlace(b);\nx_cen = (x_cen*b).cwiseProduct(x_cen);\n</code></pre>\n<p>by</p>\n<pre><code>MatrixXd b = w.ldlt().solve(x_cen.transpose());\nx_cen = b.transpose().cwiseProduct(x_cen);\n</code></pre>\n<p>But crude benchmarking showed +20% of process time ! You may want to check with real data, since it highly depends on matrix dimensions.</p>\n<p>To trigger efficiency boost :</p>\n<ul>\n<li>Use floats instead of double (for SIMD)</li>\n<li>Enable the right flags (-fopenmp, -msse2 ...)</li>\n</ul>\n<h3>General review</h3>\n<p>Post compiling code ! In <code>test_Mahalahobis</code>, <code>n</code> and <code>p</code> are not defined.</p>\n<p>It is a better design to compute covariance matrix in a separate function. You may wish to obtain the distance in regard to a covariance matrix known once for all.</p>\n<p><em>Documentation</em> : if you don't do it for you, do it for the reviewers (and vice-versa).\nFor instance, says that there is one sample by row. And legible code starts with good names :</p>\n<ul>\n<li><strong>mah</strong> : meh !</li>\n<li><strong>sub</strong> : <strong>subset</strong> is less ambiguous, and not very long to type.</li>\n</ul>\n<h3>Cosmetic points</h3>\n<p>Replace</p>\n<pre><code> RowVectorXd xs_mean=xs.colwise().sum()/ns; //---\n RowVectorXd xs_mean=xs.colwise().mean(); //+++ Explicit and shorter\n\n x_cen = (x_cen*b).cwiseProduct(x_cen); //---Deprecated\n x_cen = (x_cen*b).array() * x_cen.array() ; //+++Array operations are element wise\n\n MatrixXd xs(p+1,p); //--- Implicit assumption\n MatrixXd xs(s.size(),p); //+++\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-02-29T22:35:03.697", "Id": "15125", "Score": "0", "body": "thanks for all these comments. I would up-vote more if i could." } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-02-29T21:58:05.283", "Id": "9573", "ParentId": "9554", "Score": "1" } } ]
{ "AcceptedAnswerId": "9573", "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-02-29T13:07:20.277", "Id": "9554", "Score": "3", "Tags": [ "c++", "beginner", "matrix", "eigen" ], "Title": "Implementation of Mahalanobis distances using Eigen" }
9554
<p>For flexing my newly acquired Django &amp; Python muscles, I have set up a mobile content delivery system via Wap Push (Ringtones, wallpapers, etc).</p> <p>The idea is that a keyword comes in from an sms via an URL, let's say the keyword is "LOVE1" and the program should search if this keyboard points to a Ringtone or an Image. For this I have created a parent model class called "Categoria" (Category) and two subclasses "Ringtone" and "Wallpaper". This subclasses have a variable called "archivo" (filename) which points to the actual path of the content.</p> <p>Dynpath is a dynamic URL which has been created to download the content, so it is available only for X amount of time. After that a Celery scheduled task deletes this dynamic URL from the DB.</p> <p>I have a piece which has "code smell" which I would like to have some input from everyone here.</p> <h2>Model</h2> <pre><code>class Contenido(models.Model): nombre = models.CharField(max_length=100) fecha_creacion = models.DateTimeField('fecha creacion') keyword = models.CharField(max_length=100) class Ringtone(Contenido): grupo = models.ManyToManyField(Artista) archivo = models.FileField(upload_to="uploads") def __unicode__(self): return self.nombre class Wallpaper(Contenido): categoria = models.ForeignKey(Categoria) archivo = models.ImageField(upload_to="uploads") def __unicode__(self): return self.nombre class Dynpath(models.Model): created = models.DateField(auto_now=True) url_path = models.CharField(max_length=100) payload = models.ForeignKey(Contenido) sms = models.ForeignKey(SMS) def __unicode__(self): return str(self.url_path) </code></pre> <h2>View</h2> <p>Here is my view which checks that the Dynamic URL exists and here is where the code (which works) gets a little suspicious/ugly:</p> <pre><code> def tempurl(request,hash): p = get_object_or_404(Dynpath, url_path=hash) try: fname = str(p.payload.wallpaper.archivo) except DoesNotExist: fname = str(p.payload.ringtone.archivo) fn = open(fname,'rb') response = HttpResponse(fn.read()) fn.close() file_name = os.path.basename(fname) type, encoding = mimetypes.guess_type(file_name) if type is None: type = 'application/octet-stream' response['Content-Type'] = type response['Content-Disposition'] = ('attachment; filename=%s') % file_name return response </code></pre> <p>I am talking explictitly this snippet:</p> <pre><code> try: fname = str(p.payload.wallpaper.archivo) except DoesNotExist: fname = str(p.payload.ringtone.archivo) </code></pre> <p>I would have loved to do something like:</p> <pre><code>fname = p.payload.archivo </code></pre> <p>But it would not let me do that, from the docs:</p> <p><em>Django will raise a FieldError if you override any model field in any ancestor model.</em></p> <p>I took a look at generics, but could not make it work with them. Any ideas on a better way of doing this?</p>
[]
[ { "body": "<p>You have 2 models (Ringtone extends Contenido). As I understand you store same <code>nombre</code>, <code>fecha_creacion</code>, <code>keyword</code> in both models and every update/delete/insert operation on the first model must be synchronized with another one. You can avoid this, make foreign key to base model:</p>\n\n<pre><code>class Contenido(models.Model):\n nombre = models.CharField(max_length=100)\n fecha_creacion = models.DateTimeField('fecha creacion')\n keyword = models.CharField(max_length=100)\n\nclass Ringtone(models.Model):\n contenido = models.ForeignKey(Contenido)\n grupo = models.ManyToManyField(Artista)\n archivo = models.FileField(upload_to=\"uploads\")\n\nclass Wallpaper(models.Model):\n contenido = models.ForeignKey(Contenido) \n categoria = models.ForeignKey(Categoria)\n archivo = models.ImageField(upload_to=\"uploads\")\n</code></pre>\n\n<p>Then in your <strong>Views</strong></p>\n\n<pre><code>def tempurl(request,hash):\n p = get_object_or_404(Dynpath, url_path=hash)\n try:\n obj=Wallpaper.objects.get(contenido_id=p.id)\n except Wallpaper.DoesNotExist:\n try:\n obj=Ringtone.objects.get(contenido_id=p.id)\n except Ringtone.DoesNotExist:\n raise Http404 \n fname = str(obj.archivo)\n\n # use with statement\n with open(fname,'rb') as fn:\n response = HttpResponse(fn.read())\n</code></pre>\n\n<p>Uhh.. Is it still complicated? If you can retrieve content type (ringtone or wallpaper) and save it in Dynpath field, solution will be easier.</p>\n\n<p>P.S. Please write your code in English not Spanish )</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-03-01T10:17:53.593", "Id": "15154", "Score": "0", "body": "Thank you for review. I am not quite sure I am getting your point: As the relationship between Ringtone->Contenido is one to one, as is the case also for the relationship between Wallpaper->Contenido. and adding this foreign key would imply a many to one relationship. In other words, one keyword can only correspond to one file (archivo). My question was more about, what happens when I have not only Wallpaper and Ringtones.. lets say I must add a Game category, I would have to keep editing the code in tempurl view. Sorry about the spanish :(" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-03-01T11:36:11.533", "Id": "15167", "Score": "0", "body": "@AlexR Yes, you can use OneToOne relationship instead of OneToMany and it will be more strict and correct. But you inherited Ringtone and Wallpaper from base model Contenido, what is bad. In your case, if you want to add Game category you will have to fix template view. As I have written in the end of my answer, you can add content type to your Dynpath model and then calculate related model class `Model`. Then you will do `obj=Model.objects.get(contenido_id=p.id)` and get filename" } ], "meta_data": { "CommentCount": "2", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-02-29T20:30:34.523", "Id": "9570", "ParentId": "9555", "Score": "1" } } ]
{ "AcceptedAnswerId": "9570", "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-02-29T13:24:36.157", "Id": "9555", "Score": "3", "Tags": [ "python", "django" ], "Title": "Mobile content delivery system" }
9555
<p>I have been wondering this for a while. Take this example:</p> <pre><code>&lt;?= Zend_Registry::get('translate')-&gt;_('translate me!'); </code></pre> <p>I have my views cluttured with such code. My coworkers also complain often that its a lot to type juste to get translation and since it is repeated all over the place it gets tedious.</p> <p>Some of them would love some global function that wraps everything in a short name like:</p> <pre><code>function t($text){ return Zend_Registry::get('translate')-&gt;_($text); } </code></pre> <p>But to me this is not good design and kinda defeats the idea of putting my translation object in the registry.</p> <p>So I was wondering what others do to avoid having to write all this unnecessary code.</p> <p>One solution would be to do in my controller:</p> <pre><code>$this-&gt;view-&gt;t = Zend_Registry::get('translate); </code></pre> <p>and then in my view just:</p> <pre><code>&lt;?= $this-&gt;t-&gt;_('translate me!'); ?&gt; </code></pre> <p>Another would be to create a view helper that does the job:</p> <pre><code>&lt;?= this-&gt;translate('translate me!');?&gt; </code></pre> <p>But it is more work and again adds a layer of logic on top of the already pretty robust and straigthforward Zend_Registry+ZendTranslate. </p>
[]
[ { "body": "<p>The two real questions are:</p>\n\n<ol>\n<li>What are the advantages of having this in Zend_Registry?</li>\n<li>What would you loose when using a helper function?</li>\n</ol>\n\n<p>I believe the answers to these questions lead to this: <strong>use the helper function</strong>. This will:</p>\n\n<ul>\n<li>save you a lot of typing,</li>\n<li>highlight more importants parts of the code,</li>\n<li>only add a tiny new layer of abstraction which is trivial to understand.</li>\n</ul>\n\n<p>\"Good design\" is not about factories, registries, or whatever. It's about code that is easy to maintain and improve. The function is not going to make this any harder. If there's a translation error, the fix will stay the same: was the key correct? Is the stored translation correct? Still easy.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-02-29T18:27:13.163", "Id": "15101", "Score": "2", "body": "@Iznogood: Using the helper function tightly couples the code which the original does not. Thus you have the downside of tight coupling thus harder to specialize in the future. If this is a tradeoff you are willing to make then fine." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-02-29T18:49:42.293", "Id": "15108", "Score": "0", "body": "@Iznogood: Can you not create a child view that has a translate method(). This gives you the best of both worlds. A default implementation (that is short and easy to use) and the ability to override the definition in a further derived type." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-02-29T20:06:54.903", "Id": "15110", "Score": "0", "body": "@LokiAstari What does it couple with what? I'm sure you're right, but I don't understand." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-03-01T15:59:17.327", "Id": "15174", "Score": "0", "body": "@LokiAstari Seeing as how ZF is full of singletons and encourages you to use the registry all over the place, tight coupling is pretty much par for the course anyway :)" } ], "meta_data": { "CommentCount": "4", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-02-29T16:19:39.187", "Id": "9561", "ParentId": "9560", "Score": "2" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-02-29T15:50:24.970", "Id": "9560", "Score": "0", "Tags": [ "php", "comparative-review", "i18n", "zend-framework" ], "Title": "Fetching translated strings, keeping in the philosophy of Zend framework" }
9560
<p>This project is based on trivia (question/answer quiz). The scenario is simple but I have to improve/optimize my query using these tables:</p> <p><img src="https://i.stack.imgur.com/g3V8s.png" alt="enter image description here"></p> <pre><code>$query=$this-&gt;db-&gt;query("SELECT q.`id`, q.`topic_id`, t.`topic`, q.`question`, GROUP_CONCAT(a.`answer`) AS `answer`, GROUP_CONCAT(a.`is_correct`) AS `is_correct`, GROUP_CONCAT(a.`id`) AS `ans_id`, q.`answer_type`, q.`image_url`, q.`created_date`, (SELECT ua.`topic_id` FROM usersAnswer ua WHERE t.`id`= ua.topic_id AND ua.`user_id` = '".$user_id."' LIMIT 1) AS `userdone_topic`, (SELECT ua.`answer_id` FROM usersAnswer ua WHERE ua.`question_id` = q.`id` AND ua.`user_id`='".$user_id."' AND ua.`answer_id` IN (SELECT a.`id` FROM answers a WHERE a.`is_correct` != '0' AND a.question_id = q.`id` )) AS `user_correct_id` FROM questions q INNER JOIN topics t ON q.`topic_id`= t.`id` INNER JOIN answers a ON q.`id`=a.`question_id` WHERE (SELECT s.`status` FROM `status` s WHERE s.`month_date`= q.created_date AND s.`status`= 2 $valid) GROUP BY q.`id` "); return $query-&gt;result(); </code></pre>
[ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-02-29T10:41:44.593", "Id": "15102", "Score": "0", "body": "I agree. I'd vote to move it but there isn't an option for codereview in the migrate voting list." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-02-29T11:20:01.593", "Id": "15103", "Score": "0", "body": "Thanx for Sharing me Quasdunk..." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-02-29T12:50:40.310", "Id": "15104", "Score": "0", "body": "See http://dev.mysql.com/doc/refman/5.6/en/using-explain.html" } ]
[ { "body": "<p>well I used the MS sql for reference but that should be a bit batter. I would also reccomend you to structure your sql cos that way you get a better overview of things.\nCarefull the below seelect is not grouped you can group it as a subquery again</p>\n\n<pre><code>SELECT q.id, q.topic_id, q.question, a.answer, a.is_correct, a.id as ans_id,\n q.answer_type, q.image_url, q.created_date, uaAll.topic_id as userdone_topic,\n uaCorrect.answer_id as user_correct_id\nFROM questions q\n inner join topics t on q.topic_id = t.id\n inner join answers a on q.id = a.question_id\n inner join status s on q.created_date = s.month_date\n left outer join \n (\n SELECT top 1 ua.topic_id\n FROM UserAnswers ua\n where ua.userid = ''\n ) as uaAll on t.id = uaAll.topic_id\n left outer join (\n select ua.answer_id,ua.question_id\n FROM UserAnswers ua\n inner join answers a on a.id = ua.answer_id\n where ua.userid = '' \n and a.is_correct &lt;&gt; 0\n ) as uaCorrect on q.id = uaCorrect.question_id AND a.id = uaCorrect.answer_id\nWHERE s.status = 2\n</code></pre>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-02-29T17:36:50.810", "Id": "9566", "ParentId": "9565", "Score": "1" } } ]
{ "AcceptedAnswerId": "9566", "CommentCount": "3", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-02-29T10:35:48.883", "Id": "9565", "Score": "3", "Tags": [ "php", "sql", "mysql", "quiz" ], "Title": "Q/A trivia quiz query" }
9565
<p>I'm new to Java and this is my first program. I'm trying to verify that my thought processes are good.</p> <p>Let me know of any improvements infor the code, whether it's too few/too many comments, poorly structured code, etc.</p> <pre><code>import javax.swing.*; import java.math.*; import java.util.*; class Root { public static void main(String[] args) { //Variable &amp; Constant Declaration double coeffA=0.0; //Variable for Coefficient A double coeffB=0.0; //Variable for Coefficient B double coeffC=0.0; //Variable for Coefficient C double xroot1=0.0; //Variable for the first root double xroot2=0.0; //Variable for the second root double discriminant=0.0; //Varaible for the discriminant double root1complex=0.0; //Variable for part a of the complex root double root2complex=0.0; //Variable for part b of the complex root boolean contloop=true; //Variable for continuing loop String loop="y"; //Variable for input choice of continuing loop Scanner sc = new Scanner(System.in); //An object to read from the keyboard try{ do{ if (loop.equals("y")){ //Input System.out.println("Please enter the value for the first coefficient: "); //Asks the user to input the value for the A term coeffA=sc.nextDouble(); //Captures the keyboard input and stores it to the variable coeffA System.out.println("Please enter the value for the second coefficient: "); //Asks the user to input the value for the B term coeffB=sc.nextDouble(); //Captures the keyboard input and stores it to the variable coeffB System.out.println("Please enter the value for the third coefficient: "); //Asks the user to input the value for the C term coeffC=sc.nextDouble(); //Captures the keyboard input and stores it to the variable coeffC //Calculations discriminant=coeffB*coeffB-(4*coeffA*coeffC); //Calculates the discriminant xroot1=(-coeffB+(Math.sqrt(discriminant)))/(2*coeffA); //Calculates the first root of the polynomial xroot2=(-coeffB-(Math.sqrt(discriminant)))/(2*coeffA); //Calculates the second root of the polynomial //Output System.out.println("The Equation is:"); //Displays the value for Coefficient C System.out.println(coeffA+"x^2 + "+coeffB+"x + "+ coeffC); //Displays the equation to the user System.out.println("The discriminant is: " + discriminant); //Displays the discriminant to the user if(discriminant&lt;0){ root1complex=-coeffB/(2*coeffA); //Calculates the first part of the complex root root2complex=Math.sqrt(-discriminant)/(2*coeffA); //Calculates the second part of the complex root System.out.println("The Equation has Imaginary roots."); //Displays to the user that there are imaginary roots System.out.println("The Roots are: " + root1complex + "+" + root2complex + "i" + " and " + root1complex + "-" + root2complex + "i."); if (coeffA==0){ System.out.println("*NaN stands for \"Not a Number.\"*"); } //Ends If } //Ends If else if(discriminant==0){ System.out.println("The Root is: " + xroot1 + "."); //Displays the root if (coeffA==0){ System.out.println("*NaN stands for \"Not a Number.\"*"); } //Ends If } //Ends If else if (discriminant&gt;0){ System.out.println("The Roots are: " + xroot1 + " and " + xroot2 +"."); //Displays the roots if (coeffA==0){ System.out.println("*NaN stands for \"Not a Number.\"*"); } //Ends If } //Ends If System.out.println("Do you wish to perform another calculation?"); //Asks the user if they would like to perform another calculation loop=sc.nextLine(); //Captures the next string input and stores it to the variable loop } //Ends If else if (loop.equals("n")){ System.out.println("Quit."); //Prints "Quit" contloop=false; // Sets variable contloop to false thereby allowing therby allowing the program to exit the loop and finish } //Ends If else if ((!loop.equals("y")) || (!loop.equals("n"))){ System.out.println("Please enter \"y\" or \"n\"."); //Requests the user to enter a valid input loop=sc.nextLine(); //Captures the next string input and stores it to the variable loop } //Ends If }while(contloop==true); //Ends Loop System.exit(0); //Exits Java } //End Try catch (InputMismatchException e){ System.out.println("Invalid input format\nOnly numbers (decimals or intergers) are valid input formats.\nPlease restart program."); } //End Catch } //End Main } //End Class </code></pre>
[ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-02-29T22:10:26.367", "Id": "15118", "Score": "4", "body": "looks spaghettic. Not reusable. Merging interactive IO with the calculation (business logic)." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-03-02T18:14:35.943", "Id": "15263", "Score": "0", "body": "Consider using `BigDecimal` instead of `double`." } ]
[ { "body": "<p>You have way too many comments. Assume the developer reading your code knows Java, and can read standard library documentation. Thus, you do not need comments like:</p>\n\n<p><code>//Variable for Coefficient A</code> (or equivalent for any other variable)</p>\n\n<p><code>//Variable &amp; Constant Declaration</code></p>\n\n<p><code>//An object to read from the keyboard</code> (clear from standard library docs)</p>\n\n<p>You also don't need the end comments:</p>\n\n<pre><code>//Ends Loop\n</code></pre>\n\n<p>for the same reason. It's an essential part of the language syntax, and many editors let you toggle between the start and end brace.</p>\n\n<p>You have some small repetition, which you can factor out to a variable or method, like the part about NaN.</p>\n\n<p>A more realistic comment is something like:</p>\n\n<pre><code>// Quadratic formula from Optimized Math Algorithms p. 46\n</code></pre>\n\n<p>This is silly here, since the quadratic formula is well known. But it would be useful for more novel algorithms.</p>\n\n<p>Also, don't repeat calculations like <code>Math.sqrt(discriminant)</code> or <code>2*coeffA</code>. Use an intermediate variable.</p>\n\n<p>I would also separate the input, calculation, and output phases into different methods.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-03-07T17:33:43.780", "Id": "15498", "Score": "0", "body": "Hey, I'm really very new to this. I pretty much made this off of googling questions and reading the ide. I'm fuzzy in terminology.\n\nCould you give me an example of how I would separate the input, calculation, etc. into different methods?\n\nDo you mean something like this:\n`public output(){\n}`" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-03-07T19:38:34.497", "Id": "15510", "Score": "1", "body": "@Caleb, yes, more or less. You'll need the output to take the values to print as arguments. The input method should return the user's input." } ], "meta_data": { "CommentCount": "2", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-02-29T21:43:00.693", "Id": "9572", "ParentId": "9571", "Score": "7" } }, { "body": "<p>I agree to everything, Matthew Flaschen wrote, but like to add some more things: </p>\n\n<p>You don't declare and initialize your variables with dummy values upfront. Instead, you restrict the scope as much as possible, and delay the initialization, if possible, to first usage. </p>\n\n<p>In your example: </p>\n\n<pre><code>public static void main (String [] args)\n{ \n boolean contloop = true; \n String loop = \"y\"; \n\n Scanner sc = new Scanner (System.in); \n\n try {\n do {\n if (loop.equals (\"y\")) {\n\n System.out.println (\"Please enter the value for the first coefficient: \"); \n double coeffA = sc.nextDouble (); \n\n System.out.println (\"Please enter the value for the second coefficient: \"); \n double coeffB = sc.nextDouble (); \n\n System.out.println (\"Please enter the value for the third coefficient: \"); \n double coeffC = sc.nextDouble (); \n\n double discriminant = coeffB * coeffB - (4 * coeffA * coeffC); \n double xroot1 = (-coeffB + (Math.sqrt (discriminant))) / (2 * coeffA); \n double xroot2 = (-coeffB - (Math.sqrt (discriminant))) / (2 * coeffA); \n</code></pre>\n\n<p>This makes reasoning about what the variable is used for, who is influenced by modifying it and refactoring much more easy. </p>\n\n<p>I would suggest much more white space between the tokens. It's better readable for the human eye. The machine will not mention it. Compare yourself: </p>\n\n<pre><code>xroot1 = (-coeffB + (Math.sqrt (discriminant))) / (2 * coeffA); \nxroot1=(-coeffB+(Math.sqrt(discriminant)))/(2*coeffA); \n</code></pre>\n\n<p>If you use comments, put them infront of what is commented, so that javadoc maps them correctly. </p>\n\n<p>Avoid <code>System.exit(0); //Exits Java</code>! Your code can't be called from another Java program, if you use it, because, as written in your comment, it doesn't just stop your program, but the whole JVM. But you will often see it in tutorials. </p>\n\n<p>In your case, a <code>return;</code> is all you need.</p>\n\n<p>Trying to refactor your code, so that we would have a main loop with 3 steps:</p>\n\n<pre><code>loop \n read input\n calculation \n format output\nwhile user ok\n</code></pre>\n\n<p>with 3 method calls, and a class for the values, I mentioned, that the control is surprisingly complicated for the task, which is only whether there should be another loop or not. But we have a variable <code>loop</code>, another one <code>contloop</code>. Can they be out of sync? Why do we have two?</p>\n\n<p>But the main aspect is, to split the task into 3 smaller parts. Think of the possibility to reuse the calculation in a webinterface, Where you don't use System.out.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-02-29T23:01:49.390", "Id": "15131", "Score": "0", "body": "Thanks! Like I stated, it's my first time. In most examples I had seen on the web the variables were initialized at the point of usage. My teacher for some has continually shown us up front and wants our code formatted like that when printed." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-03-01T00:20:01.833", "Id": "15133", "Score": "0", "body": "Also: Restrict your `try` ... `catch` to only the code that can actually throw the execeptions." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-03-01T05:51:30.707", "Id": "15140", "Score": "0", "body": "If you want to use Javadoc, you also need to use Javadoc comments. This means specific tags within `/** ... */`." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-03-01T08:00:02.377", "Id": "15143", "Score": "0", "body": "@Eagle: I can't discuss with your teacher in this thread. He is welcome to visit this site and argue his viewpoint, but we can't discuss his authority in this question without him being here. Ask your teacher why he wants the variables up front." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-03-07T17:56:52.737", "Id": "15504", "Score": "0", "body": "@user unknown: I think it's just a preference for assignments on her part. And unless I get a really poor reason from her it's not worth talking about. I don't want to appear to disrespect her even on a website she'll never be on. I was in a rush in my last comment because the fire alarm went off as I was typing, so I couldn't make myself clear. :)" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-03-07T22:58:17.427", "Id": "15539", "Score": "0", "body": "Well - as a beginner, it wouldn't be a good idea to repeat my arguments without having understood them completely. You can't answer on her defense. But that doesn't mean that I don't keep my advice up." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-03-15T14:34:17.360", "Id": "16012", "Score": "0", "body": "@ user unknown\nHaha, I had no intention of getting into it with her. It's my desire to understand both her, and you. I wouldn't dare be so imprudent as to make an argument without understanding, when I know I don't understand. :)\nThanks again!" } ], "meta_data": { "CommentCount": "7", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-02-29T22:43:27.027", "Id": "9576", "ParentId": "9571", "Score": "5" } }, { "body": "<p>Here is my take:</p>\n\n<pre><code>import java.util.Scanner;\n\nclass Root {\n private static final Scanner sc = new Scanner(System.in);\n\n public static double askForCoefficient(String ordinal) {\n while (true) {\n try {\n System.out.println(\"Please enter the value for the \" + ordinal + \" coefficient: \");\n String s = sc.nextLine();\n return Double.parseDouble(s);\n } catch (NumberFormatException ex) {\n System.out.println(\"Invalid input. Please enter a number (decimal or interger)\");\n }\n }\n }\n\n public static double[] askForCoefficients() {\n double a = 0.0;\n while (a == 0.0) {\n a = askForCoefficient(\"first\");\n if (a == 0.0) {\n System.out.println(\"The first coefficient can't be 0 in a quadratic polynom.\");\n }\n }\n double b = askForCoefficient(\"second\");\n double c = askForCoefficient(\"third\");\n return new double[]{a, b, c};\n }\n\n public static boolean yesOrNo(String answer) {\n return answer.equalsIgnoreCase(\"y\") || answer.equalsIgnoreCase(\"n\");\n }\n\n public static boolean askForContinue() {\n String loop = \"\";\n System.out.println(\"Do you wish to perform another calculation (y/n)?\");\n while (!yesOrNo(loop)) {\n loop = sc.nextLine();\n if (!yesOrNo(loop)) {\n System.out.println(\"Please enter \\\"y\\\" or \\\"n\\\".\");\n }\n }\n return loop.equalsIgnoreCase(\"y\");\n }\n\n public static Complex[] calculate(double a, double b, double c) {\n double discriminant = b * b - (4 * a * c);\n System.out.println(\"The discriminant is \" + discriminant);\n Complex root1 = new Complex(-b, 0).plus(Complex.sqrt(discriminant)).multReal(0.5 / a);\n Complex root2 = new Complex(-b, 0).minus(Complex.sqrt(discriminant)).multReal(0.5 / a);\n return (root1.equals(root2)) ? new Complex[]{root1} : new Complex[]{root1, root2};\n }\n\n\n public static void main(String[] args) {\n do {\n double[] coeffs = askForCoefficients();\n System.out.println(\"The Equation is:\");\n System.out.println(coeffs[0] + \"x^2 + \" + coeffs[1] + \"x + \" + coeffs[2]);\n\n Complex[] roots = calculate(coeffs[0], coeffs[1], coeffs[2]);\n\n if (roots.length == 1) {\n System.out.println(\"The Root is \" + roots[0] + \".\");\n } else {\n if (!roots[0].isReal()) {\n System.out.println(\"The Equation has imaginary roots.\");\n }\n System.out.println(\"The Roots are: \" + roots[0] + \" and \" + roots[1]);\n }\n } while (askForContinue());\n System.out.println(\"Quit.\");\n }\n\n public static class Complex {\n public final double real;\n public final double imag;\n\n public Complex(double real, double imag) {\n this.real = real;\n this.imag = imag;\n }\n\n public Complex plus(Complex that) {\n return new Complex(this.real + that.real, this.imag + that.imag);\n }\n\n public Complex minus(Complex that) {\n return new Complex(this.real - that.real, this.imag - that.imag);\n }\n\n public boolean isReal() {\n return imag == 0.0;\n }\n\n public Complex multReal(double d) {\n return new Complex(d * real, d * imag);\n }\n\n public static Complex sqrt(double d) {\n return d &gt;= 0.0\n ? new Complex(Math.sqrt(d), 0.0)\n : new Complex(0.0, Math.sqrt(-d));\n }\n\n public String toString() {\n if (imag == 0.0) return \"\" + real;\n else if (imag &gt; 0) return real + \"+\" + imag + \"i\";\n else return real + \"\" + imag + \"i\";\n }\n\n public boolean equals(Object o) {\n Complex that = (Complex) o;\n return this.real == that.real &amp;&amp; this.imag == that.imag;\n }\n\n }\n\n} \n</code></pre>\n\n<p>I broke the class in several methods with clear, testable sub-tasks. Most notably things got cleaner and easier when I used the right data type, which is here Complex. Don't stick with the standard classes / primitives if they don't really fit. Of course if you want to reuse and extend <code>Complex</code>, you should make it a top level class.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-03-02T08:42:31.067", "Id": "9628", "ParentId": "9571", "Score": "4" } }, { "body": "<p>The last condition statement is definitely wrong:</p>\n\n<blockquote>\n<pre><code>else if ((!loop.equals(\"y\")) || (!loop.equals(\"n\")))\n</code></pre>\n</blockquote>\n\n<p>It should be <code>&amp;&amp;</code>, not <code>||</code>.</p>\n\n<p>Why choose a <code>do</code> <code>while</code> conditional statement? If you just wanna make sure it will be run at least one time, use a <code>while</code> loop.</p>\n\n<p>The main function are is large; split it to small function. You will maybe find that some code can be reused.</p>\n\n<p>For a comment like this:</p>\n\n<blockquote>\n<pre><code>Scanner sc = new Scanner(System.in); //An object to read from the keyboard\n</code></pre>\n</blockquote>\n\n<p>Everyone knows what this code does, so no need to comment. You comment simple code which already explains itself, then you repeat yourself. Remember the 'DRY' rule; don't let comments repeat yourself.</p>\n\n<p>I don't quite understand the algorithmic part. Maybe you can add one <code>MathUtil</code> class to help you do the algorithm.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-03-07T07:18:48.473", "Id": "9765", "ParentId": "9571", "Score": "2" } }, { "body": "<p>For a beginning programming class it doesn't matter, but a good principle is to separate the part of your code that do calculation from the parts that do input and output. The \"Calculations\" block should be in a separate method.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-03-07T17:43:35.593", "Id": "15500", "Score": "0", "body": "Thanks!\nI'll definitely try to do that for my next program.\nThings kinda blended together when I got going... :D\nPretty much I googled things for answers because my teacher, like so many people's, melts my mind. Plus, she doesn't teach fast enough for my tastes. I was homeschooled so I mainly look up how to do things and learn from examples before she teaches it. So my code is going to look poor for a little while.\nAnd beginning or not, it should be _perfect_. Because, well it just should be. :)" } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-03-07T17:18:34.897", "Id": "9772", "ParentId": "9571", "Score": "1" } } ]
{ "AcceptedAnswerId": "9576", "CommentCount": "2", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-02-29T21:37:26.620", "Id": "9571", "Score": "4", "Tags": [ "java", "beginner", "mathematics", "swing" ], "Title": "How does this quadratic formula program look?" }
9571
<p>I came across <a href="https://codereview.stackexchange.com/questions/9289/changing-bits-in-given-big-strings">this thread</a> and I am working on the same problem. My best algorithm passes 6/11 cases while the algorithm in the other thread does indeed pass 8/11 cases. Running time trials with random input my algorithm is significantly quicker (8 to 12 times depending on input) then the one in the other thread. So I am pretty confused on these results. </p> <p>I came across this thread and I am working on the same problem. My best algorithm passes 6/11 cases while the algorithm in the other thread does indeed pass 8/11 cases. Running time trials with random input my algorithm is significantly quicker (8 to 12 times depending on input) then the one in the other thread. So I am pretty confused on these results. </p> <p>Aside from empirical testing these are the reasons I think my code should be running better than the other implementation for these reasons.</p> <ul> <li>Appending to a <code>StringBuilder</code> and printing once should be more efficient than multiple print statements.</li> <li>Better reduction in logic for binary addition. As well doing addition from the bit index’s least significant 0 in both BitSets, a and b, reduces unnecessary computation. </li> <li>Using <code>BufferedReade</code>r has a lot less overhead than using <code>Scanner</code>.</li> <li><code>BitSet</code> really didn’t offer much difference in the terms of performance than a character array but reversing the binary strings is a waste and the <code>StringBuilder</code> reverse is not the best performance.</li> </ul> <p>Can anyone shed some light onto why the seemingly slower algorithm does better in the testing?</p> <p>Version 2</p> <pre><code>private static String floatSum() { final Scanner input = new Scanner(System.in); final int number_bits = input.nextInt(); final int number_queries = input.nextInt(); final StringBuilder builder = new StringBuilder(); final char[] a = new StringBuilder(input.next()).reverse().toString().toCharArray(); final char[] b = new StringBuilder(input.next()).reverse().toString().toCharArray(); for(int queries = 0; queries &lt; number_queries; queries++) { switch(input.next().charAt(4)) { case 'a': a[input.nextInt()] = input.next().charAt(0); break; case 'b': b[input.nextInt()] = input.next().charAt(0); break; default: final int index = input.nextInt(); int carry_bit = 0; for(int iter = index - 1; iter &gt;= 0; iter--) { if(a[iter] == b[iter]) { carry_bit = a[iter] - 48; break; } } builder.append(index == number_bits ? carry_bit : ((a[index] - 48) + (b[index] - 48) + carry_bit) % 2); break; } } return builder.toString(); } </code></pre>
[]
[ { "body": "<p>Consider this case:</p>\n\n<pre><code>A: 1111111111\nB: 1111111111\nQuery: n+1\n</code></pre>\n\n<p>The other post terminates very quckly. It knows that since both numbers end in 1, it must carry and thus doesn't have to scan throughout the entire string. On the other hand, your method tries to find clear bits but since there aren't any, it ends up going through the whole bitstring.</p>\n\n<p>Probably, yours is faster over all, but this pathological case happens to have been put first in the test cases and so your program fails.</p>\n\n<pre><code> if(carry &amp;&amp; a.get(iter) &amp;&amp; b.get(iter))\n {\n carry = true;\n value = 1;\n }\n else if((carry &amp;&amp; a.get(iter)) || (carry &amp;&amp; b.get(iter)) || (a.get(iter) &amp;&amp; b.get(iter)))\n {\n carry = true; \n value = 0;\n }\n else if(carry || a.get(iter) || b.get(iter))\n {\n carry = false;\n value = 1;\n }\n else\n {\n carry = false; \n value = 0;\n }\n</code></pre>\n\n<p>This whole bit kinda hard to follow you could instead do something like:</p>\n\n<pre><code>int bits = a.get(iter) ? 1 : 0 + b.get(iter) ? 1 : 0 + carry ? 1 : 0;\nvalue = bits % 2;\ncarry = bits / 2;\n</code></pre>\n\n<p>I think its a clearer</p>\n\n<pre><code> int a_index = a.nextClearBit(number_bits - index);\n int b_index = b.nextClearBit(number_bits - index);\n</code></pre>\n\n<p>Yeah, not gonna fly. nextClearBit has to scan through the bitset bit by bit in order to do that. You are gonna need to come up with a way to look through the bits without looking at each individual bit. I've solved this problem, and I used a specialized data structure to do it. </p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-03-01T03:51:05.787", "Id": "15138", "Score": "0", "body": "Going to have to ponder your points. \n\nSince it doesn’t seem that raw performance is the key to passing each test case is there a better metric for rating performance? As of now I loop through a number of inputs creating a text file for each input then load the file into System.in and record the milliseconds it took for each method to complete." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-03-01T03:53:09.437", "Id": "15139", "Score": "0", "body": "@ntin, well raw performance is the right metric. The problem is that there are test cases where your algorithm does really really badly. You've got to measure performance on those test cases." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-03-03T00:36:27.610", "Id": "15273", "Score": "0", "body": "I see what you mean about the data structure, TreeMap/Set is too slow with the inserts/deletes to find the pair closests to the get_c index." } ], "meta_data": { "CommentCount": "3", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-03-01T01:36:50.993", "Id": "9579", "ParentId": "9578", "Score": "3" } } ]
{ "AcceptedAnswerId": "9579", "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-03-01T00:26:37.990", "Id": "9578", "Score": "2", "Tags": [ "java", "algorithm" ], "Title": "Strange algorithm results" }
9578
<p>My code will, from a web-gui, generate <a href="http://thevash.com" rel="nofollow">Vash</a> images. This currently involves making a call to a local binary, java. I'm wondering, if I've taken reasonable measures against this being exploited by a malicious user, or not.</p> <p>The code will be used in several different places, by several different administrators, meaning both that I want to retain as much flexibility as reasonably possible, and that different users will have different opportunities to subvert the content of the <code>$arguments</code> variable.</p> <p>From the code has been striped some <strong>@todo</strong> comments, and completely hard coded error messages.</p> <p>There are three functions involved.</p> <pre><code>_vash_call_local_vash(array $arguments); // Responsible for building the command to be executed. _vash_proc_open($cmd, $context); // Executes the command built above. _vash_defaults() // Provides a set of default arguments. </code></pre> <p><code>$base_dir</code> Will be supplied by a program that I don't have any control over. Should I be doing extra validation on the sanity of that variable? At this point I don't know what the function will look like, that retrieves the exact path.</p> <p>To avoid misuse, I mainly do two things. First, I hard code the parameter names, and then read only actual parameter values from keys in the hard coded list. I believe this will avoid the possibility of someone adding <strong>extra</strong> parameters. Second, I <code>escapeshellarg()</code> all the parameter values. I'm worrying a bit that it will be possible to somehow trick Java into executing the wrong jar file?</p> <pre><code>function _vash_call_local_vash($arguments) { if (empty($arguments['data'])) { return NULL; } elseif (empty($arguments['output'])) { return NULL; } if (isset($arguments['data'])) { $arguments += _vash_defaults(); $base_dir = '/some/recieved/path/'; // Collapse the arguments array into a single line. // Use hard-coded list of argument names to avoid the possibility of using // that as an attack vector. $names = array('format', 'width', 'height', 'algorithm', 'output', 'data'); $cmd = 'java -jar ' . $vash_dir . 'Vash.jar '; foreach ($names as $name) { $cmd .= '--' . $name . ' ' . escapeshellarg($arguments[$name]) . ' '; } return _vash_proc_open($cmd); } return FALSE; } function _vash_proc_open($cmd, $context = NULL) { $descriptorspec = array( 0 =&gt; array("pipe", "r"), 1 =&gt; array("pipe", "w"), 2 =&gt; array("pipe", "w"), ); $process = proc_open($cmd, $descriptorspec, $pipes, NULL, NULL, array('context' =&gt; $context)); if (is_resource($process)) { $info = stream_get_meta_data($pipes[1]); stream_set_blocking($pipes[1], TRUE); stream_set_timeout($pipes[1], 1); $string = ''; while (!feof($pipes[1]) &amp;&amp; !$info['timed_out']) { $string .= fgets($pipes[1], 4096); $info = stream_get_meta_data($pipes[1]); }; $info = stream_get_meta_data($pipes[2]); stream_set_blocking($pipes[2], TRUE); stream_set_timeout($pipes[2], 1); while (!feof($pipes[2]) &amp;&amp; !$info['timed_out']) { $string .= fgets($pipes[2], 4096); $info = stream_get_meta_data($pipes[2]); }; fclose($pipes[0]); fclose($pipes[1]); fclose($pipes[2]); $code = proc_close($process); return array('cmd' =&gt; $cmd, 'output' =&gt; $string, 'code' =&gt; $code); } return FALSE; } function _vash_defaults() { $defaults = array( 'format' =&gt; 'png', 'width' =&gt; '512', 'height' =&gt; '512', 'algorithm' =&gt; '1.1', 'output' =&gt; '/tmp/output.png', // 'salt-file' =&gt; 'salt-file', ); return $defaults; } } </code></pre>
[ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-10-31T15:57:55.047", "Id": "53803", "Score": "0", "body": "are you running Java on the BackEnd or PHP? the question is Tagged PHP but then you mention Java and Jar files?" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-10-31T16:28:38.957", "Id": "53808", "Score": "0", "body": "@Malachi: If I read this correctly, it's PHP on the backend calling and external jar." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-10-31T16:31:43.063", "Id": "53809", "Score": "1", "body": "well it looks like a lot of fun.." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-11-01T00:05:23.710", "Id": "53872", "Score": "0", "body": "@Malachi, it is correct as Bobby says. My code is PHP, and I need to call a jar. What exactly I'm calling is probably less interesting though, as the question should be applicable in any situation where php code executes shell commands." } ]
[ { "body": "<p>You aren’t validating any user input in your code, while <code>escapeshellarg</code> protects you from malicious arguments nothing protects you from calling your JAR with wrong arguments. Properly validating everything is the best advice I can give you.</p>\n\n<p><b>Example</b></p>\n\n<pre><code>&lt;?php\n\nclass Vash {\n\n protected $args;\n\n protected $path;\n\n public function __construct(array $args, $path) {\n if (!empty($args[\"data\"]) &amp;&amp; !empty($args[\"output\"])) {\n $this-&gt;args = $args;\n $this\n -&gt;validateFormat()\n -&gt;validateDimension(\"width\")\n -&gt;validateDimension(\"height\")\n -&gt;validateAlgorithm()\n -&gt;validateOutput()\n -&gt;validateData()\n -&gt;setPath($path)\n -&gt;execute()\n ;\n }\n }\n\n protected function setPath($path) {\n if (!is_string($path)) {\n throw new IllegalArgumentException;\n }\n $path = \"{$path}Vash.jar\";\n if (!is_file($path)) {\n throw new LogicException;\n }\n $this-&gt;path = $path;\n return $this;\n }\n\n protected function validateFormat() {\n if (empty($this-&gt;args[\"format\"])) {\n $this-&gt;args[\"format\"] = \"png\";\n }\n else {\n switch ($this-&gt;args[\"format\"]) {\n case \"jpg\":\n case \"png\":\n break;\n\n default:\n throw new IllegalArgumentException;\n }\n }\n return $this;\n }\n\n protected function validateDimension($dimension, $default = 512) {\n if (empty($this-&gt;args[$dimension])) {\n $this-&gt;args[$dimension] = $default;\n }\n elseif (filter_var((integer) $this-&gt;args[$dimension], FILTER_VALIDATE_INT, array(\n \"flags\" =&gt; FILTER_REQUIRE_SCALAR,\n \"options\" =&gt; array( \"min_range\" =&gt; 10, \"max_range\" =&gt; 2000 ),\n )) === false) {\n throw new IllegalArgumentException;\n }\n return $this;\n }\n\n protected function validateAlgorithm() {\n if (empty($this-&gt;args[\"algorithm\"])) {\n $this-&gt;args[\"algorithm\"];\n }\n elseif (filter_var((float) $this-&gt;args[\"algorithm\"], FILTER_VALIDATE_FLOAT, array(\n \"flags\" =&gt; FILTER_REQUIRE_SCALAR,\n \"options\" =&gt; array( \"decimal\" =&gt; 1 ),\n )) === false || $this-&gt;args[\"algorithm\"] &lt;= 0.0 || $this-&gt;args[\"algorithm\"] &gt; 1.0) {\n throw new IllegalArgumentException;\n }\n return $this;\n }\n\n //\n // Continue with validation!\n //\n\n protected function execute() {\n $cmd = \"java -jar {$this-&gt;path}\";\n foreach (array(\"format\", \"width\", \"height\", \"algorithm\", \"output\", \"data\") as $name) {\n $arg = escapeshellarg($this-&gt;args[$name]);\n $cmd .= \" --name '{$arg}'\";\n }\n return _vash_proc_open($cmd);\n }\n\n}\n\n?&gt;\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-11-15T09:32:16.597", "Id": "57385", "Score": "0", "body": "This actually brings up a good point about the parameters that I haven't though off. Allowing arbitrary sizes has the potential to lead to a denial of service attack, since one could easily consume large amounts of disc space, processing power, and probably easily all available httpd connections. Despite that, I'm a bit hesitant to provide to rigorous checking on the other parameters, as I don't want this code to need updating should the underlying application add new options. I'll try to find a balance between the two. :)" } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-11-15T01:42:19.270", "Id": "35398", "ParentId": "9580", "Score": "2" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "4", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-03-01T07:51:34.193", "Id": "9580", "Score": "4", "Tags": [ "php", "security" ], "Title": "Safely pass user input to a CLI application on the server?" }
9580
<p>I want to design API which could handle XPATH input from a user. I currently model the XPATH input in the following way:</p> <pre><code>public interface ICondition { String getConditionString(); } public class XPathCondition implements ICondition { private Class&lt;? extends XPATHFunction&gt; clazz = null; private Operator operator = null; private String compValue = null; private String param = null; public void setXPathFunction(Class&lt;? extends XPATHFunction&gt; clazz) { this.clazz = clazz; } public void setComparisionType(Operator operator) { this.operator = operator; } public void setComparisionValue(String value) { this.compValue = value; } public void setParam(String param) { this.param = param; } public String getConditionString() { XPATHFunction function = null; try { function = (XPATHFunction) clazz.newInstance(); } catch (Exception e) { throw new RuntimeException(e.getMessage()); } return function.call(param) + operator.getOprValue() + compValue; } public static void main(String[] args) { XPathCondition xpathCond = new XPathCondition(); xpathCond.setXPathFunction(CountFunction.class); xpathCond.setParam("/CPRRegistrationInfo/*"); xpathCond.setComparisionType(Operator.GT); xpathCond.setComparisionValue("0"); System.out.println(xpathCond.getConditionString()); } } public interface XPATHFunction { public String call(String param); } public class CountFunction implements XPATHFunction { public String call(String param) { return "count(" + param + ") "; } } </code></pre> <p>There could be other XPATH functions which have to implement and interface <code>XPATHFunction</code> and implement it in its way. The API just has to create <code>XPATHCondition</code> and set appropriate functions and call the <code>getConditionString()</code> method to get the final xpath.</p> <p>Is there any better way in which I can model XPATH input?</p>
[]
[ { "body": "<p>Can I ask why you're trying to do this? If this is homework or a way to \"practice Java/Object-Oriented programming\", please say so. If it's a real question, the best way to represent XPath input is actually <strong>a string</strong>. XPath is way more complicated than what you've (XPath 2.0 even more so), and you would need a lot of more work to model this properly. If it's a subset of XPAth, then what subset?</p>\n\n<p><em>Edit</em>: A few examples.</p>\n\n<ul>\n<li>Valid XPath expressions:\n<ul>\n<li>ancestor-or-self::*</li>\n<li>../employee[@secretary and @assistant]</li>\n<li>substring(\"12345\", 1.5, 2.6)</li>\n<li>child::para[position()=5][attribute::type=\"warning\"]</li>\n</ul></li>\n<li>Valid XPath 2.0 expressions:\n<ul>\n<li>($x div $y) + xs:decimal($z)</li>\n<li>fn:error(xs:QName(\"app:err057\"), \"Unexpected value\", fn:string($v))</li>\n</ul></li>\n</ul>\n\n<p>Also note that you can evaluate XPath expressions using the standard <code>javax.xml.xpath</code>, thus not needing rolling your own. If you need something else, maybe reuse the source code of <code>javax.xml.xpath</code> to suit your needs?</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-03-01T10:50:44.060", "Id": "15155", "Score": "0", "body": "Cygal, This not homework.I am designing BPEL genertation tool and my BPEL tool API is such way that user should give XPATH as input.However enter xpath as String leads to error prone.That why i want model user input xpath into OOP. For you information BPEL contains xpath to navigate through the xml node." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-03-01T12:56:08.477", "Id": "15169", "Score": "1", "body": "So you want to validate XPath expressions? Are you aware that you can use [javax.xml.xpath](http://docs.oracle.com/javase/1.5.0/docs/api/javax/xml/xpath/package-summary.html) for this? Use XPath.evaluate() and catch the XPathExpressionException. I'd be glad to help if I didn't understand once again what you're willing to do." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-03-04T11:02:15.893", "Id": "15337", "Score": "0", "body": "Cygal,We are generating BPEL tool by accepting some of inputs from user from those inputs one input is XPATH.There could be 2 options we can accept the XPATH from user 1:take XPATH as regular expression as it is.for example setXPATH(\"/bookstore/book/title\") 2: We can model input side using Object Oriented way.In short i want give API wrapper on xpath input side. I don not want validate the XPATH.My goal is accept xpath input from user using classes and object and use this input objects and classes while generating BPEL file." } ], "meta_data": { "CommentCount": "3", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-03-01T10:10:30.273", "Id": "9584", "ParentId": "9582", "Score": "1" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-03-01T09:32:56.483", "Id": "9582", "Score": "1", "Tags": [ "java", "xpath" ], "Title": "Handling XPATH input from a user" }
9582
<p>This code is very simple, but it is intended as an experiment in the relative performance of mutexes/CAS on different platforms. The latest version can always be found at:</p> <p><a href="https://github.com/alexdowad/showcase/blob/master/ruby-threads/concurrent_stack.rb" rel="nofollow">https://github.com/alexdowad/showcase/blob/master/ruby-threads/concurrent_stack.rb</a></p> <p>It comes with a built-in benchmarking script. Please try running and post the results, along with your OS, version of Ruby, and CPU. Please also post if you can find any way to improve style or performance.</p> <p>For convenience the first version of the code is reproduced below:</p> <pre><code># 3 thread-safe stack implementations # Written by Alex Dowad # Usage: # stack.push(1) # stack.peek =&gt; 1 (1 is not removed from stack) # stack.pop =&gt; 1 (now 1 is removed from stack) require 'rubygems' # for compatibility with MRI 1.8, JRuby require 'thread' require 'atomic' # atomic gem must be installed # The easy one first class ThreadSafeStack def initialize @s,@m = [],Mutex.new end def push(value) @m.synchronize { @s.push(value) } end def pop @m.synchronize { @s.pop } end def peek @m.synchronize { @s.last } end end # a non-locking version which uses compare-and-swap to update stack class ConcurrentStack Node = Struct.new(:value,:next) def initialize @top = Atomic.new(nil) end def push(value) node = Node.new(value,nil) @top.update { |current| node.next = current; node } end def pop node = nil @top.update do |current| node = current return if node.nil? node.next end node.value end def peek node = @top.value return if node.nil? node.value end end # same as ConcurrentStack, but additionally recycles popped nodes # (to reduce load on GC) # a global free list is used, and is also updated using CAS, # in exactly the same way as the stacks themselves class RecyclingConcurrentStack Node = Struct.new(:value,:next) FREE_LIST = Atomic.new(nil) def initialize @top = Atomic.new(nil) end def push(value) node = get_node(value) @top.update { |current| node.next = current; node } end def pop node = nil @top.update do |current| return if (node = current).nil? node.next end result = node.value FREE_LIST.update do |current| node.next = current node end result end def peek node = @top.value return if node.nil? node.value end private def get_node(val) # if contention causes the CAS to fail, just allocate a new node node = FREE_LIST.value if node &amp;&amp; FREE_LIST.compare_and_swap(node,node.next) node.value = val node else Node.new(val,nil) end end end # Test driver if __FILE__ == $0 require 'benchmark' ITERATIONS_PER_TEST = 1000000 QUEUE,MUTEX = ConditionVariable.new,Mutex.new def wait_for_signal MUTEX.synchronize { QUEUE.wait(MUTEX) } end def send_signal MUTEX.synchronize { QUEUE.broadcast } end def test(klass) test_with_threads(klass,1) test_with_threads(klass,5) test_with_threads(klass,25) end def test_with_threads(klass,n_threads) stack = klass.new iterations = ITERATIONS_PER_TEST / n_threads puts "Testing #{klass} with #{n_threads} thread#{'s' if n_threads&gt;1}, iterating #{iterations}x each" threads = n_threads.times.collect do Thread.new do wait_for_signal iterations.times do stack.push(rand(100)) stack.peek stack.pop end end end n_gc = GC.count sleep(0.001) result = Benchmark.measure do send_signal threads.each { |t| t.join } end puts result puts "Garbage collector ran #{GC.count - n_gc} times" end test(ThreadSafeStack) test(ConcurrentStack) test(RecyclingConcurrentStack) end </code></pre>
[ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-03-07T18:51:43.130", "Id": "15508", "Score": "0", "body": "The bounty on this question is going to expire; if you want it, run the benchmark and post the results, even if you can't find any way to improve the code!" } ]
[ { "body": "<p>I took the latest source code from the github and have started review of this project. Here are my benchmarks results:</p>\n\n<pre><code># Intel(R) Core(TM)2 Duo CPU P7570 @ 2.26GHz\n# ruby 1.9.2p290 (2011-07-09 revision 32553) [i686-linux]\nTesting ThreadSafeStack with 1 thread, iterating 1000000x each\n 2.250000 0.000000 2.250000 ( 2.254392)\nGarbage collector ran 0 times\nTesting ThreadSafeStack with 5 threads, iterating 200000x each\n 2.350000 0.020000 2.370000 ( 2.533645)\nGarbage collector ran 0 times\nTesting ThreadSafeStack with 25 threads, iterating 40000x each\n 2.890000 0.780000 3.670000 ( 3.170657)\nGarbage collector ran 0 times\nTesting ConcurrentStack with 1 thread, iterating 1000000x each\n 2.840000 0.000000 2.840000 ( 2.836545)\nGarbage collector ran 54 times\nTesting ConcurrentStack with 5 threads, iterating 200000x each\n 2.850000 0.010000 2.860000 ( 2.871540)\nGarbage collector ran 54 times\nTesting ConcurrentStack with 25 threads, iterating 40000x each\n 2.880000 0.000000 2.880000 ( 2.881745)\nGarbage collector ran 56 times\nTesting RecyclingConcurrentStack with 1 thread, iterating 1000000x each\n 3.910000 0.000000 3.910000 ( 3.906049)\nGarbage collector ran 0 times\nTesting RecyclingConcurrentStack with 5 threads, iterating 200000x each\n 3.900000 0.000000 3.900000 ( 3.910919)\nGarbage collector ran 0 times\nTesting RecyclingConcurrentStack with 25 threads, iterating 40000x each\n 3.960000 0.000000 3.960000 ( 4.024026)\nGarbage collector ran 0 times\n</code></pre>\n\n<p>With jruby 1.6.5 (ruby-1.8.7-p330) I encountered a deadlock. With JRruby it is reproduced each time I ran the benchmark, but with MRI I've seed it only once so far. I will try to find the cause and post an update here.</p>\n\n<hr>\n\n<p><strong>UPDATE</strong></p>\n\n<p>I reviewed the implementation of concurrent stacks and did not found anything that may cause deadlocks or other issues. Looks like deadlock is caused by benchmarking code. With JRuby it just hangs (very frequently). With MRI I received 'deadlock detected' exceptions:</p>\n\n<pre><code>Testing ConcurrentStack with 25 threads, iterating 40000x each\n/home/alex/Projects/read-write-lock/concurrent-stack.rb:143:in `join': deadlock detected (fatal)\n from /home/alex/Projects/read-write-lock/concurrent-stack.rb:143:in `block (2 levels) in test_with_threads'\n from /home/alex/Projects/read-write-lock/concurrent-stack.rb:143:in `each'\n from /home/alex/Projects/read-write-lock/concurrent-stack.rb:143:in `block in test_with_threads'\n from /usr/share/ruby-rvm/rubies/ruby-1.9.2-p290/lib/ruby/1.9.1/benchmark.rb:295:in `measure'\n from /home/alex/Projects/read-write-lock/concurrent-stack.rb:141:in `test_with_threads'\n from /home/alex/Projects/read-write-lock/concurrent-stack.rb:120:in `test'\n from /home/alex/Projects/read-write-lock/concurrent-stack.rb:150:in `&lt;top (required)&gt;'\n from -e:1:in `load'\n from -e:1:in `&lt;main&gt;'\n</code></pre>\n\n<p>And</p>\n\n<pre><code>/home/alex/Projects/read-write-lock/concurrent-stack.rb:143:in `join': deadlock detected (fatal)\n from /home/alex/Projects/read-write-lock/concurrent-stack.rb:143:in `block (2 levels) in test_with_threads'\n from /home/alex/Projects/read-write-lock/concurrent-stack.rb:143:in `each'\n from /home/alex/Projects/read-write-lock/concurrent-stack.rb:143:in `block in test_with_threads'\nTesting RecyclingConcurrentStack with 1 thread, iterating 1000000x each\n from /usr/share/ruby-rvm/rubies/ruby-1.9.2-p290/lib/ruby/1.9.1/benchmark.rb:295:in `measure'\n from /home/alex/Projects/read-write-lock/concurrent-stack.rb:141:in `test_with_threads'\n from /home/alex/Projects/read-write-lock/concurrent-stack.rb:118:in `test'\n from /home/alex/Projects/read-write-lock/concurrent-stack.rb:152:in `block in &lt;top (required)&gt;'\n from /home/alex/Projects/read-write-lock/concurrent-stack.rb:151:in `loop'\n from /home/alex/Projects/read-write-lock/concurrent-stack.rb:151:in `&lt;top (required)&gt;'\n from -e:1:in `load'\n from -e:1:in `&lt;main&gt;'\n</code></pre>\n\n<p>As far as I can see, the only thing that may cause deadlock is situation when main thread does <code>QUEUE.broadcast</code> and then does <code>Thread#join</code> on the thread but this thread did not executed <code>QUEUE.wait</code> yet. Then main thread infinitely waits for this thread and MRI may detect such deadlock situation.</p>\n\n<p>When I increased sleep time from <code>0.001</code> to <code>0.01</code> and more it seemed that deadlock has gone. Looks like this issue is caused by long thread initialization time - sometimes it cannot start block execution for all threads before <code>QUEUE.broadcast</code> call.</p>\n\n<p>Also, as a small improvement, the following code may be extracted into private function like <code>cache_node</code> to improve <code>pop</code> method readability:</p>\n\n<pre><code>FREE_LIST.update do |current|\n node.next = current\n node\nend\n</code></pre>\n\n<p>Stack implementation looks correct and clear, I did not found other issues.</p>\n\n<hr>\n\n<p>With sleep == <code>0.05</code> benchmarks for JRuby are these:</p>\n\n<pre><code># jruby 1.6.5 (ruby-1.8.7-p330) (2011-10-25 9dcd388) (Java HotSpot(TM) Server VM 1.6.0_26) [linux-i386-java]\nTesting ThreadSafeStack with 1 thread, iterating 1000000x each\n 2.881000 0.000000 2.881000 ( 2.881000)\nTesting ThreadSafeStack with 5 threads, iterating 200000x each\n 2.658000 0.000000 2.658000 ( 2.658000)\nTesting ThreadSafeStack with 25 threads, iterating 40000x each\n 2.885000 0.000000 2.885000 ( 2.885000)\nTesting ConcurrentStack with 1 thread, iterating 1000000x each\n 2.142000 0.000000 2.142000 ( 2.142000)\nTesting ConcurrentStack with 5 threads, iterating 200000x each\n 1.084000 0.000000 1.084000 ( 1.084000)\nTesting ConcurrentStack with 25 threads, iterating 40000x each\n 0.969000 0.000000 0.969000 ( 0.970000)\nTesting RecyclingConcurrentStack with 1 thread, iterating 1000000x each\n 2.628000 0.000000 2.628000 ( 2.628000)\nTesting RecyclingConcurrentStack with 5 threads, iterating 200000x each\n 1.436000 0.000000 1.436000 ( 1.436000)\nTesting RecyclingConcurrentStack with 25 threads, iterating 40000x each\n 1.473000 0.000000 1.473000 ( 1.473000)\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-03-09T18:31:13.610", "Id": "15691", "Score": "0", "body": "Thanks!!! I am puzzled about the deadlock. Where does it deadlock? How many of the tests does it finish successfully?" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-03-09T20:07:42.180", "Id": "15700", "Score": "0", "body": "@AlexD, I updated my answer" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-03-10T05:33:48.100", "Id": "15713", "Score": "0", "body": "Thanks, good suggestion about `cache_node`. What benchmarking results do you get on JRuby?" } ], "meta_data": { "CommentCount": "3", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-03-09T15:59:24.953", "Id": "9858", "ParentId": "9583", "Score": "2" } } ]
{ "AcceptedAnswerId": "9858", "CommentCount": "1", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-03-01T09:58:11.177", "Id": "9583", "Score": "3", "Tags": [ "ruby", "performance", "multithreading", "stack" ], "Title": "Concurrent stack implementations in Ruby (relative performance of mutexes/CAS?)" }
9583
<p>I have the following solution structure. This is a business domain (for an amount transfer operation in bank account) which will be called by a WCF service. Is the solution structuring correct? </p> <ol> <li><p>Data Acess Layer does not create domain objects. It just pass database record wrapped in another simple object (DataEntities.AccountRow). Is it a good/standard approach?</p></li> <li><p>Manager and domain objects are in two different layers. Is it okay?</p></li> <li><p>A layer “DTOforServiceCommunication” is created for communicating with WCF service. </p></li> <li><p>Is DTOforServiceCommunication and DataEntities are redundant or a good practice?</p></li> <li><p>What are the improvement points for this solution structure?</p></li> </ol> <p>Note: The service mentioned above will be used by multiple business functions (clients). Since the SOA is not object oriented, we cannot pass business domain objects across the boundary.</p> <p><img src="https://i.stack.imgur.com/dFZHx.jpg" alt="enter image description here"></p> <p>// TransferDTO</p> <pre><code>namespace DTOforServiceCommunication { public class TransferDTO { public int UserID { get; set; } public int FromAccounutNumber { get; set; } public int ToAccountNumber { get; set; } public int AmountToTransfer { get; set; } } } </code></pre> <p>// AccountRow</p> <pre><code>namespace DataEntities { public class AccountRow { public int AccountNumber { get; set; } public string AccountType { get; set; } public int Duration { get; set; } public int DepositedAmount { get; set; } } } </code></pre> <p>// AccountManager</p> <pre><code>namespace BusinessManager { public class AccountManager { public void TransferAmount(DTOforServiceCommunication.TransferDTO transferDTO) { //DAL does not create domain objects. It just pass database record wrapped in another simple object DAL.AccountDAL accountDAL = new DAL.AccountDAL(); DataEntities.AccountRow row = accountDAL.GetAcocunt(transferDTO.UserID, transferDTO.FromAccounutNumber); DomainObject.IBankAccount bankAccount = null; if (String.Equals(row.AccountType, "Savings")) { bankAccount = new DomainObject.SavingsAccount(); bankAccount.UserID = transferDTO.UserID; bankAccount.AccountNumber = row.AccountNumber; bankAccount.AmountDeposited = row.DepositedAmount; } else { bankAccount = new DomainObject.FixedAccount(); bankAccount.UserID = transferDTO.UserID; bankAccount.AccountNumber = row.AccountNumber; bankAccount.AmountDeposited = row.DepositedAmount; } bankAccount.Transfer(transferDTO.ToAccountNumber, transferDTO.AmountToTransfer); } } } </code></pre> <p>//DAL</p> <pre><code>namespace DAL { //DAL does not create domain objects. It just pass database record wrapped in another simple object public class AccountDAL { List&lt;DataEntities.AccountRow&gt; dbRecords = new List&lt;DataEntities.AccountRow&gt;() { new DataEntities.AccountRow{AccountNumber=1,AccountType="Savings",Duration=6,DepositedAmount=50000}, new DataEntities.AccountRow{AccountNumber=2,AccountType="Fixed",Duration=6,DepositedAmount=50000} }; public DataEntities.AccountRow GetAcocunt(int userID, int accountNumber) { return dbRecords[0]; } } </code></pre> <h2> }</h2> <p>READING:</p> <ol> <li><p><a href="http://msdn.microsoft.com/en-us/magazine/dd569757.aspx" rel="nofollow noreferrer">http://msdn.microsoft.com/en-us/magazine/dd569757.aspx</a></p></li> <li><p><a href="https://stackoverflow.com/questions/125453/implementation-example-for-repository-pattern-with-linq-to-sql-and-c-sharp">https://stackoverflow.com/questions/125453/implementation-example-for-repository-pattern-with-linq-to-sql-and-c-sharp</a></p></li> <li><p><a href="https://stackoverflow.com/questions/3175/repository-pattern-tutorial-in-c-sharp/1374420#1374420">https://stackoverflow.com/questions/3175/repository-pattern-tutorial-in-c-sharp/1374420#1374420</a></p></li> <li><p><a href="https://stackoverflow.com/questions/151769/whats-the-common-way-for-oop-pattern-design-data-access">https://stackoverflow.com/questions/151769/whats-the-common-way-for-oop-pattern-design-data-access</a></p></li> <li><p><a href="https://stackoverflow.com/questions/4198136/classic-ado-net-or-entity-framework-better-for-larger-scale-database-transaction">https://stackoverflow.com/questions/4198136/classic-ado-net-or-entity-framework-better-for-larger-scale-database-transaction</a></p></li> <li><p><a href="http://sourceforge.net/projects/vanilla-dal/" rel="nofollow noreferrer">http://sourceforge.net/projects/vanilla-dal/</a></p></li> <li><p><a href="https://stackoverflow.com/questions/9474425/should-the-configuration-of-an-application-be-accessed-using-dal">https://stackoverflow.com/questions/9474425/should-the-configuration-of-an-application-be-accessed-using-dal</a></p></li> </ol>
[]
[ { "body": "<p>No, it is not. It sucked 10 yars ago and ever since LINQ and IQueryable it is just bad.</p>\n\n<p>How coms you need an AccountDAL while I have not had a DAL for a specific entity for the last 15 years, awlw\n\n<p>Please read up on RM's and all the technology that is avaialble in .NET ever since .NET 4.0 - querying is a generic interface (naturally you need a little more code below but only once or you use one of the plenthora of prepackaged open source DAL's).</p>\n\n<blockquote>\n <p>accountDAL.GetAcocunt(transferDTO.UserID, transferDTO.FromAccounutNumber);</p>\n</blockquote>\n\n<p>Two mistakes here. First, who cares about the user id? Account transfers are account to account, and account numebers better are unique REGARDLESS OF USER.</p>\n\n<p>So, it is:</p>\n\n<p>Accounting.Get(x => x.AccountNumber == transferDto.FromAccountNumber).</p>\n\n<p>Accounting is a generic repository that connects to my account indata, Get is a method implementing IQueryable and handling all loads.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-03-01T06:26:45.860", "Id": "15156", "Score": "0", "body": "Thanks. Could you please provide a link to good articles that will explain the concepts that you explained? Also, could you please answer question 4 in my post?" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-03-01T09:48:58.120", "Id": "15157", "Score": "0", "body": "Sure. Go to microsoft, read the .NET documentation. LINQ, IQueryable are standard components for more than a year." } ], "meta_data": { "CommentCount": "2", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-03-01T06:04:17.650", "Id": "9586", "ParentId": "9585", "Score": "1" } }, { "body": "<blockquote>\n <p>Data Acess Layer does not create domain objects. It just pass database record wrapped in another simple object (DataEntities.AccountRow). Is it a good/standard approach?</p>\n</blockquote>\n\n<p>Repository classes should create domain objects. The domain objects may or may not look the same as the DB entities. </p>\n\n<p>If you mean that you write your DAL by yourself (and not using a ORM): Stop with that. It's a waste of time. </p>\n\n<blockquote>\n <p>Manager and domain objects are in two different layers. Is it okay?</p>\n</blockquote>\n\n<p>Use the term WCF service and not manager. Yes. I consider WCF services to be an UI layer since it's the interface to the calling user/client.</p>\n\n<blockquote>\n <p>A layer “DTOforServiceCommunication” is created for communicating with WCF service.</p>\n</blockquote>\n\n<p>The name doesn't matter as long as you understand the difference between a domain object and a DTO.</p>\n\n<blockquote>\n <p>Is DTOforServiceCommunication and DataEntities are redundant or a good practice?</p>\n</blockquote>\n\n<p>Good practice. The DTO's should never change since it would break all clients that use them.</p>\n\n<blockquote>\n <p>What are the improvement points for this solution structure?</p>\n</blockquote>\n\n<p>No need for a <code>userId</code> in the WCF interfaces or the DTOs unless you want to let everyone be able to look at everybody elses accounts. Use the <code>userid</code> provided during authentication.</p>\n\n<p><strong>Update</strong></p>\n\n<p>Repository class using vanilla ADO.NET:</p>\n\n<pre><code>public class AccountRepository\n{\n Dictionary&lt;string, Type&gt; _accountClasses = new Dictionary&lt;string, Type&gt;{{\"savings\", typeof(SavingsAccount)}, {\"fixed\", typeof(FixedAccount)}};\n List&lt;DataEntities.AccountRow&gt; dbRecords = new List&lt;DataEntities.AccountRow&gt;()\n {\n new DataEntities.AccountRow{AccountNumber=1,AccountType=\"Savings\",Duration=6,DepositedAmount=50000},\n new DataEntities.AccountRow{AccountNumber=2,AccountType=\"Fixed\",Duration=6,DepositedAmount=50000}\n };\n\n public T Get&lt;T&gt;(int userID, int accountNumber) where T : Account\n {\n var sql = \"blabla\";\n using (var cmd = _connection.CreateCommand())\n {\n cmd.CommandText = sql;\n using (var reader = cmd.ExecuteReader())\n {\n if (!reader.Read())\n return null;\n\n var account = CreateRow(reader);\n if (account.GetType() != typeof(T));\n throw new InvalidOperationException(\"The requested account was not of the specified type\");\n\n return account;\n }\n }\n }\n\n public IEnumerable&lt;Account&gt; FindMyAccounts(int userId)\n {\n var sql = \"blabla\";\n using (var cmd = _connection.CreateCommand())\n {\n cmd.CommandText = sql;\n using (var reader = cmd.ExecuteReader())\n {\n List&lt;Account&gt; accounts = new List&lt;Account&gt;();\n while (reader.Read())\n {\n var account = CreateRow(reader);\n accounts.Add(account);\n }\n\n return accounts;\n }\n }\n } \n\n // IDataRecord = a row in a DataReader\n public Account CreateRow(IDataRecord record)\n {\n // might want to check so that the account got a \n Type type;\n if (!_accountClasses.TryGetValue(record[\"AccountType\"], out type))\n throw new InvalidOperationExcpetion(\"Account type do not exist: \" + record[\"AccountType\"]);\n\n var account = (Account)Activator.CreateInstance(record);\n\n // fill record here\n }\n\n}\n\npublic class Account\n{\n}\n\npublic class SavingsAccount : Account\n{\n}\n\npublic class FixedAccount : Account\n{\n}\n</code></pre>\n\n<p>Usage:</p>\n\n<pre><code>account = _repository.Get&lt;SavingsAccount&gt;(1, \"kdkdkdkdkd\");\n</code></pre>\n\n<p><strong>Update2</strong></p>\n\n<p>Added a <code>Find</code> method to show that the actual mapping is reused by all methods. </p>\n\n<p>The <code>Find</code> method will also return different types of accounts in the same list.</p>\n\n<p>You could also break out the <code>ExecuteReader</code> parts into two methods (one to fetch one item and one to fetch collections) to reuse the code more.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-03-01T06:32:12.257", "Id": "15158", "Score": "0", "body": "Thanks for the clear explanation. Could you please provide links for good articles/tutorials that explains use of \"Repository classes should create domain objects.\". Also, are you saying that SavingsAccount/FixedAccount should be created (after checking the type) inside DAL?" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-03-01T06:34:14.920", "Id": "15159", "Score": "1", "body": "What do your DAL contain exactly? I try to follow DDD, there are several articles about the repositories in DDD. Starting point: http://domaindrivendesign.org/" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-03-01T06:37:31.180", "Id": "15160", "Score": "0", "body": "I have updated the post with DAL code. It will actually query from database using ADO.NET in my current code. But for simplicity it is returning from a list." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-03-01T06:41:09.427", "Id": "15161", "Score": "1", "body": "That's in an essence a repository class. The difference is that it should use `SavingsAccount` and `FixedAccount` instead of `AccountRow`" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-03-01T06:48:24.087", "Id": "15162", "Score": "1", "body": "@Lijo: I've added an example of repository" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-03-01T07:36:04.303", "Id": "15163", "Score": "0", "body": "Thanks. Also, do you have any article/blog suggestion for repository pattern using LINQ to SQL?" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-03-01T07:45:11.500", "Id": "15164", "Score": "0", "body": "That you have to google yourself or ask a new question here at SO." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-03-01T08:30:33.680", "Id": "15165", "Score": "0", "body": "@Lijo: Got any more questions regarding your original question?" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-03-01T09:21:12.240", "Id": "15166", "Score": "0", "body": "jgauffin Thank you. The questions are clear now. Let me do some research and get back to you if any more questions. I am marking it as answered." } ], "meta_data": { "CommentCount": "9", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-03-01T06:24:33.600", "Id": "9587", "ParentId": "9585", "Score": "4" } } ]
{ "AcceptedAnswerId": "9587", "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-03-01T05:35:43.230", "Id": "9585", "Score": "3", "Tags": [ "c#", ".net", "object-oriented", "design-patterns" ], "Title": "Is the solution design optimal? C# 3 - Tier" }
9585
<p>This is the first piece of code I wrote on my own. I tried to use everything I know, like functions, loops and variables. Is it good or could it be simpler?</p> <p>Please be hard as you can be with me because I feel my programming knowledge is quite poor and I end up using Google for solving my problems.</p> <pre><code> // RPS.cpp : Defines the entry point for the console application. // #include "stdafx.h" #include &lt;iostream&gt; #include &lt;ctime&gt; #include &lt;cstdlib&gt; using namespace std; int nPlayerScore=0; int nComputerScore=0; int nPlayerMove=0; int nComputerMove=0; void DisplayScore() { cout &lt;&lt; "Player: " &lt;&lt; nPlayerScore &lt;&lt; endl; cout &lt;&lt; "Computer: " &lt;&lt; nComputerScore &lt;&lt; endl &lt;&lt; endl; } int GetMove() { cout &lt;&lt; "Please choose a move: \n1.Rock\n2.Paper\n3.Scissors\n"; int x; cin &gt;&gt; x; cout &lt;&lt; endl; return x; } void CalculateResults() { if (nPlayerMove==1) //player is Rock { if (nComputerMove==1) {cout &lt;&lt; "player Rock vs computer Rock: IT'S A TIE!";} if (nComputerMove==2) {cout &lt;&lt; "player Rock vs computer Paper: COMPUTER WON!"; nComputerScore=nComputerScore+1;} if (nComputerMove==3) {cout &lt;&lt; "player Rock vs computer Scissors: PLAYER WON!"; nPlayerScore=nPlayerScore+1;} } if (nPlayerMove==2) //player is Paper { if (nComputerMove==1) {cout &lt;&lt; "player Paper vs computer Rock: PLAYER WON!"; nPlayerScore=nPlayerScore+1;} if (nComputerMove==2) {cout &lt;&lt; "player Paper vs computer Paper: IT'S A TIE!";} if (nComputerMove==3) {cout &lt;&lt; "player Paper vs computer Scissors: COMPUTER WON!"; nComputerScore=nComputerScore+1;} } if (nPlayerMove==3) //player is Scissors { if (nComputerMove==1) {cout &lt;&lt; "player Scissors vs computer Rock: COMPUTER WON!"; nComputerScore=nComputerScore+1;} if (nComputerMove==2) {cout &lt;&lt; "player Scissors vs computer Paper: PLAYER WON!"; nPlayerScore=nPlayerScore+1;} if (nComputerMove==3) {cout &lt;&lt; "player Scissors vs computer Scissors: IT'S A TIE!";} } cout &lt;&lt; endl &lt;&lt; endl; } int main() { do { cout &lt;&lt; "Welcome to RPS 1.0a \tby GeTAFIX \n\n"; DisplayScore(); nPlayerMove=GetMove(); srand((unsigned)time(0)); nComputerMove=rand()%(3)+1; CalculateResults(); //cout &lt;&lt; "Press any key to continue..."; system("pause"); system("cls"); } while (1==1); } </code></pre>
[]
[ { "body": "<p>First of all, stop using <code>system(\"pause\");</code> and <code>system(\"cls\");</code>. Both of those are not portable, and are silly ways of achieving what you want. Take a look <a href=\"https://stackoverflow.com/q/1173208/559931\">here</a> for an actual solution.</p>\n\n<p>Secondly, you are seeding the random number generator every iteration. This is not only unnecessary, it is harmful: if you do this in a program that calls <code>rand</code> more than once a second, you will get the same result each call. Even if you are only accessing it once a second (as you may be here), it is bad practice in any case, and can lead to a decrease in randomness.</p>\n\n<p>Thirdly, I think you're getting a little far with splitting things into functions. It might make sense to split the move-reading part into a separate function if you're going to perform input validation, but I think it currently just complicates matters.</p>\n\n<p>Your <code>CalculateResults</code> function is overcomplicated. If 0 is rock, 1 is paper, and 2 is scissors, and <code>x</code> and <code>y</code> are the choices of the players, you can tell who won with <code>(3+x-y)%3</code>. If the result is 1 then <code>x</code> has won; if it is 2, then <code>y</code> has won; otherwise (if it is 0) there has been a tie.</p>\n\n<p>Further stylistic issues: you should fix your indentation, turn the <code>do ... while</code> loop into a <code>while(true)</code> or <code>for(;;)</code> loop, stop using <code>using namespace std;</code>, and disable precompiled headers (they offer no benefit for a single-file solution). You should also output <code>'\\n'</code> instead of <code>std::endl</code> unless you explicitly want to flush the stream; an expression like <code>std::cout &lt;&lt; std::endl &lt;&lt; std::endl</code> simply doesn't make sense.</p>\n\n<p>By the way, if you're using Google to solve your C++ problems, you're likely picking up a lot of information that's very wrong. Make sure you have a good book to learn from, such as <a href=\"http://rads.stackoverflow.com/amzn/click/020170353X\" rel=\"nofollow noreferrer\">Accelerated C++</a>.</p>\n\n<p>Your code could be simplified to this, although the behaviour isn't quite the same:</p>\n\n<pre><code>#include &lt;iostream&gt;\n#include &lt;string&gt;\n#include &lt;cassert&gt;\n#include &lt;ctime&gt;\n#include &lt;cstdlib&gt;\n\nstd::string numberToWeapon(int n) {\n switch (n) {\n case 0: return \"rock\";\n case 1: return \"paper\";\n case 2: return \"scissors\";\n }\n assert(!\"Invalid parameter\");\n}\n\nint main() {\n std::cout &lt;&lt; \"Rock-Paper-Scissors v1.0\\n\";\n\n int playerScore = 0;\n int ourScore = 0;\n std::srand(static_cast&lt;unsigned int&gt;(time(0)));\n\n while (true) {\n int playerMove;\n std::cout &lt;&lt; \"Please enter 1 for rock, 2 for paper, or 3 for scissors.\\n\";\n if (!(std::cin &gt;&gt; playerMove))\n return 0;\n --playerMove;\n if (playerMove &lt; 0 || playerMove &gt; 2) {\n std::cout &lt;&lt; \"Invalid input.\\n\";\n continue;\n }\n\n int ourMove = rand()%3;\n\n std::cout &lt;&lt; \"You played: \" &lt;&lt; numberToWeapon(playerMove) &lt;&lt; \". \";\n std::cout &lt;&lt; \"We played: \" &lt;&lt; numberToWeapon(ourMove) &lt;&lt; \".\\n\";\n switch ((3 + playerMove - ourMove) % 3) {\n case 0:\n std::cout &lt;&lt; \"The game is a tie.\\n\";\n break;\n case 1:\n std::cout &lt;&lt; \"You won!\\n\";\n ++playerScore;\n break;\n case 2:\n std::cout &lt;&lt; \"We won!\\n\";\n ++ourScore;\n break;\n }\n\n std::cout &lt;&lt; \"The score is currently:\\n\";\n std::cout &lt;&lt; \"You - \" &lt;&lt; playerScore &lt;&lt; \".\\n\";\n std::cout &lt;&lt; \"We - \" &lt;&lt; ourScore &lt;&lt; \".\\n\";\n }\n}\n</code></pre>\n\n<p>This results in a larger <code>main</code> function, but no global variables. You can argue on whether that's any better or not: personally, I think it's clear as it is, and I don't see any duplication, but you may want to experiment.</p>\n\n<p>If you are using C++11, you can get even more awesome syntax than the <code>numberToWeapon</code> function, namely:</p>\n\n<pre><code>std::array&lt;4, std::string&gt; weapons = {\"rock\", \"paper\", \"scissors\"};\n</code></pre>\n\n<p>And then use <code>weapons.at(num)</code> (or <code>weapons[num]</code> if you're sure you're in-bounds).</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-03-01T18:51:16.503", "Id": "15186", "Score": "0", "body": "I would note that re-seeding the rand even every second is still bad and leads to non random numbers." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-03-01T22:17:09.387", "Id": "15189", "Score": "0", "body": "thank you for all the critic, I like the code and your thought process and hope I can learn thinking in code like that soon... I also wanna go to school for either computer science or software engineering but still a little afraid i won't be disciplined about my codes and have a good struct thinking process of how to build it" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-03-02T05:30:40.993", "Id": "15201", "Score": "3", "body": "@johnsmith: Your code is not particularly bad; most of your errors may simply be a matter of not getting good information. The fact that you're asking for code reviews is already a good sign, and I advise you follow that path if you think it would be enjoyable." } ], "meta_data": { "CommentCount": "3", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-03-01T16:49:12.443", "Id": "9604", "ParentId": "9590", "Score": "5" } }, { "body": "<p>Agree with most of what Anton already mentioned:</p>\n\n<p>In addition:</p>\n\n<pre><code> using namespace std;\n</code></pre>\n\n<p>Stop using this.<br>\nIt works out great for small programs but for large programs it becomes more of a problem. Getting in to the habit of <strong>not</strong> using it.</p>\n\n<p>I would avoid over use of std::endl everywhere. What it does is place a newline character then flush the stream. If you have lots of output then it will cause the output to perform sub-optimally. </p>\n\n<pre><code>cout &lt;&lt; \"Player: \" &lt;&lt; nPlayerScore &lt;&lt; endl;\ncout &lt;&lt; \"Computer: \" &lt;&lt; nComputerScore &lt;&lt; endl &lt;&lt; endl;\n</code></pre>\n\n<p>In this case change two of the std::endl into \"\\n\". Then use the last one to flush the output to the screen.</p>\n\n<p>Good start but you should validate the input.<br>\nWhat If I typed Rock instead of 1. Then the stream gets broken and all further input is ignored. So validate your input and fix the stream if the bad bit is set.</p>\n\n<pre><code>int GetMove()\n{\n cout &lt;&lt; \"Please choose a move: \\n1.Rock\\n2.Paper\\n3.Scissors\\n\";\n int x;\n cin &gt;&gt; x;\n cout &lt;&lt; endl;\n return x;\n}\n</code></pre>\n\n<p>In this function:</p>\n\n<pre><code>void CalculateResults()\n</code></pre>\n\n<p>There are a lot of repeating strings. Anton suggested using functions to solve this. I think that is overkill for this situation and would just set up an array of strings.</p>\n\n<pre><code>static std::string weapon[] = { \"Rock\", \"Paper\", \"Scissors\" };\nstatic std::string result[3][] = {{ \"IT'S A TIE!\", \"COMPUTER WON!\", \"PLAYER WON!\" },\n { \"PLAYER WON!\", \"IT'S A TIE!\", \"COMPUTER WON!\"},\n { \"COMPUTER WON!\", \"PLAYER WON!\", \"IT'S A TIE!\" }\n };\n</code></pre>\n\n<p>Now you can easily display the weapons with:</p>\n\n<pre><code>std::cout &lt;&lt; \"player \" &lt;&lt; weapon[nPlayerMove-1]\n &lt;&lt; \" Vs \"\n &lt;&lt; \"computer \" &lt;&lt; weapon[nComputerMove-1]\n &lt;&lt; \" \" &lt;&lt; result[nPlayerMove-1][nComputerMove-1];\n</code></pre>\n\n<p>Lat of all:</p>\n\n<pre><code>cout &lt;&lt; \"Welcome to RPS 1.0a \\tby GeTAFIX \\n\\n\";\n</code></pre>\n\n<p>Here I would have used std::endl just to force a flush. Because the std::cin and std::cout are bound together with magic it does not really matter though.</p>\n\n<p>Initializing the random number generator should be done <strong>once</strong> in the application. So do it just after main() starts. There is no need to cast the result to unsigned. A lot of people think 0 is good here I still like using the macro NULL (the problem with NULL is that on crappy compilers it is not defined correctly for C++). To me the NULL conveys more information in that it is supposed to be a pointer not the number 0. Though with C++11 I am trying to use nullptr.</p>\n\n<p>Using this technique for generating a random value will get a lot of fanatics complaining.</p>\n\n<pre><code>nComputerMove=rand()%(3)+1;\n</code></pre>\n\n<p>Personally for this problem I think its fine. But a slightly better version would be:</p>\n\n<pre><code> nComputerMove=(rand() / (RAND_MAX * 1.0)) * 3 + 1;\n</code></pre>\n\n<p>This makes the distribution slightly more even. Because 3 does not divide exactly into RAND_MAX your version has a slightly higher probability of being Rock 1/10922 than Scissors 1/10923 (assuming RAND_MAX of 32767). If you want to be really pedantic about it you would throw out any values greater than <code>RAND_MAX/3*3</code>. Then use mod 3.</p>\n\n<p>Don't use this:</p>\n\n<pre><code>system(\"pause\");\nsystem(\"cls\");\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-03-01T22:19:18.287", "Id": "15190", "Score": "0", "body": "thank you :) I like the arrays idea and the way you print the results, ill fix my code soon with notes of everything you and Anton wrote." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-03-01T22:26:08.380", "Id": "15193", "Score": "0", "body": "Not always `1/10922` but rather `1/(RAND_MAX/3)`? On my computer, `RAND_MAX` is 2147483647." } ], "meta_data": { "CommentCount": "2", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-03-01T19:20:40.083", "Id": "9607", "ParentId": "9590", "Score": "4" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-03-01T12:10:46.983", "Id": "9590", "Score": "4", "Tags": [ "c++", "beginner", "game", "rock-paper-scissors" ], "Title": "Rock-Paper-Scissors game" }
9590
<p>I'm working on some code that deals with mangled C++ function names. I'm displaying these to the user, so to help with readability of some of the really long C++ template class/function names, I'm removing some of the template arguments based on how deeply nested the template argument is.</p> <p>The code below works fine, but it seems fairly clunky. It feels like I'm "writing C in any language". I'm wondering if I can improve it, shorten it, and make it more pythonic.</p> <pre><code>def removeTemplateArguments(str, depthToRemove): """ Remove template arguments deeper than depthToRemove so removeTemplateArguments("foo&lt;int&gt;()", 1) gives foo&lt;&gt;() removeTemplateArguments("foo&lt; bar&lt;int&gt; &gt;()", 1) gives foo&lt; &gt;() removeTemplateArguments("foo&lt; bar&lt;int&gt; &gt;()", 2) gives foo&lt; bar&lt;&gt; &gt;()""" if depthToRemove &lt;= 0: return str currDepth = 0 res = "" for c in str: if currDepth &lt; depthToRemove: res += c if c == "&lt;": currDepth += 1 elif c == "&gt;": currDepth -= 1 if currDepth &lt; depthToRemove: res += "&gt;" return res </code></pre>
[ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2015-05-02T17:12:32.953", "Id": "160487", "Score": "2", "body": "This is a C++ comment rather than a Python answer, but, please be aware that attempting to parse C++ template names with hand-written code places you in a state of sin just as much as if you were [considering arithmetical methods of producing random digits](https://en.wikiquote.org/wiki/John_von_Neumann). Consider how your code will handle `bool_< 1<2 >` or `bool_< (1>2) >` or `bool_< 1>= 2 >` (assuming `template<bool X> using bool_ = std::integral_constant<bool,X>` of course), and then consider whether you are *really* helping your users with this code." } ]
[ { "body": "<p>First of all, your code doesn't seem to work: <code>removeTemplateArguments(\"foo&lt; bar&lt;int&gt; &gt;()\", 2)</code> has a trailing \">\" that shouldn't be here according to your docstring:</p>\n\n<ul>\n<li><code>foo&lt; bar&lt;&gt; &gt;()</code> (expected)</li>\n<li><code>foo&lt; bar&lt;&gt; &gt;&gt;()</code> (actual)</li>\n</ul>\n\n<p>You nearly have written a <a href=\"http://docs.python.org/library/doctest.html\" rel=\"nofollow\">doctest</a>, finishing the work would have helped you catch the bug. Seems not that easy to fix by the way.</p>\n\n<p>Next, I would avoid using names like <code>str</code> which shadows the <a href=\"http://docs.python.org/library/functions.html#str\" rel=\"nofollow\">standard <code>str()</code> function</a>.</p>\n\n<p>My solution relies on <em>greedy</em> regular expressions and recursion (which seems natural here, given the nested template arguments).</p>\n\n<pre><code>import re\n\ndef removeTemplateArguments(function_name, depth):\n to_match = \"(?P&lt;class&gt;\\w+)&lt;\\s*(?P&lt;nested&gt;.*)\\s*&gt;(?P&lt;paren&gt;\\(?\\)?)\"\n parts = re.match(to_match, function_name).groupdict()\n nested = '' if depthToRemove == 1\n else removeTemplateArguments(parts['nested'], depth-1)\n\n return \"%s&lt;%s&gt;%s\" % (parts['class'], nested, parts['paren'])\n</code></pre>\n\n<p>Not sure how pythonic it is. I do not add any spaces since between chevrons. I could add some logic to add them if needed. I'm using named subgroups to make my regular expression more easy to read.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-03-01T13:45:29.927", "Id": "9594", "ParentId": "9592", "Score": "2" } }, { "body": "<p>For that kind of parsing <a href=\"http://docs.python.org/py3k/library/itertools.html#itertools.groupby\" rel=\"nofollow noreferrer\"><code>itertools.groupby</code></a> is the right tool.</p>\n<p>With <code>groupby</code>, as I used it down below, every group is either: <code>&lt;</code>,<code>&gt;</code> or an actual piece of code (like <code>foo</code>). So the only thing left to do is to increment/decrement the depth level and decide if the group should be appended or not to the final result list.</p>\n<pre><code>from itertools import groupby\n\ndef remove_arguments(template, depth):\n res = []\n curr_depth = 0\n for k,g in groupby(template, lambda x: x in ['&lt;', '&gt;']):\n text = ''.join(g) # rebuild the group as a string\n if text == '&lt;':\n curr_depth += 1\n\n # it's important to put this part in the middle\n if curr_depth &lt; depth:\n res.append(text)\n elif k and curr_depth == depth: # add the inner &lt;&gt;\n res.append(text)\n\n if text == '&gt;':\n curr_depth -= 1\n\n return ''.join(res) # rebuild the complete string\n</code></pre>\n<p>It's important to put the depth-level check in between the increment and decrement part, because it has to be decided if the <code>&lt;</code>/<code>&gt;</code> are <em>in</em> or <em>out</em> the current depth level.</p>\n<p>Output examples:</p>\n<pre><code>&gt;&gt;&gt; remove_arguments('foo&lt;int&gt;()', 1)\nfoo&lt;&gt;()\n&gt;&gt;&gt; remove_arguments('foo&lt; bar&lt;int&gt; &gt;()', 1)\nfoo&lt;&gt;()\n&gt;&gt;&gt; remove_arguments('foo&lt; bar&lt;int&gt; &gt;()', 2)\nfoo&lt; bar&lt;&gt; &gt;()\n&gt;&gt;&gt; remove_arguments('foo&lt; bar &gt;()', 2)\nfoo&lt; bar &gt;()\n</code></pre>\n<p>Also, a couple of quick style notes:</p>\n<ul>\n<li>Don't use <code>str</code> as variable name or you'll shadow the builitin <a href=\"http://docs.python.org/py3k/library/functions.html#str\" rel=\"nofollow noreferrer\"><code>str</code></a>.</li>\n<li>Don't use <code>CamelCase</code> for functions/variable names (look at <a href=\"http://www.python.org/dev/peps/pep-0008/\" rel=\"nofollow noreferrer\">PEP8</a>).</li>\n</ul>\n<hr />\n<p>Inspired by <em>lvc</em> comment, I've grouped here possible lambdas/functions to be used in <code>groupby</code>:</p>\n<pre><code>groupby(template, lambda x: x in ['&lt;', '&gt;']) # most obvious one\ngroupby(template, lambda x: x in '&lt;&gt;') # equivalent to the one above\ngroupby(template, '&lt;&gt;'.__contains__) # this is ugly ugly\ngroupby(template, '&lt;&gt;'.count) # not obvious, but looks sweet\n</code></pre>\n<hr />\n<h3>Update</h3>\n<p>To handle cases like: <code>foo&lt;bar&lt;int&gt;&gt;()</code>, you'll need a better <code>groupby</code> key function. To be specific, a key function that return the current depth-level for a given charachter.</p>\n<p>Like this one:</p>\n<pre><code>def get_level(ch, level=[0]):\n current = level[0]\n if ch == '&lt;':\n level[0] += 1\n if ch == '&gt;':\n level[0] -= 1\n current = level[0]\n\n return current\n</code></pre>\n<p>That take advantage of the mutable argument <code>level</code> to perform some kind of memoization.</p>\n<p>Observe that <code>remove_arguments</code> will now be more simple:</p>\n<pre><code>def remove_arguments(template, depth):\n res = []\n for k,g in groupby(template, get_level):\n if k &lt; depth:\n res.append(''.join(g))\n return ''.join(res)\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-03-02T00:26:47.713", "Id": "15196", "Score": "0", "body": "You don't need a list in the lambda - `x in '<>'` does the same." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-03-02T08:12:25.613", "Id": "15207", "Score": "0", "body": "`Template` is actually a class from `string`, we both got that wrong. :)" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-03-02T15:53:43.477", "Id": "15237", "Score": "0", "body": "What about something like `foo<bar<int>>`? Its legal in the new standard (and likely to get used inadvertently regardless)" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-03-02T20:07:53.883", "Id": "15267", "Score": "0", "body": "@WinstonEwert: Thanks for noticing that. I didn't thought/known of that case, it requires a better `groupby` key function to handle it. I've updated my answer :)" } ], "meta_data": { "CommentCount": "4", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-03-01T15:06:41.907", "Id": "9596", "ParentId": "9592", "Score": "5" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "1", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-03-01T12:53:24.207", "Id": "9592", "Score": "2", "Tags": [ "python" ], "Title": "Removing C++ template arguments from a C++ function name" }
9592
<p>I have two more methods the same as this except that they query a different table. Is there another way to know if the result of the query is <code>null</code>? The <code>hasher.CompareStringToHash()</code> method is not allowed to have a <code>null</code> value.</p> <p>If it's not <code>null</code>, it proceeds to an <code>else</code> condition, and inside that it checks if the encrypted password and password in the textfield are the same. If it's the same it will go to another <code>else</code> statement.</p> <p>Is there another way to shorten this code? Keep in mind that I should not have a <code>null</code> value in the <code>hasher.CompareStringToHash()</code>. Or, if possible, restrict calling that method if the result is <code>null</code> and lessen the <code>if</code> statements. How can I make this code cleaner and more efficient?</p> <pre><code>public void CheckAssistantsPassword() { DbClassesDataContext myDb = new DbClassesDataContext(dbPath); var password = (from userAccounts in myDb.Assistants where userAccounts.Ass_UserName== txtUserName.Text select userAccounts.Ass_Password).FirstOrDefault(); var hasher = new Hasher() { SaltSize = 16 }; if (password == null) { MessageBox.Show("Invalid Account"); } else { bool isOkay = hasher.CompareStringToHash(txtPassword.Text,password); if (isOkay) { MessageBox.Show("You May Now Login"); } else { MessageBox.Show("INVALID PASSWORD"); } } } </code></pre>
[ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-03-01T17:28:39.117", "Id": "15183", "Score": "6", "body": "Minor recommendation: Don't prefix or abbreviate things as \"Ass\". Use \"Asst\" for \"Assistant\"." } ]
[ { "body": "<p>I believe you're looking for <a href=\"http://msdn.microsoft.com/en-us/library/system.string.isnullorempty.aspx\" rel=\"nofollow\"><code>String.IsNullOrEmpty</code></a>.</p>\n\n<pre><code>// test for null or empty string\nif (!String.IsNullOrEmpty(password) {\n}\n\n// -- OR --\n\n// If the hasher call just can't accept null values, you can specify\n// an empty string to fall back on like so:\n(...LINQ...).FirstOrDefault(String.Empty);\n</code></pre>\n\n<p>I would also probably refactor this a bit:</p>\n\n<pre><code>public void CheckAssistantsPassword()\n{\n using (DbClassesDataContext myDb = new DbClassesDataContext(dbPath))\n {\n var password = (from userAccounts in myDb.Assistants\n where userAccounts.Ass_UserName == txtUserName.Text\n select userAccounts.Ass_Password).FirstOrDefault(String.Empty);\n\n var hasher = new Hasher { SaltSize = 16 };\n if (hasher.CompareStringToHash(txtPassword.Text, password))\n {\n // Success\n }\n else\n {\n // Invalid password\n }\n }\n}\n</code></pre>\n\n<p>Optionally you can place error checking on your context making sure you <em>can</em> establish a connection. Also, I recommend placing a <code>using()</code> block around your context to free it up after you're done with it.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-03-01T15:14:32.910", "Id": "15175", "Score": "0", "body": "Where would I insert that?" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-03-01T15:15:37.260", "Id": "15176", "Score": "0", "body": "@KyelJmD: I updated my answer with the implemented version. If you have any questions though, feel free to ask." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-03-01T15:21:56.030", "Id": "15177", "Score": "0", "body": "Is there anyway you could lessen the ifs? and put it in a method?" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-03-01T15:33:40.870", "Id": "15178", "Score": "0", "body": "@KyelJmD: Can `hasher.CompareStringToHash` accept a `String.Empty` (just not a `null`?) If so, I can drop at least one `if()`" } ], "meta_data": { "CommentCount": "4", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-03-01T15:07:47.710", "Id": "9598", "ParentId": "9597", "Score": "4" } }, { "body": "<p>I guess it's a matter of taste, but I would write your method like that :</p>\n\n<pre><code>public void CheckAssistantsPassword() {\n\n DbClassesDataContext myDb = new DbClassesDataContext(dbPath);\n var matches = (from userAccounts in myDb.Assistants\n where userAccounts.Ass_UserName== txtUserName.Text\n select userAccounts.Ass_Password)\n\n if (matches.Count() &gt; 0)\n {\n var hasher = new Hasher() { SaltSize = 16 };\n var password = matches(0);\n\n if (hasher.CompareStringToHash(txtPassword.Text,password))\n MessageBox.Show(\"You May Now Login\");\n else\n MessageBox.Show(\"Invalid Account\");\n }\n else {\n MessageBox.Show(\"INVALID PASSWORD\");\n } \n}\n</code></pre>\n\n<p>Then, as mentionned above, there's always the String.IsNullOrEmpty or <a href=\"http://msdn.microsoft.com/en-us/library/system.string.isnullorwhitespace.aspx\" rel=\"nofollow\">String.IsNullOrWhitespace</a> if you want to make sure your string is not made up of only blanks.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-03-01T15:13:10.813", "Id": "9600", "ParentId": "9597", "Score": "1" } }, { "body": "<p>Maybe try separating out your logic, from the display &amp; control flow: for example:</p>\n\n<pre><code>public enum LoginState\n{\n None,\n InvalidAccount,\n Valid,\n InavlidPassword\n}\n\npublic LoginState CheckPassword(string password, string userPassword)\n{\n if(string.IsNullOrEmpty(password))\n return LoginState.InavlidPassword;\n else\n {\n var hasher = new Hasher() { SaltSize = 16 };\n return hasher.CompareStringToHash(password, userPassword) ? LoginState.Valid : LoginState.InvalidAccount;\n }\n}\n</code></pre>\n\n<p>And then using it like so:</p>\n\n<pre><code>var loginState = CheckPassword(txtPassword.Text, password);\n\nswitch (loginState)\n{\n case InvalidAccount:\n MessageBox.Show(\"INVALID PASSWORD\"); \n break;\n case .... etc\n}\n</code></pre>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-03-01T15:14:54.377", "Id": "9601", "ParentId": "9597", "Score": "0" } }, { "body": "<p>I'd probably do it something like this:</p>\n\n<pre><code>public void CheckAssistantsPassword()\n{\n DbClassesDataContext myDb = new DbClassesDataContext(dbPath);\n var password = (from userAccounts in myDb.Assistants\n where userAccounts.Ass_UserName== txtUserName.Text\n select userAccounts.Ass_Password).FirstOrDefault();\n\n var hasher = new Hasher() { SaltSize = 16 };\n if (hasher.CompareStringToHash(txtPassword.Text, password ?? String.Empty);\n MessageBox.Show(\"You May Now Login\");\n else\n MessageBox.Show(\"INVALID PASSWORD\"); \n }\n</code></pre>\n\n<p>The <code>??</code> operator returns the value on the left side if it is not null. Otherwise, it returns the value on the right side.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-03-01T15:15:37.357", "Id": "9602", "ParentId": "9597", "Score": "0" } }, { "body": "<p>Your code looks logically OK to me. I have refactored it below which may or may not help.</p>\n\n<pre><code>private Hasher _hasher;\n\npublic Ctor(Hasher hasher) { _hasher = hasher; }\n\npublic bool IsPasswordValid(string pwd, Func&lt;context, string&gt; getHash, DbClassesDataContext context) {\n var hash = getHash(context);\n\n return hash == null ? false : _hasher.CompareStringToHash(pwd, hash);\n}\n</code></pre>\n\n<ul>\n<li>Password parameterised to improve testability and reduce responsibility of method</li>\n<li>Returns bool to reduce responsibility of method (another type can show the message box or whatever).</li>\n<li>Accepts query to remove need for the two other similar methods querying other tables and improve testability.</li>\n<li>Use of var to improve terseness (as requested), and readability.</li>\n<li>Injection of context to improve testability, remember to use using to ensure dispose is called.</li>\n<li>Magic number extraction to const for salt size to keep DRY.</li>\n<li>I modified the code directly in S/O, so high chance of typos!</li>\n<li>Method renamed to follow .NET convention surrounding methods returning booleans.</li>\n<li>Hasher injected into type ctor (ideally by IOC container) for improved testability.</li>\n</ul>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-03-01T15:26:53.220", "Id": "9603", "ParentId": "9597", "Score": "3" } }, { "body": "<p>Ever since LINQ came out I've been talking about how the <code>from ... in ... select</code> syntax is really awful. It looks friendly at first but it completely hides what is really going on which is really useful to understand. Here is the much shorter way of writing it with the extension methods off of IQueryable along with a few other adjustements.</p>\n\n<pre><code>public void CheckAssistantsPassword() {\n\n DbClassesDataContext myDb = new DbClassesDataContext(dbPath);\n var hasher = new Hasher() { SaltSize = 16 };\n\n var userAccount = myDb.Assistants.FirstOrDefault(x=&gt;x.Ass_UserName== txtUserName.Text);\n\n if(userAccount == null || userAccount.password == null) {\n MessageBox.Show(\"Invalid Account\");\n return;\n }\n if(hasher.CompareStringToHash(txtPassword.Text,password) ;\n MessageBox.Show(\"You May Now Login\");\n else\n MessageBox.Show(\"INVALID PASSWORD\"); \n}\n</code></pre>\n\n<p>A few notes, </p>\n\n<ul>\n<li>The <code>my*</code> naming convention is very visual-basic, you will never see it in C#</li>\n<li>I would probably move both the hasher and the db to a field on the class rather than creating them here.</li>\n<li>MessageBox.Show() is super-icky and hard to work with</li>\n<li>It seems like you are doing this directly in a codebehind form. That is generally going to become VERY hard to maintain. You might want to look into the Model-View-Presenter pattern but the basic idea is to put only your 'ui' logic in the code behind and any stuff like this into other classes. At the very least you do not want to have the same code that references ui elements (such as txtUserName) ALSO referencing database connections. It becomes a mess very quickly.</li>\n</ul>\n\n<p>As for similar methods, as you start to understand the above format you can start to understand lambdas and expressions, you don't have to understand them very deeply, but you can learn that they are simply another syntax for creating certain types of objects. Therefore you could refactor to this (using a refactoring plugin like CodeRush/Refactor Pro or Resharper will help immensely):</p>\n\n<pre><code>public void CheckAssistantsPassword() {\n CheckSomeonesPassword(this.myDb.Assistants, x=&gt;x.Ass_UserName== txtUserName.Text, x=&gt;x.password);\n}\npublic void CheckAssistantsPassword() {\n CheckBestFreindsPassword(this.myDb.Friends, x=&gt;x.FriendType == \"Best\", x=&gt;x.password);\n}\n\nprivate void CheckSomeonesPassword&lt;ENTITY_TYPE&gt;(IQueryable&lt;ENTITY_TYPE&gt; people, Expression&lt;Func&lt;ENTITY_TYPE, bool&gt;&gt; filter, Func&lt;ENTITY_TYPE, string&gt; getPassword) \n where ENTITY_TYPE : class {\n var person = people.FirstOrDefault(filter);\n\n if(person == null || getPassword(person)) {\n MessageBox.Show(\"Invalid Account\");\n return;\n }\n if(this.hasher.CompareStringToHash(txtPassword.Text,getPassword(password)) ;\n MessageBox.Show(\"You May Now Login\");\n else\n MessageBox.Show(\"INVALID PASSWORD\"); \n}\n</code></pre>\n\n<p>** The above code is untested but it should be enough to get you on the right track ** </p>\n\n<p>Feel free to ask questions in the comments area</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-03-01T21:59:24.550", "Id": "9611", "ParentId": "9597", "Score": "1" } }, { "body": "<p>I know there are already many responses to this question, but here are a few other tweaks:</p>\n\n<p>1 - Refactor the method to return a boolean result.. the method shouldn't really care about how you report errors, it should care about returning a simple result... <code>true</code>, the password's match, <code>false</code>, they don't:</p>\n\n<pre><code>public bool ValidatePassword(string username, string password)\n{\n if (string.IsNullOrEmpty(username)) throw new ArgumentException(\"Username is required.\", \"username\");\n if (string.IsNullOrEmpty(password)) throw new ArgumentException(\"Password is required.\", \"password\");\n\n using (var context = CreateDataContext())\n {\n string hash = GetPasswordHash(context, username);\n var hasher = new Hasher { SaltSize = 16 };\n\n return hasher.CompareStringToHash(password, hash);\n }\n}\n</code></pre>\n\n<p>2 - Throw an appropriate exception that represents the exceptional state.\n3 - Separate out how you are creating your <code>DbClassesDataContext</code> into its own method, so should this need to be changed, it is changed in one place:</p>\n\n<pre><code>public static DbClassesDataContext CreateDataContext()\n{\n return new DbClassesDataContext(_dbPath);\n}\n</code></pre>\n\n<p>4 - User compiled queries where possible. If you know you might be performing a query multiple times, there is little sense in having the query provider generate the sql each time, you might as well take advantage of the <code>CompiledQuery</code> type:</p>\n\n<pre><code>private static readonly Func&lt;DbClassesDataContext, string, IQueryable&lt;string&gt;&gt; GetPasswordHash\n = CompiledQuery.Compile((DbClassesDataContext context, string username) =&gt; \n context.Assistants.Where(a =&gt; a.Ass_UserName == username).Select(a =&gt; a.Ass_Password));\n</code></pre>\n\n<p>Other comments:</p>\n\n<p>5 - Rename your data context type to something more applicable. I'm sure your app isn't called <code>DbClasses</code>? The naming of a type should be relevant, in terms of data contexts, you might want to name it after the database name.\n6 - You're not storing the plain text password in the database are you? Only ever store the hash.</p>\n\n<p>Importantly the changes above allow you to logically separate out the concerns of the original method, now your validate function should be more streamlined:</p>\n\n<pre><code>public void CheckAssistantsPassword()\n{\n try \n {\n if (!ValidatePassword(txtUserName.Text, txtPassword.Text))\n MessageBox.Show(\"INVALID PASSWORD\");\n } \n catch (ArgumentException ex) \n {\n MessageBox.Show(ex.Message);\n }\n}\n</code></pre>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-03-08T14:23:16.637", "Id": "9807", "ParentId": "9597", "Score": "1" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "1", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-03-01T15:03:43.340", "Id": "9597", "Score": "4", "Tags": [ "c#", "performance", ".net", "authentication" ], "Title": "Check assistant's password" }
9597
<p>I'd like to get input on a F# actor that coordinates receives around a blocking message buffer. The actor is a piece of code that continuously tries to fetch messages from Azure Service Bus.</p> <pre><code>(* Copyright 2012 Henrik Feldt Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. *) namespace MassTransit.Async open Microsoft.ServiceBus open Microsoft.ServiceBus.Messaging open FSharp.Control open System open System.Threading open System.Runtime.CompilerServices open System.Collections.Concurrent open MassTransit.AzureServiceBus open MassTransit.Async.Queue open MassTransit.Async.AsyncRetry type internal Agent&lt;'T&gt; = AutoCancelAgent&lt;'T&gt; /// communication with the worker agent type RecvMsg = Start | Pause | Halt of AsyncReplyChannel&lt;unit&gt; | SubscribeQueue of QueueDescription * Concurrency | UnsubscribeQueue of QueueDescription | SubscribeTopic of TopicDescription * Concurrency | UnsubscribeTopic of TopicDescription /// concurrently outstanding asynchronous requests (workers) and Concurrency = uint32 /// State-keeping structure, mapping a description to a pair of cancellation token source and /// receiver set list. The CancellationTokenSource can be used to stop the subscription that /// it corresponds to. type WorkerState = { QSubs : Map&lt;QueueDescription, CancellationTokenSource * ReceiverSet list&gt;; TSubs : Map&lt;TopicDescription, // unsubscribe action (unit -&gt; Async&lt;unit&gt;) * CancellationTokenSource * ReceiverSet list&gt; } /// A pair of a messaging factory and a list of message receivers that /// were created from that messaging factory. and ReceiverSet = Pair of MessagingFactory * MessageReceiver list type ReceiverDefaults() = interface ReceiverSettings with member x.Concurrency = 1u member x.BufferSize = 1000u member x.NThAsync = 5u member x.ReceiveTimeout = TimeSpan.FromMilliseconds 50.0 /// Create a new receiver, with a queue description, /// a factory for messaging factories and some control flow data type Receiver(desc : QueueDescription, newMf : (unit -&gt; MessagingFactory), nm : NamespaceManager, receiverName : string, ?settings : ReceiverSettings) = let sett = defaultArg settings (ReceiverDefaults() :&gt; ReceiverSettings) let logger = MassTransit.Logging.Logger.Get(typeof&lt;Receiver&gt;) /// The 'scratch' buffer that tunnels messages from the ASB receivers /// to the consumers of the Receiver class. let messages = new BlockingCollection&lt;_&gt;(int &lt;| sett.BufferSize) /// Creates a new child token from the parent cancellation token source let childTokenFrom ( cts : CancellationTokenSource ) = let childCTS = new CancellationTokenSource() let reg = cts.Token.Register(fun () -&gt; childCTS.Dispose()) // what to do with the IDisposable...? childCTS let getToken ( cts : CancellationTokenSource ) = cts.Token /// Starts stop/nthAsync new clients and messaging factories, so for stop=500, nthAsync=100 /// it loops 500 times and starts 5 new clients let initReceiverSet newMf stop newReceiver pathDesc = let rec inner curr pairs = async { match curr with | _ when stop = curr -&gt; // we're stopping return pairs | _ when curr % sett.NThAsync = 0u -&gt; // we're at the first item, create a new pair logger.DebugFormat("creating new mf &amp; recv '{0}'", (pathDesc : PathBasedEntity).Path) let mf = newMf () let! r = pathDesc |&gt; newReceiver mf let p = Pair(mf, r :: []) return! inner (curr + 1u) (p :: pairs) | _ -&gt; // if we're not at an even location, just create a new receiver for // the same messaging factory match pairs with // of mf&lt;-&gt; receiver list | [] -&gt; return failwith "curr != 1, but pairs empty. curr &gt; 1 -&gt; pairs.Length &gt; 0" | (Pair(mf, rs) :: rest) -&gt; logger.Debug(sprintf "creating new recv '%s'" (desc.ToString())) let! r = desc |&gt; newReceiver mf // the new receiver let p = Pair(mf, r :: rs) // add the receiver to the list of receivers for this mf return! inner (curr + 1u) (p :: rest) } inner 0u [] let initReceiverSet1 : ((MessagingFactory -&gt; PathBasedEntity -&gt; Async&lt;MessageReceiver&gt;) -&gt; PathBasedEntity -&gt; _) = initReceiverSet newMf (sett.Concurrency) /// creates an async workflow worker, given a message receiver client let worker client = //logger.Debug "worker called" async { while true do //logger.Debug "worker loop" let! bmsg = sett.ReceiveTimeout |&gt; recv client if bmsg &lt;&gt; null then logger.Debug(sprintf "received message on '%s'" (desc.ToString())) messages.Add bmsg else //logger.Debug("got null msg due to timeout receiving") () } let startPairsAsync pairs token = async { for Pair(mf, rs) in pairs do for r in rs do Async.Start(r |&gt; worker, token) } /// cleans out the message buffer and disposes all messages therein let clearLocks () = async { while messages.Count &gt; 0 do let m = ref null if messages.TryTake(m, TimeSpan.FromMilliseconds(4.0)) then try do! Async.FromBeginEnd((!m).BeginAbandon, (!m).EndAbandon) (!m).Dispose() with | x -&gt; let entry = sprintf "could not abandon message#%s" &lt;| (!m).MessageId logger.Error(entry, x) } /// Closes the pair of a messaging factory and a list of receivers let closePair pair = let (Pair(mf, rs)) = pair logger.InfoFormat("closing {0} receivers and their single messaging factory", rs.Length) if not(mf.IsClosed) then try mf.Close() // this statement has cost a LOT of money in developer time, waiting for a timeout with | x -&gt; logger.Error("could not close messaging factory", x) for r in rs do if not(r.IsClosed) then try r.Close() with | x -&gt; logger.Error("could not close receiver", x) /// An agent that implements the reactor pattern, reacting to messages. /// The mutually recursive function 'initial' uses the explicit functional /// state pattern as described here: /// http://www.cl.cam.ac.uk/~tp322/papers/async.pdf /// /// A receiver can have these states: /// -------------------------------- /// * Initial (waiting for a Start or Halt(chan) message). /// * Starting (getting all messaging factories and receivers up and running) /// * Started (main message loop) /// * Paused (cancelling all async workflows) /// * Halted (closing things) /// * Final (implicit; reference is GCed) /// /// with transitions: /// ----------------- /// Initial -&gt; Starting /// Initial -&gt; Halted /// /// Starting -&gt; Started /// /// Started -&gt; Paused /// Started -&gt; Halted /// /// Paused -&gt; Starting /// Paused -&gt; Halted /// /// Halted -&gt; Final (GC-ed here) /// let a = Agent&lt;RecvMsg&gt;.Start(fun inbox -&gt; let rec initial () = async { logger.Debug "initial" let! msg = inbox.Receive () match msg with | Start -&gt; // create WorkerState for initial subscription (that of the queue) // and move to the started state let! rSet = initReceiverSet1 newReceiver desc let mappedRSet = Map.empty |&gt; Map.add desc (new CancellationTokenSource(), rSet) return! starting { QSubs = mappedRSet ; TSubs = Map.empty } | Halt(chan) -&gt; return! halted { QSubs = Map.empty; TSubs = Map.empty } chan | _ -&gt; // because we only care about the Start message in the initial state, // we will ignore all other messages. return! initial () } and starting state = async { logger.Debug "starting" do! desc |&gt; create nm use ct = new CancellationTokenSource () // start all subscriptions state.QSubs |&gt; Seq.map (fun x -&gt; x.Value) |&gt; Seq.append (state.TSubs |&gt; Seq.map(fun x -&gt; let (sd,cts,rs) = x.Value in cts,rs)) |&gt; Seq.collect (fun ctsAndRs -&gt; snd ctsAndRs) |&gt; Seq.collect (fun (Pair(_, rs)) -&gt; rs) |&gt; Seq.iter (fun r -&gt; Async.Start(r |&gt; worker, ct.Token)) return! started state ct } and started state cts = async { logger.DebugFormat("started '{0}'", desc.Path) let! msg = inbox.Receive() match msg with | Pause -&gt; cts.Cancel() return! paused state | Halt(chan) -&gt; logger.DebugFormat("halt '{0}'", desc.Path) cts.Cancel() logger.DebugFormat("moving to halted state '{0}'", desc.Path) return! halted state chan | SubscribeQueue(qd, cc) -&gt; logger.DebugFormat("SubscribeQueue '{0}'", qd.Path) do! qd |&gt; create nm // create new receiver sets for the queue description and kick them off as workflows let childAsyncCts = childTokenFrom cts // get a new child token to control the computation with let! recvSet = initReceiverSet1 newReceiver qd // initialize the receivers and potentially new messaging factories do! childAsyncCts |&gt; getToken |&gt; startPairsAsync recvSet // start the actual async workflow let qsubs' = state.QSubs.Add(qd, (childAsyncCts, recvSet)) // update the subscriptions mapping, from description to cts*ReceiverSet list. return! started { QSubs = qsubs' ; TSubs = state.TSubs } cts | UnsubscribeQueue qd -&gt; logger.Warn "SKIP:UnsubscribeQueue (TODO - do we even need this?)" return! started state cts | SubscribeTopic(td, cc) -&gt; logger.DebugFormat("SubscribeTopic '{0}'", td.Path) let childAsyncCts = childTokenFrom cts let! sub = td |&gt; Topic.subscribe nm receiverName let! pairs = initReceiverSet1 (Topic.newReceiver sub) td do! childAsyncCts |&gt; getToken |&gt; startPairsAsync pairs let tsubs' = state.TSubs.Add(td, ((fun () -&gt; sub |&gt; Topic.unsubscribe nm td), childAsyncCts, pairs)) return! started { QSubs = state.QSubs ; TSubs = tsubs' } cts | UnsubscribeTopic td -&gt; logger.DebugFormat("UnsubscribeTopic '{0}'", td.Path) match state.TSubs.TryFind td with | None -&gt; logger.WarnFormat("Called UnsubscribeTopic('{0}') on non-subscribed topic!", td.Path) return! started state cts | Some( unsubscribe, childCts, recvSet ) -&gt; childCts.Cancel() recvSet |&gt; List.iter (fun set -&gt; closePair set) let tsubs' = state.TSubs.Remove(td) do! unsubscribe () return! started { QSubs = state.QSubs ; TSubs = tsubs' } cts | Start -&gt; return! started state cts } and paused state = async { logger.DebugFormat("paused '{0}'", desc.Path) let! msg = inbox.Receive() match msg with | Start -&gt; return! starting state | Halt(chan) -&gt; return! halted state chan | _ as x -&gt; logger.Warn(sprintf "got %A, despite being paused" x) } and halted state chan = async { logger.DebugFormat("halted '{0}'", desc.Path) let subs = asyncSeq { for x in (state.QSubs |&gt; Seq.collect (fun x -&gt; snd x.Value)) do yield x for x in (state.TSubs |&gt; Seq.collect (fun x -&gt; let (s,cts,rs) = x.Value in rs)) do yield x } for rs in subs do closePair rs for unsub in state.TSubs |&gt; Seq.map (fun x -&gt; let (s, _, _) = x.Value in s) do do! unsub () do! clearLocks () // then exit chan.Reply() } initial ()) /// Starts the receiver which starts the consuming from the service bus /// and creates the queue if it doesn't exist member x.Start () = logger.InfoFormat("start called for queue '{0}'", desc) a.Post Start /// Stops the receiver; allowing it to start once again. /// (Stopping is done by disposing the receiver.) member x.Pause () = logger.InfoFormat("stop called for queue '{0}'", desc) a.Post Pause member x.Subscribe ( td : TopicDescription ) = logger.InfoFormat("subscribe called for topic description '{0}'", td) a.Post &lt;| SubscribeTopic( td, sett.Concurrency ) member x.Unsubscribe ( td : TopicDescription ) = logger.InfoFormat("unsubscribe called for topic description '{0}'", td) a.Post &lt;| UnsubscribeTopic( td ) /// Returns a message if one was added to the buffer within the timeout specified, /// or otherwise returns null. member x.Get(timeout : TimeSpan) = let mutable item = null let _ = messages.TryTake(&amp;item, timeout.Milliseconds) item member x.Consume() = asyncSeq { while true do yield messages.Take() } interface System.IDisposable with /// Cleans out all receivers and messaging factories. member x.Dispose () = logger.DebugFormat("dispose called for receiver on '{0}'", desc.Path) a.PostAndReply(fun chan -&gt; Halt(chan)) type ReceiverModule = /// &lt;code&gt;address&lt;/code&gt; is required. &lt;code&gt;settings&lt;/code&gt; is optional. static member StartReceiver(address : AzureServiceBusEndpointAddress, settings : ReceiverSettings) = match settings with | null -&gt; let r = new Receiver(address.QueueDescription, (fun () -&gt; address.MessagingFactoryFactory.Invoke()), address.NamespaceManager, NameHelper.GenerateRandomName()) r.Start () r | _ -&gt; let r = new Receiver(address.QueueDescription, (fun () -&gt; address.MessagingFactoryFactory.Invoke()), address.NamespaceManager, NameHelper.GenerateRandomName(), settings) r.Start () r </code></pre> <p>Focus on this code, but I would very much like code reviewers to review <a href="https://github.com/mpsbroadband/MassTransit-AzureServiceBus" rel="nofollow" title="MassTransit Azure Service Bus Transport">the larger body of code</a> as well.</p> <p>Questions; have I made beginner's mistakes when writing this code? It's one of my first production-level actors.</p> <p>Can things be optimized in ways that allure me? E.g. am I leaking performance somewhere or memory somewhere else?</p>
[ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-03-05T13:18:22.877", "Id": "15396", "Score": "0", "body": "So let's say something to try to get this question up into the active set." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-03-13T13:37:13.457", "Id": "15879", "Score": "1", "body": "long code + F# + concurrency + azure = difficult to review." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-03-14T06:28:13.127", "Id": "15932", "Score": "1", "body": "also = difficult to get right" } ]
[ { "body": "<p><em>Disclaimer:</em> I know some OCaml and a bit of Erlang, but never implemented an F# actor before. I also read the async paper you mentioned in the comments (apart from \"Semantics\" and \"Implementation\").</p>\n\n<h1>Style</h1>\n\n<p><strong>Indentation</strong></p>\n\n<pre><code>type RecvMsg =\n Start\n | Pause\n</code></pre>\n\n<p>You should indent Start like this:</p>\n\n<pre><code>type RecvMsg =\n | Start\n | Pause\n</code></pre>\n\n<p>The syntax allows you to omit the initial pipe, but it's because of one-liners like <code>type RecvMsg = Start | Pause | ...</code></p>\n\n<p><strong>Declaring types</strong></p>\n\n<pre><code>/// concurrently outstanding asynchronous requests (workers)\nand Concurrency = uint32\n</code></pre>\n\n<p>You should use <code>and</code> only for mutually recursive types. Concurrency could as well be defined just above <code>RecvMsg</code>.</p>\n\n<p><strong>Returning unit</strong> <code>else ()</code> is implicit and not needed.</p>\n\n<p><strong>Pattern matching</strong></p>\n\n<pre><code>let (Pair(mf, rs)) = pair\n</code></pre>\n\n<p>Why don't you <code>match pair with Pair(mf, rs) -&gt; ...</code>?</p>\n\n<p><strong>Comments</strong> Your comments are good! I especially liked the comment of the main agent, which helps to understand the state machine.</p>\n\n<h1>Code</h1>\n\n<p><strong>Tail Recursion</strong> Section 2.2 of the async paper mentions a way to define <code>count</code> that is elegant, concise and efficient. You should consider replacing the ugly <code>while True</code> loops with nice tail recursive functions. :)</p>\n\n<p><strong>States</strong></p>\n\n<p>I don't like all those \"in-between\" states, they make your actor look super complicated and don't seem natural. I have little experience with actors, so I can't tell if this is recommended or not.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-03-14T09:42:31.660", "Id": "15934", "Score": "0", "body": "\"Long code\": interesting that you say so. I don't want to have long code; this is as compact as I've been able to make it. Do you think I should be moving some of the utility functions out of the Receiver type? An argument against this is that it lessens cohesion and understandability." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-03-14T09:42:57.553", "Id": "15935", "Score": "0", "body": "\"match pair with Pair\": well said; changed to your suggestion!" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-03-14T09:43:57.443", "Id": "15936", "Score": "0", "body": "\"Recursive types\": I changed it into separate types; but in this case I used the `and` notation to show that it goes together with the type just above; what do you think about that?" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-03-14T09:47:11.637", "Id": "15938", "Score": "0", "body": "\"In-between states\": I've been thinking a lot about that. I'd really like to construct some type of formal proof on the actor to have my back clear, and then small states are usually easier. That said, `Initial` is because I want to initialize the **ReceiverSet** before the actor needs to start consuming messages. `starting` might be possible to collapse into `SubscribeQueue` message handler - but then I would have to pass a flag that it's the top-most queue and hence the 'major' cancellation token? `paused`, `halted` are in my eyes pretty nice." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-03-14T09:59:22.993", "Id": "15940", "Score": "0", "body": "About \"recursive types\", I think it's enough to just put `Concurrency` before `RecvMsg`." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-03-14T10:00:22.540", "Id": "15941", "Score": "0", "body": "\"In-between states\": In fact, it's the \"Starting\" state that seems wrong since it's going to be there for only one \"tick\". If it makes the proof easier, maybe it's OK. Sorry, I really don't know much about actor idioms, and can't help here (even though it seems to be the most important part)." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-03-14T10:01:41.557", "Id": "15942", "Score": "0", "body": "\"Long code\" was mainly an observation: more than 100 lines is \"long \" on Code Review, that's all. I don't know how to make it shorter anyway." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-03-24T23:44:22.590", "Id": "16424", "Score": "0", "body": "I don't see anything wrong with 'while true do'. It is more readable and less risky than a tail recursive function. By risky, I mean it is easy to mistake a function for being tail-recursive when it isn't." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-03-24T23:45:54.883", "Id": "16425", "Score": "0", "body": "In the same vein, I prefer 'if cond then x else y' for a two case scenario. Don't make it a match if it doesn't need to be." } ], "meta_data": { "CommentCount": "9", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-03-13T21:26:41.090", "Id": "9995", "ParentId": "9605", "Score": "2" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "3", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-03-01T18:31:31.800", "Id": "9605", "Score": "3", "Tags": [ "c#", ".net", "f#", "actor" ], "Title": "Review an asynchronous/message-oriented library actor" }
9605
<p>As I thought about <a href="https://stackoverflow.com/questions/9523476/how-to-skip-a-field-without-entering-value-in-c">this question</a> on SO, I realized that I wanted to implement either a string trimmer or a trimmed string inputter. </p> <p>This is what I came up with, but I have a nagging feeling I could have done better.</p> <p>Would you critique this, please?</p> <pre><code>#include &lt;string&gt; #include &lt;iostream&gt; #include &lt;sstream&gt; #include &lt;cassert&gt; template &lt;typename Ch, typename Tr, typename Alloc&gt; void trim(std::basic_string&lt;Ch, Tr, Alloc&gt;&amp; str, const std::locale&amp; loc) { // (b,e)=ltrim(str) typename std::basic_string&lt;Ch, Tr, Alloc&gt;::const_iterator b = str.begin(); typename std::basic_string&lt;Ch, Tr, Alloc&gt;::const_iterator e = str.end(); while( b != e &amp;&amp; std::isspace(*b, loc) ) b++; // (b,e)=rtrim(b,e) // Query: this loop looks u-g-l-y. Can it be less ugly? while( b != e ) { e--; if(!std::isspace(*e, loc)) { e++; break; } } // str=(b,e) // Query: this string self-assigns (sort of). Is this UB? str.assign(b, e); } template &lt;typename Ch, typename Tr, typename Alloc&gt; std::basic_istream&lt;Ch,Tr&gt;&amp; getTrimmedLine(std::basic_istream&lt;Ch,Tr&gt;&amp; is, std::basic_string&lt;Ch, Tr, Alloc&gt;&amp; str) { // Get raw data from input std::getline(is, str); // And trim it trim(str, is.getloc()); return is; } #define TEST #ifdef TEST template&lt;typename T, std::size_t N&gt; std::size_t countof( T (&amp; a)[N] ) { return N; } int main () { const char * const inputs[] = { "simple", " front", "back ", " both ", " front2", "back2 ", " both2 ", "\n", "", "\n\n\n", " \n", " ", " \n\n\n" }; const char * const outputs[] = { "simple", "front", "back", "both", "front2", "back2", "both2", "", "", "", "", "", "" }; assert(countof(inputs) == countof(outputs)); for(std::size_t i = 0; i &lt; countof(inputs); i++) { std::istringstream is(inputs[i]); std::string result; getTrimmedLine(is, result); assert(result == outputs[i]); } } #endif </code></pre>
[]
[ { "body": "<p>Some thoughts:</p>\n\n<ul>\n<li>Would you lose anything if <code>trim</code> took a single template parameter that would accept the type of the string? You're not doing anything with the individual parameters, after all.</li>\n<li>I don't think the second loop is particularly ugly. You could use <code>operator-</code> first and then only decrement if it's not a space, but I don't think that's particularly useful.</li>\n<li>Honestly don't know, about the undefined behaviour, you should ask on StackOverflow (I'm fairly certain that's on-topic there).</li>\n<li>I think you should check that <code>std::getline</code> left the stream in a good state before applying <code>trim</code>. You may also want to provide the possibility to pass extra parameters to <code>std::getline</code>.</li>\n<li><code>countof</code> should have the signature <code>std::size_t countof( T const (&amp; a)[N] )</code>.</li>\n</ul>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-03-02T22:03:59.490", "Id": "9654", "ParentId": "9610", "Score": "1" } }, { "body": "<pre><code>typename std::basic_string&lt;Ch, Tr, Alloc&gt;::const_iterator e = str.end();\n...\n\n// Query: this loop looks u-g-l-y. Can it be less ugly?\n while( b != e ) {\n e--;\n if(!std::isspace(*e, loc)) {\n e++;\n break;\n }\n }\n</code></pre>\n\n<p>This looks weird and tends to go UB.</p>\n\n<p>1) e = str.end();</p>\n\n<p>2) e--; /* it's better to use --e in this case */ you move one more far position after end()!!!</p>\n\n<p>3) std::isspace(<strong>*e</strong>, loc) &lt;--- UB, accessing the memory that haven't been allocated</p>\n\n<p>If you need to find the first and the last spaces in the string, use this:</p>\n\n<pre><code>b = find_if(str.begin(), str.end(), isspace_predicate);\ne = find_if(str.rbegin(), str.rend(), isspace_predicate);\n</code></pre>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-03-13T09:41:33.360", "Id": "9956", "ParentId": "9610", "Score": "2" } } ]
{ "AcceptedAnswerId": "9654", "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-03-01T21:46:32.250", "Id": "9610", "Score": "3", "Tags": [ "c++" ], "Title": "String Trimmer and trimmed Input routine" }
9610
<p>I'm building a GWT application for GAE, using JDO for Datastore access. I use and Entity class for data mapping, so it contains lots of Persistence annotations:</p> <pre><code>@PersistenceCapable(identityType = IdentityType.APPLICATION) public class AppointmentEntity implements Serializable { private static final long serialVersionUID = 1L; @PrimaryKey @Persistent(valueStrategy = IdGeneratorStrategy.IDENTITY) private Long id; @Persistent private String firstName; @Persistent private String lastName; @Persistent private String DNI; @Persistent private Date appointmentDate; @Persistent private String attendant; @Persistent private String treatment; @Persistent private String details; @Persistent private Date nextAppointment; @Persistent(serialized = "true") private DownloadableFile file; //getters and setters... </code></pre> <p>Because of GWT and JDO nature, i can't use this Entity classes in my presentation layer; so there's a need of passing Entity Object attributes to the corresponding DTO, which is a POJO that has the same attributes of the Entity class:</p> <pre><code>public class AppointmentDTO implements Serializable { private static final long serialVersionUID = 1L; private Long id; private String firstName; private String lastName; private String DNI; private Date appointmentDate; private Date nextAppointmentDate; private String attendant; private String treatment; private String details; //getters and setters... </code></pre> <p>To do the Job of mapping attributes i make a Wrapper class that handles it, but it doesn't feel quite right to me. Does anyone have a better approach?</p> <pre><code>public class AppointmentWrapper { private List&lt;AppointmentEntity&gt; entitiesList; public AppointmentWrapper(List&lt;AppointmentEntity&gt; appointmentEntities) { entitiesList = appointmentEntities; } public List&lt;AppointmentDTO&gt; getDTOList() { List&lt;AppointmentDTO&gt; dtoList = new ArrayList&lt;AppointmentDTO&gt;(); for (AppointmentEntity entity : entitiesList) { AppointmentDTO dto = new AppointmentDTO(); dto.setId(entity.getId()); dto.setFirstName(entity.getFirstName()); dto.setLastName(entity.getLastName()); dto.setAppointmentDate(entity.getAppointmentDate()); dto.setNextAppointmentDate(entity.getNextAppointment()); dto.setAttendant(entity.getAttendant()); dto.setDetails(entity.getDetails()); dto.setDNI(entity.getDNI()); dto.setTreatment(entity.getTreatment()); dtoList.add(dto); } return dtoList; } } </code></pre>
[ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-03-02T12:48:17.123", "Id": "15221", "Score": "0", "body": "My feeling is that few members have GWT/JDO experience, but lot of them have design/programming experience. Linking to what Entity or DTO are would probably help everyone understand the issue in order to help you." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-03-02T15:10:39.477", "Id": "15235", "Score": "0", "body": "As request, i'm included full classes source code. It's not a GWT/JDO problem, is more a design issue" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-03-02T16:22:38.143", "Id": "15251", "Score": "0", "body": "Solutions to design issues are frequently dependent on the technology being used." } ]
[ { "body": "<p>There is this <a href=\"http://code.google.com/p/objectify-appengine/wiki/ObjectifyWithGWT\" rel=\"nofollow\">concerning GWT and GAE objects</a>. If that doesn't work for you, I would rather have a class of public static methods that does the conversions rather than sticking it into some kind of \"wrapper class\" that contains object states. For example,</p>\n\n<pre><code>public final class JDOEntityUtil {\n\n static public AppointmentDTO toDTO(AppointmentEntity entity) {\n AppointmentDTO dto = new AppointmentDTO();\n dto.setId(entity.getId());\n dto.setFirstName(entity.getFirstName());\n dto.setLastName(entity.getLastName());\n dto.setAppointmentDate(entity.getAppointmentDate());\n dto.setNextAppointmentDate(entity.getNextAppointment());\n dto.setAttendant(entity.getAttendant());\n dto.setDetails(entity.getDetails());\n dto.setDNI(entity.getDNI());\n dto.setTreatment(entity.getTreatment());\n return dto;\n }\n\n static public AppointmentEntity toEntity(AppointmentDTO dto) {\n AppointmentEntity entity = new AppointmentEntity();\n entity.setId(dto.getId()); /* or however you want to construct this */\n entity.setFirstName(dto.getFirstName());\n entity.setLastName(dto.getLastName());\n entity.setAppointmentDate(dto.getAppointmentDate());\n entity.setNextAppointmentDate(dto.getNextAppointment());\n entity.setAttendant(dto.getAttendant());\n entity.setDetails(dto.getDetails());\n entity.setDNI(dto.getDNI());\n entity.setTreatment(dto.getTreatment());\n return entity;\n }\n}\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-03-02T17:00:32.007", "Id": "15255", "Score": "0", "body": "Using static methods makes more sense. Thanks!" } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-03-02T16:20:48.097", "Id": "9640", "ParentId": "9619", "Score": "3" } } ]
{ "AcceptedAnswerId": "9640", "CommentCount": "3", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-03-02T01:09:24.600", "Id": "9619", "Score": "1", "Tags": [ "java" ], "Title": "Parsing: Entity Classes to DTO" }
9619
<p>My goal in the method is to write a simple clustering program that determines if a clustering document is valid based on these rules:</p> <ul> <li>All clusterings start with <code>&lt;</code> and end with <code>&gt;</code>. Every start clustering <code>&lt;something&gt;</code> must be followed (eventually) by an end clustering <code>&lt;/something&gt;</code>.</li> <li>Clusterings must be properly nested as follows <code>&lt;a&gt;&lt;b&gt;data&lt;/b&gt;&lt;/a&gt;</code>. This is not allowed: <strike><code>&lt;a&gt;&lt;b&gt;data&lt;/a&gt;&lt;/b&gt;</code></strike>.</li> <li>The first clustering of the document is the <strong>root clustering</strong>. The document can have only one root clustering (and corresponding end clustering). Everything else must be enclosed inside the root's start and end clusterings. In the example above, <code>&lt;songdata&gt;</code> is the root.</li> <li>All clusterings are <strong>case-sensitive</strong>. This means <strong><code>&lt;song&gt;</code></strong> is not the same as <strong><code>&lt;Song&gt;</code></strong>, which is not the same as <strong><code>&lt;SONG&gt;</code></strong>, etc.</li> <li><p>Start and end clusterings do not have to occur on the same line, but each clustering can <strong>not</strong> be broken between two lines. So you <strong>can't</strong> do this:</p> <pre> &lt;dura tion> </pre></li> <li><p>The clustering name can contain <strong>only letters</strong>.</p></li> <li>Everything that is not a clustering is considered document data.</li> <li>Extra white space is ignored. Thus, <strong><code>&lt;a&gt; &lt;b&gt;data&lt;/b&gt; &lt;/a&gt;</code></strong> is the same as <strong><code>&lt;a&gt;&lt;b&gt;data&lt;/b&gt;&lt;/a&gt;</code></strong>.</li> </ul> <p>This is the code that I'm using to accomplish my task:</p> <pre><code>data=in.readLine(); ++line; nextDataValue=data.trim();//removes whitespace from both ends if(nextDataValue.charAt(0)!='&lt;') error("No enclosing root pillow.", line);//Everything else must be enclosed inside the root's start and end pillows. StringTokenizer tokenizer1=new StringTokenizer(nextDataValue, "&gt;"); while(tokenizer1.hasMoreTokens()) { nextDataValue=tokenizer1.nextToken();//extract each data element of the string if (nextDataValue.indexOf('&lt;') == -1) break;// no &lt; in line, so get next pillow=nextDataValue.substring(nextDataValue.indexOf('&lt;')+1, nextDataValue.length());// pillow=get &lt; to &gt; exclusive in nextDataValue if(pillow.charAt(0)!='/') { stack.push(pillow);//start start_pillow_pushed=true; } else if(pillow.charAt(0)=='/')//end { start_pillow_pushed=false; if(!stack.isEmpty()) { if(!nextDataValue.equals(stack.pop())) error("Mismatched start pillow "+nextDataValue+"&gt;", line);// For each pillow you find, pop the stack to see if the matching start pillow is there. } else error("Missing start pillow "+nextDataValue+"&gt;", line);//empty stack } } for(; (data=in.readLine())!=null;) { ++line; nextDataValue=data.trim();//removes whitespace from both ends if(nextDataValue.charAt(0)!='&lt;') error("No enclosing root pillow.", line);//Everything else must be enclosed inside the root's start and end pillows. StringTokenizer tokenizer2=new StringTokenizer(nextDataValue, "&gt;"); while(tokenizer2.hasMoreTokens()) { nextDataValue.trim(); nextDataValue=tokenizer2.nextToken();//extract each data element of the string if (nextDataValue.indexOf('&lt;') == -1) break;// no &lt; in line, so get next pillow=nextDataValue.substring(nextDataValue.indexOf('&lt;')+1, nextDataValue.length());// pillow=get &lt; to &gt; exclusive in nextDataValue if(pillow.charAt(0)!='/') { stack.push(pillow);//start start_pillow_pushed=true; } else if(pillow.charAt(0)=='/')//end { start_pillow_pushed=false; if(!stack.isEmpty()) { if(!nextDataValue.equals(stack.pop())) error("Mismatched start pillow "+nextDataValue+"&gt;", line);// For each pillow you find, pop the stack to see if the matching start pillow is there. } else error("Missing start pillow "+nextDataValue+"&gt;", line);//empty stack } } } if(stack.isEmpty()) System.out.println("Input clustering document is valid.");//reports the document is valid based on the clustering rules above else error("Missing end pillow for "+nextDataValue+"&gt;", line); </code></pre> <p>Please indicate what can be improved in this.</p>
[ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-03-02T06:37:26.480", "Id": "15203", "Score": "3", "body": "The headline of your question." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-03-02T12:22:04.053", "Id": "15217", "Score": "0", "body": "1/ It may not be homework, but it does feel like it since you're basically writing a parser of a subset of XML (if it is homework, please add the [tag:homework] tag). 2/ \"clustering\" is surprising choice for talking about what is [an element](http://www.w3.org/TR/1998/REC-DOM-Level-1-19981001/level-one-core.html#ID-745549614). (And [clustering](http://en.wikipedia.org/wiki/Clustering) already has a lot of meanings.) 3/ What is a pillow?" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-03-02T14:36:29.643", "Id": "62787", "Score": "0", "body": "+1 to everything @Cygal said. I would just add that you can probably make the code cleaner and more concise by using recursion, rather than an explicit stack." } ]
[ { "body": "<p>Thanks for sharing your code! Let's see what can be improved.</p>\n\n<h2>Design</h2>\n\n<p>You're mixing a lot of things in your code. This makes it difficult to read and write. It also violates the <a href=\"http://en.wikipedia.org/wiki/Single_responsibility_principle\" rel=\"nofollow\">Single Responsibility Principle</a>. I'd recommend separating those three \"responsibilities\" in different functions/classes. The easiest way to do it is to have three functions:</p>\n\n<ol>\n<li><p>The handling of multiple lines (String -> String)</p>\n\n<pre><code>readfile(\"&lt;a&gt; &lt;b&gt;\\ndata&lt;/b&gt;\\n &lt;/a&gt;\") == \"&lt;a&gt; &lt;b&gt; data&lt;/b&gt; &lt;/a&gt;\"\n</code></pre></li>\n<li><p>The tokenizing of the tag names (String -> List)</p>\n\n<pre><code>tokenize(\"&lt;a&gt; &lt;b&gt; data&lt;/b&gt; &lt;/a&gt;\") == [\"&lt;a&gt;\", \"&lt;b&gt;\", \"data\", \"&lt;/b&gt;\", \"&lt;/a&gt;\"]\n</code></pre></li>\n<li><p>The use of the stack to ensure that the document is valid (List -> bool)</p>\n\n<pre><code>isValid([\"&lt;a&gt;\", \"&lt;b&gt;\", \"data\", \"&lt;/b&gt;\", \"&lt;/a&gt;\"]) == true\n</code></pre></li>\n</ol>\n\n<p>If you're worried about performance (you shouldn't, most XML parsers keep the whole tree in memory), you can always group the first and second function in a Iterator, which will decouple the reading/tokenizing from the validation logic, and you will still be doing stream-based parsing. This simply reduces memory usage, and can be a bit faster.</p>\n\n<h2>Code</h2>\n\n<ol>\n<li>You're <a href=\"https://en.wikipedia.org/wiki/Don%27t_repeat_yourself\" rel=\"nofollow\">repeating yourself</a> before and after the loop. Use a <code>do { } while()</code> construct to avoid this issue.</li>\n<li>Be careful about your indentation. For example, <code>if(nextDataValue.charAt(0)!='&lt;') error(\"No enclosing root pillow.\", line);</code> is not the starting of a block, and you should not indent what's after. Java IDEs can indent code if you don't know how to do it.</li>\n<li>When checking for <code>pillow.charAt(0)</code>, don't use <code>else if</code> but <code>else</code> for the second block. It makes it clear that the two conditions cover every case.</li>\n<li>The <code>start_pillow_pushed</code> variable is not used anywhere. Never keep dead code around, it simply confuses the reader.</li>\n</ol>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-03-02T12:43:45.057", "Id": "9634", "ParentId": "9620", "Score": "11" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "3", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-03-02T02:14:58.087", "Id": "9620", "Score": "2", "Tags": [ "java", "validation", "clustering" ], "Title": "Validating a clustering document" }
9620
<p>I have created this model for Codeigniter. It's working fine, but I need to know if it can be more optimized.</p> <pre><code>class Basic_Function_Model extends CI_Model { var $msg_invalid_array; var $msg_no_table; function __construct() { parent::__construct(); $this-&gt;msg_invalid_array = "Data must be provided in the form of array"; $this-&gt;msg_no_table = "Table does not exist in database"; $this-&gt;load-&gt;database(); } public function insertInDatabase($table, $insertData, $mode = "single") { if( !is_array($insertData) ) { return $this-&gt;msg_invalid_array; } if( !$this-&gt;validateTable($table) ) { return $this-&gt;msg_no_table; } if( $mode == "batch" ) { return $this-&gt;db-&gt;insert_batch($table, $insertData); } else { $this-&gt;db-&gt;insert($table, $insertData); return $this-&gt;db-&gt;insert_id(); } } public function updateInDatabase($table, $updateData, $conditionData) { if( !is_array($updateData) || !is_array($conditionData) ) { return $this-&gt;msg_invalid_array; } if( !$this-&gt;validateTable($table) ) { return $this-&gt;msg_no_table; } if( $this-&gt;db-&gt;update($table, $updateData, $conditionData) ) return $this-&gt;db-&gt;affected_rows(); else return false; } public function deleteFromDatabase($table, $conditionData) { if( !is_array($conditionData) ) { return $this-&gt;msg_invalid_data; } if( !$this-&gt;validateTable($table) ) { return $this-&gt;msg_no_table; } return $this-&gt;db-&gt;delete($table, $conditionData); } public function insertOnDuplicateKeyUpdate($table, $tableData) { if( !is_array($tableData) ) { return $this-&gt;msg_invalid_data; } if( !$this-&gt;validateTable($table) ) { return $this-&gt;msg_no_table; } foreach( $tableData as $column =&gt; $value ) { $columnNames[] = $column; $insertValues[] = "'".$value."'"; $updateValues[] = $column." = '".$value."'"; } $this-&gt;db-&gt;query("insert into $table(".implode(', ', $columnNames).") values(".implode(', ', $insertValues).") on duplicate key update ".implode(', ', $updateValues)); return $this-&gt;db-&gt;insert_id(); } private function validateTable($tableName) { $result = $this-&gt;db-&gt;list_tables(); foreach( $result as $row ) { if( $row == $tableName ) return true; } return false; } } </code></pre>
[]
[ { "body": "<p>First of all, thanks for sharing your code, this is the best way to improve yourself!</p>\n\n<h2>The M in MVC</h2>\n\n<p>A <em>Model</em> in any MVC framework should provide an easy way to access a <em>specific</em> type of data. It allows you to stop worrying about database details and only access your specific type of data in a meaningful way. For a StackOverflow-like website, this means that your Controller can relax! Your controller doesn't want to know about <code>INSERT INTO Questions(id, title, message, author) VALUES (9624, \"Codeigniter Model Optimization\", \"...\", \"Shayan\")</code>. He just wants to do <code>$questions-&gt;add(\"Codeigniter Model Optimization\", \"...\", \"Shayan\")</code> and know that all details (including security) are going to be handled by the Model.</p>\n\n<p>The model should be in charge of ensuring everything goes well with the database, but that's not what you're doing here. You're creating a <a href=\"http://www.joelonsoftware.com/articles/LeakyAbstractions.html\" rel=\"nofollow\">Leaky Abstraction</a>, and this doesn't help you. Try coming up with a model that reduces the work the controller needs to do.</p>\n\n<h2>A few comments on the code itself.</h2>\n\n<ul>\n<li>You're repeating yourself a lot at the start of each function. One fix would be to put this in a function:\n $checks = $this->check($table, $conditionData);\n if ($checks !== FALSE) return $checks;</li>\n<li>But the real fix is to remove those. <a href=\"http://codeigniter.com/user_guide/database/queries.html\" rel=\"nofollow\"><code>$this-&gt;db-&gt;query()</code></a> already removes FALSE when there's an issue. You should use it to check if there's an issue, and then decide what to do then. The handling of issues is what makes abstractions successful. Remember than <em>\"It's easier to ask for forgiveness than it is to get permission\"</em>.</li>\n<li>Please use <a href=\"http://www.codeigniter.com/user_guide/database/queries.html\" rel=\"nofollow\">query bindings (at then end of the page)</a> which will avoid SQL injections. They're using <a href=\"http://www.php.net/manual/en/pdo.prepared-statements.php\" rel=\"nofollow\">PHP's prepared statements</a>, which you should learn about if you want to write secure applications.</li>\n</ul>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-03-02T09:01:46.083", "Id": "15208", "Score": "0", "body": "Thanx for your valuable advices. I have used the security class of codeigniter to prevent from sql injection. what i believe model should only interact with the database it does not perform the validations and other security checks that are not related to database the only reason for using validation of parameter is that if parameters are not provided then codeigniter prints the complete query on browser which is definately a flaw. According to my opinion security checks must be done in controller. So please tell me the advantages of doing that in model instead of controller...." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-03-16T09:45:20.743", "Id": "16045", "Score": "0", "body": "you are wrong about the printing query when i changed the environment to production it still prints the entire query when an error occurs" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-03-16T10:10:39.533", "Id": "16048", "Score": "0", "body": "Production mode hides PHP errors. Set [db_debug](http://codeigniter.com/user_guide/database/configuration.html) to false to also hide database queries." } ], "meta_data": { "CommentCount": "3", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-03-02T08:02:38.917", "Id": "9626", "ParentId": "9624", "Score": "3" } }, { "body": "<p>The code </p>\n\n<pre><code>$insertValues[] = \"'\".$value.\"'\";\n</code></pre>\n\n<p>in function <code>insertOnDuplicateKeyUpdate</code>.</p>\n\n<p>If you have sent values for some date field as <code>SYSDATE()</code> or <code>NOW()</code>, it won't execute the function and will not insert the proper value.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-03-02T12:04:12.557", "Id": "9633", "ParentId": "9624", "Score": "1" } }, { "body": "<p>Obviously much time has passed since the posting of this question, but I thought I would take a moment to add my review.</p>\n<ol>\n<li><p>I wouldn't declare/use either of the strings that describe the query error relating to table name or datatype. If you have a script that is not using the correct table name or datatype, then you are going to find these occurrence during testing. If you have such flexible controllers that dynamic (or even user-supplied) table names are being passed in, then you need to validate the data before it gets to the model. Trash these:</p>\n<pre><code> $this-&gt;msg_invalid_array = &quot;Data must be provided in the form of array&quot;;\n $this-&gt;msg_no_table = &quot;Table does not exist in database&quot;;\n</code></pre>\n</li>\n<li><p>That said, if you are going to declare class properties, then obey <a href=\"https://www.php-fig.org/psr/psr-12/#:%7E:text=Visibility%20MUST,%20used%20to%20declare%20a%20property\" rel=\"nofollow noreferrer\">the PSR-12 standard</a>:</p>\n<blockquote>\n<p>Visibility MUST be declared on all properties.</p>\n<p>The var keyword MUST NOT be used to declare a property.</p>\n</blockquote>\n<p>...but again just trash <code>var $msg_invalid_array;</code> and <code>var $msg_no_table;</code></p>\n</li>\n<li><p>By removing the error strings that you originally return in the validating conditions, you standardize the return value's datatype as <code>int</code> on all &quot;writing&quot; queries. I do not recommend returning a mix of integer type data and booleans; I prefer to return (sometimes nullable) int types.</p>\n</li>\n<li><p>Because single row inserts have a fundamentally different data structure and return value versus bulk inserts, I don't see any value in trying to merge them into a single method. I recommend declaring separate methods, and declaring the datatypes.</p>\n<pre><code> public function insertRowWrapper(string $table, array $data): int\n { \n $this-&gt;db-&gt;insert($table, $insertData);\n return $this-&gt;db-&gt;insert_id(); \n }\n\n public function insertBatchWrapper(string $table, array $data): int\n return $this-&gt;db-&gt;insert_batch($table, $insertData); // returns affected_rows\n }\n</code></pre>\n</li>\n<li><p>Again, remove the conditions and declare the data types in your update and delete methods. Different from the insert queries, the update and delete queries can execute without error and have 0 affected rows. For this reason, you should differentiate query results which truly affected rows and queries that made no changes to the database -- all subsequent processes will be far more accurate about the data used/presented.</p>\n<pre><code> public function updateWrapper(string $table, array $setData, array $conditions): int\n {\n $this-&gt;db-&gt;update($table, $setData, $conditions);\n return $this-&gt;db-&gt;affected_rows();\n }\n\n public function deleteWrapper(string $table, array $conditions): int\n {\n $this-&gt;db-&gt;delete($table, $conditions);\n return $this-&gt;db-&gt;affected_rows();\n }\n</code></pre>\n</li>\n<li><p>The only method that is providing some semblance of utility is the <code>insertOnDuplicate()</code> method, but it isn't implementing proper quoting on identifiers nor escaping the values. Of course, this method is employeeing driver-specific syntax, so it will not be instantly migratable to all possible drivers. If it works for what your current driver, okay; it's just that if your driver changes, then this method might need to change as well.</p>\n<pre><code> public function insertElseUpdate(string $table, array $data): int\n {\n foreach ($tableData as $column =&gt; $value) {\n $insertColumns[] = $this-&gt;db-&gt;protect_identifiers($column);\n $insertValues[] = $value;\n $updateExpressions[] = $this-&gt;db-&gt;protect_identifiers($column) . ' = ?';\n }\n $insertPlaceholders = implode(', ', array_fill(0, count($insertValues), '?'));\n\n $sql = 'INSERT INTO ' . $this-&gt;db-&gt;protect_identifiers($table)\n . ' (' . implode(', ', $insertColumns) . ')'\n . ' VALUES (' . $insertPlaceholders . ')'\n . ' ON DUPLICATE KEY UPDATE ' . implode(', ', $updateExpressions)\n $this-&gt;db-&gt;query($sql, [...$insertValues, ...$insertValues]);\n return $this-&gt;db-&gt;insert_id(); // I honestly didn't test how this would behave in either scenario\n }\n</code></pre>\n</li>\n</ol>\n<p>Ultimately, I don't see much benefit in writing this class of CRUD wrappers. I recommend writing classes that individualize the entities/objects of your application, so that specific tailoring can be done within the scope of the class.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-11-28T13:23:35.910", "Id": "252785", "ParentId": "9624", "Score": "0" } } ]
{ "AcceptedAnswerId": "9626", "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-03-02T06:05:40.640", "Id": "9624", "Score": "5", "Tags": [ "php", "codeigniter" ], "Title": "Codeigniter Model Optimization" }
9624
<p>Flash messages are generally composed in the controller. Sometimes we need those flash messages to have links in them (like an <kbd>undo</kbd> button).</p> <p>How would you compose such a message?</p> <p>The only sane way I have found to create such messages is by a presenter that includes much of ActionView in it (in order to gain access to most of the view helpers).</p> <p>Right now the code in the controller looks like this:</p> <pre><code>def publish @post.publish! flash[:notice] = "Post &lt;a href=\"/posts/#{@post.id}\"&gt;#{@post.title}&lt;/a&gt; " + "was published successfully" redirect_to @post end </code></pre> <p>and in the view I do a <code>&lt;%= raw flash[:notice] %&gt;</code> to display it.</p>
[]
[ { "body": "<p>You actually have several options. One way to clean this up a bit would be to use Rails' <a href=\"http://guides.rubyonrails.org/i18n.html\" rel=\"nofollow\">I18n</a> module, e.g.:\n</p>\n\n<pre class=\"lang-none prettyprint-override\"><code># config/locales/en.yml\nen:\n post_successful_html: Post &lt;a href=\"%{url}\"&gt;%{title}&lt;/a&gt; was\n published successfully.\n\n# the `_html` suffix marks the string as HTML-safe automatically\n</code></pre>\n\n<p>Then in your controller:\n</p>\n\n<pre class=\"lang-rb prettyprint-override\"><code>flash[:notice] = t :post_successful_html, :url =&gt; post_path( @post ),\n :title =&gt; @post.title\n</code></pre>\n\n<p>And the view:\n</p>\n\n<pre class=\"lang-html prettyprint-override\"><code>&lt;%= flash[:notice] %&gt;\n</code></pre>\n\n<p>(You could also do this the other way around and just put \"<code>:post_successful_html</code>\" in <code>flash</code> and then call <code>t flash[:notice], :url =&gt; ...</code> in the view but that feels messier to me.) Using I18n for just one thing seems a little like overkill but it is nice and clean (and if you've ever considered localizing your your app it's never too early to start).</p>\n\n<hr>\n\n<p>An alternative is to break what you need out into a partial, e.g. <code>_post_successful_flash.html.erb</code>:</p>\n\n<pre class=\"lang-html prettyprint-override\"><code>Post &lt;%= link_to post.title, post %&gt; was published successfully.\n</code></pre>\n\n<p>And then in your controller:\n</p>\n\n<pre class=\"lang-rb prettyprint-override\"><code>flash[:notice] = render_to_string :partial =&gt; 'post_successful_flash',\n :object =&gt; @post, :as =&gt; :post\n</code></pre>\n\n<hr>\n\n<p>Finally, you could do it in a helper instead:</p>\n\n<pre class=\"lang-rb prettyprint-override\"><code>module PostsHelper\n def render_post_successful post\n \"Post #{link_to post.title, post} was published successfully.\"\n end\nend\n</code></pre>\n\n<p>Then in the controller:</p>\n\n<pre class=\"lang-rb prettyprint-override\"><code>flash[:notice] = :post_successful\n</code></pre>\n\n<p>And the view:\n</p>\n\n<pre class=\"lang-html prettyprint-override\"><code>&lt;%= render_post_successful @post if flash[:notice] == :post_successful %&gt;\n</code></pre>\n\n<hr>\n\n<p>Which one you should use is sort of a toss-up to me. I'm fond of the I18n approach but partly because I prefer to keep messages like this in locales anyway. Use whatever makes the most sense to you.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-03-05T09:11:24.990", "Id": "15392", "Score": "0", "body": "I think I'll use the `render_to_string` approach and might give a try to the i18n approach on a new project that's still young and fit for experimentation. Thanks :-)" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-11-27T02:50:30.477", "Id": "129728", "Score": "0", "body": "Excellent idea to use render_to_string to do this!" } ], "meta_data": { "CommentCount": "2", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-03-03T02:40:17.767", "Id": "9659", "ParentId": "9629", "Score": "2" } } ]
{ "AcceptedAnswerId": "9659", "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-03-02T09:27:21.967", "Id": "9629", "Score": "4", "Tags": [ "ruby", "ruby-on-rails", "mvc" ], "Title": "HTML flash messages" }
9629
<p>Can this Code be any shorter? because it seems it is very long with just simple insertion of data using LINQ TO SQL</p> <pre><code> public void addPatientInformation() { using(DbClassesDataContext myDb = new DbClassesDataContext()){ PatientInfo patientInfo = new PatientInfo(); patientInfo.Phy_ID = physcianID; patientInfo.Pat_First_Name = txtFirstName.Text; patientInfo.Pat_Middle_Init = txtMiddleName.Text; patientInfo.Pat_Last_Name = txtLastName.Text; patientInfo.Pat_Gender = cmbGender.Text; patientInfo.Pat_Marital_Status = cmbMaritalStatus.Text; patientInfo.Pat_Date_Of_Birth = dtpDOB.Value; patientInfo.Pat_Home_Add = txtHomeAdd.Text; patientInfo.Pat_Home_Num = txtPhone.Text; patientInfo.Pat_Work_Add = txtWorkAdd.Text; patientInfo.Pat_Work_Num = txtWorkPhone.Text; patientInfo.Pat_Prim_Physician = txtPrimPhysician.Text; patientInfo.Pat_Ref_Physician = txtRefePhysician.Text; myDb.PatientInfos.InsertOnSubmit(patientInfo); myDb.SubmitChanges(); } </code></pre>
[]
[ { "body": "<p>Yes. You can use <a href=\"http://msdn.microsoft.com/en-us/library/bb384062.aspx\">object initializer</a> syntax and bring the amount of text down a bit:</p>\n\n<pre><code> public void addPatientInformation() {\n using(DbClassesDataContext myDb = new DbClassesDataContext()) {\n myDb.PatientInfos.InsertOnSubmit(new PatientInfo {\n Phy_ID = physcianID,\n Pat_First_Name = txtFirstName.Text,\n Pat_Middle_Init = txtMiddleName.Text,\n Pat_Last_Name = txtLastName.Text,\n Pat_Gender = cmbGender.Text,\n Pat_Marital_Status = cmbMaritalStatus.Text,\n Pat_Date_Of_Birth = dtpDOB.Value,\n Pat_Home_Add = txtHomeAdd.Text,\n Pat_Home_Num = txtPhone.Text,\n Pat_Work_Add = txtWorkAdd.Text,\n Pat_Work_Num = txtWorkPhone.Text,\n Pat_Prim_Physician = txtPrimPhysician.Text,\n Pat_Ref_Physician = txtRefePhysician.Text,\n });\n myDb.SubmitChanges();\n }\n }\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-03-02T15:38:58.800", "Id": "15236", "Score": "1", "body": "Alternately, create a constructor for the `PatientInfo` class that takes all of those parameters and assigns them appropriately. Then you'll trim a bit more out of this call." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-03-03T06:18:06.050", "Id": "15280", "Score": "2", "body": "No magic here, this is one of those simple, dumb and tedious code is the right code situations. I would however maybe put the form with all the controls into a custom control with a method you can call on it that will do this mapping and spit out the Patient object for you since the mapping is coupled to that particular group of controls." } ], "meta_data": { "CommentCount": "2", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-03-02T15:25:59.037", "Id": "9639", "ParentId": "9638", "Score": "5" } }, { "body": "<p>In short. No. The mapping between object properties and fields on the form has to be <em>somewhere</em>.</p>\n\n<p>What you could do though is to set it up by convention. So if the field on the form had the same name as the corresponding property on the object you could use reflection (or a tool like <a href=\"http://automapper.codeplex.com/\" rel=\"nofollow\">Automapper</a>) to do that shifting. In pseudo code (because I don't have a set up .Net environment in front of me right now) it would be something like:</p>\n\n<pre><code>public static void MapControlValuesToFields&lt;T, F&gt;(T obj, F form) \n where T : class\n where F : Form { //or whatever your base class for forms is\n get all fields of typeof(F)\n where type of the field inherits from Control\n where typeof(T) has a similarly named setter property\n get the value of each in form (the .Text of .Value logic would go here)\n for each set the value on object\n}\n</code></pre>\n\n<p>and then you would be able to do something like</p>\n\n<pre><code> var patient = new PatientInfo();\n MapControlValuesToFields(patient, form);\n //at this point the values are in the patient and you can save it\n</code></pre>\n\n<p>This is of course fairly advanced coding but it is possible and probably only about 10 lines of code. Like I said you can look at Automapper for some of this functionality out of the box (though I don't know how well it would do with windows/web forms).</p>\n\n<p>I will say that what you're looking for is similar to the functionality provided by the MVVM pattern so if you're doing windows forms you can look at <a href=\"http://truss.codeplex.com/\" rel=\"nofollow\">Truss</a>. If you're doing web forms...well I wouldn't do web forms, this functionality is already in ASP MVC and silverlight which are both like a million times easier to work with but I remember there being some buzz about <a href=\"http://webformsmvp.com/\" rel=\"nofollow\">the ASP MVP project</a> that would help with those issues.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-03-02T16:33:43.303", "Id": "9647", "ParentId": "9638", "Score": "1" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-03-02T15:19:27.373", "Id": "9638", "Score": "1", "Tags": [ "c#", ".net", "sql", "linq" ], "Title": "Inserting Data in The Database using LINQ TO SQL" }
9638
<pre><code>&lt;html&gt; &lt;body&gt; &lt;?php $username = $_POST['username']; $password = $_POST['password']; $name = $_POST['name']; echo "Doing ``"."useradd $username -p '$password' "."'' as ".get_current_user()."..&lt;br/&gt;"; passthru("/usr/bin/sudo /usr/bin/sbin/useradd $username -p '$password'" ); echo "finished ok&lt;br&gt;"; ?&gt; &lt;p&gt; &lt;a href="index.html"&gt;Go back and try again&lt;/a&gt; &lt;/body&gt; &lt;/html&gt; </code></pre>
[ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-03-02T20:36:57.760", "Id": "15268", "Score": "0", "body": "I have no idea how to sanitize that properly. Do you really need it? Oh and add a `$return_var` parameter to see what sudo returns to you." } ]
[ { "body": "<p>I strongly suggest to sanitize the input ($_POST[]) before using. Even more in your case that you execute shell command with it.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-03-02T19:46:58.293", "Id": "9652", "ParentId": "9649", "Score": "2" } }, { "body": "<p>I can exploit that in a few moments:</p>\n\n<p>Set username to \"; newcommand here to pwn your box\" or \" || other command\"</p>\n\n<p>YOU NEED to sanitize the values prior to running this.</p>\n\n<p>Using strpos and check for possible exploits.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-03-05T16:29:07.807", "Id": "9719", "ParentId": "9649", "Score": "2" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "1", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-03-02T17:06:38.737", "Id": "9649", "Score": "-2", "Tags": [ "php" ], "Title": "Add User Via php" }
9649
<p>I have experience is C#/ASP.NET, and I've done MVC in Ruby On Rails, so I figured making the jump to ASP.NET MVC would be a breeze. Unfortunately, I'm second-guessing my every decision. I'd like some more eyes on this to tell me if my way of doing things is insane.</p> <p>My main question is around editing an entity.</p> <p>My <code>GET</code> looks like this:</p> <pre><code>public ActionResult Edit(int id) { var viewModel = from c in db.centres // some joins are here where c.id == id select new CentreViewModel { CentreId = c.id, CentreName = c.Name, etc... }; return View( viewModel ); } </code></pre> <p>And my <code>POST</code> is something like this:</p> <pre><code>public ActionResult Edit(CentreViewModel viewModel) { // NOTE - Validation &amp; Error handling exists, but has been omitted for berevity var centre = db.centres.First(c =&gt; c.id == viewModel.CentreId); centre = Mapper.Map&lt;CentreViewModel, CentreEntity&gt;(viewModel, centre); db.centres.ApplyCurrentValues( centre ); db.SaveChanges(); } </code></pre> <p>Is this kinda-sorta right? Are there any red flags here? Is <code>ApplyCurrentValues</code> correct? I see others using <code>repository.Entry()</code>, but I don't have a repository for my classes, near as I can tell...</p>
[ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-03-02T17:39:00.157", "Id": "15259", "Score": "1", "body": "Not enough expirience with EF to answer your question (which DOES look right btw) but I generally disparage people away from the `from...where...select` LINQ syntax as it hides what's actually going on in a very unhelpful way. Since LINQ has been out, in 100% of the scenarios that I've seen that using the expression syntax is more powerful, terse, and more likely to convey to developers what's really happening. In your case you should be able to shorten the actual query to `db.centres.First(x=>x.id == id)`.. though it is missing the projection part which you have to do separately in code." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-03-02T18:28:08.390", "Id": "15264", "Score": "0", "body": "The reason I went with the LINQ syntax is because the joins don't have foreign keys and, based on about 30 seconds of googling, this was the easiest way to join on tables without FKs. I'll take another look, see if I can improve it." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-03-02T21:58:01.187", "Id": "15270", "Score": "1", "body": "Well both are technically LINQ syntax. There is nothing that you can do with query syntax that you can't do with lambda syntax. There is a lot you can do with lambda syntax that you can't the other way around though." } ]
[ { "body": "<p>Here is a link to <a href=\"http://www.asp.net/mvc/tutorials/getting-started-with-ef-using-mvc/implementing-basic-crud-functionality-with-the-entity-framework-in-asp-net-mvc-application\" rel=\"nofollow\">the \"official\" tutorial on basic CRUD operations in ASP.NET MVC and EF</a>. </p>\n\n<p>The main difference is the validation checking, and the exception handling. I recommend adding in the validation, and possibly the exception handling <em>if you need it</em>. Don't randomly swallow exceptions and show the user some generic error message.</p>\n\n<p>Other than that, they use a slightly different way of letting EF know about the entity to be updated, but I think they're accomplishing the same thing. I <em>think</em> the functional difference is that you are only posting back the necessary data to be updated, and having EF get the entity and update it with those changes for you. With their method, I <em>think</em> that they are posting back the <em>entire</em> entity, and having EF \"reattach\" the entity and mark it as modified.</p>\n\n<p>So I <em>think</em> the differences in the update code boil down to partial vs. full entity updates.</p>\n\n<p><strong>Side Note 1</strong></p>\n\n<p>I like your way better. In their case they are relying on the end user to postback the <strong><em>entire entity</em></strong>. While that is a basic demo, using this method blindly opens up your application to vulnerabilities where people can update any field they want, even if the field doesn't appear in the HTML form (Think of an \"IsAdmin\" flag). I believe that this is known as a <strong>Mass Assignment</strong> vulnerability that bit Rails and Github <strong><em>last week!</em></strong> (Source: <a href=\"https://github.com/blog/1068-public-key-security-vulnerability-and-mitigation\" rel=\"nofollow\">https://github.com/blog/1068-public-key-security-vulnerability-and-mitigation</a>)</p>\n\n<p><strong>Side Note 2</strong></p>\n\n<p>About the comments and the LINQ syntax... I also like the expression syntax a little more, at least for short, small queries. But when doing joins in the past, I've gone with the query syntax. Just a personal preference. Here is what the code would look like with the LINQ expression syntax (as opposed to the query syntax):</p>\n\n<pre><code>db.centres\n .Join(...)\n .Where(c =&gt; c.id == id)\n .Select(new CentreViewModel\n {\n CentreId = c.id,\n CentreName = c.Name,\n etc...\n };\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-03-08T15:57:25.057", "Id": "15587", "Score": "0", "body": "That's weird, I don't have that `Entry` method they're using. Ah well, no one's told me that I'm completely out to lunch, so I think my way of doing it is Good Enough™." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-03-08T16:12:33.227", "Id": "15589", "Score": "1", "body": "I think they have a simplified [DbContext](http://msdn.microsoft.com/en-us/library/system.data.entity.dbcontext(v=vs.103).aspx) class now. I would check it out since it's supposed to make things a bit cleaner. You should be able to update to the latest EF version through Nuget." } ], "meta_data": { "CommentCount": "2", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-03-08T15:47:28.657", "Id": "9811", "ParentId": "9650", "Score": "2" } }, { "body": "<p>I usually use generics to handle my database contexts. Here is an example of how I would approach it explicitly.</p>\n\n<pre><code> db.centres.Attach(centre);\n db.Entry(centre).State = EntityState.Modified;\n db.SaveChanges();\n</code></pre>\n\n<p>Moreover, here is a link to one of the best tutorials out there in my opinion for mvc3.</p>\n\n<p><a href=\"http://www.asp.net/mvc/tutorials/getting-started-with-ef-using-mvc/creating-an-entity-framework-data-model-for-an-asp-net-mvc-application\" rel=\"nofollow\">http://www.asp.net/mvc/tutorials/getting-started-with-ef-using-mvc/creating-an-entity-framework-data-model-for-an-asp-net-mvc-application</a> (Make sure to note that there are 10 different parts, the link to the next step is at the bottom of the page).</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-03-09T21:59:01.030", "Id": "9872", "ParentId": "9650", "Score": "1" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "3", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-03-02T17:12:31.053", "Id": "9650", "Score": "2", "Tags": [ "c#", "entity-framework", "asp.net-mvc-3" ], "Title": "Am I approaching this ASP.Net MVC/Entity Framework pattern incorrectly?" }
9650
<p>Could someone be kind enough to review this Fourier transformation, please? I'm especially interested in going about unit testing the code (I don't really know where to begin, beyond applying the fft twice to retrieve the input), and have left test functions blank.</p> <p>If you do spot a bug (and no doubt there are some), please don't tell me. I'd like to find them myself.</p> <pre><code>/* A simple radix 2 fast fourier transform. */ #include &lt;complex&gt; #include &lt;iostream&gt; #include &lt;cassert&gt; #define _USE_MATH_DEFINES #include &lt;cmath&gt; typedef std::complex&lt;double&gt; Complex; void TestSpike(Complex* data, int length){ assert( 1.0 == data[1]); } //Generates a spike in the DC bin, used for testing the fft void GenerateSpike(Complex* data, int length){ for(int i = 0 ; i &lt; length ; i++) { if(1 == i){ data[i] = 1.0; } else { data[i] = 0.0; } } TestSpike(data, length); } void TestTwiddle(){ } void TestButterfly(){ } Complex w(int bin, int length){ return (cos(2*M_PI*bin/length), sin(2*M_PI*bin/length)); } void butterfly(Complex* data, int bin, int stepSize, int fftlength){ Complex x0 = data[bin]; Complex x1 = data[bin+stepSize]; data[bin] = x0 + w(bin, fftlength)*x1; data[bin+stepSize] = x0 - w(bin, fftlength)*x1; } //Decimation in time void FFT(Complex *data, int length){ for(int bflySize = 2 ; bflySize &lt; length ; bflySize *= 2) { int numBflys = length/bflySize; for(int i = 0 ; i &lt; numBflys ; i++) { int stepSize = bflySize/2; for(int j = 0 ; j &lt; bflySize ; j+= stepSize) { butterfly(data, (bflySize*i)+j, bflySize/2, length); } } } } int Reverse(unsigned int i, int size){ int reversed = 0; while(size &gt; 1){ reversed = (reversed &gt;&gt; 1) | (i &amp; 1); i &gt;&gt;= 1; size &gt;&gt;= 1; } return reversed; } int main(int argv, char** argc){ int length; std::cout &lt;&lt; "Please input the length of the FFT" &lt;&lt; std::endl; std::cin &gt;&gt; length; std::complex&lt;double&gt; data[length]; GenerateSpike(data, length); FFT(data, length); for(int i = 0 ; i &lt; length ; i++) { int j = Reverse(i,length); std::cout &lt;&lt; data[j] &lt;&lt; std:: endl; } return 0; } </code></pre>
[ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-03-02T21:59:18.903", "Id": "15271", "Score": "0", "body": "Wish I knew enough C++ to be of help here. I remember the fourier transform from image processing class - it was fun." } ]
[ { "body": "<p>Using <code>operator==</code> on doubles isn't usually a good idea, although it may be okay in the <code>TestSpike</code> case as you know you've assigned exactly 1.0 to it previously.</p>\n\n<p>I would write <code>GenerateSpike</code> as follows:</p>\n\n<pre><code>void GenerateSpike(Complex* data, int length) {\n std::fill(data, data+length, 0.0);\n if (length &gt;= 2)\n data[1] = 1.0;\n}\n</code></pre>\n\n<p>By the way, you're not checking that the array is of sufficient length in <code>TestSpike</code>.</p>\n\n<p><code>stepSize</code> in <code>FFT</code> does not depend on the parameters of the second-outermost loop, so it should be in the outermost loop. You should also use <code>stepSize</code> instead of <code>bflySize/2</code> in the call to <code>butterfly</code>.</p>\n\n<p>About testing: <code>w</code>, <code>butterfly</code>, <code>Reverse</code>, and <code>FFT</code> all seem to be pure functions, so you can test them simply by checking the return value. You might want to get a framework like GTest or Boost.Test to make them easier to write.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-03-03T08:00:08.560", "Id": "9666", "ParentId": "9651", "Score": "2" } } ]
{ "AcceptedAnswerId": "9666", "CommentCount": "1", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-03-02T19:39:05.723", "Id": "9651", "Score": "3", "Tags": [ "c++", "signal-processing" ], "Title": "Fourier transformation" }
9651
<p>Problem:</p> <p>What is an effective design pattern to allow an end user to indirectly modify the state of data in an object based on a prioritized list of user specified modifers?</p> <p>Explanation : This is very general of course, but hang in there for a second so I can elaborate - I'm not a software person by trade so I don't know the appropriate language to use. Say I have a class called 'Grid' who's purpose is to:</p> <ol> <li>Store a regular 2D Cartesian grid of 'colors'</li> <li>Allows the user to initialize all the colors to some state </li> <li><p>The Grid tracks the "evolution" of the colors. By this I mean the state of the data in the grid can change by some function Grid(n+1) = f( Grid(n) ). Where F( Grid(n) ) is a function that transforms a grid at step n to step n+1. An example of this could be</p> <p>if a node to my right is red and I am not red:</p> <p>then</p> <pre><code>swap colors </code></pre> <p>else</p> <pre><code>do nothing </code></pre></li> </ol> <p>So a "grid" at step n that looks like this:</p> <pre><code>BLUE BLUE BLUE BLUE BLUE RED BLUE BLUE BLUE </code></pre> <p>Will look like this at step n+1</p> <pre><code>BLUE BLUE BLUE BLUE RED BLUE BLUE BLUE BLUE </code></pre> <p>And at n+2 this:</p> <pre><code>BLUE BLUE BLUE RED BLUE BLUE BLUE BLUE BLUE </code></pre> <p>I will leave this F( Grid(n) ) as an opaque process because this is not where I have a design issue - I do mention this so that some design decisions I make in the future will have some context.</p> <ol> <li>The user is allowed to modify the data at every step via a multiset that uses a comparison object based on a priority. The multset contains an object that somehow modifies the state of my grid of colors.</li> </ol> <p>Ok What do I mean by this? Take a look :</p> <pre><code>class Grid { private: vector&lt; vector&lt; colors &gt; &gt; colorGrid; multiset&lt; shared_ptr&lt; SetGrid &gt;, comp &gt; setRules; // ... // public: Grid( dims d2 ); // dims is a typedef for pair&lt;int,int&gt; // ... // void addSetRule( shared_ptr&lt; SetGrid &gt; sg ); // ... // void applyRules( void ); }; </code></pre> <p>Where I have defined SetGrid to be an ABC:</p> <pre><code>class SetGrid { protected: int priority; colors c; public: SetGrid(colors clr ) : c(clr){}; int getPriority() const; virtual void apply( vector&lt; vector&lt; colors &gt; &gt; &amp; cg) const=0; }; </code></pre> <p>The 'comp' object in the multiset declaration compares priorities through the getPriority() member function. So now you may see whats going on. Classes Derived from SetGrid can change the state of coloGrid by Grid::applyRules() function:</p> <pre><code>void Grid::applyRules( ){ multiset&lt; shared_ptr&lt; SetGrid &gt;,comp &gt;::iterator it; for (it = setRules.begin(); it != setRules.end(); ++it) (*it)-&gt;apply( colorGrid ); } </code></pre> <p>The multiset orders items it contains base on their priority. So at this point a user could derive a class from SetGrid to set all colors in a users specified column to RED and derive another class from SetGrid whos function is to set a subset of a row to GREEN <em>after</em> RED is set. Example:</p> <p>G(n):</p> <pre><code>BLUE BLUE RED BLUE RED BLUE BLUE BLUE BLUE </code></pre> <p>setRules now contains a "set columns to RED" object with high priority and a "set a subset of a row to GREEN" with lower priority, so the state changes as follow:</p> <p>set column to RED ( say I set column 0 to RED) :</p> <pre><code>RED BLUE RED RED RED BLUE RED BLUE BLUE </code></pre> <p>And <em>now</em> set a subset of a row GREEN (say row 1, items 0 and 1):</p> <pre><code>RED BLUE RED GREEN GREEN BLUE RED BLUE BLUE </code></pre> <p>And now we can apply our Function F( G(n) ) -> G(n+1) and repeat this process however many times we like or until something bad happens. </p> <p>So that is the functionality I desire from this 'Grid' class - What is the name of the design pattern I have used/what is a better design pattern to achieve this goal? I feel like what I have done is acceptable - but I hope there is a more elegant solution that is more expressive/compact than what I have.</p> <p>A full listing of my simple example is on <a href="http://codepad.org/uYrHYaFn" rel="nofollow">this codepad page</a> - Note that I compiled with g++4.5 -std=c++0x -Wall (no optimizations) and use things defined in the new c++11 standard. I did not put it here because in total the full code is ~160 lines, a little too much for the eyes on one page.</p>
[]
[ { "body": "<h2>Design pattern?</h2>\n\n<p>Thanks for your detailed question. Sorry, but what you're looking for is not a \"design pattern\". Look at this quote from Wikipedia (emphasis mine):</p>\n\n<blockquote>\n <p>In software engineering, a design pattern is a general reusable\n solution to a <strong>commonly occurring</strong> problem within a given context in\n software design.</p>\n</blockquote>\n\n<p>Your issue is probably not a commonly occurring one. More specifically, it probably hasn't occurred enough for someone to notice an useful pattern. I did have this issue once(!) at school, and the solution we opted for back then was way more complicated than what you have right now. (For example, we implemented <a href=\"http://en.wikipedia.org/wiki/Flocking_%28behavior%29\" rel=\"nofollow\">flocking behavior</a> in <a href=\"http://gitorious.org/cellulart/cellulart/blobs/master/modules/agents/brains/flocking_bird.py\" rel=\"nofollow\">this Python code</a>).</p>\n\n<p>It's still possible that you'll use some design patterns in the solution. One can argue that a \"rule-based system\" is a design pattern. Rule-based systems are certainly used extensively in many fields with the same semantics. It also allows you to <a href=\"http://en.wikipedia.org/wiki/Decoupling#Software_development\" rel=\"nofollow\">decouple</a> the different rules since they are in their own class. In a sense, you used a design pattern here.</p>\n\n<p>Also note that design patterns don't aim for code conciseness. For example, the <a href=\"http://en.wikipedia.org/wiki/Composite_pattern\" rel=\"nofollow\">Composite pattern</a> involves using a <em>lot</em> of new classes. It does make the code better when properly used, though. Trying to get below 150 lines would probably involve using less classes, and would make your code harder to extend.</p>\n\n<h2>Code comments</h2>\n\n<ol>\n<li><pre><code>bool operator()( const shared_ptr&lt; SetGrid &gt; &amp; lhs, const shared_ptr&lt;SetGrid&gt; &amp; rhs){\n</code></pre>\n\n<p>This is only one example to show that you should care more about spacing. <code>&lt; SetGrid &gt;</code> or <code>&lt;SetGrid&gt;</code>. I'd recommend <code>&lt;SetGrid&gt;</code>.</p></li>\n<li><p>Use <a href=\"http://en.wikipedia.org/wiki/C%2B%2B11#Strongly_typed_enumerations\" rel=\"nofollow\">strong enums</a>.</p></li>\n<li>I'd recommend for using <code>std::vector</code> instead of <code>vector</code>, but that's up to you.</li>\n<li>Are you aware that you do not need a comp object, since <code>operator&lt;</code> in <code>SetGrid</code> would be enough? This means you don't need to expose the priority, but also makes it less explicit that you are going to compare <code>SetGrid</code>s. Up to you!</li>\n</ol>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-03-03T13:53:58.930", "Id": "15287", "Score": "0", "body": "Thanks for the commmens - 1. what do you recommend? I like the spacing but of course it can get long with templated template parameters. 2. Changed it 3. std::vector where? std::vector in place of the multiset? 4. I forgot about operator <, that I can use. Thanks!" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-03-03T14:12:29.967", "Id": "15288", "Score": "0", "body": "I was just thinking and realized I have to use an outside class for the comparison object in multiset, since it is templated for a shared_ptr ! oh well... it would have been nice to use a member function" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-03-03T14:52:10.647", "Id": "15290", "Score": "0", "body": "I recommend `<SetGrid>`, ie. no spaces. Sorry, I had forgotten the \"``\", and markdown thought it was an html tag. For `vector`, I was referring to `std::`. I edited!" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-03-03T17:19:59.730", "Id": "15291", "Score": "0", "body": "Ah yes - once I break this out into its own source file all the std library components are going to be properly scoped. Otherwise would you say the design is sound/straightforward/suggest any other fundamental changes to my approach?" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-03-03T20:35:25.500", "Id": "15294", "Score": "0", "body": "I do think you chose the right approach! :)" } ], "meta_data": { "CommentCount": "5", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-03-03T10:50:31.097", "Id": "9668", "ParentId": "9656", "Score": "2" } }, { "body": "<p>The <em>command</em> pattern describes your idea of encapsulating the various mutators as objects, but it doesn't address your priority queue.</p>\n\n<p>As for the overall design:</p>\n\n<ol>\n<li><p>it isn't clear why the <code>Grid</code> has to own it's transient list of mutators: it creates a circular dependency (although that isn't particularly a problem), and if you plan to display this grid and want to use something like the <em>Model/View/Controller (MVC)</em> pattern, it's pulling controller state into the model.</p></li>\n<li><p>the <code>SetGrid</code> mutators operate directly on the grid's internal vector of vectors, meaning you're voluntarily breaking encapsulation for something whose (concrete) type you don't know</p>\n\n<ul>\n<li>either encapsulation is useful here, in which case <code>SetGrid::apply</code> should just take a <code>Grid&amp;</code> argument and call mutator methods on that object</li>\n<li>or it isn't, and your Grid can be trivially decomposed into an essentially public vector of vectors, and <em>something</em> which manages and iterates over the priority queue of <code>SetGrid</code>s</li>\n</ul></li>\n</ol>\n\n<p>neither of those are problems that will stop it working, but the code doesn't feel that well aligned with what you're trying to express.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-03-06T01:28:34.067", "Id": "15430", "Score": "0", "body": "1. Grid is never displayed - I just used it as an example that would make my problem easier to understand (actually has nothing to do with visualization/user interaction). 2.a - If I would take this route I would have to provide a public interface to the internal state of grid. 2.b Isn't my 'grid' interface that 'something' that stores the vectors and iterates over the mutators? Thanks for your feedback - I agree what I am doing doesn't quite feel 'natural' and am looking to improve - If you could post an edit of how you might suggest a change I would appreciate it." } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-03-05T22:09:45.870", "Id": "9731", "ParentId": "9656", "Score": "1" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-03-03T00:55:48.207", "Id": "9656", "Score": "0", "Tags": [ "c++", "c++11" ], "Title": "How to design a class that allows a user to indirectly modify its internal state through a prioritized list of desired modifications?" }
9656
<p>As a learning exercise, I decided to write a script for helping me maintain my Unix configuration/dot-files under a git repository. I check out a copy of the repository in my home directory called .dotfiles, and, inside that, I have the Python script called linkify, which deals with creating links from my home directory to the real files inside the .dotfiles directory.</p> <p>For your reference, the <a href="https://github.com/rbrito/dotfiles/blob/716652/linkify" rel="nofollow">respective code</a> is in my GitHub repository.</p> <pre><code>#!/usr/bin/env python import errno import os to_keep_private = [ 'cifs-credentials', 'config', 'fetchmailrc', 'gitconfig', 'gnupg', 'mpoprc', 'msmtprc', 'mutt', 'netrc', 'offlineimaprc', 'pim', 'purple', 'quodlibet', 'ssh', ] to_ignore = [ '.', '.git', '.gitignore', 'linkify', ] def make_private(files=[]): if len(files) == 0: files = os.listdir('.') else: # Use the list of files passed by the user, if it is not empty pass for filename in files: if os.path.isdir(filename): os.chmod(filename, 0700) else: os.chmod(filename, 0600) def linkify(files=[]): if len(files) == 0: files = os.listdir('.') else: # Use the list of files passed by the user, if it is not empty pass os.chdir(os.path.join(os.environ['HOME'], '.dotfiles')) for source in files: if source not in to_ignore: target = os.path.join('..', '.' + source) source = os.path.join('.dotfiles', source) try: os.unlink(target) except OSError, e: if e.errno == errno.ENOENT: pass elif e.errno == errno.EISDIR: print("%s is a directory. Ignoring." % target) else: print errno.errorcode[e.errno] finally: os.symlink(source, target) def add_hook(): f = open('.git/hooks/post-commit', 'w') f.write('#!/bin/sh\ngit push\n') f.close() os.chmod('.git/hooks/post-commit', 0755) def parse_cli(): import optparse parser = optparse.OptionParser() parser.add_option('-H', '--install-hook', help='Install git hook for automatic push.', action='store_true', default=False) parser.add_option('-n', '--no-linkify', help='Disable creation of symlinks', action='store_true', default=False) parser.add_option('-P', '--no-fix-perms', help='Disable fix of permission for private files.', action='store_true', default=False) return parser.parse_args() if __name__ == '__main__': opts, args = parse_cli() if not opts.no_linkify: linkify(args) if not opts.no_fix_perms: make_private(args) if opts.install_hook: add_hook() </code></pre>
[]
[ { "body": "<pre><code>#!/usr/bin/env python\n\nimport errno\nimport os\n\nto_keep_private = [\n</code></pre>\n\n<p>By convention, global constants are in ALL_CAPS in python</p>\n\n<pre><code> 'cifs-credentials',\n 'config',\n 'fetchmailrc',\n 'gitconfig',\n 'gnupg',\n 'mpoprc',\n 'msmtprc',\n 'mutt',\n 'netrc',\n 'offlineimaprc',\n 'pim',\n 'purple',\n 'quodlibet',\n 'ssh',\n ]\n\nto_ignore = [\n '.',\n '.git',\n '.gitignore',\n 'linkify',\n]\n\n\ndef make_private(files=[]):\n</code></pre>\n\n<p>Generally, its dangerous to have mutable objects as defaults. They don't behave like we might expect. </p>\n\n<pre><code> if len(files) == 0:\n files = os.listdir('.')\n</code></pre>\n\n<p>I'd expect an empty list of files to do nothing, not operate on the current directory. For this sort of case, its more usual to use <code>None</code>. Have <code>None</code> be the default and check for that.</p>\n\n<pre><code> else:\n # Use the list of files passed by the user, if it is not empty\n pass\n</code></pre>\n\n<p>uhh.... this has no effect.</p>\n\n<pre><code> for filename in files:\n if os.path.isdir(filename):\n os.chmod(filename, 0700)\n else:\n os.chmod(filename, 0600)\n\n\ndef linkify(files=[]):\n if len(files) == 0:\n files = os.listdir('.')\n else:\n # Use the list of files passed by the user, if it is not empty\n pass\n</code></pre>\n\n<p>Again. Don't do this.</p>\n\n<pre><code> os.chdir(os.path.join(os.environ['HOME'], '.dotfiles'))\n</code></pre>\n\n<p>I avoid changing the current directory. It gives the function unintended semantics. For example all your <code>os.listdir</code> calls will return different results after this. Instead, use absolute paths.</p>\n\n<pre><code> for source in files:\n if source not in to_ignore:\n target = os.path.join('..', '.' + source)\n source = os.path.join('.dotfiles', source)\n try:\n os.unlink(target)\n except OSError, e:\n if e.errno == errno.ENOENT:\n pass\n elif e.errno == errno.EISDIR:\n print(\"%s is a directory. Ignoring.\" % target)\n else:\n print errno.errorcode[e.errno]\n</code></pre>\n\n<p>Do you really want to try carrying on after an unknown error code?</p>\n\n<pre><code> finally:\n os.symlink(source, target)\n\n\ndef add_hook():\n f = open('.git/hooks/post-commit', 'w')\n f.write('#!/bin/sh\\ngit push\\n')\n f.close()\n</code></pre>\n\n<p>avoid one letter variable names. They make code harder to follow. Also you should use with</p>\n\n<pre><code> with open('.git/hooks/post-commit', 'w') as hook:\n hook.write('#1/bin/sh\\ngitush\\n')\n</code></pre>\n\n<p>This will take of closing files even in the face of an exception.</p>\n\n<pre><code> os.chmod('.git/hooks/post-commit', 0755)\n\n\ndef parse_cli():\n import optparse\n</code></pre>\n\n<p>Usually better to import everything at the top of the file, not in functions</p>\n\n<pre><code> parser = optparse.OptionParser()\n\n parser.add_option('-H',\n '--install-hook',\n help='Install git hook for automatic push.',\n action='store_true',\n default=False)\n parser.add_option('-n',\n '--no-linkify',\n help='Disable creation of symlinks',\n action='store_true',\n default=False)\n parser.add_option('-P',\n '--no-fix-perms',\n help='Disable fix of permission for private files.',\n action='store_true',\n default=False)\n\n return parser.parse_args()\n</code></pre>\n\n<p>This is the bit where you actually interpreting the command line. I'd do the <code>os.listdir()</code> here as to my mind, its part of the command line interpretation.</p>\n\n<pre><code>if __name__ == '__main__':\n opts, args = parse_cli()\n</code></pre>\n\n<p>I'd call <code>args</code>: <code>filenames</code> to get a better idea of what's going on</p>\n\n<pre><code> if not opts.no_linkify:\n linkify(args)\n if not opts.no_fix_perms:\n make_private(args)\n if opts.install_hook:\n add_hook()\n</code></pre>\n\n<h2>Issues of else:</h2>\n\n<p>The original has the following code:</p>\n\n<pre><code> if len(files) == 0:\n files = os.listdir('.')\n else:\n # Use the list of files passed by the user, if it is not empty\n pass\n</code></pre>\n\n<p>and I said this was a bad idea because the else did nothing. You've asked for clarification on this point. I think you put the else block in there to make it more explicit what you are doing, that way you have clearly delinated the two cases. I'd say if you want it to be explicit, make it explicit via code not comments</p>\n\n<pre><code>if len(files_) == 0:\n files = os.listdir(.)\nelse:\n files = files_\n</code></pre>\n\n<p>I think this is better because the code conveys the message, rather then inline english text.</p>\n\n<p>However, I'm not sure that much is gained for explicitness here. If I see:</p>\n\n<pre><code>if len(files) == 0:\n files == os.listdir('.')\n</code></pre>\n\n<p>I can see that its implementing the logic for a default parameter, because that's a pretty common practice. I don't see that you gain much by making it more explict what the other case is. The other case is pretty obvious.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-03-04T04:47:59.597", "Id": "15326", "Score": "0", "body": "Thanks for comments @Winston. There are some points where I would appreciate some clarification, though., but there are some points where I would appreciate clarification. The most important of these are your comments regarding the `else` with a `pass`, even if it has a comment to not let the reader know that that's deliberate." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-03-05T21:02:57.247", "Id": "15407", "Score": "0", "body": "@rbrito, I've added to the answer trying to clarify a bit about my else/pass comments" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-03-06T02:06:48.687", "Id": "15431", "Score": "0", "body": "thanks for the additional comments regarding the `else`/`pass` issue. This is just a long-time habit that I carried over, as I (still) feel bad whenever I see an if without the corresponding else.\n\nBTW, I have implemented most of the issues you both pointed out in a new version of the code. Not everything, but almost all points." } ], "meta_data": { "CommentCount": "3", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-03-03T03:27:30.127", "Id": "9660", "ParentId": "9657", "Score": "3" } }, { "body": "<h3>Some guidelines to follow:</h3>\n\n<ul>\n<li><p>If possible, as it is in your case, work with absolute path.<br>\nYou'll have at the beginning to do more or less something like:</p>\n\n<pre><code>dir = '/home/rik/'\nfiles = [os.path.join(dir,file) for file in os.listdir(dir)]\n</code></pre>\n\n<p>But everything should be easier and straighforward later on.</p></li>\n<li><p>You need to move the default behaviour - <code>files = os.listdir('.')</code> - one level up.<br>\nI can see one symptom and one reason for that:</p>\n\n<ol>\n<li>You've wrote two times the exact same code.</li>\n<li>The two different functions with that code should ignore what's your default directory, since they operate on list of files.</li>\n</ol>\n\n<p>So, if the user does not provide his own custom list, you need to generate the list of files in . and pass it to both your functions. This also means that the functions should not have a default argument value.</p></li>\n<li><p>If you can, use <a href=\"http://docs.python.org/library/argparse.html\" rel=\"nofollow\"><code>argparse</code></a> instead of <a href=\"http://docs.python.org/library/optparse.html\" rel=\"nofollow\"><code>optparse</code></a>.<br>\nI'm not sure from which version <code>optparse</code> was deprecated, but the main point is that if you have <code>argpare</code> in your standard library use that. You have only a couple of arguments so switching shouldn't take long.</p></li>\n<li><p>Be consistent with your variable names. </p>\n\n<pre><code>def make_private(files=[]):\n # [...]\n for filename in files:\n # [...]\n\ndef linkify(files=[]):\n # [...]\n for source in files:\n # [...]\n</code></pre>\n\n<p>Why one time <code>files</code> is a list of <em>filenames</em> and another a list of <em>sources</em>?<br>\nIf you strongly believe that one function works on filenames and the other on sources maybe you need to change the argument name, otherwise being consistent will help the readability of your code.</p></li>\n<li><p>As <em>Winston Ewert</em> already told you, you should use capital letter for your constants names. Quoting from <a href=\"http://www.python.org/dev/peps/pep-0008/\" rel=\"nofollow\">PEP8</a>:</p>\n\n<blockquote>\n <p>Constants are usually defined on a module level and written in all\n capital letters with underscores separating words. Examples include\n MAX_OVERFLOW and TOTAL.</p>\n</blockquote></li>\n</ul>\n\n<h3>Additional notes</h3>\n\n<p>Don't do this:</p>\n\n<pre><code>def function(lst=[]):\n # ...\n</code></pre>\n\n<p>Do this instead:</p>\n\n<pre><code>def function(lst=None):\n if lst is None:\n lst = []\n # ... \n</code></pre>\n\n<p>The reason for that is well explained <a href=\"http://effbot.org/zone/default-values.htm\" rel=\"nofollow\">here</a> (or google it, because it's a very well known problem in which <em>everyone</em> stumbles sooner or later).</p>\n\n<p>I'd say that by doing this you'll also remove the useless <code>else</code>, but as I explained it above you should remove the whole check and move it one level up against the user arguments.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-03-04T09:28:44.807", "Id": "15331", "Score": "0", "body": "Thanks for the comments. Both yours and @Winston's were very helpful and I chose yours as an answer because you have fewer reputation points (I hope that he doesn't care too much here)." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-03-06T02:13:53.173", "Id": "15433", "Score": "0", "body": "thanks for the suggestions. They are very much appreciated. One thing that I didn't incorporate was the change to `argparse` from `optparse`, as I have systems with old versions of Python.\n\n(And, unfortunately, since I don't even have enough reputation points, I can't upvote your answer.)" } ], "meta_data": { "CommentCount": "2", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-03-03T09:53:22.317", "Id": "9667", "ParentId": "9657", "Score": "4" } } ]
{ "AcceptedAnswerId": "9667", "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-03-03T01:04:10.570", "Id": "9657", "Score": "3", "Tags": [ "python", "beginner", "file-system", "git", "unix" ], "Title": "Symlinking git-managed dotfiles into a home directory" }
9657
<p>I am writing a shell script to sort my files by extension and unzip archives. It works in simple cases, but I haven't tested it extensively. How can I make it more robust against the set of file names that may be present?</p> <pre><code>#!/bin/bash #File sorter SECONDS=0 SAVEIFS=$IFS IFS=$(echo -en "\n\b") echo "trigger took place in $(pwd)" for i in $( ls -1); do echo "processing $i ..." fileext=${i##*.} case ${i##*.} in zip) mkdir archive mkdir $(pwd)/archive/${i%%.*} unzip $i -d $(pwd)/archive/${i%%.*} ;; *) echo "nonzip" mkdir ${i##*.} mv $i $(pwd)/${i##*.} ;; esac done echo "Done in $SECONDS seconds!" </code></pre>
[ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-03-03T01:18:49.257", "Id": "15276", "Score": "0", "body": "Given that two of us have posted a review of your code, I'm going to suggest that this question be migrated to [codereview.se]. Do not repost there! Once you've figured out what you wanted to do with ask, please ask a new question here on [unix.se]." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-03-03T02:20:38.277", "Id": "15277", "Score": "0", "body": "I've edited your question to make it fit the CR format better, because I think that's what would benefit you most at this point. Please do come back here on [unix.se] to ask about that report in awk." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-03-04T00:45:00.080", "Id": "15305", "Score": "0", "body": "@Gilles I wanted to ask how I can generate report. So you mean, I should not attach my codes since that would be counted as code review? I attached the codes so I would give more explanation on what I actually do. But thank, I have got some really good comments about the codes." } ]
[ { "body": "<p>I don't see why you want to use awk, or what kind of report you want to see. I have made some code-review-type adjustments to your script:</p>\n\n<pre><code>#!/bin/bash\n# sort files into subdirectories\nstart=$SECONDS # this is a magic bash variable\necho \"trigger took place in $PWD\"\nfor file in *; do # don't need to call ls\n echo \"processing $file ...\"\n fileext=${file##*.} # if you define a variable, you might as well use it\n case $fileext in\n zip)\n dirname=archive/${file%.*}\n mkdir -p \"$dirname\" # make the parent and the subdir in one call\n unzip \"$file\" -d \"$dirname\"\n ;;\n *)\n echo \"nonzip\"\n mkdir -p \"$fileext\" # -p option suppresses error message if dir exists\n mv \"$file\" \"$fileext\"\n ;;\n esac\ndone\necho \"Done in $((SECONDS-start)) seconds!\"\n</code></pre>\n\n<p>If you have any questions, please add a comment.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-03-03T01:27:37.280", "Id": "15278", "Score": "0", "body": "Looks like we had the same leaning. I caught a few more bugs. `SECONDS` would work as intended in the original, it can be assigned to." } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-03-03T01:08:31.667", "Id": "9663", "ParentId": "9662", "Score": "2" } }, { "body": "<p>I don't see where awk fits in this. I'm going to point out a few problems in your script, so you'll at least get something useful out of this. But please do tell us what you're actually trying to do.</p>\n\n<blockquote>\n<pre><code>IFS=$(echo -en \"\\n\\b\")\n</code></pre>\n</blockquote>\n\n<p>There's a simpler way of writing that in bash: <code>IFS=$'\\n\\b'</code>. I don't understand why you're setting <code>$IFS</code> to include a backspace character; and whatever need you may have found to set <code>IFS</code> is probably caused by other problems that I'll point out below.</p>\n\n<blockquote>\n<pre><code>echo \"trigger took place in $(pwd)\"\n</code></pre>\n</blockquote>\n\n<p>There's a variable <code>$PWD</code> that contains the current working directory. <code>$PWD</code> is equivalent to <code>$pwd</code> and a little faster.</p>\n\n<blockquote>\n<pre><code>for i in $( ls -1); do\n</code></pre>\n</blockquote>\n\n<p><a href=\"http://mywiki.wooledge.org/ParsingLs\">Do not parse the output of <code>ls</code>.</a> <code>ls</code> is a tool for displaying the attributes of files. The shell has a perfectly good construct for listing files in a directory: wildcards. Make this <code>for i in *; do …</code> This way has the advantage that it can cope with arbitrary file names; parsing the output of <code>ls</code> will always choke on some “strange” file names.</p>\n\n<blockquote>\n<pre><code>fileext=${i##*.}\n</code></pre>\n</blockquote>\n\n<p>You should use this variable below.</p>\n\n<blockquote>\n<pre><code>mkdir archive\n</code></pre>\n</blockquote>\n\n<p>If you run this part multiple times, the directory will already exist. Test for the directory's existence first, or call <code>mkdir -p archive</code>.</p>\n\n<blockquote>\n<pre><code>mkdir $(pwd)/archive/${i%%.*}\n</code></pre>\n</blockquote>\n\n<p>Again, <code>$PWD</code>. Except that there's no point in using it, a relative path would do. Also, you need double quotes around all variable and command substitutions; otherwise the shell splits the result of the substitution at <code>$IFS</code> characters, then interprets the pieces as glob patterns (file name wildcards) and expands them. <strong>Always put double quotes around variable and command substitutions</strong> unless you know why you need to leave them off.</p>\n\n<p>Another point: <code>${i%%.*}</code> strips everything after the first <code>.</code> in the file name. This is not compatible with the definition of <code>$fileext</code>. To get the file except for its last extension, use <code>${%.*}</code> (truncate at the last <code>.</code>).</p>\n\n<blockquote>\n<pre><code>$(unzip $i -d $(pwd)/archive/${i%%.*})\n</code></pre>\n</blockquote>\n\n<p>I don't know what you're trying to do here, interpreting the output of <code>unzip</code> as a shell snippet. Again, double quotes around variable substitutions.</p>\n\n<blockquote>\n<pre><code> mkdir ${i##*.}\n</code></pre>\n</blockquote>\n\n<p>Again, double quotes. Also, if the file name sans prefix happens to begin with a <code>-</code>, the <code>mkdir</code> command will interpret its argument as an option. To avoid this, use <code>--</code> to indicate the end of the option list (this is a convention that most utilities respect): <code>mkdir -- \"${i##*.}\"</code></p>\n\n<p>Also, there's a case you don't handle: what if the file name contains no <code>.</code>? In that case, <code>mkdir</code> will attempt to overwrite the file (and fail). One solution is to create the directory with a temporary name, move the file, then rename it.</p>\n\n<p>Here's the fixed code:</p>\n\n<pre><code>#!/bin/bash\n#File sorter\nset -e # Abort in case of error\nSECONDS=0\nSAVEIFS=$IFS\necho \"trigger took place in $PWD\"\nfor i in *; do\n echo \"processing $i ...\"\n case $i in\n *.zip)\n [ -d archive ] || mkdir archive\n mkdir \"archive/${i%.*}\"\n unzip -d \"archive/${i%.*}\" \"./$i\";;\n *.*)\n mkdir -p \"${i##*.}\"\n mv -- \"$i\" \"${i##*.}/\";;\n *)\n tmp=$(TMPDIR=. mktemp -d)\n mv -- \"$i\" \"$tmp/\"\n mv -- \"$tmp\" \"$i\";;\n esac\ndone\necho \"Done in $SECONDS seconds!\"\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-03-03T01:28:12.820", "Id": "15279", "Score": "0", "body": "P.S. I haven't tested the resulting code, there may be remaining bugs." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-03-03T17:23:20.110", "Id": "15292", "Score": "0", "body": "+1 nice explanation. You don't need the SAVEIFS variable now that you no longer change IFS." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-03-04T00:55:05.623", "Id": "15306", "Score": "0", "body": "@Gilles WOW. Thank man I really really appreciate what you did. Let me clarify what I want to do. I want to make directory for every file's extension that is present in $PWD and move the file there. Except if it is a zip file I want to extract it to the directory archive. I needed to overwrite $IFS since the filenames with spaces was counted as multiple files in the loop. And I needed to generate a report of what file moved/extracted where after it finished its process. That is why I wanted to use AWK. I hope I explained well what I want to do. Thank you really much for what you said so far." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-03-04T01:08:56.407", "Id": "15308", "Score": "0", "body": "@Erfan Please post a new question on [unix.se] explaining what you want in that report. What you wrote in your comment here is a good start; an example report for a couple of input files would help a lot." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-03-04T01:27:57.470", "Id": "15309", "Score": "0", "body": "@Gilles Thanks man. I actually got what I need just a simple text report and I made it. I just have only 1 problem and I really do not have a clue how to do it. I want to pass command arguments along with my shell script. For example the user would be able to write `sh fsorter.sh -d /Downloads` and the script runs in Downloads. Or some other ones. Can you help me understand where to start?" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-03-04T01:48:24.033", "Id": "15310", "Score": "0", "body": "@Erfan Again, please ask on [unix.se].." } ], "meta_data": { "CommentCount": "6", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-03-03T01:15:29.200", "Id": "9664", "ParentId": "9662", "Score": "7" } } ]
{ "AcceptedAnswerId": "9664", "CommentCount": "3", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-03-02T23:07:46.880", "Id": "9662", "Score": "4", "Tags": [ "bash", "shell" ], "Title": "Script to group files by extension and unzip archives" }
9662
<p>I'm worried about my own attempt at a solution for a Sphere-Plane collision testing. I originally implemented a solution I found on a mix of Game Development websites around the place, which was similar enough to the following:</p> <pre><code>bool intersecting(BoundingSphere const&amp; s, Vector3 const&amp; s_origin, BoundingPlane const&amp; p, float const p_distance) { Vector3 const p_origin = p.normal * p_distance; Vector3 const cp = s_origin + p.normal * dot((p_origin - s_origin), p.normal); return (distance2(s_origin, cp) &lt; s.radius * s.radius); } </code></pre> <p>But I have recently spent a bit more time doing linear algebra since and basic geometry, and decided upon revising the above solution (to see if I understood the problem space better).</p> <p>In thinking about it as a simple check: distance of a point from a line being less than the radius. I came up with the following:</p> <pre><code>bool intersecting2(BoundingSphere const&amp; s, Vector3 const&amp; s_origin, BoundingPlane const&amp; p, float const p_distance) { return abs&lt;float&gt;(dot(p.normal, s_origin) - p_distance) &lt; s.radius; } </code></pre> <p>It has so far passed all my tests practically, but I still worry about my mathematical ability and I don't want an edge case to bite me in the ass that I might have missed. One thing I have definitely noticed is the solution is highly sensitive to the normalised form of the plane normal. If it is simply a rough estimation, ie not truly normalised, it will fail completely (exponential error).</p> <p>The fact I never saw a solution that short worries me haha.</p> <p>edit: My testbed: <a href="http://pastie.org/3512889" rel="nofollow">http://pastie.org/3512889</a></p> <p>proposed tags: collision-detection &amp;&amp; math</p>
[ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-03-03T23:00:38.937", "Id": "15297", "Score": "1", "body": "Off topic. Would probably by a better for http://math.stackexchange.com/" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-03-04T10:22:03.337", "Id": "15335", "Score": "1", "body": "What about http://gamedev.stackexchange.com/? :)" } ]
[ { "body": "<p>I'm not sure what kind of error your getting but here is a very simple collision test:</p>\n\n<pre><code>#include &lt;cmath&gt;\n#include &lt;iostream&gt;\n\nclass float3 {\n public:\n float x,y,z;\n};\n\nclass float4 {\n public:\n float a,b,c,d;\n float norm() const{\n return sqrt(a*a+b*b+c*c);\n }\n};\n\ntypedef float4 plane;\n\nclass sphere {\n public:\n float3 position;\n float radius;\n};\n\nfloat project( const float3 &amp; spherePos, const plane &amp; p){\n return std::abs( spherePos.x*p.a + spherePos.y*p.b + spherePos.z*p.c + p.d );\n}\n\nbool const collision( const sphere &amp; s, const plane &amp; p){\n return project(s.position,p)/p.norm() &lt; s.radius;\n}\n\nint main( int argc, char * argv[]){\n\n plane p = {0.0,-1.0,0.0, 2.0 };\n sphere s = { {0.0,1.5,0.0}, 1.0 };\n\n if ( collision(s,p) )\n std::cout &lt;&lt; \"Collision detected\" &lt;&lt; std::endl;\n\n}\n</code></pre>\n\n<p>The advantage here is that you don't need a normalized plane. The line that bothers me is this:</p>\n\n<pre><code>return abs&lt;float&gt;(dot(p.normal, s_origin) - p_distance) &lt; s.radius;\n</code></pre>\n\n<p>Just write your solution such that it can handle un-normalized planes. If you're working with normalized planes (which may be what is contained in \"p.normal\"?) I believe you need :</p>\n\n<pre><code>return abs&lt;float&gt;(dot(p.normal, s_origin) + p_distance) &lt; s.radius;\n</code></pre>\n\n<p>See the <a href=\"http://mathworld.wolfram.com/Point-PlaneDistance.html\" rel=\"nofollow\">wolfram</a> page on this topic - it is straight forward. It is not clear how you have implemented BoundingPlane - but if you are getting errors, that would be the first place to look.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-03-04T00:58:25.087", "Id": "15307", "Score": "0", "body": "BoundingPlane is just a container for `Vector3 normal`, a normalised vector for the normal of the plane. Distance from the origin is a variable which is passed `p_distance`. I originally came up with what you have in the second statement, but it only gave the correct results when I did the `- p_distance`, which I don't understand." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-03-04T02:21:43.330", "Id": "15317", "Score": "1", "body": "\" but it only gave the correct results when I did the - p_distance \" . I'm not sure what you 'expect' the results to be - I think your error lies in your interpretation of the representation of a plane. See http://mathworld.wolfram.com/Plane.html for more info about the formal definition of a plane. What you have is very close though!" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-03-04T03:55:15.267", "Id": "15324", "Score": "0", "body": "I'm pretty sure I have the right understanding. The normal of the plane is obvious enough (the vector perpendicular to the plane), and that is normalised. Then p_distance is the distance of that normal from the origin (0,0,0). Therefore a Plane with a normal of (0, 1, 0) would be flat, and a p_distance of 5 would put the plane at y = 5." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-03-04T06:15:52.590", "Id": "15330", "Score": "0", "body": "traditionally, if you have a plane defined by ax + by + cz + d = 0, if you specified the normal to be (0,1,0) you would have the equation y = -d/b = -d, where in this case the intercept is y = - d. So if you set d=5, the y intercept is at -5 (y = - d, y = -5 ). Make sure you are being consistent with the math - I don't believe what you have done is what you expected you did - thus the errors. Simple things like this that 'work' in one case will cause huge headaches down the road one you attempt more complicated operations" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-03-28T09:55:18.340", "Id": "16564", "Score": "0", "body": "Its taken me this long (24 days?), just reading a paragraph on building planes made me realise you were right. I had a fundamental problem with my understand of distance to the origin. I didn't realise distance could be negative OR positive, based on the normal of the plane. I thought it was simply absolute. Which makes perfect sense now. Hence. Thanks for your answer." } ], "meta_data": { "CommentCount": "5", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-03-03T18:30:37.270", "Id": "9673", "ParentId": "9672", "Score": "4" } } ]
{ "AcceptedAnswerId": "9673", "CommentCount": "2", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-03-03T17:48:17.010", "Id": "9672", "Score": "2", "Tags": [ "c++" ], "Title": "Sphere-Plane collision test" }
9672
<p>I use the following code:</p> <pre><code> var newValue = ($(event.target).is(":checked")) ? 1 : 0; var oldValue = (!$(event.target).is(":checked")) ? 1 : 0; sendMessage(this.name, oldValue, newValue); </code></pre> <p>Is there any better approach?</p>
[]
[ { "body": "<p><code>sendMessage(this.name, +!event.target.checked, +event.target.checked)</code></p>\n\n<p>Not your sending <code>sendMessage(text, !bool, bool)</code> which is silly just send one bool.</p>\n\n<p>Also <code>$(thing).is(\":checked\")</code> is stupid (jQuery ಠ_ಠ)</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-03-03T20:47:08.467", "Id": "15295", "Score": "2", "body": "LA_, note that `+true == 1`, and `+false == 0` in JS." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2017-08-23T16:19:26.280", "Id": "329740", "Score": "0", "body": "The real answer is in the comments" } ], "meta_data": { "CommentCount": "2", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-03-03T20:41:12.990", "Id": "9675", "ParentId": "9674", "Score": "8" } }, { "body": "<p>As Cygal noted in one of the comments, using the <a href=\"https://developer.mozilla.org/en/JavaScript/Reference/Operators/Arithmetic_Operators#.2B_%28Unary_Plus%29\" rel=\"nofollow\"><code>unary</code></a> operator (+) coerces <code>true</code> and <code>false</code> into numbers. So doing <code>+true</code> will yield 1 while using <code>+false</code> will yield 0.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-03-07T15:47:52.957", "Id": "15489", "Score": "2", "body": "The `+` is not \"the\" unary operator, it's **one example of** a unary operator. It's called \"unary\" because it takes one argument. Even the page you linked references another unary operator (-). You can compare with ternary operators—which take three arguments (e.g. foo ? bar : bat)—and many binary operators (e.g. foo + bar). The bang (!) is also a common unary operator." } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-03-03T22:17:55.677", "Id": "9677", "ParentId": "9674", "Score": "6" } }, { "body": "<p>For the record: <code>Number</code> will also convert to 1 or 0:</p>\n\n<pre><code>sendMessage(this.name, Number(!event.target.checked), Number(event.target.checked));\n</code></pre>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-03-29T10:21:24.280", "Id": "10435", "ParentId": "9674", "Score": "3" } }, { "body": "<p>Ah I forgot that rep doesn't transfer over, apparently I don't have enough to comment. I was going to reply to Cygal's comment on Raynos's answer:</p>\n\n<p>While it is true that <code>+true == 1</code>, and <code>+false == 0</code> that isn't exactly helpful since <code>true == 1</code> and <code>false == 0</code> as well. You probably meant to say that <code>+true === 1</code> and <code>+false === 0</code></p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-03-29T23:58:40.640", "Id": "10472", "ParentId": "9674", "Score": "3" } } ]
{ "AcceptedAnswerId": "9675", "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-03-03T20:37:53.773", "Id": "9674", "Score": "3", "Tags": [ "javascript", "jquery" ], "Title": "How to transform true and false to 1 and 0?" }
9674
<p>I'm attempting to improve my coding style by concentrating on simple and focused OOP client-server interfaces and error handling - atm in the context of designing a Blackjack game. I'm starting with the Card class that represents an individual card. I'm looking for any improvements on or flaws with my approach.</p> <pre><code>#include &lt;sstream&gt; #include &lt;stdexcept&gt; #include &lt;string&gt; class Card { public: enum Ranks { Ace = 1, Ten = 10, Jack, Queen, King }; enum Suits { Spades, Hearts, Diamonds, Clubs }; Card( int rank, int suit ) throw(std::range_error) { if( rank &lt; 1 || rank &gt; 13 ) { std::stringstream errMsg; errMsg &lt;&lt; "Card(): rank '" &lt;&lt; rank &lt;&lt; "' out of range"; throw std::range_error( errMsg.str() ); } else if( suit &lt; 0 || suit &gt; 3 ) { std::stringstream errMsg; errMsg &lt;&lt; "Card(): suit '" &lt;&lt; suit &lt;&lt; "' out of range"; throw std::range_error( errMsg.str() ); } m_rank = rank; m_suit = suit; } int rank() const { return m_rank; } int suit() const { return m_suit; } std::string str( bool useStrings = false ) const { std::stringstream ret; if( useStrings ) ret &lt;&lt; sRanks[m_rank] &lt;&lt; " of " &lt;&lt; sSuits[m_suit]; else ret &lt;&lt; cRanks[m_rank] &lt;&lt; cSuits[m_suit]; return ret.str(); } private: static const char cRanks[14]; static const char cSuits[4] static const std::string sRanks[14]; static const std::string sSuits[4]; int m_rank; int m_suit; }; const std::string Card::sSuits[4] = {"Spades", "Hearts", "Diamonds", "Clubs"}; const std::string Card::sRanks[14] = { "\0", "Ace", "Two", "Three", "Four", "Five", "Six", "Seven", "Eight", "Nine", "Ten", "Jack", "Queen", "King" }; const char Card::cSuits[4] = { 's', 'h', 'd', 'c' }; const char Card::cRanks[14] = { '\0', 'A', '2', '3', '4', '5', '6', '7', '8', '9', 'T', 'J', 'Q', 'K' }; </code></pre> <p>The client can create a card either using the Card enum constants or integers, like</p> <pre><code>Card card(Card::Ace, Card::Diamonds); Card card2(0, 3); // throws an exception </code></pre> <p>I'm dubious on how useful the public enum constants are for client code. Also, I'm very new to exception programming and I'm not sure if this is a good approach or whether the constructor should throw an exception. Any improvements or suggestions?</p>
[]
[ { "body": "<p>If you are going to go to the trouble of creating Rank and Suit enum then use them.</p>\n\n<pre><code>Card( int rank, int suit ) throw(std::range_error)\n</code></pre>\n\n<p>I would have done</p>\n\n<pre><code>Card(Rank rank,Suit suit )\n</code></pre>\n\n<p>That way you can't accidentally go: <code>Card(Card::Hearts,2)</code> The compiler type checking will catch this at compiletime. Just use the enums all through your code. C++ is a strongly typed language use the compiler to catch your errors.</p>\n\n<p>The exception specifications have been deprecated. They were mostly useless anyway (if you fail and throw an illegal exception it causes your application to terminate without unwinding the stack). So in general don't use them. For the one case where they are usfull (no throw specifications) they are good but I use them more as documentation to remind me that I should make sure the method does not throw.</p>\n\n<p>But yes the constructor should throw an exception if it gets a value outside the expected range. There is no point in allowing an invalid object to propagate threw your code it will just cause problems with your invariants.</p>\n\n<p>Prefer to use the initializer list rather than initializing variables in the constructor.</p>\n\n<pre><code>Card(Rank rank, Suit suit)\n : m_rank(rank)\n , m_suit(suit)\n</code></pre>\n\n<p>Again another place that it would have been nice to use the enum to make the code more eadable:</p>\n\n<pre><code> if( rank &lt; 1 || rank &gt; 13 ) {\n</code></pre>\n\n<p>Try:</p>\n\n<pre><code> if( rank &lt; Ace || rank &gt; King ) {\n</code></pre>\n\n<p>Hate getters/setter they spoil encapsulation. Do you really need to get the values of the card? Any operation that manipulates the card is usually a method on the card or a friendly class.</p>\n\n<pre><code>int rank() const { return m_rank; }\nint suit() const { return m_suit; }\n</code></pre>\n\n<p>Don't try and write C++ like Java. We don;t need a string function. It is much more preferable (and flexable) to write an output (and probably input) stream operator.</p>\n\n<pre><code>std::string str() const\n{\n return std::string( Ranks[m_rank] + Suits[m_suit] );\n}\n</code></pre>\n\n<p>I would have done:</p>\n\n<pre><code>friend std::ostream&amp; operator&lt;&lt;(std::ostream&amp; stream, Card const&amp; card)\n{\n return stream &lt;&lt; card.Ranks[card.m_rank] &lt;&lt; card.Suits[card.m_suit];\n}\n</code></pre>\n\n<h3>Adding Cards to a deck. (Based on comment below)</h3>\n\n<pre><code>#include &lt;vector&gt;\n\nclass Card\n{\n public:\n enum Ranks { Ace = 1, Ten = 10, Jack, Queen, King };\n enum Suits { Spades, Hearts, Diamonds, Clubs };\n\n Card(Ranks rank, Suits suit){}\n};\n\n// Need to add the ++ operators for Ranks/Suits\nCard::Ranks&amp; operator++(Card::Ranks&amp; r)\n{\n return r = Card::Ranks(static_cast&lt;int&gt;(r)+1);\n}\nCard::Suits&amp; operator++(Card::Suits&amp; s)\n{\n return s = Card::Suits(static_cast&lt;int&gt;(s)+1);\n}\n\n\n\nint main()\n{\n std::vector&lt;Card&gt; deck;\n\n // Does not look that verbose to me.\n for(Card::Ranks rank=Card::Ace;rank &lt;= Card::King;++rank)\n {\n for(Card::Suits suit=Card::Spades;suit &lt;= Card::Clubs;++suit)\n {\n deck.push_back(Card(rank, suit));\n }\n }\n\n // Compared to \n for(int rank=Card::Ace;rank &lt;= Card::King;++rank)\n {\n for(int suit=Card::Spades;suit &lt;= Card::Clubs;++suit)\n {\n deck.push_back(Card(rank, suit));\n }\n }\n}\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-03-03T23:10:02.920", "Id": "15298", "Score": "0", "body": "regarding the initializer list, what benefit does it give? I know that members have their values set in the initializer list before the constructor body runs, but is there any other benefit?" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-03-03T23:21:02.903", "Id": "15299", "Score": "0", "body": "Yes. If the objects are class objects then there constructors are run. So if you don't use the initializer list then you will run the constructor to initialize them then you will run the assignment operator to put the value you want in them. Which is a bit impractical." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-03-03T23:22:07.957", "Id": "15300", "Score": "0", "body": "But you may argue my objects are POD and have no constructor. But I would counter argue with 2 points: A) Half of coding is being consistent so you should treat all members the same otherwise you initialize half in one place and half in another. B) What happens if somebody changes the type from `enum Suit` to `class Suit`. Now you need to modify your code to make sure it works correctly with a class. While changing the type of an object should really require no code changes otherwise maintaining the code becomes much harder than it needs to be." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-03-03T23:25:10.747", "Id": "15301", "Score": "0", "body": "regarding the use of enums as constructor parameters, I didn't want to limit the client to having to use them. Like if a Deck class needs to build a collection of cards by iterating through a range of suits and ranks, this would be impossible as far as I know due to casting an int argument to an enum parameter, but also verbose and somewhat nonsensical in the case of suits: for( int rank = Card::Ace; rank <= Card::King; ++rank ) for( int suit = Card::Spades; suit <= Card::Clubs; suit++ ) { // add card to collection" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-03-03T23:44:44.967", "Id": "15302", "Score": "0", "body": "Impossible that is without casting rank back to type Ranks and suit to Suits, which seems like we're creating too much complexity and burden to warrant the type safety" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-03-03T23:47:43.963", "Id": "15303", "Score": "0", "body": "It's not that verbose. See above" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-03-04T00:05:06.110", "Id": "15304", "Score": "0", "body": "Ah, I didn't think to overload the global ++ operator. There's no overhead with returning a new Ranks/Suits object from operator++() is there, since enums are built-in? And I guess it's no less nonsensical to say for( Card::Suits suit = Card::Spades; suit <= Card::Clubs; suit++ ) than it is to say for( int suit = 0; suit <= 3; suit++ ), just a bit more verbose." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-03-04T02:24:05.093", "Id": "15318", "Score": "0", "body": "I would say that Cards::Clubs is much clearer in what it means than 3. In fact I would go one further I would have and end marker on both enums (but that is just a style thing and what you have is fine)." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-03-04T02:25:12.770", "Id": "15319", "Score": "0", "body": "Also Note: I am returning reference from the operator++. And it will probably be inlined so there is no cost." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-03-04T03:35:19.827", "Id": "15322", "Score": "0", "body": "Ah, I was wondering why they weren't references before - thought you had a good reason! Thanks for all your help Loki!" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-03-07T22:18:16.363", "Id": "15538", "Score": "0", "body": "Though there's practically no way the underlying types in this example are not `int`, I like to use unary + to numerify an enum expression without making assumptions about underlying type. `operator++(Card::Ranks& r) { return r = Card::Ranks(+r + 1); }`" } ], "meta_data": { "CommentCount": "11", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-03-03T22:53:20.757", "Id": "9678", "ParentId": "9676", "Score": "6" } }, { "body": "<p>I cleaned it up a bit taking most of Loki's advice, though I'm not sure about the public getter functions not being a good approach here. In the Blackjack program I'm making, and in most card games, your program logic will want to get the rank or suit of the card in question, not just print a string representation of the card. And the client probably shouldn't be able to change the value of the card, so there's no setter function. If a client has say a Hand class that represents a Blackjack hand, and needs to keep a cumulative point total of card ranks, I don't see another way to do this other than declaring Hand a friend inside Card and removing the getter functions, which seems like a poor approach.</p>\n\n<p>One last question I have would be how I could create my own manipulator so that my overloaded stream operator could format its output in a variable way, like</p>\n\n<pre><code>std::cout &lt;&lt; print_as_phrase &lt;&lt; card &lt;&lt; std::endl;\n</code></pre>\n\n<p>where print_as_string is a manipulator that causes my overloaded operator to return the commented out option in my code below. Right now I can only think of adding a function to card like void print_as_phrase( bool printPhrase = true ); to set a Card data member and have my overloaded friend operator function check that, but that seems more cumbersome than the original str() method I was using.</p>\n\n<pre><code>#include &lt;iostream&gt;\n#include &lt;string&gt;\n#include &lt;stdexcept&gt;\n#include &lt;sstream&gt;\n#include &lt;vector&gt;\n\nclass Card\n{\npublic:\n enum Rank {\n Ace = 1, Two, Three, Four, Five, Six, Seven,\n Eight, Nine, Ten, Jack, Queen, King, RankEnd\n };\n enum Suit { Spades, Hearts, Diamonds, Clubs, SuitEnd };\n\n Card( Rank rank, Suit suit )\n : m_rank(rank), m_suit(suit)\n {\n if( rank &lt; Ace || rank &gt; King ) {\n std::stringstream errMsg;\n errMsg &lt;&lt; \"Card(): rank '\" &lt;&lt; rank &lt;&lt; \"' out of range\";\n throw std::range_error( errMsg.str() );\n } else if( suit &lt; Spades || suit &gt; Clubs ) {\n std::stringstream errMsg;\n errMsg &lt;&lt; \"Card(): suit '\" &lt;&lt; suit &lt;&lt; \"' out of range\";\n throw std::range_error( errMsg.str() );\n }\n }\n\n Rank rank() const { return m_rank; }\n Suit suit() const { return m_suit; }\n std::string str() const\n {\n std::stringstream ret;\n ret &lt;&lt; sRanks[m_rank] &lt;&lt; \" of \" &lt;&lt; sSuits[m_suit];\n return ret.str();\n }\n\n friend std::ostream&amp; operator&lt;&lt;( std::ostream &amp;os, const Card &amp;card )\n {\n return os &lt;&lt; card.cRanks[card.m_rank] &lt;&lt; card.cSuits[card.m_suit];\n // return os &lt;&lt; card.sRanks[card.m_rank] &lt;&lt; \" of \" &lt;&lt; card.sSuits[card.m_suit];\n }\n\nprivate:\n static const std::string sRanks[14];\n static const std::string sSuits[4];\n static const char cRanks[14];\n static const char cSuits[4];\n Rank m_rank;\n Suit m_suit;\n};\n\nconst std::string Card::sRanks[14] = {\n \"\\0\", \"Ace\", \"Two\", \"Three\", \"Four\", \"Five\", \"Six\", \"Seven\",\n \"Eight\", \"Nine\", \"Ten\", \"Jack\", \"Queen\", \"King\"\n};\nconst std::string Card::sSuits[4] = { \"Spades\", \"Hearts\", \"Diamonds\", \"Clubs\" };\nconst char Card::cRanks[14] = {\n '\\0', 'A', '2', '3', '4', '5', '6', '7',\n '8', '9', 'T', 'J', 'Q', 'K'\n};\nconst char Card::cSuits[4] = { 's', 'h', 'd', 'c' };\n\n\nCard::Rank&amp; operator++( Card::Rank &amp;rank )\n{\n return rank = Card::Rank( static_cast&lt;int&gt;(rank) + 1 );\n}\n\nCard::Suit&amp; operator++( Card::Suit &amp;suit )\n{\n return suit = Card::Suit( static_cast&lt;int&gt;(suit) + 1 );\n}\n\n\nint main()\n{\n std::vector&lt;Card&gt; deck;\n for( Card::Suit suit = Card::Spades; suit &lt; Card::SuitEnd; ++suit )\n for( Card::Rank rank = Card::Ace; rank &lt; Card::RankEnd; ++rank ) {\n deck.push_back( Card(rank, suit) );\n std::cout &lt;&lt; deck.back() &lt;&lt; \"\\n\";\n }\n\n return 0;\n}\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-03-04T06:13:10.457", "Id": "15329", "Score": "0", "body": "Note: The `return 0` at the end of main() (in C++ only) is optional. If left out it implies a successful return value." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-03-04T19:39:10.053", "Id": "15353", "Score": "0", "body": "If you want to write a stream manipulator that affects how the card is printed. Then you need to look up [xalloc](http://www.cplusplus.com/reference/iostream/ios_base/xalloc/). This allows you to store information in the stream that can then be subsequently used by output stream operator to determine formatting." } ], "meta_data": { "CommentCount": "2", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-03-04T05:44:03.863", "Id": "9688", "ParentId": "9676", "Score": "0" } } ]
{ "AcceptedAnswerId": "9678", "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-03-03T21:39:05.297", "Id": "9676", "Score": "3", "Tags": [ "c++", "beginner", "playing-cards" ], "Title": "Card class for card games" }
9676
<p>I feel that my app could be more efficient but I am not sure what else I can do. I feel like I could be reusing more. If you could give me some tips on how I could improve this, I would really appreciate it.</p> <pre><code>public class Main { /** * @param args * @throws InterruptedException */ public static void main(String[] args) throws InterruptedException { //creating a new instance of my Calc class Calc calc = new Calc(); // setting the variables calc.term = 30; calc.interestRate = (float) 0.0575; calc.principal = (float) 200000.00; calc.monthlyPayment = 0; //format currency correctly DecimalFormat df = new java.text.DecimalFormat("$,###.00"); //Method call to calc class calc.DoWork(); //out put System.out.println("\n__________________________________________________________________________________________________________"); System.out.println("\nPrincipal Amount: " + df.format (calc.principal )); System.out.println("interest rate: " + calc.interestRate); System.out.println("Term of loan(number of years): " + calc.term); System.out.println("Monthly payment is: " + df.format (calc.monthlyPayment)); System.out.println("__________________________________________________________________________________________________________\n"); Thread.sleep(600); calc.DoWorkAmortization(); } } </code></pre> <hr> <pre><code>package com.mortgagecalc; import java.text.DecimalFormat; public class Calc { int term; //how long the loan is float interestRate; // loan interest rate float principal; // loan amount float monthlyPayment; // monthly payment private int period = 12; // 12 months in a year //Amortization Variables int n = 360; double i = 0.0575; double a = 200000.00; double r = (1+i/12); DecimalFormat df = new java.text.DecimalFormat("$,###.00"); //Method to calculate the payment. void DoWork() throws InterruptedException { //Payment calculation monthlyPayment = (float) (principal * Math.pow(1 + interestRate / period, term * period) * (interestRate / period) / (Math.pow(1 + interestRate / period, term * period) - 1)); }//Method to calculate Amortization void DoWorkAmortization() throws InterruptedException { int number = 1; double monthlyPayments = a * ( r - 1 ) / ( 1 - Math.pow(r,-n)); System.out.println ("Month \t\t Payment \t\0\0\0\0 Interest Paid \t\0\0\0\0 Principal Paid \t\0\0\0\0 Remaining Balance"); System.out.println("__________________________________________________________________________________________________________"); for ( number = 1; number &lt;= 360; number++) { double interest = a * ( i/12 ); double principal = monthlyPayments - interest ; double balance = a - principal; a = balance; System.out.println ("\0\0"+ number + "\t\t" + df.format(monthlyPayments)+"\t\t" + df.format(interest)+"\t\t\t"+ df.format(principal)+ "\t\t\t" +df.format(balance)); if (number % 12 == 0){ Thread.sleep(600); } } } } </code></pre>
[ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-03-04T12:54:42.227", "Id": "15338", "Score": "0", "body": "Note that you don't need to write `(float) 0.0575`, just `0.0575F`." } ]
[ { "body": "<ol>\n<li><p>I believe you'd be better off with having term, interestRate,... as privates, and provide those in the Calc constructor.</p></li>\n<li><p>The name DoWork does not convey the task the function performs; a better name could be CalculatePayment. Also, the \"do\" in \"DoWork\" suggests that either the function has a side effect or takes a lot of time to compute. The same for DoWorkAmortization, it prints stuff and sleeps; could be PrintAmortizations. Calc class name should also be mor\ntelling.</p></li>\n<li><p>But the act of conveying information to the user, using a specific way (System.out) and sleeping does not belong to the Calc class. It is better to leave only the calculation responsibility to Calc and the rest to the program.</p></li>\n<li><p><s>But while you have that function print to the user, then at least catch the InterruptedException and act on it in the function and not pass it further.</s></p></li>\n<li><p><s>DoWork does not have to declare InterruptedException as it will not be thrown there.</s></p></li>\n<li><p>Use intermediate values for subexpressions in DoWork to make the code more readable.</p></li>\n</ol>\n\n<p>Those are my 2¢.</p>\n\n<p>EDIT: Removed 4. and 5., as <a href=\"http://www.ibm.com/developerworks/library/j-jtp05236/\" rel=\"nofollow\">InterruptedException should be propagated in this case</a>.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-03-04T01:51:33.850", "Id": "15311", "Score": "0", "body": "Thank you for your tips :) I was having trouble with just putting the calculations for the Amortization in the Calc class... I am not sure how to pass this. Again thank you for your review." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-03-04T01:55:36.577", "Id": "15312", "Score": "0", "body": "You could create a class having getInterest(), getPrincipal() and getBalance() and return it's instances from a CalculateStateOnDay(int day)." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-03-04T02:03:27.440", "Id": "15314", "Score": "0", "body": "ahh so its more of a getter / setter ? can i do this with in Calc class ? Im going to rename that class btw lol" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-03-04T02:07:28.880", "Id": "15315", "Score": "0", "body": "interest, principal and balance are all related to a specific day, and as such should not be inside Calc - which is not bound to a specific day. What I'm suggesting is to return them in instances of some class InterestData, which has getters for the three. Those are not really getters from the Calc class." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-03-04T02:11:07.083", "Id": "15316", "Score": "0", "body": "But in this simple Calc exercise, it would be easier to have functions getInterest(day), getPrincipal(day) and getBalance(day) in Calc, so you don't have a InterestData class with all properties and no operations" } ], "meta_data": { "CommentCount": "5", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-03-04T01:35:03.870", "Id": "9682", "ParentId": "9680", "Score": "11" } }, { "body": "<ol>\n<li><p>Standard naming for Java functions uses a lower case for the first letter - for example instead of <code>DoWorkAmortization</code> it would be <code>doWorkAmortization</code>.</p></li>\n<li><p>In <code>DoWorkAmortization</code>, the declaration of the variable number should occur at the top of the for loop:</p>\n\n<pre><code>for (int number = 1; number &lt;= 360; number++)\n</code></pre>\n\n<p>rather than four statements above the loop. It's one thing to use a vague variable name as a loop index, but separating the declaration from the use for no reason only invites confusion. A more informative name wouldn't be out of line either - <code>moNumber</code>, or even <code>moNr</code>.</p></li>\n<li><p>In methods that write output (such as <code>DoWorkAmortization</code>), it isn't a bad idea to pass in a <code>PrintStream</code> parameter rather than hard coding <code>System.out</code>.</p></li>\n</ol>\n\n<p>Another 2 cents.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-03-04T04:59:42.873", "Id": "9687", "ParentId": "9680", "Score": "7" } } ]
{ "AcceptedAnswerId": "9682", "CommentCount": "1", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-03-04T01:20:42.640", "Id": "9680", "Score": "4", "Tags": [ "java", "finance" ], "Title": "Mortgage calculator" }
9680
<p>I have a sort of database with a <a href="http://www.tomjewett.com/dbdesign/dbdesign.php?page=manymany.php" rel="nofollow" title="many-to-many">many-to-many</a> association between tags and files. For various reasons, I decided to forgo a junction table in favor of having the left and right tables store the associated values in the tables themselves. However I've ended up writing code like this:</p> <pre><code>GHashTable *tagdb_get_tag_files (tagdb *db, int tag_code) { return g_hash_table_lookup(db-&gt;reverse, GINT_TO_POINTER(tag_code)); } GHashTable *tagdb_get_file_tags (tagdb *db, int file_id) { return g_hash_table_lookup(db-&gt;forward, GINT_TO_POINTER(file_id)); } void tagdb_remove_tag (tagdb *db, int id) { GHashTable *its_files = g_hash_table_lookup(db-&gt;reverse, GINT_TO_POINTER(id)); if (its_files == NULL) { return; } GHashTableIter it; gpointer key, value; g_hash_table_iter_init(&amp;it, its_files); if (g_hash_table_iter_next(&amp;it, &amp;key, &amp;value)) { tagdb_remove_tag_from_file(db, id, key); } g_hash_table_remove(db-&gt;reverse, GINT_TO_POINTER(id)); } void tagdb_remove_file(tagdb *db, int id) { GHashTable *its_tags = g_hash_table_lookup(db-&gt;forward, GINT_TO_POINTER(id)); if (its_tags == NULL) { return; } GHashTableIter it; gpointer key, value; g_hash_table_iter_init(&amp;it, its_tags); if (g_hash_table_iter_next(&amp;it, &amp;key, &amp;value)) { tagdb_remove_file_from_tag(db, id, key); } g_hash_table_remove(db-&gt;forward, GINT_TO_POINTER(id)); } </code></pre> <p>Where only a few identifiers change, but basically the same thing happens, just on different sides. Is there a simpler, less error prone way to do this in c? Maybe with macros?</p>
[ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-03-04T03:23:16.940", "Id": "15321", "Score": "0", "body": "What are the types of `db->forward` and `db->reverse`" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-03-04T03:49:20.907", "Id": "15323", "Score": "0", "body": "both are `HashTable*`" } ]
[ { "body": "<p>You can pass a function that gets the correct object from tagdb.<br>\nAKA Service Locator pattern</p>\n\n<pre><code>typedef HashTable* (*ITEM_GETTER)(tagdb*);\n\nHashTable* getTag(tagdb *db) { return db-&gt;reverse;}\nHashTable* getFile(tagdb *db) { return db-&gt;forward;}\n\nGHashTable *tagdb_get_item_files (tagdb *db, int itemId, ITEM_GETTER getter)\n{\n return g_hash_table_lookup(getter(db), GINT_TO_POINTER(itemId));\n}\n\nvoid tagdb_remove_item (tagdb *db, int id, ITEM_GETTER getter)\n{\n GHashTable *its_files = g_hash_table_lookup(getter(db), GINT_TO_POINTER(id));\n if (its_files == NULL)\n {\n return;\n }\n\n GHashTableIter it;\n gpointer key, value;\n g_hash_table_iter_init(&amp;it, its_files);\n if (g_hash_table_iter_next(&amp;it, &amp;key, &amp;value))\n {\n tagdb_remove_tag_from_file(db, id, key);\n }\n g_hash_table_remove(getter(db), GINT_TO_POINTER(id));\n}\n</code></pre>\n\n<h3>Edit for clarity:</h3>\n\n<p>The old functions can now be implanted like this:</p>\n\n<pre><code>GHashTable *tagdb_get_tag_files (tagdb *db, int tag_code)\n{\n return tagdb_get_item_files(db, tag_code, getTag);\n}\n\nGHashTable *tagdb_get_file_tags (tagdb *db, int file_id)\n{\n return return tagdb_get_item_files(db, file_id, getFile);\n}\n\nvoid tagdb_remove_tag (tagdb *db, int id)\n{\n tagdb_remove_item(db, id, getTag);\n}\n\nvoid tagdb_remove_file(tagdb *db, int id)\n{\n tagdb_remove_item(db, id, getFile);\n}\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-03-04T04:18:16.083", "Id": "15325", "Score": "0", "body": "I think I like this. I'm not sure about the tagdb_remove_tag_from_file since it removes from an item in the opposite table." } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-03-04T03:29:55.030", "Id": "9684", "ParentId": "9681", "Score": "3" } }, { "body": "<p>So what I've done is to index the tables numerically while passing in the index to each function that accesses a particular table. The setup isn't much different to Loki's, but additionally allows me to work with my notion of parity by checking the passed in table id.</p>\n\n<pre><code>GHashTable *tagdb_get_sub (tagdb *db, int item_id, int sub_id, int table_id)\n{\n GHashTable *sub_table = tagdb_get_item(db, item_id, table_id);\n return g_hash_table_lookup(sub_table, GINT_TO_POINTER(sub_id));\n}\n\nvoid tagdb_remove_sub (tagdb *db, int item_id, int sub_id, int table_id)\n{\n GHashTable *sub_table = tagdb_get_item(db, item_id, table_id);\n if (sub_table != NULL)\n {\n g_hash_table_remove(sub_table, GINT_TO_POINTER(item_id));\n }\n}\n\nvoid tagdb_remove_item (tagdb *db, int item_id, int table_id)\n{\n GHashTable *its_associates = tagdb_get_item(db, item_id, table_id);\n if (its_associates == NULL)\n {\n return;\n }\n\n GHashTableIter it;\n gpointer key, value;\n g_hash_table_iter_init(&amp;it, its_associates);\n int other = (table_id == FILE_TABLE)?TAG_TABLE:FILE_TABLE;\n if (g_hash_table_iter_next(&amp;it, &amp;key, &amp;value))\n {\n printf(\"removing %d from %s\\n\", GPOINTER_TO_INT(key), (other == FILE_TABLE)?\"File table\":\"Tag table\");\n tagdb_remove_sub(db, item_id, GPOINTER_TO_INT(key), other);\n }\n g_hash_table_remove(db-&gt;tables[table_id], GINT_TO_POINTER(item_id));\n}\n\nGHashTable *tagdb_get_item (tagdb *db, int item_id, int table_id)\n{\n return g_hash_table_lookup(db-&gt;tables[table_id], GINT_TO_POINTER(item_id));\n}\n</code></pre>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-03-04T23:58:13.657", "Id": "9704", "ParentId": "9681", "Score": "2" } } ]
{ "AcceptedAnswerId": "9704", "CommentCount": "2", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-03-04T01:34:22.357", "Id": "9681", "Score": "4", "Tags": [ "c" ], "Title": "Creating a common interface" }
9681
<p>As you can see from the code below, my <code>set</code> function accepts two types of parameters: either strings or arrays. Now, ideally I would like to be using operator overloading to handle this, but since PHP doesn't offer anything like that I am stuck with code like this. Is there a better way to write this (or perhaps a better way to address the problem altogether)?</p> <pre><code>class View { // stores file passed to View private $template; // setter function for template variables public function set($var, $content) { if (is_array($var) &amp;&amp; is_array($content)) { if (sizeof($var) == sizeof($content)) { foreach ($var as $vari) { foreach ($content as $contenti) { $this-&gt;template = str_replace("{" . "$vari" . "}", $contenti, $this-&gt;template); } } } } else { $this-&gt;template = str_replace("{" . "$var" . "}", $content, $this-&gt;template); } } } </code></pre>
[]
[ { "body": "<p>First, there is a simple way to flatten out those loops, but it is not what I would suggest. Here is the simple way:</p>\n\n<pre><code>if ((sizeof($var) == sizeof($content))) {\n $count = sizeof($var);\n\n for ($i =0; $i &lt; $count; $i++) {\n $this-&gt;template = str_replace(\n '{' . $var[$i] . '}', $content[$i], $this-&gt;template);\n }\n}\n</code></pre>\n\n<p>Note that you are currently silently doing nothing when the size of your arrays don't match. I think that is a bug.</p>\n\n<h2>My Suggestions</h2>\n\n<p><code>$var</code> and <code>$content</code> are not very descriptive: I would suggest <code>$match</code> and <code>$replacement</code>.</p>\n\n<p><a href=\"http://php.net/str_replace\" rel=\"nofollow\">str_replace</a> can handle arrays as input. I would suggest filling your match with the '{' and '}' beforehand. The code then becomes:</p>\n\n<pre><code>public function set($match, $replacement)\n{\n $this-&gt;template = str_replace($match, $replacement, $this-&gt;template);\n}\n</code></pre>\n\n<p>I would place any sanity checks before the str_replace that you require. str_replace uses blank replacements when the matches array is larger than the replacements. If you want to avoid that use:</p>\n\n<pre><code> if (is_array($match) &amp;&amp; is_array($replacement) &amp;&amp;\n sizeof($match) &gt; sizeof($replacement))\n {\n throw new InvalidArgumentException(\n __METHOD__ . ' Each match must have a replacement');\n }\n</code></pre>\n\n<p>This avoids <a href=\"http://www.codinghorror.com/blog/2006/01/flattening-arrow-code.html\" rel=\"nofollow\">arrow code</a> which will make the code easier to test, reduce its complexity and make it easier to maintain.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-03-04T05:08:27.183", "Id": "15327", "Score": "0", "body": "Interesting, I had no idea I could pass arrays directly into `str_replace` and it would handle the iteration for me behind the scenes! Additionally, I believe you forgot to include the third parameter in your str_replace function; shouldn't it read: `$this->template = str_replace($match, $replacement, $this->template);`" } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-03-04T04:51:18.903", "Id": "9686", "ParentId": "9683", "Score": "2" } }, { "body": "<p>You could use <code>preg_replace_callback</code> to iterate through your array and replace any data. </p>\n\n<pre><code>public function set($data){ // data = array\n\n $callback = function ($matches) use ($data)\n {\n return ( isset($data[$matches[1]]) ) \n ? $data[$matches[1]] \n : $matches[0];\n };\n\n return preg_replace_callback(\n '/\\{(.*?)\\}/', \n $callback, \n $this-&gt;template);\n}\n</code></pre>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-03-04T10:09:07.643", "Id": "9691", "ParentId": "9683", "Score": "2" } } ]
{ "AcceptedAnswerId": "9686", "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-03-04T02:37:46.603", "Id": "9683", "Score": "1", "Tags": [ "php", "template" ], "Title": "Setting a variable for a view template" }
9683
<pre><code>public void AddClient(Client obj){ try{ using(System.Data.SQLite.SQLiteConnection conn = stock.db.SqlLiteConnection.getSQLLiteConnection()){ System.Data.SQLite.SQLiteCommand cmd = conn.CreateCommand(); string sql="insert into Client (email,firstName,lastName,telephone,address,city,state,zip,web) values(@email,@firstName,@lastName,@telephone,@address,@city,@state,@zip,@web)"; cmd.CommandText = sql; cmd.Parameters.AddWithValue("@email", obj.Email); cmd.Parameters.AddWithValue("@firstName", obj.FirstName); cmd.Parameters.AddWithValue("@lastName", obj.LastName); cmd.Parameters.AddWithValue("@telephone", obj.Telephone); cmd.Parameters.AddWithValue("@address", obj.Address); cmd.Parameters.AddWithValue("@city", obj.City); cmd.Parameters.AddWithValue("@state", obj.State); cmd.Parameters.AddWithValue("@zip", obj.Zip); cmd.Parameters.AddWithValue("@web", obj.Web); cmd.ExecuteNonQuery(); } }catch (Exception ex){} } </code></pre> <p>I have couple of questions for the above code</p> <ol> <li>Do I have to close connection manually?</li> <li>Do I need to dispose Command object?</li> <li>If exception occurs, do I have to close connection and command</li> <li>How do I enhance this code further?</li> </ol>
[ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-03-04T14:36:12.240", "Id": "15340", "Score": "1", "body": "You should add relevant tags to get a better responce" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-03-04T16:16:15.187", "Id": "15351", "Score": "0", "body": "Please explain (4) a bit more..." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2015-06-04T14:12:33.823", "Id": "168286", "Score": "2", "body": "I'm voting to close this question as off-topic because questions seeking explanations are off topic." } ]
[ { "body": "<p>OK, here goes: </p>\n\n<ol>\n<li><p>No. You're using <code>using</code> which means that the object will be disposed of in the end of the block. As part of the <code>Dispose()</code> method, the connection will be closed and its resources released.</p></li>\n<li><p>Not manually, you should open another <code>using</code> block to cause the object to <code>Dispose()</code> in the end.</p></li>\n<li><p>Thanks to the <code>using</code> block, when an exception occurs, the object will be disposed because you're thrown out of the block.</p></li>\n<li><p>\"<em>Enhance</em>\" is vague...</p></li>\n</ol>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-03-04T15:47:53.633", "Id": "15347", "Score": "0", "body": "2) in your first answer says resources will be released inside code block. Why should I open another \"using\" to dispose command object" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-03-04T16:01:50.427", "Id": "15350", "Score": "0", "body": "The resources of the object that is handled by the using block... in your case it's the object referenced by `conn`" } ], "meta_data": { "CommentCount": "2", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-03-04T15:39:31.513", "Id": "9695", "ParentId": "9694", "Score": "2" } } ]
{ "AcceptedAnswerId": "9695", "CommentCount": "3", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-03-04T14:08:08.110", "Id": "9694", "Score": "0", "Tags": [ "c#", "sql" ], "Title": "Basic SQL user database" }
9694
<p>I'm working on a framework (partly out of frustration with Zend, and partially as a learning exercise to improve my coding). I've constructed a fairly solid library of classes for data validation, and the next step was to string them all together with dependency injection. </p> <p>However, I was finding it to be a bit laborious to assemble all the classes together into a unit capable of doing useful work. After doing a bit of digging around I found some stuff on DI Containers and figured that this might be a solution to the problem. </p> <p>Here is the code I originally wrote to assemble my classes together into a unit for validation of a simple password + confirm password form.</p> <pre><code>use gordian\reefknot\autoload\Autoload, gordian\reefknot\input\validate, gordian\reefknot\input\validate\type, gordian\reefknot\input\validate\prop; new Autoload (); $password = new validate\Field (new type\IsString ()); $pwConf = new validate\Field (new type\IsString ()); $password -&gt; addProp (new prop\Required ()) -&gt; addProp (new prop\Min (array ('limit' =&gt; 5))) -&gt; addProp (new prop\Max (array ('limit' =&gt; 15))) -&gt; addProp (new prop\RegexMatch (array ('needle' =&gt; '/[a-zA-Z0-9_]{5,15}/'))); $pwConf -&gt; addProp (new prop\Required ()) -&gt; addProp (new prop\Equals (array ('value' =&gt; $password))); $pwForm = new validate\DataSet (new type\IsArray ()); $pwForm -&gt; addProp (new prop\Required ()) -&gt; addProp (new prop\Min (array ('limit' =&gt; 2))) -&gt; addProp (new prop\Max (array ('limit' =&gt; 2))) -&gt; addField ('password', $password) -&gt; addField ('pwConf', $pwConf); </code></pre> <p>After reading up on DI frameworks, especially the slides <a href="http://www.slideshare.net/fabpot/dependency-injection-with-php-53" rel="nofollow">here</a>, I came up with the following DI Container implementation:</p> <pre><code>namespace gordian\reefknot\di; class Container implements iface\Container { protected $store = array (); /** * Add a new parameter to the container * * @param string $key * @param mixed $value * @return Container */ public function __set ($key, $value) { $this -&gt; store [$key] = $value; } /** * Retrieve an item from the container * * @param string $key * @return mixed * @throws \InvalidArgumentException if you attempt to access a non-existant key */ public function __get ($key) { $param = NULL; if (isset ($this -&gt; store [$key])) { $param = is_callable ($this -&gt; store [$key])? $this -&gt; store [$key] ($this): $this -&gt; store [$key]; } else { throw new \InvalidArgumentException ('Parameter ' . $key . 'not defined'); } return ($param); } /** * Retrieve the same instance of an object from the container. * * @param \Closure $callable * @return Object */ public function single (\Closure $callable) { return (function ($c) use ($callable) { static $object = NULL; if (is_null ($object)) { $object = $callable ($c); } return ($object); }); } } </code></pre> <p>Unfortunately, this was the point at which stuff started going wrong, when I tried to use the container to construct the same form validation class assembly from above. I did get an assembly that worked in the end, but it takes up far more code than the original version did!</p> <pre><code>use gordian\reefknot\autoload\Autoload, gordian\reefknot\di\Container, gordian\reefknot\input\validate, gordian\reefknot\input\validate\type, gordian\reefknot\input\validate\prop; new Autoload (); $container = new Container (); // Configure params $container -&gt; formSize = 2; $container -&gt; pwMinLen = 5; $container -&gt; pwMaxLen = 15; $container -&gt; pwPattern = '/[a-zA-Z0-9_]{5,15}/'; // Configure types and props $container -&gt; IsString = function () { return (new type\IsString ()); }; $container -&gt; IsArray = function () { return (new type\IsArray ()); }; $container -&gt; Required = function () { return new prop\Required (); }; $container -&gt; Min = function (Container $c) { return new prop\Min (array ('limit' =&gt; $c -&gt; pwMinLen)); }; $container -&gt; Max = function (Container $c) { return new prop\Max (array ('limit' =&gt; $c -&gt; pwMaxLen)); }; $container -&gt; Match = function (Container $c) { return new prop\RegexMatch (array ('needle' =&gt; $c -&gt; pwPattern)); }; $container -&gt; Equals = function (Container $c) { return new prop\Equals (array ('value' =&gt; $c -&gt; password)); }; $container -&gt; FormMin = function (Container $c) { return new prop\Min (array ('limit' =&gt; $c -&gt; formSize)); }; $container -&gt; FormMax = function (Container $c) { return new prop\Max (array ('limit' =&gt; $c -&gt; formSize)); }; // Configure fields $container -&gt; password = $container -&gt; single (function (Container $c) { $field = new validate\Field ($c -&gt; IsString); $field -&gt; addProp ($c -&gt; Required) -&gt; addProp ($c -&gt; Min) -&gt; addProp ($c -&gt; Max) -&gt; addProp ($c -&gt; Match); return ($field); }); $container -&gt; pwConf = $container -&gt; single (function (Container $c) { $field = new validate\Field ($c -&gt; IsString); $field -&gt; addProp ($c -&gt; Required) -&gt; addProp ($c -&gt; Equals); return ($field); }); $container -&gt; form = $container -&gt; single (function (Container $c) { $form = new validate\DataSet ($c -&gt; IsString); $form -&gt; addProp ($c -&gt; Required) -&gt; addProp ($c -&gt; FormMin) -&gt; addProp ($c -&gt; FormMax) -&gt; addField ('password', $c -&gt; password) -&gt; addField ('pwConf', $c -&gt; pwConf); return ($form); }); $pwForm = $container -&gt; form; </code></pre> <p>This seems like something of a backward step to me. As you can see, the version that uses the container takes up far more code than the version that just does raw DI for setup.</p> <p>I'm sure that a DI framework can offer me a shortcut to building up dependency trees/graphs such as the one in my above example. However, this simple DI container doesn't look like it's the way to go about it.</p> <p>Have I missed something in my use of the container that I need to address? Can a container like the one I implemented produce real benefits over raw DI?</p>
[ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-03-06T22:42:44.487", "Id": "15473", "Score": "0", "body": "Will look through this later, but I sent this to the guy who made the Zend DI Container :) He says https://github.com/ralphschindler/Zend_DI-Examples" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-03-12T20:00:21.667", "Id": "15818", "Score": "0", "body": "I think you are confusing \"Dependency Injection\" with \"dependency Injection Container\"" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-03-12T20:23:10.593", "Id": "15819", "Score": "0", "body": "@teresko: The first example is pure DI (for want of a better term) and works OK but is a bit verbose. I was hoping to implement a DI container (second code block) to make life easier. But it actually ended up in a lot more code to achieve the same goal (third code block)." } ]
[ { "body": "<p>I think the real problem here is your over-zealousness of using classes.</p>\n\n<p>Consider this snippet of your code:</p>\n\n<pre><code>$password -&gt; addProp (new prop\\Required ())\n -&gt; addProp (new prop\\Min (array ('limit' =&gt; 5)))\n -&gt; addProp (new prop\\Max (array ('limit' =&gt; 15)))\n -&gt; addProp (new prop\\RegexMatch (array ('needle' =&gt; '/[a-zA-Z0-9_]{5,15}/')));\n</code></pre>\n\n<p>Why can't it be:</p>\n\n<pre><code>$password -&gt; addProperties ([\n 'required' =&gt; true,\n 'min' =&gt; 5,\n 'max' =&gt; 15,\n 'rule' =&gt; '/[a-zA-Z0-9_]{5,15}/'\n ]);\n</code></pre>\n\n<p>One of the main goals of any framework should be to make your life easier. You are adding complication for hardly anything gained, and at the expense of more keystrokes. </p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-03-12T20:25:55.023", "Id": "15820", "Score": "0", "body": "That's more or less exactly what similar code in Zend Framework would look, and whilst it's okay for simpler cases I've found ZF's frustration level to rise exponentially with the complexity of what you're trying to achieve with it, especially when Decorators are thrown into the mix... (shudder). This is mostly an exercise in exploring alternative approaches." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-03-12T20:28:02.867", "Id": "15821", "Score": "0", "body": "I fail to see how `$password->addDecorator($decorator)` wouldn't work . . ." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-03-12T20:53:28.413", "Id": "15825", "Score": "0", "body": "I was just using decorators as an example of where Zend gets to be painful. :) I'm keen to avoid code like your example because it would mean that somewhere inside the Field class there would have to be code to instantiate classes of whichever type is specified in the array. That would complicate unit testing. In this particular case though, I expect just doing it that way would be easier. The whole thing is after all meant to be a learning exercise and learning when not to use pattern X is certainly part of that. :)" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-03-12T20:54:58.193", "Id": "15826", "Score": "0", "body": "I was really just hoping for an answer along the lines of either \"DI container XYZ could assemble your classes in a cleaner way, you might want to look at how that works\", or \"Your DI container works pretty much how the others do, but if you use it in XYZ way you'll find it more useful\", or even \"No DI container is going to help make your code less verbose, just give it up\" :)" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-03-13T08:01:01.067", "Id": "15846", "Score": "0", "body": "After giving it a lot of thought I'm thinking that a Builder class of some sort would be a good compromise here, you'd pass it in an array structure like the one in your example and it would do all the instantiation and wiring up of the relevant classes. That should hopefully cut down on keystrokes whilst still allowing each class to be easily unit tested in isolation/reused/etc. So as you gave me the idea and as it's unlikely that anyone else is going to answer before the bounty expires you get the bounty." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-11-20T15:33:14.540", "Id": "58138", "Score": "0", "body": "In retrospect I want to clarify that my recommendation was given because you seemed to want simple code; it's not necessarily as flexible but it is simple. The Builder class you came up with is probably a good solution." } ], "meta_data": { "CommentCount": "6", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-03-12T19:45:16.070", "Id": "9939", "ParentId": "9696", "Score": "1" } }, { "body": "<p>I think the reason you are not getting the efficiencies you are hoping for are the intentions behind most DI frameworks and containers. </p>\n\n<p>For the example of the input validation you are not doing DI. You are implementing the <a href=\"http://en.wikipedia.org/wiki/Strategy_pattern\" rel=\"nofollow\">strategy pattern</a>. That is you have moved the logic for specific types of validation out of your validation manager object. This is a great idea and gives you massive amounts of flexibility and functionality without one class getting too bloated.</p>\n\n<p>The strategy pattern is one way to achieve inversion of control (IoC). Let's not forget that DI is also a form of IoC. So while what you are doing is IoC it is not DI.</p>\n\n<p>To get the connivance you are looking for creating a builder that maybe took arrays of params or had specialized methods for common cases would be a good approach. </p>\n\n<p>IoC is a very good way to write code and I think you are going down the correct path. I think you have just gotten side tracked by solutions for other problems.</p>\n\n<p>Hope this helps.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-03-23T16:21:40.387", "Id": "10288", "ParentId": "9696", "Score": "1" } } ]
{ "AcceptedAnswerId": "9939", "CommentCount": "3", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-03-04T17:57:31.927", "Id": "9696", "Score": "5", "Tags": [ "php", "design-patterns", "dependency-injection" ], "Title": "DI container for data validation" }
9696
<p>This code is a mess due the complex nature of the job, so I'd like to know your opinions. The concept is very simple if you know what this is about, but there are some things I'm not being able to refactor.. </p> <p>Examples of what I want as an answer: Macroing of repetitive tasks? Declaring pointers in stack? But I also want to keep it as clear as possible, and I don't think want to declare a macro or a pointer just for using it only 2 times. </p> <p>The major problem I found for refactoring (as muchs as I'd like to) is that even being so similiar the code for each tile orientation, they are a still different. </p> <pre><code>int32_t ropp::BuildTerrainGeometryFromGND( const GND_TILE_DATA* lstTileData, uint32_t nTileCount, const GND_ATTRIBUTE_DATA* pAttributeData, int32_t nGNDAttributeCount, uint32_t nTextureCount, float fHeightScale, uint32_t nColumnSubgrids, uint32_t nRowSubgrids, uint32_t nSubgridColumnTiles, uint32_t nSubgridRowTiles, Vector3* out_pVertices, uint32_t* out_nVertexCount, void* out_pIndices, bool* b32Bit, uint32_t* out_nIndexCount, Vector2* out_pTexCoord, Vector3* out_pNormals, uint32_t* out_pAttributes, uint32_t* out_nMeshAttributeCount, MESH_ATTRIBUTE_DATA* out_pAttributeData, GND_TILE_INDICES* out_lstTileIndices, MESH_NODE_DATA* out_pNodeData, uint32_t* nTopTileCount, uint32_t* nFrontTileCount, uint32_t* nRightTileCount )// node count is nRowSubgrids*nColumnSubgrids { const GND_TILE_DATA * pTile = 0, * pTileF = 0, * pTileR = 0; const GND_ATTRIBUTE_DATA* pAttr=0; GND_TILE_INDICES* pTileIndices=0; if( 0 != out_pNormals ) { if( 0 != out_lstTileIndices ) pTileIndices = out_lstTileIndices; else pTileIndices = (GND_TILE_INDICES*)malloc( sizeof( GND_TILE_INDICES )*nTileCount ); if( pTileIndices ) memset( pTileIndices, 0, sizeof(GND_TILE_INDICES)*nTileCount ); } uint32_t nTotalWidth = nColumnSubgrids*nSubgridColumnTiles; uint32_t nTotalDepth = nRowSubgrids*nSubgridRowTiles; bool bCountOnly = false; if( 0 == out_pVertices ) bCountOnly = true; if( false == bCountOnly ) { if( 0 == out_pIndices ) return -1; } if( 0 == nRowSubgrids || 0 == nColumnSubgrids || 0 == nSubgridColumnTiles || 0 == nSubgridRowTiles ) return -1; if( 0 == nTextureCount || 0 == pAttributeData || 0 == lstTileData || 0 == nTileCount ) return -1; uint32_t nTileOffsetX, nTileOffsetZ; // i: local row, j: local column, k: TextureIndex, rs: row subgrid, cs: column subgrid uint32_t i=0, j=0, k=0, cs=0, rs=0, nGlobalTileIndex=0; uint32_t nVertexCount=0, nIndexCount=0, nTriangleCount=0, nAttributeCount=0; uint32_t nAttrID, nVertexStart, nAttrVertexCount, nFaceStart, nFaceCount; if( out_pNormals ) memset( out_pNormals, 0, sizeof( Vector3 )*(*out_nVertexCount) ); uint32_t nGlobalTileX, nGlobalTileZ; Vector3 vFinalOffset = Vector3( nTotalWidth*fHeightScale*-.5f, 0.0f, nTotalDepth*fHeightScale*-.5f ); uint32_t nSubgridIndex = 0; Vector3 * out_Vert0, * out_Vert1, * out_Vert2, * out_Vert3; Vector3 * pvMax, * pvMin; for( rs=0; rs&lt;nRowSubgrids; rs++ ) { for( cs=0; cs&lt;nColumnSubgrids; cs++ ) { nSubgridIndex = (rs*nColumnSubgrids)+cs; nTileOffsetX = (nSubgridColumnTiles)*cs; nTileOffsetZ = (nSubgridRowTiles)*rs; if( out_pNodeData ) { pvMax = &amp;out_pNodeData[nSubgridIndex].BoundingVolume.vMax; pvMin = &amp;out_pNodeData[nSubgridIndex].BoundingVolume.vMin; pvMin-&gt;x = (nTileOffsetX)*fHeightScale; pvMin-&gt;z = (nTileOffsetZ)*fHeightScale; pvMax-&gt;x = (nTileOffsetX+nSubgridColumnTiles)*fHeightScale; pvMax-&gt;z = (nTileOffsetZ+nSubgridRowTiles)*fHeightScale; } for( k=0; k&lt;nTextureCount; k++ ) { if( out_pAttributeData ) { if( nAttributeCount &lt; *out_nMeshAttributeCount ) { out_pAttributeData[nAttributeCount].nAttributeID = nAttributeCount; out_pAttributeData[nAttributeCount].nTextureIndex = k; out_pAttributeData[nAttributeCount].nVertexStart = nVertexCount; out_pAttributeData[nAttributeCount].nTriangleStart = nTriangleCount; } } else { nAttrID = nAttributeCount; nFaceStart = nTriangleCount; nVertexStart = nVertexCount; } for( i=0; i&lt;nSubgridRowTiles; i++ ) { for( j=0; j&lt;nSubgridColumnTiles; j++ ) { nGlobalTileIndex = (nTileOffsetZ+i)*nTotalWidth+j+nTileOffsetX;; nGlobalTileX = (j + nTileOffsetX); nGlobalTileZ = (i + nTileOffsetZ); //nGlobalTileX = nGlobalTileIndex % nTotalWidth; //nGlobalTileZ = nGlobalTileIndex / nTotalWidth; pTile = &amp;lstTileData[nGlobalTileIndex]; pTileF = GetFrontTile( lstTileData, nGlobalTileIndex, nTotalWidth, nTotalDepth ); pTileR = GetRightTile( lstTileData, nGlobalTileIndex, nTotalWidth, nTotalDepth ); if( ( pTile-&gt;TopAttributeIndex &gt;= 0 ) &amp;&amp; ( pTile-&gt;TopAttributeIndex &lt; nGNDAttributeCount ) &amp;&amp; k == pAttributeData[pTile-&gt;TopAttributeIndex].nTextureIndex ) { if( false == bCountOnly ) { pAttr = &amp;pAttributeData[pTile-&gt;TopAttributeIndex]; out_Vert0 = &amp;out_pVertices[nVertexCount+0]; out_Vert1 = &amp;out_pVertices[nVertexCount+1]; out_Vert2 = &amp;out_pVertices[nVertexCount+2]; out_Vert3 = &amp;out_pVertices[nVertexCount+3]; (*out_Vert0) = Vector3( (nGlobalTileX)*fHeightScale, -pTile-&gt;fHeight[0], (nGlobalTileZ)*fHeightScale ); (*out_Vert1) = Vector3( (nGlobalTileX+1)*fHeightScale, -pTile-&gt;fHeight[1], (nGlobalTileZ)*fHeightScale ); (*out_Vert2) = Vector3( (nGlobalTileX)*fHeightScale, -pTile-&gt;fHeight[2], (nGlobalTileZ+1)*fHeightScale ); (*out_Vert3) = Vector3( (nGlobalTileX+1)*fHeightScale, -pTile-&gt;fHeight[3], (nGlobalTileZ+1)*fHeightScale ); (*out_Vert0) += vFinalOffset; (*out_Vert1) += vFinalOffset; (*out_Vert2) += vFinalOffset; (*out_Vert3) += vFinalOffset; if( out_pNodeData ) { pvMax-&gt;y = max( pvMax-&gt;y, out_Vert0-&gt;y ); pvMin-&gt;y = min( pvMin-&gt;y, out_Vert0-&gt;y ); pvMax-&gt;y = max( pvMax-&gt;y, out_Vert1-&gt;y ); pvMin-&gt;y = min( pvMin-&gt;y, out_Vert1-&gt;y ); pvMax-&gt;y = max( pvMax-&gt;y, out_Vert2-&gt;y ); pvMin-&gt;y = min( pvMin-&gt;y, out_Vert2-&gt;y ); pvMax-&gt;y = max( pvMax-&gt;y, out_Vert3-&gt;y ); pvMin-&gt;y = min( pvMin-&gt;y, out_Vert3-&gt;y ); } AssignIndices( nIndexCount, nVertexCount, out_pIndices, *b32Bit ); AssignTexCoord( nVertexCount, pAttr, out_pTexCoord ); if( out_pNormals ) { out_pNormals[nVertexCount+0] = out_pNormals[nVertexCount+1] = out_pNormals[nVertexCount+2] = out_pNormals[nVertexCount+3] = Vector3( 0.0f, 1.0f, 0.0f ); } if( out_pNormals || out_lstTileIndices ) { pTileIndices[nGlobalTileIndex].VerticesTop[0] = nVertexCount+0; pTileIndices[nGlobalTileIndex].VerticesTop[1] = nVertexCount+1; pTileIndices[nGlobalTileIndex].VerticesTop[2] = nVertexCount+2; pTileIndices[nGlobalTileIndex].VerticesTop[3] = nVertexCount+3; } // set attribute if( out_pAttributes ) { out_pAttributes[nTriangleCount] = nAttributeCount; out_pAttributes[nTriangleCount+1] = nAttributeCount; } } nVertexCount += 4; nIndexCount += 6; nTriangleCount += 2; if( 0 != nTopTileCount ) (*nTopTileCount)++; } else if( -1 == pTile-&gt;TopAttributeIndex &amp;&amp; ( out_pNormals || out_lstTileIndices ) ) { pTileIndices[nGlobalTileIndex].VerticesTop[0] = pTileIndices[nGlobalTileIndex].VerticesTop[1] = pTileIndices[nGlobalTileIndex].VerticesTop[2] = pTileIndices[nGlobalTileIndex].VerticesTop[3] = -1; } if( ( pTile-&gt;FrontAttributeIndex &gt;= 0 ) &amp;&amp; ( pTile-&gt;FrontAttributeIndex &lt; nGNDAttributeCount ) &amp;&amp; k == pAttributeData[pTile-&gt;FrontAttributeIndex].nTextureIndex ) { if( false == bCountOnly ) { pAttr = &amp;pAttributeData[pTile-&gt;FrontAttributeIndex]; out_Vert0 = &amp;out_pVertices[nVertexCount+0]; out_Vert1 = &amp;out_pVertices[nVertexCount+1]; out_Vert2 = &amp;out_pVertices[nVertexCount+2]; out_Vert3 = &amp;out_pVertices[nVertexCount+3]; (*out_Vert0) = Vector3( (nGlobalTileX+1)*fHeightScale, -pTile-&gt;fHeight[3], (nGlobalTileZ+1)*fHeightScale ); (*out_Vert1) = Vector3( (nGlobalTileX+1)*fHeightScale, -pTile-&gt;fHeight[1], (nGlobalTileZ)*fHeightScale ); if( pTileF ) { (*out_Vert2) = Vector3( (nGlobalTileX+1)*fHeightScale, -pTileF-&gt;fHeight[2], (nGlobalTileZ+1)*fHeightScale ); (*out_Vert3) = Vector3( (nGlobalTileX+1)*fHeightScale, -pTileF-&gt;fHeight[0], (nGlobalTileZ)*fHeightScale ); } else { (*out_Vert2) = Vector3( (nGlobalTileX+1)*fHeightScale, -0, (nGlobalTileZ+1)*fHeightScale ); (*out_Vert3) = Vector3( (nGlobalTileX+1)*fHeightScale, -0, (nGlobalTileZ)*fHeightScale ); } (*out_Vert0) += vFinalOffset; (*out_Vert1) += vFinalOffset; (*out_Vert2) += vFinalOffset; (*out_Vert3) += vFinalOffset; AssignIndices( nIndexCount, nVertexCount, out_pIndices, *b32Bit ); AssignTexCoord( nVertexCount, pAttr, out_pTexCoord ); if( out_pNormals ) { if( (pTile-&gt;fHeight[1]*fHeightScale) &gt; ( (0 != pTileF) ? (pTileF-&gt;fHeight[0]*fHeightScale) : 0 ) ) { out_pNormals[nVertexCount+0] = out_pNormals[nVertexCount+1] = out_pNormals[nVertexCount+2] = out_pNormals[nVertexCount+3] = Vector3( -1.0f, 0.0f, 0.0f ); } else { out_pNormals[nVertexCount+0] = out_pNormals[nVertexCount+1] = out_pNormals[nVertexCount+2] = out_pNormals[nVertexCount+3] = Vector3( 1.0f, 0.0f, 0.0f ); } } if( out_lstTileIndices ) { pTileIndices[nGlobalTileIndex].VerticesFront[0] = nVertexCount+0; pTileIndices[nGlobalTileIndex].VerticesFront[1] = nVertexCount+1; pTileIndices[nGlobalTileIndex].VerticesFront[2] = nVertexCount+2; pTileIndices[nGlobalTileIndex].VerticesFront[3] = nVertexCount+3; } // set attribute if( out_pAttributes ) { out_pAttributes[nTriangleCount] = nAttributeCount; out_pAttributes[nTriangleCount+1] = nAttributeCount; } } nVertexCount += 4; nIndexCount += 6; nTriangleCount += 2; if( 0 != nFrontTileCount ) (*nFrontTileCount)++; } else if( -1 == pTile-&gt;FrontAttributeIndex ) { if( out_lstTileIndices ) { pTileIndices[nGlobalTileIndex].VerticesFront[0] = pTileIndices[nGlobalTileIndex].VerticesFront[1] = pTileIndices[nGlobalTileIndex].VerticesFront[2] = pTileIndices[nGlobalTileIndex].VerticesFront[3] = -1; } } if( ( pTile-&gt;RightAttributeIndex &gt;= 0 ) &amp;&amp; ( pTile-&gt;RightAttributeIndex &lt; nGNDAttributeCount ) &amp;&amp; k == pAttributeData[pTile-&gt;RightAttributeIndex].nTextureIndex ) { if( false == bCountOnly ) { pAttr = &amp;pAttributeData[pTile-&gt;RightAttributeIndex]; out_Vert0 = &amp;out_pVertices[nVertexCount+0]; out_Vert1 = &amp;out_pVertices[nVertexCount+1]; out_Vert2 = &amp;out_pVertices[nVertexCount+2]; out_Vert3 = &amp;out_pVertices[nVertexCount+3]; (*out_Vert0) = Vector3( (nGlobalTileX)*fHeightScale, -pTile-&gt;fHeight[2], (nGlobalTileZ+1)*fHeightScale ); (*out_Vert1) = Vector3( (nGlobalTileX+1)*fHeightScale,-pTile-&gt;fHeight[3], (nGlobalTileZ+1)*fHeightScale ); if( pTileR ) { (*out_Vert2) = Vector3( (nGlobalTileX)*fHeightScale, -pTileR-&gt;fHeight[0], (nGlobalTileZ+1)*fHeightScale ); (*out_Vert3) = Vector3( (nGlobalTileX+1)*fHeightScale,-pTileR-&gt;fHeight[1], (nGlobalTileZ+1)*fHeightScale ); } else { (*out_Vert2) = Vector3( (nGlobalTileX)*fHeightScale, -0, (nGlobalTileZ+1)*fHeightScale ); (*out_Vert3) = Vector3( (nGlobalTileX+1)*fHeightScale, -0, (nGlobalTileZ+1)*fHeightScale ); } (*out_Vert0) += vFinalOffset; (*out_Vert1) += vFinalOffset; (*out_Vert2) += vFinalOffset; (*out_Vert3) += vFinalOffset; AssignIndices( nIndexCount, nVertexCount, out_pIndices, *b32Bit ); AssignTexCoord( nVertexCount, pAttr, out_pTexCoord ); if( out_pNormals ) { if( (pTile-&gt;fHeight[2]) &gt; ( (0 != pTileR) ? (pTileR-&gt;fHeight[0]) : 0) ) { out_pNormals[nVertexCount+0] = out_pNormals[nVertexCount+1] = out_pNormals[nVertexCount+2] = out_pNormals[nVertexCount+3] = Vector3( 0.0f, 0.0f, -1.0f ); } else { out_pNormals[nVertexCount+0] = out_pNormals[nVertexCount+1] = out_pNormals[nVertexCount+2] = out_pNormals[nVertexCount+3] = Vector3( 0.0f, 0.0f, 1.0f ); } } if( out_lstTileIndices ) { pTileIndices[nGlobalTileIndex].VerticesRight[0] = nVertexCount+0; pTileIndices[nGlobalTileIndex].VerticesRight[1] = nVertexCount+1; pTileIndices[nGlobalTileIndex].VerticesRight[2] = nVertexCount+2; pTileIndices[nGlobalTileIndex].VerticesRight[3] = nVertexCount+3; } // set attribute if( out_pAttributes ) { out_pAttributes[nTriangleCount] = nAttributeCount; out_pAttributes[nTriangleCount+1] = nAttributeCount; } } nVertexCount += 4; nIndexCount += 6; nTriangleCount += 2; if( 0 != nRightTileCount ) (*nRightTileCount)++; } // else if( -1 == pTile-&gt;RightAttributeIndex ) { if( out_lstTileIndices ) { pTileIndices[nGlobalTileIndex].VerticesRight[0] = pTileIndices[nGlobalTileIndex].VerticesRight[1] = pTileIndices[nGlobalTileIndex].VerticesRight[2] = pTileIndices[nGlobalTileIndex].VerticesRight[3] = -1; } } } // j=0; } // i=0; if( out_pAttributeData ) { if( nAttributeCount &lt; *out_nMeshAttributeCount ) { out_pAttributeData[nAttributeCount].nVertexCount = nVertexCount - out_pAttributeData[nAttributeCount].nVertexStart; out_pAttributeData[nAttributeCount].nTriangleCount = nTriangleCount - out_pAttributeData[nAttributeCount].nTriangleStart; if( out_pAttributeData[nAttributeCount].nVertexCount &gt; 0 ) { if( out_pNodeData ) { out_pNodeData[nSubgridIndex].lstAttributeIndices [out_pNodeData[nSubgridIndex].nAttributeCount] = nAttributeCount; out_pNodeData[nSubgridIndex].nAttributeCount++; if( out_pNodeData[nSubgridIndex].nAttributeCount == 64 ) throw( "" ); } nAttributeCount++; } // we skip empty attributes } } else { nFaceCount = nTriangleCount - nFaceStart; nAttrVertexCount = nVertexCount - nVertexStart; if( nAttrVertexCount &gt; 0 ) nAttributeCount++; } } // k=0 if( false == bCountOnly &amp;&amp; out_pNodeData ) { out_pNodeData[nSubgridIndex].BoundingVolume.vCenter = (*pvMin)+( ((*pvMax)-(*pvMin))*.5f ); } } // cs=0; }// rs=0; if( nVertexCount &gt; 0xFFFF ) *b32Bit = true; else *b32Bit = false; if( (false == bCountOnly) &amp;&amp; out_pNormals ) CalcNormals( out_pVertices, pTileIndices, lstTileData, nTotalWidth, nTotalDepth, fHeightScale, out_pNormals ); *out_nVertexCount = nVertexCount; *out_nIndexCount = nIndexCount; if( out_nMeshAttributeCount ) *out_nMeshAttributeCount = nAttributeCount; if( 0 != out_pNormals &amp;&amp; 0 == out_lstTileIndices ) free( pTileIndices ); return 0; }; </code></pre>
[ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-03-04T21:26:07.377", "Id": "15356", "Score": "0", "body": "So what is the question? \"The concept is very simple if you know what it is about.\"..so, what is it about?" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-03-04T21:28:23.787", "Id": "15357", "Score": "0", "body": "Building 3d geometry from tile description, creating VBOs on-the-fly" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-03-04T21:28:43.833", "Id": "15358", "Score": "0", "body": "If you look at the code you will understand, a single function is around 40k lines" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-03-04T21:54:29.790", "Id": "15363", "Score": "0", "body": "I mean 40k characters (it won't let me edit)" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-03-04T22:46:33.823", "Id": "15375", "Score": "1", "body": "What is a 'tile description'? Perhaps you could post an image of what the end result is so people can draw on their experiences with similar problems." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-03-05T22:32:22.830", "Id": "15415", "Score": "0", "body": "You question doesn't obey the rules of this site. You need to include the code you want reviewed in the actual question, not as a link. If you include the actual code there is a good chance somebody will be able to provide some assistance on the areas you are most interested in. If you don't add the code, I'll be forced to close this question." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-03-05T23:03:33.993", "Id": "15416", "Score": "0", "body": "@WinstonEwert Yes, that's in what I need help. I managed to get rid of half the characters but then the code is unreadable and I expect no help if I do that. I don't know how much experience do you have on these kind of algorithms, but I'm gonna cite someone else: \"Is hard to review, since one would need to exactly understand the underlying mathematics, then understand your code, then propose meaningful abstractions. I also believe that for complicated code like that, it's OK to repeat yourself, since it's often hard to encapsulate and to modify without having to understand the whole thing.\"" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-03-05T23:04:26.677", "Id": "15417", "Score": "0", "body": "So either you close it, move to GameDev.SE, or show me how to make the code fit." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-03-05T23:46:06.320", "Id": "15422", "Score": "1", "body": "@PabloAriel, if your concern is that the code is too long to post (fair enough), then let's narrow it down. Pick a specific part of the code you want a review on. Is the particular part of the code that you really want review on? For example, you could get a review just on the CalcNormals function. If there is another part you are more interested in, then go with that." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-03-05T23:51:40.103", "Id": "15423", "Score": "0", "body": "As for the underlying math, I do have some familiarity with it. If we bring your post into lines with the rules, I can probably suggest some specific improvements." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-03-06T00:24:58.610", "Id": "15428", "Score": "0", "body": "Ok I will try to remove characters enough to make it fit. The particular function I need is BuildTerrainGeometryFromGND, which is still huge, even when I removed many lines already. I do want and appreciate your help, and I will try to improve the question asap (just give me some time). I also would like your help in my other question, which is exactly about the CalcNormals function, given you're familiar with the underlying math." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-03-06T02:07:23.337", "Id": "15432", "Score": "2", "body": "I'm taking a look at your code. It appears to be in C++ but mostly using C idioms. Is this a deliberate choice?, if so: why? Your code can be much simplified by using some C++ idioms and the standard template library, but I need to know if you've got some good reason to avoid them." } ]
[ { "body": "<h3>Turn on your compiler warnings: (Fix this first)</h3>\n<p>Even at the most basic warning level I get a whole bunch of warnings. Personally I compile at a much higher warning level then basic and then I get two pages of warning messages.</p>\n<p>They may be called warnings but really they are <strong>logical</strong> errors in your code. You really should <strong>fix them all</strong> (or at least address them to make sure the code works correctly). Personally I always tell the compiler to treat warnings as errors thus it will fail to compile unless I fix them.</p>\n<h3>Major Comments on code: (Fix this second)</h3>\n<p>Refactor the code so you do not have functions that are 500 lines long.<br />\nIdeally (not always achievable) one screen is a good rule of thumb. Then you should be able to see the whole function in a glance.</p>\n<h3>Second Major comment: (Fix this third)</h3>\n<p>You tagged your question as C but your file is *.cpp (which implies C++) and you are using namespace.</p>\n<pre><code>using namespace ropp;\n</code></pre>\n<p>So please pick a language and stick to it. Intermixing the two is really bad idea. Looking at your code you are definitely still writing C you just happen to be using some C++ features which makes it impossible to compile with a C compiler and completely horrible C++. This is commonly refereed to as <code>C with Classes</code> (a zone of badly written C++).</p>\n<ol>\n<li>Learn to write only C</li>\n<li>Or. Learn how to use C++ which probably means learning OO and the idioms associated with it.</li>\n</ol>\n<h3>Normal Comments: (Now start looking at these).</h3>\n<p>This is a bad idea.</p>\n<pre><code>using namespace ropp;\n</code></pre>\n<p>You are polluting the global namespace. It is best to prefix types and object with their appropriate namespace or selectively bring into the current scope just the bits you need.</p>\n<p>Code that look like this:</p>\n<pre><code> if( &lt;TEST&gt; )\n return &lt;VALUE-1&gt;;\n return &lt;Value-2&gt;;\n</code></pre>\n<p>In my opinion is easier to read and write as:</p>\n<pre><code> return &lt;TEST&gt; ? &lt;Value-1&gt; : &lt;Value-2&gt;;\n</code></pre>\n<p>I could go on. But I think your first task to better organize your code so that it is readable. After that we can go into how it to make it better but you are a long long way from being able to do anything useful.</p>\n<p>Yoda conditionals:</p>\n<pre><code>if( false == bCountOnly )\n</code></pre>\n<p>These were in style about 10 years ago. They are no longer in style (thank god) and some (like me (though not everybody)) consider them bad practice. I think it makes the code harder to read. They may have given you a slight protection against accidental assignment but the compiler already does that. Just make sure your code compiler with no warnings and you will have better code anyway.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-03-04T21:44:12.533", "Id": "15361", "Score": "0", "body": "Yea I could easily do that with python/java then my realtime app will easily take an hour to load a map chunk which my implementation does instantly. I could easily rename the variables so people who read the code don't understand which index references which vector. I managed to cut in half the character count that way, but it became unreadable. Your answer is so useless that I can't believe how you got that rep. I've been refactoring for long, that's why I'm here, and I'm downvoting you ASAP." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-03-04T21:55:16.637", "Id": "15364", "Score": "0", "body": "@PabloAriel: I think I will survive you down vote. But I stand by answer. The best thing you can do for your code is refactor to make it readable (in my opinion its practically unmaintainable). You asked for a review of you code; that's what I gave you, do not shoot the messenger because you don't like the advice. PS. I am not sure how the first 3/4 of your comment is relevant or even meaningful (seems like meaningless trolling)." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-03-04T21:56:32.910", "Id": "15366", "Score": "0", "body": "I don't think you're understanding, again, I'm asking how to refactor this more than I already did." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-03-04T21:57:29.210", "Id": "15367", "Score": "0", "body": "Without losing performance! If you don't understand the meaning then you don't have a clue about performance coding I suppose." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-03-04T22:00:14.730", "Id": "15368", "Score": "2", "body": "You might want to try being less abrasive." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-03-04T22:02:10.623", "Id": "15369", "Score": "0", "body": "@Bart Well, that's actually an useful comment." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-03-04T22:04:46.690", "Id": "15370", "Score": "0", "body": "Ok now at least I got a real answer. Thanks, I'll take a look." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-03-04T22:09:07.463", "Id": "15371", "Score": "0", "body": "I could easily remove the cpp features by adding #ifdef __cplusplus or something like that, that's not what I need to know and I want a C api that can be used in C++ code without name clashing. I could easily make this both OO and structured style, I'm asking about the BuildTerrainGeometry function, I think I clarified that too in my post." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-03-04T22:14:32.107", "Id": "15372", "Score": "0", "body": "@PabloAriel: If you think splitting it into smaller functions will drastically affect performance I am not sure you really understand how a compiler works. The first step in writing high performance code is writing good code. No point in making bad code faster first as you will miss opportunities to spot optimizations that are hard to understand unless the code is written well. Remember the first rule \"Premature optimization is the root of all evil\"" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-03-04T22:18:37.140", "Id": "15373", "Score": "0", "body": "@PabloAriel: Using #ifdef will not work as you expect. That will make half the code think it is C++ and half think it is C. When you try and link them together it will fail. Thus you definitely do not have a C API. You need to use either C or C++ not a hybrid approach especially since you don't understand the problems." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-03-04T22:28:06.380", "Id": "15374", "Score": "0", "body": "so I'd should write many functions and objects to write into a single buffer? or maybe 2 buffers.. I know how a compiler works, and I know how a single loop is better than 40 of them, one for each kind of tile I need to write" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-03-04T23:04:44.883", "Id": "15377", "Score": "0", "body": "Ok your answer got much better now. Still, I'd like to improve the function I said (the 500-line one), and I'm not sure on how to do it. Even if your answer provides some good coding hints, they are minor changes that don't really solve this issue. There is also some doubts I have now, reading what you said about warnings, ie. that I'm not casting the int-to-float to actually get the compiler warning (yea I do it on purpose to be warned it's being casted! should I remove them?)." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-03-04T23:07:00.450", "Id": "15378", "Score": "0", "body": "`I know how a single loop is better than 40 of them`. Really. Why. Maybe the compiler is unrolling them anyway. Maye it is combining them into a single loop. Making such broad statements is silly and shows you actually don't know what the compiler is doing (or capable off). Your problem seems to stem from this as you are trying to manually do micro optimizations (like in-lining and loop unrolling) (the compiler already does this and very well; much better than a human). You need to work on writing good code so you can spot the algorithmic optimizations that the compiler can not do." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-03-04T23:22:59.233", "Id": "15379", "Score": "0", "body": "let us [continue this discussion in chat](http://chat.stackexchange.com/rooms/2694/discussion-between-pablo-ariel-and-loki-astari)" } ], "meta_data": { "CommentCount": "14", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-03-04T21:38:34.320", "Id": "9701", "ParentId": "9697", "Score": "6" } }, { "body": "<p>The first thing you need is a <code>enum</code> to specify the different direction</p>\n\n<pre><code>enum TileOrientation\n{\n TOP,\n FRONT,\n RIGHT,\n\n ORIENTATION_COUNT\n}\n</code></pre>\n\n<p>Right now you have code like:</p>\n\n<pre><code>pTile-&gt;FrontAttributeIndex\n</code></pre>\n\n<p>Change your Tile struct so that you can do</p>\n\n<pre><code>pTile-&gt;AttributeIndex[FRONT]\n</code></pre>\n\n<p>Create a function that configures that out parameters. In fact everywhere you have different variables for the different orientations, make them into an array.</p>\n\n<pre><code>void generateVertices(int nGlobalTileX, int nGlobalTileZ, float fHeightScale, GND_TILE_DATA ** pTile, Vector3 * pVertex, TileOrientation orientation)\n{\n switch(orientation)\n {\n case TOP:\n pVertex[0] = Vector3( (nGlobalTileX)*fHeightScale, -pTile[TOP]-&gt;fHeight[0], (nGlobalTileZ)*fHeightScale );\n pVertex[1] = Vector3( (nGlobalTileX+1)*fHeightScale, -pTile[TOP]-&gt;fHeight[1], (nGlobalTileZ)*fHeightScale );\n pVertex[2] = Vector3( (nGlobalTileX)*fHeightScale, -pTile[TOP]-&gt;fHeight[2], (nGlobalTileZ+1)*fHeightScale );\n pVertex[3] = Vector3( (nGlobalTileX+1)*fHeightScale, -pTile[TOP]-&gt;fHeight[3], (nGlobalTileZ+1)*fHeightScale );\n break;\n case FRONT:\n pVertex[0] = Vector3( (nGlobalTileX+1)*fHeightScale, -pTile[TOP]-&gt;fHeight[3], (nGlobalTileZ+1)*fHeightScale );\n pVertex[1] = Vector3( (nGlobalTileX+1)*fHeightScale, -pTile[TOP]-&gt;fHeight[1], (nGlobalTileZ)*fHeightScale );\n if( pTileF )\n {\n pVertex[2] = Vector3( (nGlobalTileX+1)*fHeightScale, -pTile[FRONT]-&gt;fHeight[2], (nGlobalTileZ+1)*fHeightScale );\n pVertex[3] = Vector3( (nGlobalTileX+1)*fHeightScale, -pTile[FRONT]-&gt;fHeight[0], (nGlobalTileZ)*fHeightScale );\n }\n else\n {\n pVertex[2] = Vector3( (nGlobalTileX+1)*fHeightScale, -0, (nGlobalTileZ+1)*fHeightScale );\n pVertex[3] = Vector3( (nGlobalTileX+1)*fHeightScale, -0, (nGlobalTileZ)*fHeightScale );\n }\n break;\n case RIGHT:\n // something similiar\n break;\n }\n}\n</code></pre>\n\n<p>You should be able to write a similiar function to handle the normals. Then you should be able to write a good chunk of your function as something like</p>\n\n<pre><code>for(TileOrientation orientation = 0; orientation &lt; ORIENTATION_COUNT; orientation)\n{\n if( pTile[TOP]-&gt;OrientationIndex[orientation] &gt;= 0)\n {\n generateVerticies(nGlobalTileX, nGlobalTileZ, pTile, pVertex + nVertexCount);\n generateNormals(...)\n // do other stuff\n nVertexCount += 4;\n nTriangleCount += 2;\n }\n}\n</code></pre>\n\n<p>That should deal with your biggest problem, repeating sections which are almost exactly the same. Your code could use cleanup in a variety of other ways as well, but that really needs to be fixed first.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-03-06T04:43:34.523", "Id": "15436", "Score": "0", "body": "This is exactly what I needed, thank you very much, I'll leave the question open for another day just in case someone else want to add something more, but this already helps a lot. Thanks again." } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-03-06T02:54:02.467", "Id": "9734", "ParentId": "9697", "Score": "4" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "12", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-03-04T21:19:03.377", "Id": "9697", "Score": "2", "Tags": [ "c++", "computational-geometry" ], "Title": "Building 3d geometry from tile description" }
9697
<p>It does generate pretty decent normals but I'm not sure if I could improve it even more without losing performance.</p> <p>You can find the whole code here:</p> <ul> <li><a href="http://code.google.com/p/roplusplus/source/browse/RO%2B%2B/ropp_map.h" rel="nofollow">ropp_map.h</a></li> <li><a href="http://code.google.com/p/roplusplus/source/browse/RO%2B%2B/gnd.cpp" rel="nofollow">gnd.cpp</a></li> </ul> <p>What do you think about this one? Other than declaring an Epsilon constant, of course.</p> <pre><code>void CalcNormals( const Vector3* pVertices, const GND_TILE_INDICES* pTileIndices, const GND_TILE_DATA* pTileData, uint32_t nWidth, uint32_t nDepth, float fHeightScale, Vector3 *out_pNormals ) { float fScale = -.1f; if( fHeightScale != 0.0f ) fScale = -1.0f/fHeightScale; uint32_t i,nIndexX = 0, nIndexZ = 0, nTotalTiles = nWidth*nDepth; const GND_TILE_INDICES* pIdxCurrent=0, * pIdxFront=0, * pIdxRight=0, * pIdxFrontRight=0; const GND_TILE_DATA* pTileCurrent=0, * pTileFront=0, * pTileRight=0, * pTileFrontRight=0; Vector3 BlendNormalFinal; Vector3 BlendNormal0; Vector3 BlendNormal1; Vector3 BlendNormal2; Vector3 BlendNormal3; // first pass builds triangle normals independently (no normal smoothing) for( i=0; i&lt;nTotalTiles; i++ ) { pIdxCurrent = &amp;pTileIndices[i]; pTileCurrent = &amp;pTileData[i]; if( -1 == pIdxCurrent-&gt;VerticesTop[0] ) continue; ////------------------------------- //BlendNormal0 = ( (pVertices[pIdxCurrent-&gt;VerticesTop[2]] - pVertices[pIdxCurrent-&gt;VerticesTop[0]]) ) // .Cross( (pVertices[pIdxCurrent-&gt;VerticesTop[1]] - pVertices[pIdxCurrent-&gt;VerticesTop[0]]) ); //BlendNormal1 = ( (pVertices[pIdxCurrent-&gt;VerticesTop[3]] - pVertices[pIdxCurrent-&gt;VerticesTop[1]]) ) // .Cross( -(pVertices[pIdxCurrent-&gt;VerticesTop[0]] - pVertices[pIdxCurrent-&gt;VerticesTop[1]]) ); //BlendNormal2 = ( (pVertices[pIdxCurrent-&gt;VerticesTop[3]] - pVertices[pIdxCurrent-&gt;VerticesTop[2]]) ) // .Cross( (pVertices[pIdxCurrent-&gt;VerticesTop[0]] - pVertices[pIdxCurrent-&gt;VerticesTop[2]]) ); //BlendNormal3 = ( (pVertices[pIdxCurrent-&gt;VerticesTop[2]] - pVertices[pIdxCurrent-&gt;VerticesTop[3]]) ) // .Cross( -(pVertices[pIdxCurrent-&gt;VerticesTop[1]] - pVertices[pIdxCurrent-&gt;VerticesTop[3]]) ); BlendNormal0 = ( (Vector3(0.0f, pTileCurrent-&gt;fHeight[2]*fScale, 1.0f) - Vector3(0.0f, pTileCurrent-&gt;fHeight[0]*fScale, 0.0f)) ) .Cross( (Vector3(1.0f, pTileCurrent-&gt;fHeight[1]*fScale, 0.0f) - Vector3(0.0f, pTileCurrent-&gt;fHeight[0]*fScale, 0.0f)) ); BlendNormal1 = ( (Vector3(1.0f, pTileCurrent-&gt;fHeight[3]*fScale, 1.0f) - Vector3(1.0f, pTileCurrent-&gt;fHeight[1]*fScale, 0.0f)) ) .Cross( -(Vector3(0.0f, pTileCurrent-&gt;fHeight[0]*fScale, 0.0f) - Vector3(1.0f, pTileCurrent-&gt;fHeight[1]*fScale, 0.0f)) ); BlendNormal2 = ( (Vector3(1.0f, pTileCurrent-&gt;fHeight[3]*fScale, 1.0f) - Vector3(0.0f, pTileCurrent-&gt;fHeight[2]*fScale, 1.0f)) ) .Cross( (Vector3(0.0f, pTileCurrent-&gt;fHeight[0]*fScale, 0.0f) - Vector3(0.0f, pTileCurrent-&gt;fHeight[2]*fScale, 1.0f)) ); BlendNormal3 = ( (Vector3(0.0f, pTileCurrent-&gt;fHeight[2]*fScale, 1.0f) - Vector3(1.0f, pTileCurrent-&gt;fHeight[3]*fScale, 1.0f)) ) .Cross( -(Vector3(1.0f, pTileCurrent-&gt;fHeight[1]*fScale, 0.0f) - Vector3(1.0f, pTileCurrent-&gt;fHeight[3]*fScale, 1.0f)) ); out_pNormals[pIdxCurrent-&gt;VerticesTop[0]] = //(BlendNormal0+BlendNormal1+BlendNormal2+BlendNormal3).Normalize(); out_pNormals[pIdxCurrent-&gt;VerticesTop[1]] = //(BlendNormal1+BlendNormal0+BlendNormal3+BlendNormal2).Normalize(); out_pNormals[pIdxCurrent-&gt;VerticesTop[2]] = //(BlendNormal2+BlendNormal0+BlendNormal3+BlendNormal1).Normalize(); out_pNormals[pIdxCurrent-&gt;VerticesTop[3]] = (BlendNormal3+BlendNormal1+BlendNormal2+BlendNormal0).Normalize(); } Vector3 preBlendFrontRight; // iterate again to perform the normal blending for( i=0; i&lt;nTotalTiles; i++ ) { pIdxCurrent = &amp;pTileIndices[i]; pTileCurrent = &amp;pTileData[i]; if( -1 == pIdxCurrent-&gt;VerticesTop[0] ) continue; if( i &lt; (nTotalTiles-1) ) { pIdxFront = &amp;pTileIndices[i+1]; pTileFront = &amp;pTileData[i+1]; if( -1 == pIdxFront-&gt;VerticesTop[0] ) { pTileFront = 0; pIdxFront = 0; } if( i &lt; (nTotalTiles-nWidth) ) { pIdxRight = &amp;pTileIndices[i+nWidth]; pTileRight = &amp;pTileData[i+nWidth]; if( -1 == pIdxRight-&gt;VerticesTop[0] ) { pTileRight = 0; pIdxRight = 0; } if( i &lt; (nTotalTiles-nWidth-1) ) { pIdxFrontRight = &amp;pTileIndices[i+nWidth+1]; pTileFrontRight = &amp;pTileData[i+nWidth+1]; if( -1 == pIdxFrontRight-&gt;VerticesTop[0] ) { pTileFrontRight = 0; pIdxFrontRight = 0; } } else { pIdxFrontRight = 0; pTileFrontRight = 0; } } else { pIdxRight = 0; pIdxFrontRight = 0; pTileRight = 0; pTileFrontRight = 0; }; } else { pIdxFront = 0; pIdxRight = 0; pIdxFrontRight = 0; pTileFront = 0; pTileRight = 0; pTileFrontRight = 0; }; if( -1 != pIdxCurrent-&gt;VerticesTop[0] ) { preBlendFrontRight = out_pNormals[pIdxCurrent-&gt;VerticesTop[3]]; // *.5f; preBlendFrontRight += out_pNormals[pIdxCurrent-&gt;VerticesTop[2]]; // *.5f; preBlendFrontRight += out_pNormals[pIdxCurrent-&gt;VerticesTop[1]]; // *.5f; preBlendFrontRight.Normalize(); } else preBlendFrontRight.x = preBlendFrontRight.y = preBlendFrontRight.z = 0; if( pIdxFront &amp;&amp; (fabs(pTileCurrent-&gt;fHeight[3] - pTileFront-&gt;fHeight[2]) &lt; 0.0001f) ) { preBlendFrontRight += out_pNormals[pIdxFront-&gt;VerticesTop[2]]; preBlendFrontRight += out_pNormals[pIdxFront-&gt;VerticesTop[3]]; preBlendFrontRight += out_pNormals[pIdxFront-&gt;VerticesTop[1]]; } if( pIdxRight &amp;&amp; (fabs(pTileCurrent-&gt;fHeight[3] - pTileRight-&gt;fHeight[1]) &lt; 0.0001f) ) { preBlendFrontRight += out_pNormals[pIdxRight-&gt;VerticesTop[1]]; preBlendFrontRight += out_pNormals[pIdxRight-&gt;VerticesTop[2]]; preBlendFrontRight += out_pNormals[pIdxRight-&gt;VerticesTop[3]]; } if( pIdxFrontRight &amp;&amp; (fabs(pTileCurrent-&gt;fHeight[3] - pTileFrontRight-&gt;fHeight[0]) &lt; 0.0001f) ) { preBlendFrontRight += out_pNormals[pIdxFrontRight-&gt;VerticesTop[0]]; preBlendFrontRight += out_pNormals[pIdxFrontRight-&gt;VerticesTop[1]]; preBlendFrontRight += out_pNormals[pIdxFrontRight-&gt;VerticesTop[2]]; } preBlendFrontRight.Normalize(); // --------------------------------- Front Right!! -------------------------- out_pNormals[pIdxCurrent-&gt;VerticesTop[3]] = (preBlendFrontRight); out_pNormals[pIdxCurrent-&gt;VerticesTop[3]].Normalize(); if( pIdxFront &amp;&amp; (fabs(pTileCurrent-&gt;fHeight[3] - pTileFront-&gt;fHeight[2]) &lt; 0.0001f) ) { out_pNormals[pIdxFront-&gt;VerticesTop[2]] = (preBlendFrontRight); out_pNormals[pIdxFront-&gt;VerticesTop[2]].Normalize(); } if( pIdxRight &amp;&amp; (fabs(pTileCurrent-&gt;fHeight[3] - pTileRight-&gt;fHeight[1]) &lt; 0.0001f) ) { out_pNormals[pIdxRight-&gt;VerticesTop[1]] = (preBlendFrontRight); out_pNormals[pIdxRight-&gt;VerticesTop[1]].Normalize(); } if( pIdxFrontRight &amp;&amp; (fabs(pTileCurrent-&gt;fHeight[3] - pTileFrontRight-&gt;fHeight[0]) &lt; 0.0001f) ) { out_pNormals[pIdxFrontRight-&gt;VerticesTop[0]] = (preBlendFrontRight); out_pNormals[pIdxFrontRight-&gt;VerticesTop[0]].Normalize(); } }; }; </code></pre>
[ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-03-04T21:35:04.700", "Id": "15360", "Score": "0", "body": "Examples of what I want as an answer: Macroing of repetitive tasks? Declaring pointers in stack? But I also want to keep it as clear as possible, and I don't think want to declare a macro or a pointer just for using it in only 2 different lines." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-03-05T07:29:07.650", "Id": "15387", "Score": "1", "body": "I added [tag:computational-geometry], which is more general than \"terrain\", and could be applied to more questions." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-03-06T03:39:13.980", "Id": "15434", "Score": "0", "body": "This is C++ or \"C with Classes\" code: the type `Vector3` is used like a function, so that must be a C++ constructor call." } ]
[ { "body": "<p>Your code is hard to review, since one would need to exactly understand the underlying mathematics, then understand your code, then propose meaningful abstractions. I do hope someone will do it, but I can't. I also believe that for complicated code like that, it's OK to repeat yourself, since it's often hard to encapsulate and to modify without having to understand the whole thing.</p>\n\n<p>What I can do is provide some comments on the code itself:</p>\n\n<ol>\n<li>You can do better than declaring an epsilon constant: encapsulate the equality test! It's an implementation detail and easy to get wrong.</li>\n<li><p>You should care more about spacing: at least make it consistent, eg. avoid this:</p>\n\n<pre><code> pIdxRight = 0;\n pIdxFrontRight = 0;\n</code></pre>\n\n<p>I think the way SE displays the code doesn't help.</p></li>\n<li><p>This one is borderline code obfuscation. It's better in your repository (without the comments). :) Consider using a temporary variable.</p>\n\n<pre><code>out_pNormals[pIdxCurrent-&gt;VerticesTop[0]] = //(BlendNormal0+BlendNormal1+BlendNormal2+BlendNormal3).Normalize();\nout_pNormals[pIdxCurrent-&gt;VerticesTop[1]] = //(BlendNormal1+BlendNormal0+BlendNormal3+BlendNormal2).Normalize();\nout_pNormals[pIdxCurrent-&gt;VerticesTop[2]] = //(BlendNormal2+BlendNormal0+BlendNormal3+BlendNormal1).Normalize();\nout_pNormals[pIdxCurrent-&gt;VerticesTop[3]] = (BlendNormal3+BlendNormal1+BlendNormal2+BlendNormal0).Normalize();\n</code></pre></li>\n<li>I didn't know you could end loops and functions with <code>};</code>. Deleting the <code>;</code> would prevent confusion with the syntax for classes.</li>\n</ol>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-03-05T15:04:05.957", "Id": "15399", "Score": "0", "body": "Thanks, you got it right, one of the problems I do find with these kind of programming is to encapsulate without losing track ie sometimes it's better to have the code right there inlined instead of having a separate function and have to switch to understand what's going on. Most people would give me the advice to encapsulate when I actually do inline on purpose because it's easier for me to work on it." } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-03-05T08:18:18.243", "Id": "9711", "ParentId": "9698", "Score": "2" } }, { "body": "<p>What I take to be the problematic portion of this code is the portion that assigns pIdxFront and friends. </p>\n\n<p>What you need to do is convert your related variables into arrays and then do things in a loop.</p>\n\n<pre><code>enum Directions\n{\n Front,\n Top,\n TopFront\n\n DIRECTION_COUNT\n};\n\nGND_TILE_INDICES * pIdx[DIRECTION_COUNT]; \nGND_TILE_DATA * pTile[DIRECTION_COUNT];\nfor(Direction direction = 0; direction &lt; DIRECTION_COUNT; direction++)\n{\n int index;\n switch(direction)\n { \n case Front:\n index = i + 1;\n break;\n case Top:\n index = i + mWidth;\n break;\n case FrontTop:\n index = i + mWidth + 1;\n break;\n }\n\n pIdx[direction] = pTileIndices[i + 1];\n pTile[direction] = pTileData[i + 1];\n if(-1 == pIdx[direction]-&gt;VerticesTop[0])\n {\n pIdx[direction] = 0;\n pTile[direction] = 0;\n }\n}\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-03-06T04:38:19.427", "Id": "15435", "Score": "0", "body": "Thanks! It seems so obvious now you say it, but I really lost that one." } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-03-06T03:19:22.543", "Id": "9735", "ParentId": "9698", "Score": "3" } } ]
{ "AcceptedAnswerId": "9735", "CommentCount": "3", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-03-04T21:28:03.803", "Id": "9698", "Score": "2", "Tags": [ "c++", "computational-geometry" ], "Title": "Normal calculation for tile terrain geometry" }
9698
<p>I have a large library (four packages) of data processing code that I have written over the last 12 months. I am quite new to python and would like to see if I am doing things correctly.</p> <p>This utility/convenience code is currently kept in a module called utils that is imported in many places (for an example, see <a href="https://codereview.stackexchange.com/questions/9702/data-cleaning-am-i-using-classes-correctly-here">this</a> question). I thought it would be a simple place to start as it has no dependency on my other code.</p> <p>The purpose of the first two functions is to switch between cumulative energy meter readings and actual energy consumption values.</p> <p>The second two functions allow me to move between datetime and timestamp values, usually because I store datetime information in numpy arrays of timestamps for some calculations but need them as datetimes for formatting.</p> <p>The switching between gaps and flags is useful because data interpolation identifies missing data and records it as boolean numpy arrays (flags) but I often need to identify contiguous chunks of missing data.</p> <pre><code>import numpy as np, datetime, time, logging def movement_from_integ(integ): return np.append(np.nan, np.diff(integ)) def integ_from_movement(movement): return np.append(0.0, np.cumsum(movement[1:])) def timestamp_from_datetime(dt): return np.array([time.mktime(d.timetuple()) for d in dt]) def datetime_from_timestamp(ts): return [datetime.datetime.fromtimestamp(s) for s in ts] def gaps_from_flags(flags, ts): logger = logging.getLogger('gaps_from_flags') """given missing flags and timestamps produces a list of contiguous gaps""" _gap = {'from': None, 'to': None} result = [] for i in xrange(len(flags)): if not flags[i]: logger.debug(flags[i]) if _gap['from'] != None: result.append(_gap) logger.debug('Gap saved [%s -&gt; %s]' % (_gap['from'], _gap['to'])) _gap = {'from': None, 'to': None} else: if _gap['from'] == None: logger.debug('%s: New gap initialised at %s' % (flags[i], ts[i])) _gap['from'] = ts[i] logger.debug('%s: Gap extended to %s' % (flags[i], ts[i])) _gap['to'] = ts[i] if _gap['from'] != None: result.append(_gap) logger.debug('Gap saved [%s -&gt; %s]' % (_gap['from'], _gap['to'])) return result def flags_from_gaps(gaps, ts): """given gaps and timestamps produces an array of boolean values indicating whether data are missing at each timestamp""" flags = np.array([False]*len(ts), dtype=bool) for g in gaps: a = (ts &gt;= g['from']) &amp; (ts &lt;=g['to']) flags[a] = True return flags </code></pre> <p>Is it OK to keep a set of functions like this in an otherwise object oriented project?</p> <p>Am I doing the flags->gaps->flags processing in a sensible way?</p> <p>I am aware there is such a thing as a masked array in numpy but I'm not sure how much work it would be to convert my entire code base over to using it.</p>
[]
[ { "body": "<p>It was really hard to understand what you're code is doing, but it does have some easy spottable \"problems\":</p>\n\n<h2><code>is None</code> vs. <code>== None</code></h2>\n\n<p>PEP8 clearly states: </p>\n\n<blockquote>\n <p>Comparisons to singletons like <em>None</em> should always be done with <code>is</code> or <code>is not</code>, never the equality operators.</p>\n</blockquote>\n\n<p>There's some further explaination <a href=\"http://jaredgrubb.blogspot.com/2009/04/python-is-none-vs-none.html\" rel=\"nofollow\">here</a>.</p>\n\n<p>So you should change lines like:</p>\n\n<pre><code>if _gap['from'] == None\n</code></pre>\n\n<p>to:</p>\n\n<pre><code>if _gap['from'] is None\n</code></pre>\n\n<h2><a href=\"http://docs.python.org/library/functions.html#zip\" rel=\"nofollow\"><code>zip()</code></a>/<a href=\"http://docs.python.org/library/itertools.html#itertools.izip\" rel=\"nofollow\"><code>izip()</code></a></h2>\n\n<p>Let's take a look about what <code>zip()</code> does:</p>\n\n<pre><code>&gt;&gt;&gt; x = [1, 2, 3]\n&gt;&gt;&gt; y = ['a', 'b', 'c']\n&gt;&gt;&gt; for num,ch in zip(x,y):\n... print num,ch\n... \n1 a\n2 b\n3 c\n</code></pre>\n\n<p><code>itertools.izip()</code> is just the generator version of zip in Python 2 (like <code>xrange()</code> for <code>range()</code>). So instead of:</p>\n\n<pre><code>for i in xrange(len(flags)):\n</code></pre>\n\n<p>You may want to do:</p>\n\n<pre><code>from itertools import izip\n\nfor flag,time_stamp in izip(flags,ts):\n # ...\n</code></pre>\n\n<h2>Don't pile imports</h2>\n\n<p>Is usually a better practice to import each package on its own line (it really helps readability). So, in your case, this will be better:</p>\n\n<pre><code>import logging # I usually import logging as first\nimport numpy as np\nimport datetime\nimport time\n</code></pre>\n\n<p>Python has a very flexible syntax (as you've surely noticed), use it smartly and do not abuse of it.</p>\n\n<h2><a href=\"http://docs.python.org/reference/expressions.html#binary-bitwise-operations\" rel=\"nofollow\">&amp;</a> vs <a href=\"http://docs.python.org/reference/expressions.html#boolean-operations\" rel=\"nofollow\">and</a></h2>\n\n<p>You have this line:</p>\n\n<pre><code>a = (ts &gt;= g['from']) &amp; (ts &lt;=g['to'])\n</code></pre>\n\n<p>Are you sure you weren't looking for:</p>\n\n<pre><code>a = (ts &gt;= g['from']) and (ts &lt;=g['to'])\n</code></pre>\n\n<p>Or better:</p>\n\n<pre><code>a = g['to'] &lt;= ts &lt;= g['from']\n</code></pre>\n\n<h2><code>_gap</code>: unPythonic name</h2>\n\n<p>Your <code>gaps_from_flags</code> is full of <code>_gap</code>, <code>self._gap</code> might be a \"private\" attribute of an object, but <code>_gap</code> is a very strange name, if it's a gap just call it <code>gap</code>!</p>\n\n<h2>numpy.array creation</h2>\n\n<p>I would suggest a <a href=\"http://www.scipy.org/Tentative_NumPy_Tutorial#head-d3f8e5fe9b903f3c3b2a5c0dfceb60d71602cf93\" rel=\"nofollow\">numpy tutorial</a>.</p>\n\n<p>After reading it, you may want to change this line:</p>\n\n<pre><code>flags = np.array([False]*len(ts), dtype=bool)\n</code></pre>\n\n<p>with:</p>\n\n<pre><code>flags = np.zeros((1,len(ts)), dtype=bool)\n</code></pre>\n\n<h2>Let's talk about Design</h2>\n\n<p>Now that we cleared some things a bit, let's talk about your design. As I stated at the beginning I don't fully understand what you're doing, so fell free to provide more information, correct me if get things wrong, etc... etc...</p>\n\n<ul>\n<li><p>First: go read <a href=\"http://www.python.org/dev/peps/pep-0020/\" rel=\"nofollow\">The Zen of Python</a> if you haven't already and then come back. Have you read it? Well! Now keep it mind every time you write a new line of code :)</p></li>\n<li><p>Let me state this clear: I don't like those first four functions.<br>\nThere's really a point of having one-line utility function? Are they really that useful if you'll have to replace one line with another one line?<br>\nIf you had only one of them, with a complex one line and it was a real pain to repeat it all the times I might understand, but there are four of them and they are doing a very simple task: convertion. </p></li>\n<li><p>So this leads me to: Why are you converting so much?<br>\nDo you really need it? I guess a better design will get rid of that. One conversion at the beginning and one at the end I'd say that's what one usually need with the proper design.</p></li>\n<li><p>It seems like you're logging too much, but that's just my opinion thrown there.</p></li>\n<li><p><code>gaps_from_flags</code> is doing some really strange things. It seems that it's using a temporary gap dict. It looks very unpythonic. Borrowing from the Zen of Python I'd say that is <em>ugly</em>, <em>complex</em> and <em>readability counts</em>.<br>\n<strong>If</strong> I get what you're trying to do, you could use <a href=\"http://docs.python.org/library/itertools.html#itertools.groupby\" rel=\"nofollow\"><code>itertools.groupby()</code></a>, probably something like this:</p>\n\n<pre><code>res = []\nfor k,g in itertools.groupby(zip(flags,tp), lambda x: x[0]):\n time_stamps = list(g)\n res.append({'from': time_stamps[0], 'to': time_stamps[-1]})\n</code></pre>\n\n<p>There's still way room for improvement in the above example, but as I said it's just a wild guess and an example. (Probably it doesn't even perfectly fit your flagging system).</p></li>\n<li><p>Once again this leads me to think that you could probably get rid entirely of your flagging system. It looks painful to maintain. Is it really necessary? Perhaps there's a better design for what you're trying to do.</p></li>\n<li><p>It seems like you're using numpy arrays like simple lists. There's a particular reason for using numpy here? And remember that: <a href=\"http://en.wikipedia.org/wiki/Program_optimization\" rel=\"nofollow\">\"premature optimization is the root of all evil\"</a>.</p></li>\n<li><p>You asked if it's ok to keep a set of function in an OO project. Well, the answer for Python is surely: <a href=\"http://docs.python.org/howto/functional.html\" rel=\"nofollow\">Yes!</a> </p></li>\n</ul>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-03-05T07:43:15.150", "Id": "15388", "Score": "1", "body": "It's a great answer, albeit a bit too harsh at times (\"gaps_from_flags looks just ugly\"). I'd like to point out that functional programming is a bit more than keeping a set of functions in a project (that would be procedural programming, I think). See the [functional programming Wikipedia entry](http://en.wikipedia.org/wiki/Functional_programming)." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-03-05T07:45:26.443", "Id": "15389", "Score": "0", "body": "Oh and one-line functions have all the benefits of normal functions, I don't believe they should be discarded, and it does avoid repeating oneself. I would simply put them in another module, and find a better name than \"utils\" for this one." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-03-05T09:09:25.480", "Id": "15391", "Score": "0", "body": "@Cygal: No offese was meant, I was just alluding to the first line of the [zen of python](http://www.python.org/dev/peps/pep-0020/), I've also often experienced that if you are not very explict (but honest) about what you think (expecially on design), others will not get how really you don't like their code. But you are probably right, thanks for noticing that, I will edit my answer and revisit my stetements in a more polite fashion." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-03-05T09:15:32.773", "Id": "15393", "Score": "0", "body": "I have probably said harsher things than that already. It's an interesting (meta) question. I think the answer is that you should refrain from being \"harsh\" when it's not something you would like to hear from a nice stranger about **your** code." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-03-05T23:21:00.393", "Id": "15418", "Score": "0", "body": "I am very happy with this answer, thanks Rik Poggi. itertools.groupby has reduced my ugly method down to a few lines. Perfect. I'm not sure about the & vs and point but otherwise pretty much spot on for me." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-03-05T23:53:54.500", "Id": "15424", "Score": "1", "body": "@Graeme: I'm glad you liked it :) `&` is a [bitwise operator](http://wiki.python.org/moin/BitwiseOperators), unless otherwise defined like for example for sets where it does an [intersection](http://docs.python.org/library/stdtypes.html#set.intersection). `and` is boolean operator, it's what you would normally use: (`True and False`, `if something and some:`, etc...)" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-03-06T00:03:51.650", "Id": "15426", "Score": "0", "body": "@RikPoggi: OK, the way I am using it is to create an indexing array for ts which is a numpy array. Use of 'and' leads to ValueError: The truth value of an array with more than one element is ambiguous. Use a.any() or a.all()" } ], "meta_data": { "CommentCount": "7", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-03-05T00:39:21.440", "Id": "9705", "ParentId": "9700", "Score": "3" } } ]
{ "AcceptedAnswerId": "9705", "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-03-04T21:34:29.007", "Id": "9700", "Score": "2", "Tags": [ "python", "numpy" ], "Title": "Simple utility/convenience module - am I doing it right?" }
9700
<p>I have a data processing application that does some data cleaning as the first step. This is the module I import for that purpose.</p> <p>The only 'public' part of the api is the 'clean' function which returns a processed version of the input data.</p> <p>So to clean data I currently do something like this:</p> <pre><code>c = TemperatureCleaner(data) clean_data = c.clean(15) </code></pre> <p>The 'data' that is used to initialise the objects is a dictionary with various elements. data['timestamp'] and data['value'] are numpy arrays, data['datetime'] is a list of datetime objects. The output also has a dictionary in the data['cleaned'] recording the parameters of the cleaning process (only sd_limit, the number of standard deviations from the mean that determines the filtering limit).</p> <p>The module utils is mine and is included in <a href="https://codereview.stackexchange.com/questions/9700/simple-utility-convenience-module-am-i-doing-it-right">this</a> question.</p> <pre><code>import logging, time import numpy as np import utils """ DataCleaning must handle consumption data and temperature data These data sources should be treated differently as consumption should be cleaned based on the rate of consumption whilst temperature should be cleaned on absolute values Also, consumption is currently expected to be provided as cumulative totals - this may change or may be specified with input data (i.e. 'type' information) """ class CleanerBase(object): def clean(self, sd_limit): self.logger.debug('cleaning process started') clean = self.raw.copy() ts = self.raw['timestamp'] value = self.raw['value'] while self._has_invalid_dates(ts): ok = self._valid_dates(ts) ts = ts[ok] value = value[ok] ts, value = self._trim_ends(ts, value) ts, value = self._remove_extremes(ts, value, sd_limit) clean['timestamp'] = ts clean['datetime'] = utils.datetime_from_timestamp(ts) clean['value'] = value clean['cleaned'] = {'sd_limit': sd_limit} return clean def _has_invalid_dates(self, dates): gap = np.diff(dates) return any(gap&lt;=0) def _valid_dates(self, dates): """remove duplicate dates and oddness""" self.logger.debug('preparing data for cleaning') gap = np.diff(dates) ok = np.append(True, (gap&gt;0)) return ok def _trim_ends(self, date, value): """ Uses date array to identify big gaps. Value field is trimmed to match. """ if len(date) == 0: raise NoDataError("Can't trim ends from an empty dataset") n = 0 big_gap = 60*60*24*7 for i in range(0, len(date)-1): gap = date[i+1] - date[i] if gap &lt; big_gap: break else: n += 1 logging.debug("gap-&gt;: %s [hr]" % (gap / (60*60))) start = i for j in range(len(date)-1): i = len(date)-1 - j gap = date[i] - date[i-1] if gap &lt; big_gap: break else: n += 1 logging.debug("&lt;-gap: %s [hr]" % (gap / (60*60))) end = i+1 if n &gt; 0: logging.debug("%s points removed from ends ( so [0:%s] became [%s:%s])" % (n, len(date)-1, start, end)) else: logging.debug("No points removed from ends") return date[start:end], value[start:end] def _remove_extremes(self, date, integ, sd_limit): self.logger.debug('removing extremes') nremoved, new_date, new_integ = self._filter(date, integ, sd_limit) total_removed = nremoved self.logger.debug('--&gt;%i readings removed' % nremoved) while nremoved &gt; 0: nremoved, new_date, new_integ = self._filter(new_date, new_integ, sd_limit) self.logger.debug('--&gt;%i readings removed' % nremoved) total_removed += nremoved if total_removed &gt; 0: self.logger.debug("%s extreme record(s) removed in total" % total_removed) else: self.logger.debug("No extreme records removed") return new_date, new_integ def _limits(self, data, sd_limit, allow_negs = False): mean = np.mean(data) std = np.std(data) limit = std * sd_limit result = [mean - limit, mean + limit] if not allow_negs: result[0] = max(0, result[0]) return result class ConsumptionCleaner(CleanerBase): def __init__(self, data): self.raw = data self.logger = logging.getLogger("DataCleaning:ConsumptionCleaner") def _filter(self, date, integ, sd_limit): r = self._rate(date, integ) lower_limit, upper_limit = self._limits(r, sd_limit) keep, remove = (r&gt;=lower_limit) &amp; (r&lt;=upper_limit), (r&lt;lower_limit) | (r&gt;upper_limit) filtered = any(remove) nremoved = len(r[remove]) keep, remove = np.append(True, keep), np.append(True, remove) #add one element to the beginning to keep the first integ and date values intact filtered_date = date[keep] movement = utils.movement_from_integ(integ) filtered_integ = utils.integ_from_movement(movement[keep]) return nremoved, filtered_date, filtered_integ def _rate(self, date, integ): gap = np.diff(date) if any(gap&lt;0): raise negativeGapError if any(gap==0): a = (gap==0) raise zeroGapError, "Cannot determine rate for a zero length gap %s" % [time.strftime('%Y-%m-%d %H:%M:%S', time.gmtime(d)) for d in date[a]] movement = np.diff(integ) return movement/gap class TemperatureCleaner(CleanerBase): def __init__(self, data): self.raw = data self.logger = logging.getLogger("DataCleaning:TemperatureCleaner") def _filter(self, date, movement, sd_limit): lower_limit, upper_limit = self._limits(movement, sd_limit, allow_negs=True) keep, remove = (movement&gt;=lower_limit) &amp; (movement&lt;=upper_limit), (movement&lt;lower_limit) | (movement&gt;upper_limit) filtered = any(remove) nremoved = len(movement[remove]) filtered_date = date[keep] filtered_movement = movement[keep] return nremoved, filtered_date, filtered_movement </code></pre> <p>I suppose I have number of questions, but my main one is am I using classes correctly?Methods such as _trim_ends could be defined outside of the class as it never refers to the instance data, which way is better? Also, my <strong>init</strong> function isn't doing much, should I initialise a cleaner with an sd_limit and pass data into the clean function?</p> <p>Other questions:</p> <ul> <li>Is my algorithm any good?</li> <li>Am I being efficient in implementing my algorithm?</li> <li>Should I separate out the input data a bit more?</li> <li>Am I presenting a convenient api to the rest of my code?</li> </ul>
[]
[ { "body": "<p>I wasn't able to fully understand what your code does, but there are a couple of improvements that could be made. I will go through them first, and answer your questions after.</p>\n\n<h2>Inheritance</h2>\n\n<p>There's a pattern going on here:</p>\n\n<pre><code>class ConsumptionCleaner(CleanerBase):\n def __init__(self, data):\n self.raw = data\n self.logger = logging.getLogger(\"DataCleaning:ConsumptionCleaner\")\n # ...\n\nclass TemperatureCleaner(CleanerBase):\n def __init__(self, data):\n self.raw = data\n self.logger = logging.getLogger(\"DataCleaning:TemperatureCleaner\")\n # ...\n</code></pre>\n\n<p>This means that you could move <code>__init__</code> into the base class:</p>\n\n<pre><code>class CleanerBase(object):\n def __init__(self, data):\n self.raw = data\n self.logger = logging.getLogger(\"DataCleaning:{}\".format(self.__class__.__name__))\n</code></pre>\n\n<p>Advantages: </p>\n\n<ul>\n<li><code>CleanerBase</code> will no longer be an (implict) abstract class.</li>\n<li><code>__init__</code> will be inherited.</li>\n</ul>\n\n<h2>Staticmethods and generators</h2>\n\n<blockquote>\n <p>Methods such as _trim_ends could be defined outside of the class as it never refers to the instance data.</p>\n</blockquote>\n\n<p>It could be defined outside, but it's ok to carry it along in your class, that's what <a href=\"http://docs.python.org/library/functions.html#staticmethod\" rel=\"nofollow\"><code>staticmethod</code></a> are for :)</p>\n\n<p>It also seems that <code>_trim_ends</code> could be easily implemented as a generator, take a look at this example:</p>\n\n<pre><code>@staticmethod\ndef _trim_ends(date, value, big_gap=60*60*24*7):\n if not date:\n raise NoDataError(\"Can't trim ends from an empty dataset\")\n n = 0\n last = date[0]\n for d,v in izip(date[1:],value):\n gap = d - last\n last = d\n if gap &lt; big_gap:\n n += 1\n yield v\n</code></pre>\n\n<p><code>yield</code> is what make it a generator.</p>\n\n<p>Notes:</p>\n\n<ul>\n<li>The <code>@staticmethod</code> decorator let's you explicit declare that <code>_trim_ends</code> doesn't need <code>self</code>.</li>\n<li><code>if len(date) == 0:</code> should be <code>if not date:</code></li>\n<li>It would also be better to have it in two lines (readability counts).</li>\n<li><code>yield</code> is what makes it a generator.</li>\n<li>If <code>_trim_ends</code> is a generator, it would be <em>way better</em> to get rid of <code>raise</code> and do the check one level up, or improve the algoritm so that it will work with on empy dates returning <code>None</code> or an empty list.</li>\n</ul>\n\n<h2>Q &amp; A</h2>\n\n<blockquote>\n <p>Also, my <code>__init__</code> function isn't doing much, should I initialise a cleaner with an sd_limit and pass data into the clean function?</p>\n</blockquote>\n\n<p><code>__init__</code> methods aren't meant for \"doing much\", meaning that one shouldn't put heavy computation there. Cleared this, what you're asking is a desing choice, if an instance of this class will alwayse use the same <code>sd_limit</code> then yes, you should make <code>sd_limit</code> an attribute and initialise it in <code>__init__</code>.</p>\n\n<blockquote>\n <p>Is my algorithm any good?</p>\n</blockquote>\n\n<p>It's really hard to tell, since they are hardly understandable/readable.<br>\nSome of them do look too complex. So far for what I could grasp, and since you said to be \"quite new to python\", I'd say there should be room for improvement.</p>\n\n<blockquote>\n <p>Am I being efficient in implementing my algorithm?</p>\n</blockquote>\n\n<p>Same answer as above.</p>\n\n<blockquote>\n <p>Should I separate out the input data a bit more?</p>\n</blockquote>\n\n<p>I'm not sure I understand this question. Input data should already be very clear and clean. Usually a good function does only one thing and it's very good at it, it's a responsability of an higher level to manage and distribute the workflow.</p>\n\n<blockquote>\n <p>Am I presenting a convenient api to the rest of my code?</p>\n</blockquote>\n\n<p>You are only presenting the <code>clean()</code> method to the rest of the code, so if that's the only thing you'll need the answer is yes, otherwise it's no. </p>\n\n<p>The internal implementation is up to you, and that seems a little over-complicated, but once again: I wasn't really able to dig inside your code.</p>\n\n<p><strong>Note:</strong> It seems that your <code>clean</code> method is actually filtering, if that's what it does I would call it <code>filter</code>, and I'd also say that your classes should be implementations of some <code>BaseFilter</code> too. If you change your classes names to <code>SomethingFilter</code> you may want to put the filtering code inside <code>__call__</code>.</p>\n\n<blockquote>\n <p>My main one is: am I using classes correctly?</p>\n</blockquote>\n\n<p>If the python compiler doesn't complain, well yes.</p>\n\n<p>But I'm pretty sure that's not what you meant :)<br>\nYou are the one who really knows your code, we can only give pointers/share some thoughts on a narrow piece of code, but at the end it's up to up to put it all togheter and be the judge how good is your whole implementation is.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-03-05T23:55:37.960", "Id": "15425", "Score": "0", "body": "Thanks Rik Poggi, I like the refactor in the __init__ function and the use of @staticmethod. However, I don't think your answer regarding the _trim_ends method is going to work. Should I edit the question to focus down on the method or should I just create a new question?" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-03-06T00:06:49.850", "Id": "15427", "Score": "0", "body": "@GraemeStuart: Probably I got wrong what `_trim_ends` is doing, my main point was to show that generator would be a good design for that task (but maybe I misunderstood that too). I think you should open a new question here on CR, or if you move the focus on your goal, with a polished version of your code (without logging and n count), it should also be on topin on SO." } ], "meta_data": { "CommentCount": "2", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-03-05T11:42:29.487", "Id": "9713", "ParentId": "9702", "Score": "1" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-03-04T23:09:57.433", "Id": "9702", "Score": "1", "Tags": [ "python", "numpy" ], "Title": "Data cleaning - am I using classes correctly here?" }
9702
<p>Consider the following CSV file:</p> <pre><code>A; B; ; B; ; A; C; ; E F; D; ; E; E; C; ; </code></pre> <p>The fields:</p> <ul> <li><code>$1</code>: the <code>jname</code>. A unique id of the entry.</li> <li><code>$2</code>: a " "(space)-separated list of <code>incond</code>.</li> <li><code>$3</code>: a " "(space)-separated list of <code>outcond</code>.</li> </ul> <p>For the "link" <code>A-B</code> to be valid, <code>jname</code> A must define B as <code>outcond</code>, and job B must define A as <code>incond</code>. </p> <p>In the above example, <code>D-E</code> is not a valid "link" because E doesn't define D as <code>incond</code>. <code>C-F</code> is not a valid "link" because F doesn't exist.</p> <p>A <code>cond</code> is not valid if the link it forms is not valid. The script must detect all non valid <code>conds</code> and which jobs are infected.</p> <pre><code>#!/usr/bin/awk -f BEGIN { FS=" *; *"; delim = "-"; conds[""]=0; } { icnd_size = split($2, incond_list, " "); for (i=1; i&lt;=icnd_size; ++i) { conds[incond_list[i] delim $1]++; } ocnd_size = split($3, outcond_list, " "); for (i=1; i&lt;=ocnd_size; ++i) { conds[$1 delim outcond_list[i]]--; } } END { for (i in conds) { sz = split(i, answer, delim); if (conds[i] == 1) { j = answer[2]; c = answer[1]; inorout = "INCOND"; } if (conds[i] == -1) { j = answer[1]; c = answer[2]; inorout = "OUTCOND"; } if (conds[i] != 0) print "Invalid", inorout, c, "on job", j; } } </code></pre> <p>The script works, although I do not have large data to test against. I see 2 problems with it:</p> <ol> <li>the script will break if some <code>cond</code> has the character <code>delim</code> in the name</li> <li>the script might break (and/or return false positives) if a line is inserted twice or if two lines have the same <code>jname</code>.</li> </ol> <p>I could use any tip on addressing the two problems, as well as any critique of the code, it's literally my first Awk code.</p>
[ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-03-05T17:09:28.317", "Id": "15401", "Score": "1", "body": "Not really a CSV file is it! C => Comma => ','. You have a SSC. Semicolon separated file." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2016-03-11T17:43:18.427", "Id": "228402", "Score": "0", "body": "way late on this one, if you're still interestest, are you trying to make a `tsort` substitute here? Good luck." } ]
[ { "body": "<h3>Your main questions</h3>\n\n<blockquote>\n <p>The script works, although I do not have large data to test against.</p>\n</blockquote>\n\n<p>You don't necessarily need a large dataset.\nIt's better to think of all possible corner cases.\nFor example, your sample data demonstrates failures of <code>OUTCOND</code> but not of <code>INCOND</code>.\nAlso, although there is an example of more than one outgoing links,\nbut there is no example of more than one incoming links.\nThere are not too many interesting cases,\nif you add examples for all them,\nthen you can be fairly confident in your solution.</p>\n\n<blockquote>\n <ol>\n <li>The script will break if some cond has the character delim in the name</li>\n </ol>\n</blockquote>\n\n<p>If you want to be really safe, you could add a sanity check for that, and raise an error when such name is found, for example by calling <code>exit</code> with a non-zero value.</p>\n\n<blockquote>\n <ol start=\"2\">\n <li>The script might break (and/or return false positives) if a line is inserted twice or if two lines have the same jname.</li>\n </ol>\n</blockquote>\n\n<p>Ditto.</p>\n\n<h3>Simplify</h3>\n\n<p>Many things can be simplified in this code.</p>\n\n<p>The <code>conds[\"\"]=0;</code> is unnecessary, you can simply delete that line.</p>\n\n<p>Instead of this:</p>\n\n<blockquote>\n<pre><code>icnd_size = split($2, incond_list, \" \");\n\nfor (i=1; i&lt;=icnd_size; ++i) {\nconds[incond_list[i] delim $1]++;\n}\n</code></pre>\n</blockquote>\n\n<p>You don't really need the return value of <code>split</code>,\nbecause instead of a counting loop,\nyou can use a more idiomatic for-each loop:</p>\n\n<pre><code>split($2, inconds, \" \");\n\nfor (i in inconds) {\n conds[inconds[i] delim $1]++;\n}\n</code></pre>\n\n<p>The same goes for <code>outconds</code> as well.</p>\n\n<h3>Mutually exclusive <code>if</code> statements</h3>\n\n<p>These <code>if</code> statements cannot be both true at the same time:</p>\n\n<blockquote>\n<pre><code>if (conds[i] == 1) {\n # ...\n}\n\nif (conds[i] == -1) {\n # ...\n}\n</code></pre>\n</blockquote>\n\n<p>So they should be chained together with an <code>else if</code>.</p>\n\n<h3>Formatting</h3>\n\n<p>Instead of this:</p>\n\n<blockquote>\n<pre><code>for (i=1; i&lt;=ocnd_size; ++i) {\nconds[$1 delim outcond_list[i]]--;\n}\n</code></pre>\n</blockquote>\n\n<p>It would be better to write like this:</p>\n\n<pre><code>for (i = 1; i &lt;= ocnd_size; ++i) {\n conds[$1 delim outcond_list[i]]--;\n}\n</code></pre>\n\n<h3>Naming</h3>\n\n<p>Some of the names are not so great.\nFor example <code>sz</code>, <code>i</code>, <code>j</code>, <code>c</code> in the <code>END</code> block.\n<code>sz</code> is actually unnecessary,\nand I would rename the others to <code>pair</code>, <code>job</code>, and <code>cond</code>,\nrespectively.</p>\n\n<h3>Putting it together</h3>\n\n<p>Consider this alternative implementation:</p>\n\n<pre><code>#!/usr/bin/awk -f\n\nBEGIN {\n FS = \" *; *\";\n delim = \"-\";\n}\n\n{\n split($2, inconds, \" \");\n\n for (i in inconds) {\n conds[inconds[i] delim $1]++;\n }\n\n split($3, outconds, \" \");\n\n for (i in outconds) {\n conds[$1 delim outconds[i]]--;\n }\n}\n\nEND {\n oformat = \"Invalid %s %s on job %s\\n\";\n for (pair in conds) {\n split(pair, parts, delim);\n\n if (conds[pair] == 1) {\n job = parts[2];\n cond = parts[1];\n inorout = \"INCOND\";\n } else if (conds[pair] == -1) {\n job = parts[1];\n cond = parts[2];\n inorout = \"OUTCOND\";\n }\n if (conds[pair] != 0) print \"Invalid\", inorout, cond, \"on job\", job;\n }\n}\n</code></pre>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2017-01-12T21:14:46.493", "Id": "152495", "ParentId": "9706", "Score": "1" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "2", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-03-05T03:46:27.003", "Id": "9706", "Score": "2", "Tags": [ "shell", "awk" ], "Title": "Linking input/output states and conditions in an input file" }
9706
<p>The <a href="/questions/tagged/computational-geometry" class="post-tag" title="show questions tagged &#39;computational-geometry&#39;" rel="tag">computational-geometry</a> tag should be assigned to questions about computation and manipulation of locations or properties of geometric identities or objects. Since geometry computations are highly tolerance dependent, definition and computation of tolerances are welcome, too.</p>
[]
[]
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-03-05T07:28:06.933", "Id": "9707", "Score": "0", "Tags": null, "Title": null }
9707
Computer geometry is a branch of computer science devoted to the study of algorithms which can be stated in terms of geometry.
[]
[]
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-03-05T07:28:06.933", "Id": "9708", "Score": "0", "Tags": null, "Title": null }
9708
<p>Note that I'm using a C++ compiler ( hence, the cast on the <code>calloc</code> function calls) to do this, but the code is essentially C.</p> <p>Basically, I have a <code>typedef</code> to an <code>unsigned char</code> known as <code>viByte</code>, which I'm using to create a string buffer to parse a file from binary (a TGA file, to be exact - but, that's irrelevant).</p> <p>I'm writing basic functions for it right now; append, prepend, new, etc.</p> <p>The problem is that, on the first iteration of the first loop in <code>viByteBuf_Prepend</code>, I get a segmentation fault. I need to know why, exactly, as this is something which could keep me up all night without some pointers (pun intended). </p> <p>I also would like to know if my algorithms are correct in terms of how the buffer is <em>pre-pending</em> the <code>viByte</code> string. For example, I have a feeling that using <code>memset</code> too much might be a bad idea, and whether or not my printf format for the unsigned char is correct (I have a feeling it isn't, as nothing is getting output to my console). </p> <p>Compiling on GCC, Linux.</p> <pre><code>#ifdef VI_BYTEBUF_DEBUG void viByteBuf_TestPrepend( void ) { viByteBuf* buf = viByteBuf_New( 4 ); buf-&gt;str = ( viByte* ) 0x1; printf(" Before viByteBuf_Prepend =&gt; %uc ", buf-&gt;str); viByteBuf_Prepend( buf, 3, ( viByte* ) 0x2 ); printf(" After viByteBuf_Prepend =&gt; %uc ", buf-&gt;str); } #endif viByteBuf* viByteBuf_New( unsigned int len ) { viByteBuf* buf = ( viByteBuf* ) calloc( sizeof( viByteBuf ), 1 ); const int buflen = len + 1; buf-&gt;str = ( viByte* ) calloc( sizeof( viByte ), buflen ); buf-&gt;len = buflen; buf-&gt;str[ buflen ] = '\0'; return buf; } void viByteBuf_Prepend( viByteBuf* buf, unsigned int len, viByte* str ) { unsigned int pos, i; const unsigned int totallen = buf-&gt;len + len; viByteBuf* tmp = viByteBuf_New( totallen ); viByte* strpos = buf-&gt;str; memset( tmp-&gt;str, 0, tmp-&gt;len ); int index; for( i = 0; i &lt; buf-&gt;len; ++i ) { index = ( buf-&gt;len - i ) - 1; *strpos = buf-&gt;str[ 0 ]; ++strpos; } memset( buf-&gt;str, 0, buf-&gt;len ); printf( "%uc\n", buf-&gt;str ); i = totallen; for ( pos = 0; pos &lt; len; ++pos ) { tmp-&gt;str[ pos ] = str[ pos ]; tmp-&gt;str[ i ] = buf-&gt;str[ i ]; --i; } memset( buf-&gt;str, 0, buf-&gt;len ); buf-&gt;len = tmp-&gt;len; memcpy( buf-&gt;str, tmp-&gt;str, tmp-&gt;len ); viByteBuf_Free( tmp ); //memset( ) //realloc( ( viByteBuf* ) buf, sizeof( viByteBuf ) * tmp-&gt;len ); } </code></pre>
[ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-03-05T14:43:47.360", "Id": "15398", "Score": "1", "body": "This question is a bit offtopic since the code doesn't work, and that's forbidden (cf. the faq). But since there's also an interesting question about code correctness, it could be kept here." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-03-05T16:36:06.533", "Id": "15400", "Score": "0", "body": "What is the definition of `viByteBuf` ?" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-03-05T18:08:56.383", "Id": "15403", "Score": "0", "body": "`viByteBuf` is just a struct with two properities, `str` (`unsigned char`) and `len` (`unsigned int`). It's supposed to represent a buffer which can dynamically grow/shrink." } ]
[ { "body": "<p>Your problem is here:</p>\n<pre><code>buf-&gt;str[ buflen ] = '\\0';\n</code></pre>\n<p>You allocate a buffer (str) of buflen bytes.<br />\nThis means you can index it (str) from 0 -&gt; (buflen-1).</p>\n<p>Thus the accesses above is writing one past the end of the buffer and corrupting memory.<br />\nYou probably meant:</p>\n<pre><code>buf-&gt;str[ len ] = '\\0';\n</code></pre>\n<p>Since you are using C++ compiler. You should use <code>std::vector&lt;viByte&gt;</code> or <code>std::basic_string&lt;viByte&gt;</code>.</p>\n<p>This kind of bug is easy to introduce and unless you have good unit test hard to find. So why not use a class that already is unit test and has had 10 years of millions of people lookign at it to make sure it works correctly.</p>\n<h3>Other comments:</h3>\n<p>Broken and illegal.</p>\n<pre><code> buf-&gt;str = ( viByte* ) 0x1;\n</code></pre>\n<p>Wrong. buf-&gt;str is a pointer and it was expecting a unsigned integer (they are not the same). Use %p to print a pointer value.</p>\n<pre><code> printf(&quot; Before viByteBuf_Prepend =&gt; %uc &quot;, buf-&gt;str);\n</code></pre>\n<p>Broken and illegal (0x2 is not yours)</p>\n<pre><code> viByteBuf_Prepend( buf, 3, ( viByte* ) 0x2 );\n</code></pre>\n<p>No check for NULL. (calloc can return NULL when it fails).</p>\n<pre><code> viByteBuf* buf = ( viByteBuf* ) calloc( sizeof( viByteBuf ), 1 );\n</code></pre>\n<p>Again no check for NULL.</p>\n<pre><code> buf-&gt;str = ( viByte* ) calloc( sizeof( viByte ), buflen );\n</code></pre>\n<p>Is this really what you want? Buflen includes the portion with the '\\0' character. You need to be consistent and decide if len does or does not include the null.</p>\n<pre><code> buf-&gt;len = buflen;\n</code></pre>\n<p>As pointed out above (write past the end of the buffer).</p>\n<pre><code> buf-&gt;str[ buflen ] = '\\0';\n</code></pre>\n<p>How do you handle failure?<br />\nAs pointed out above calloc can fail. How do you propagate that failure to the caller.</p>\n<pre><code> viByteBuf* tmp = viByteBuf_New( totallen );\n</code></pre>\n<p>Why are you nulling the whole array. You are just about to write over it.<br />\nSeems like a complete waste of time.</p>\n<pre><code> memset( tmp-&gt;str, 0, tmp-&gt;len );\n</code></pre>\n<p>Looks like this loop is trying to reverse the string in place.<br />\nWhich will fail as by the time you overwrite the first half the second half is a copy of the back half. Luckily it completely fails because you don't actually use the <code>index</code> variable.</p>\n<pre><code> for( i = 0; i &lt; buf-&gt;len; ++i )\n {\n\n index = ( buf-&gt;len - i ) - 1;\n\n *strpos = buf-&gt;str[ 0 ];\n ++strpos;\n }\n</code></pre>\n<p>Now that you have failed to reverse it. You then overwrite it again with 0 (presumably to cover up the failure to reverse it).</p>\n<pre><code> memset( buf-&gt;str, 0, buf-&gt;len );\n</code></pre>\n<p>Illegal parameter to printf() again.</p>\n<pre><code> printf( &quot;%uc\\n&quot;, buf-&gt;str );\n</code></pre>\n<p>More copying for unknow reason.</p>\n<pre><code> memcpy( buf-&gt;str, tmp-&gt;str, tmp-&gt;len );\n</code></pre>\n<h1>This code is so full of bugs. It has no write to work.</h1>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-03-07T00:33:27.407", "Id": "15474", "Score": "0", "body": "Hmm...why do you think I asked for a review on this site? I appreciate your objective analysis, but that last snippet there was completely unnecessary.\n\nAlso, the reason why I'm not using the std::vector is because I'm writing this on Android, AND I want to actually learn a thing or two rather than just mindlessly pass values to a vector." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-03-07T00:38:55.550", "Id": "15475", "Score": "2", "body": "@Holland: Code review site is for working code. This is obviously very broken." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-03-07T00:40:12.810", "Id": "15476", "Score": "0", "body": "Also, you don't even offer a solution to the problems presented, which means that your answer, while tearing apart my code and showing me what I've done wrong, *hasn't taught me a damn thing*, because you don't offer a solution." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-03-07T00:45:06.230", "Id": "15477", "Score": "0", "body": "@Holland: Can't offer a solution because there is nothing to define what you want it to do (I am not psychic). This is not a site for fixing code; It is a site to review **WORKING** code to make it better and show were common problems can arise. Unfortunately I can't write your code for you. If you did not learn anything then you need to read it again." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-03-07T00:47:04.013", "Id": "15478", "Score": "1", "body": "@Holland: Easy solution use std::string rather than trying to write your own." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-03-08T17:40:01.067", "Id": "15603", "Score": "1", "body": "Should probably be moved to stackoverflow.com" } ], "meta_data": { "CommentCount": "6", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-03-05T20:29:38.100", "Id": "9727", "ParentId": "9709", "Score": "3" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "3", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-03-05T07:58:57.860", "Id": "9709", "Score": "1", "Tags": [ "c", "strings", "parsing" ], "Title": "C-Style unsigned char parsing and manipulation" }
9709
<p>Mostly a question on which approach would be better <em>and</em> when utilizing the <code>using</code> keyword, would it still be neccesary to close streams programatically. If an object implements <code>IDisposable</code> should <code>using</code> always be used?</p> <p>Link to my full answer using this sample: <a href="https://stackoverflow.com/questions/9563302/calling-and-get-result-text-from-service/9564067#9564067">Stackoverflow Answer</a></p> <p>Option 1:</p> <pre><code>WebClient webClient; webClient = new WebClient(); string json = webClient.DownloadString(@"urlToTheJsonResponse"); MemoryStream stream = new MemoryStream((Encoding.UTF8.GetBytes(json))); DataContractJsonSerializer ser = new DataContractJsonSerializer(typeof(GISData)); stream.Position = 0; GISData data = (GISData)ser.ReadObject(stream); stream.Close(); </code></pre> <p>Option 2:</p> <pre><code>WebClient webClient; MemoryStream stream; string json; GISData data; using (webClient = new WebClient()) { json = webClient.DownloadString(@"urlToTheJsonResponse"); } using (stream = new MemoryStream((Encoding.UTF8.GetBytes(json)))) { DataContractJsonSerializer ser = new DataContractJsonSerializer(typeof(GISData)); data = (GISData)ser.ReadObject(stream); stream.Close(); } using (webClient = new WebClient()) { webClient.DownloadFile(data.href, "C:/" + data.href.Substring(data.href.LastIndexOf("/") + 1)); } </code></pre>
[]
[ { "body": "<p>Yes, always. Unless it's a class-level variable in which your type should then implement <code>IDisposable</code> and dispose of them in its <code>Dispose()</code> method.</p>\n\n<p>So, option 2.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2016-11-03T14:55:20.127", "Id": "274265", "Score": "0", "body": "Well, except HttpClient. Because a rule wouldn't be a rule without an exception somewhere: http://aspnetmonsters.com/2016/08/2016-08-27-httpclientwrong/" } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-03-05T13:14:55.970", "Id": "9715", "ParentId": "9714", "Score": "3" } }, { "body": "<p>Yes you should, classes which implement IDisposable are basically stating that they internally have used managed or unmanaged resources which require explicit tidy up outside of the remit of the garbage collector. The using statement is simply a compiler short cut to a try/finally block which ensures that the dispose method is called even if the code inside the using block throws an exception.</p>\n\n<pre><code>using (webClient = new WebClient())\n{\n webClient.DownloadFile(data.href, \"C:/\" + data.href.Substring(data.href.LastIndexOf(\"/\") + 1));\n}\n</code></pre>\n\n<p>becomes</p>\n\n<pre><code>WebClient webClient = new WebClient();\ntry\n{\n webClient.DownloadFile(data.href, \"C:/\" + data.href.Substring(data.href.LastIndexOf(\"/\") + 1));\n}\nfinally\n{\n if (webClient != null)\n {\n webClient.Dispose();\n }\n}\n</code></pre>\n\n<p>Although the garbage collector will call the Finalize() method on any IDisposable instance that implements one, that won't happen until the object is available for garbage collection and therefore the tidy up won't happen until some point in the future.</p>\n\n<p>Most classes with a finalizer will call the dispose method but usually only tidy up unmanaged resources when called from the finalizer, therefore it is still recommended to call dispose yourself as soon as you are finished with an object to ensure that you don't hold on to other resources longer than necessary.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-03-05T19:52:55.067", "Id": "15406", "Score": "0", "body": "This is completely wrong. The GC **never** calls `Dispose()`. But it does call the finalizer, which usually does the same cleanup of unmanaged resources as `Dispose()`." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-03-05T21:46:48.660", "Id": "15412", "Score": "3", "body": "@svick - I don't think you understand the meaning of the word \"completely.\" For example, finding a pedantic error among a multi-faceted answer that is otherwise correct is not \"completely wrong.\" I'm only saying something because your comment may mislead some people with regards to the quality of the question." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-03-05T22:08:31.243", "Id": "15414", "Score": "1", "body": "@SeanH, well, I don't think that's a pedantic error. I think it's quite important and if you believe what Trevor wrote, it might bite you big time." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-03-05T23:38:36.077", "Id": "15420", "Score": "1", "body": "@svick is correct, I meant to say Finalize not Dispose in that last paragraph I'll update the answer to correct it." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-03-06T01:00:16.140", "Id": "15429", "Score": "0", "body": "@TrevorPilley, it's still not correct. Your current text makes it sound like `Finalize()` has something to do with `IDisposable`. Sure, when you have `Finalize()` you almost always implement `IDisposable` too, but it's not technically necessary." } ], "meta_data": { "CommentCount": "5", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-03-05T13:56:25.933", "Id": "9718", "ParentId": "9714", "Score": "5" } }, { "body": "<p>Under normal circumstances, you should always either call <code>Dispose()</code> explicitly or use a <code>using</code> block. This applies especially for streams and related types (like <code>StreamWriter</code>), where not disposing can have very visible bad consequences (e.g. the end of the text won't be written to the file).</p>\n\n<p>But there are some types for which calling <code>Dispose()</code> doesn't actually do anything useful. And <code>WebClient</code> and <code>MemoryStream</code> are among them. They are <code>IDisposable</code> primarily because they inherit that interface from their base class (<code>Component</code> and <code>Stream</code>, respectively). So, I think your Option 1 is fine.</p>\n\n<p>If you are unsure whether you should dispose objects of some type or whether it's one of the few types where not disposing is safe, err on the side of caution and dispose it.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-03-05T20:04:56.563", "Id": "9726", "ParentId": "9714", "Score": "14" } }, { "body": "<p>I realize this is over two years later, but I thought I should point out a redundancy in the code in the OP. I see this:</p>\n\n<pre><code>using (stream = new MemoryStream((Encoding.UTF8.GetBytes(json)))) {\n DataContractJsonSerializer ser = new DataContractJsonSerializer(typeof(GISData));\n data = (GISData)ser.ReadObject(stream);\n stream.Close();\n}\n</code></pre>\n\n<p>Notice that <code>stream.Close();</code> at the end of the block - which, of course, is unnecessary since <code>stream</code> is the object of the <code>using</code>.</p>\n\n<p>(I would have just used comment under the OP, but I just signed up to this particular branch of stackexchange and don't have the rep requirement.)</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2015-11-10T21:12:12.053", "Id": "203387", "Score": "0", "body": "Welcome to Code Review SE. Good catch on the `stream.Close()`." } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2015-11-10T20:06:25.120", "Id": "110394", "ParentId": "9714", "Score": "7" } } ]
{ "AcceptedAnswerId": "9726", "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-03-05T12:03:16.090", "Id": "9714", "Score": "14", "Tags": [ "c#" ], "Title": "Using statement in context of streams and WebClients" }
9714
<p>I try to implement a simple RLE compression algorithm as a learning task. In the first step, i need to split my source list to sequences of repeating and non-repeating elements. I've done it, but code seems to be so ugly. Can I simplify it?</p> <pre><code>src = [1,1,2,3,3,4,2,1,3,3,4,3,3,3,3,3,4,5] from itertools import izip isRepeat = False sequence = [] def out(sequence): if sequence: print sequence def testRepeate(a, b, pr): global isRepeat global sequence if a == b: if isRepeat: sequence.append(pr) else: out(sequence) sequence = [] sequence.append(pr) isRepeat = True else: if isRepeat: sequence.append(pr) out(sequence) sequence = [] isRepeat = False else: sequence.append(pr) for a, b in izip(src[:-1], src[1:]): testRepeate(a, b, a) testRepeate(src[-2], src[-1], src[-1]) out(sequence) </code></pre>
[]
[ { "body": "<p>First of all I must tell you that Python makes astonishing easy to write a <a href=\"http://en.wikipedia.org/wiki/Run-length_encoding\" rel=\"nofollow\">Run-length encoding</a>:</p>\n\n<pre><code>&gt;&gt;&gt; src = [1,1,2,3,3,4,2,1,3,3,4,3,3,3,3,3,4,5]\n&gt;&gt;&gt; from itertools import groupby\n&gt;&gt;&gt;\n&gt;&gt;&gt; [(k, sum(1 for _ in g)) for k,g in groupby(src)]\n[(1, 2), (2, 1), (3, 2), (4, 1), (2, 1), (1, 1), (3, 2), (4, 1), (3, 5), (4, 1), (5, 1)]\n</code></pre>\n\n<p>Take a look at how <a href=\"http://docs.python.org/library/itertools.html#itertools.groupby\" rel=\"nofollow\"><code>itertools.groupby()</code></a> to see how a generator will be a good choice for this kind of task</p>\n\n<hr>\n\n<p>But that doesn't mean that it wasn't a bad idea try to implement it yourself. So let's take a deeper look at your code :)</p>\n\n<p><strong>The best use of <code>global</code> is usually the one that doesn't use <code>global</code> at all</strong></p>\n\n<p>The use of the <code>global</code> keyword among beginners is almost always a sign of trying to program using some other language's mindset. Usually, if a function need to know the value of somthing, pass that something along as an argument.</p>\n\n<p>In your case, what you need, is a function that loops through your list holding the value of <code>isRepeat</code>.</p>\n\n<p>Something like this:</p>\n\n<pre><code>def parse(seq):\n is_repeat = False\n old = None\n for num in seq:\n is_repeat = num == old # will be True or False\n if is_repeat:\n # ...\n</code></pre>\n\n<p>I didn't go too far since, as you may have already noticed, the <code>is_repeat</code> flag is a bit useless now, so we'll get rid of that later.</p>\n\n<p>You may have also noted that I called <code>isReapeat</code> <code>is_repeat</code>, I did that to follow some naming style guide (see <a href=\"http://www.python.org/dev/peps/pep-0008/\" rel=\"nofollow\">PEP8</a> for more info).</p>\n\n<p><strong>Cleared this, let's get at your statement:</strong></p>\n\n<blockquote>\n <p>In the first step, I need to split my source list to sequences of repeating and non-repeating elements.</p>\n</blockquote>\n\n<p>Ok, to split a sequence we'll have to parse it item by item, so while we'll be at it why don't already count how many times an item occurs?</p>\n\n<p>The wrong step was to build a <code>testRepeat</code> function, such function should act on 2 items at the time, but that will lose the \"view\" of the whole sequence one item after the other. Well ok, a recursive solution could also be found, but I can't go through all the possible solutions.</p>\n\n<p>So, to do achive our goal one could:</p>\n\n<ul>\n<li>parse the list item by item.</li>\n<li>see if an item is the same as the previous one.</li>\n<li>if it is <code>count += 1</code>.</li>\n<li>else store that item with its count.</li>\n</ul>\n\n<p>This might be the code:</p>\n\n<pre><code>def rle(seq):\n result = []\n old = seq[0]\n count = 1\n for num in seq[1:]:\n if num == old:\n count += 1\n else:\n result.append((old, count)) # appending a tuple\n count = 1 # resetting the counting\n old = num\n result.append((old, count)) # appending the last counting\n return result\n</code></pre>\n\n<p>There could still be room for improvement (also it doesn't handle empty list like <em>hdima</em> noticed), but I just wanted to show an easy example and premature optimization is the root of (most) evil. (Also, there's groupby waiting to be used.)</p>\n\n<p><strong>Notes</strong></p>\n\n<p>It's very common to fall in some of the mistakes you did. Keep trying and you'll get better. Keep also in mind some of the following:</p>\n\n<ul>\n<li>Think hard about the your design.</li>\n<li>Do you really need an <code>out</code> function? Couldn't you just place the code there?</li>\n<li>Do you really want to not print at all, if you get an empty list? I would really like to see what my code is returning, so I wouldn't block its output.</li>\n<li>Don't write cryptic code, write readable one.<br>\nWhat are <code>a</code>, <code>b</code> and <code>pr</code>. A variable name should be something that reflect what it holds.</li>\n<li>The same could be said for <code>sequence</code>, if <code>sequece</code> is the resulting sequence call it <code>result</code> or something like that.</li>\n<li>Whorship <a href=\"http://www.python.org/dev/peps/pep-0020/\" rel=\"nofollow\">The Zen of Python</a> as an almighty guide!</li>\n</ul>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-03-05T21:15:14.907", "Id": "15408", "Score": "0", "body": "The `rle()` function needs to be fixed. Currently it's always lose the last element and raise `IndexError` for empty `seq`." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-03-05T21:53:33.893", "Id": "15413", "Score": "0", "body": "@Nativeborn: Yes `groupby` is the right tool. Knowing the standard library is a must, but I hope you got that the main point was to learn something and improve one's own coding skills :)" } ], "meta_data": { "CommentCount": "2", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-03-05T20:46:43.443", "Id": "9728", "ParentId": "9721", "Score": "5" } }, { "body": "<p>It seems your solution is overly over-engineered. To implement <a href=\"http://en.wikipedia.org/wiki/Run-length_encoding\" rel=\"nofollow\">RLE</a> algorithm you just need to iterate over the input sequence and store the current element and the counter. For example the following code implements RLE for lists:</p>\n\n<pre><code>def rle(src):\n result = []\n if src:\n current = src.pop(0)\n counter = 1\n for e in src:\n if e == current:\n counter += 1\n else:\n result.append((counter, current))\n current = e\n counter = 1\n result.append((counter, current))\n return result\n</code></pre>\n\n<p>And the following code for any iterator:</p>\n\n<pre><code>def irle(src):\n iterator = iter(src)\n current = next(iterator)\n counter = 1\n for e in iterator:\n if e == current:\n counter += 1\n else:\n yield counter, current\n current = e\n counter = 1\n yield counter, current\n</code></pre>\n\n<p>Some usage examples:</p>\n\n<pre><code>&gt;&gt;&gt; rle([])\n[]\n&gt;&gt;&gt; rle([1])\n[(1, 1)]\n&gt;&gt;&gt; rle([1, 1, 1, 2, 3, 3])\n[(3, 1), (1, 2), (2, 3)]\n&gt;&gt;&gt; list(irle(iter([])))\n[]\n&gt;&gt;&gt; list(irle(iter([1])))\n[(1, 1)]\n&gt;&gt;&gt; list(irle(iter([1, 1, 1, 2, 3, 3])))\n[(3, 1), (1, 2), (2, 3)]\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-03-05T21:44:17.203", "Id": "15410", "Score": "0", "body": "Thank you for correction. But I think, that `itertools` will be more convinient." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-03-06T09:02:53.660", "Id": "15438", "Score": "0", "body": "However `itertools.groupby` is more convenient in Python, but if you know _how_ to implement the algorithm then you can implement it in any language." } ], "meta_data": { "CommentCount": "2", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-03-05T21:03:54.967", "Id": "9729", "ParentId": "9721", "Score": "0" } } ]
{ "AcceptedAnswerId": "9728", "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-03-05T18:33:55.590", "Id": "9721", "Score": "3", "Tags": [ "python" ], "Title": "List splitting for RLE compression algorithm" }
9721
<p>I have a problem to solve. My algorithm is assigning Players to Positions. On the start I have a list of about 16 positions and 4 players. The problem is to assing every player to it's closest positions so the overall distance is as low as possible.</p> <p>I've already done this:</p> <pre><code>List players = ... List positions = ... Set posPerms = positions.permutations().collect { it.subList(0, playmakers.size()) } as Set List assignation = posPerms.min { List perm -&gt; int v = 0 perm.eachWithIndex { Position pos, int index -&gt; v += pos.distance(players[index]) } v } [players, assignation].transpose().collectEntries { it } </code></pre> <p>I get what I want, but the performance is a problem. positions.permutations() generates massive lists. Is there any more optimal way to do this?</p>
[]
[ { "body": "<p>You could use the <a href=\"http://groovy.codehaus.org/groovy-jdk/java/util/Collection.html#eachPermutation%28groovy.lang.Closure%29\" rel=\"nofollow\"><code>eachPermutation</code></a> method to avoid building the set of permutations in memory.</p>\n\n<p>That said, with 16 positions there will be about 2 billion permutations. You might want to think about a more efficient algorithm. I think this problem is an instance of the <a href=\"https://en.wikipedia.org/wiki/Assignment_problem\" rel=\"nofollow\">Assignment problem</a>. The <a href=\"https://en.wikipedia.org/wiki/Hungarian_algorithm\" rel=\"nofollow\">Hungarian algorithm</a> can solve this using a matrix of values of size <code>players</code> * <code>positions</code>, instead of the factorial of <code>positions</code>.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-03-05T18:37:57.607", "Id": "9724", "ParentId": "9723", "Score": "0" } }, { "body": "<p>If you have always at most 4 player and the number of positions is smaller than 100 (like your 16 start positions), then checking all possible position and players takes 100<sup>4</sup>, which is small enough. but if you looking for faster solution (harder implementation) You can use <a href=\"http://en.wikipedia.org/wiki/Edmonds%27s_matching_algorithm#Weighted_matching\" rel=\"nofollow\">Maximum Weighted Matching by Edmound</a>, First you should create a graph, you can draw graph, by setting </p>\n\n<pre><code>Vertices = players position Union available position as nodes.\nEdges = draw edge between each player and all available positions\n</code></pre>\n\n<p>For setting weight to edges you should do it in reverse, In fact first find the maximum distance (between all possible (player , position) pair, name it MaxDistance, now set your graph edges as MaxDistance - EdgeDistance + 1, here EdgeDistance is distance between player and desired position. </p>\n\n<p>You can find good implementation of Edmond's algorithm in c++ in <a href=\"http://lemon.cs.elte.hu/trac/lemon\" rel=\"nofollow\">Lemon package</a>.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-03-05T19:23:48.737", "Id": "9725", "ParentId": "9723", "Score": "2" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-03-05T17:19:33.803", "Id": "9723", "Score": "1", "Tags": [ "algorithm", "groovy" ], "Title": "Groovy: permutations() with size limit" }
9723
<p>I needed to create a method that would sanitize DOM IDs based on the HTML 4 criteria (yeah, HTML 5 is a lot looser). Does this make sense? Did I get too cute with making it concise? Am I totally misinterpreting what a DOM id is? I presumed it meant something like <code>&lt;p id="annoying_paragraph"&gt;&lt;/p&gt;</code>.</p> <pre><code>def sanitize_dom_id(candidate_id) #The HTML 4.01 spec states that ID tokens must begin with a letter ([A-Za-z]) and may be followed by any number of letters, digits ([0-9]), #hyphens (-), underscores (_), colons (:), and periods (.). prefix = candidate_id.slice!(0) #replace invalid prefix with Z_ prefix = "Z_" if [/[a-zA-Z]/].nil? #replace invalid internal characters with underscore "_" candidate_id.gsub!(/[^a-zA-Z0-9\.:_-]/,"_") "#{prefix}#{candidate_id}" end </code></pre> <p>Sample input and output:</p> <blockquote> <pre class="lang-none prettyprint-override"><code>sanitize_dom_id("1htmlid") Should result with "Z_htmlid" sanitize_dom_id("html id") Should result with "html_id" </code></pre> </blockquote>
[ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-03-06T14:05:48.633", "Id": "15455", "Score": "0", "body": "are you using Rails? You know there is such helpers in Rails?" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-03-07T13:44:50.133", "Id": "15482", "Score": "0", "body": "@jipiboily.com Can you link to them?" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-03-07T18:44:51.453", "Id": "15507", "Score": "1", "body": "@Cygal The helper he mentioned just returns the same id entered. I am working on the TODO to add in the cleansing process to the helper he brings up" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-03-07T18:08:40.850", "Id": "208125", "Score": "0", "body": "There is this exact method in Rails: [sanitize_dom_id](http://api.rubyonrails.org/classes/ActionController/RecordIdentifier.html#method-i-sanitize_dom_id)" } ]
[ { "body": "<p>Here is my implementation, the early return and extra variable are probably a matter of taste. \nThat early return doesn't feel idiomatic.</p>\n\n<p>It attempts to remove invalid characters at the start of the candidate_id, until it finds valid ones. It will only prefix if it can't find a valid id somewhere in the candidate.</p>\n\n<pre><code>def sanitize_dom_id(candidate_id)\n # Replace non-ascii chars with an ascii version\n # See ActiveSupport::Inflector#transliterate\n sanitized_id = transliterate(candidate_id)\n\n # Replace invalid characters with underscore \"_\"\n sanitized_id.gsub!(/[^a-zA-Z0-9\\.:_-]/,\"_\")\n\n # Remove invalid (non Alpha) leading characters \n valid_id = sanitized_id.gsub(/^[^a-zA-Z]+/, '')\n\n return valid_id unless valid_id.empty?\n\n # Prefix the ID with a known valid prefix.\n \"n_\" + sanitized_id\nend\n</code></pre>\n\n<p>Example output.</p>\n\n<pre><code>\"100-1012foo foo-bar f-=-=- ba9 --dash 9999 66-66\".split.map {|id| sanitize_dom_id id }\n&gt;&gt; [\"foo\", \"foo-bar\", \"f-_-_-\", \"ba9\", \"dash\", \"n9999\", \"n66-66\"]\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-03-13T12:30:20.840", "Id": "15860", "Score": "0", "body": "About the early return: why don't you declare a prefix like it has been done in the question?" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-03-13T13:22:28.883", "Id": "15874", "Score": "0", "body": "I could probably replace the last 2 lines with a ternary operator, but I dont think it would be as clear.\n\nvalid_id.empty? ? \"n_\" + sanitized_id : valid_id" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-03-13T13:28:14.753", "Id": "15877", "Score": "0", "body": "What about the same thing with if/else? :)" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-03-15T00:35:34.450", "Id": "15981", "Score": "0", "body": "On second thought, I think I prefer the early return, but that it also a matter of taste. Using if/else to determine a return value, but without an explicit return always throws me." } ], "meta_data": { "CommentCount": "4", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-03-13T12:13:30.597", "Id": "9961", "ParentId": "9730", "Score": "2" } }, { "body": "<p>I don't believe that your <code>'Z_'</code> prefix replacement works: <code>[/[a-zA-Z]/]</code> is an array consisting of one <code>Regexp</code>, and that array is never <code>nil</code>.</p>\n\n<p>Your implementation using <code>#slice!</code> is tricky to follow. I suggest writing it this way:</p>\n\n<pre><code>def sanitize_dom_id(name)\n # http://www.w3.org/TR/html4/types.html#type-name\n #\n # ID and NAME tokens must begin with a letter ([A-Za-z]) and\n # may be followed by any number of letters, digits ([0-9]),\n # hyphens (\"-\"), underscores (\"_\"), colons (\":\"), and periods (\".\").\n name.sub(/\\A[A-Z]/i, 'Z_').gsub(/[^A-Z0-9.:_-]/i, '_')\nend\n</code></pre>\n\n<p>Note that inside a character class, <code>.</code> is taken literally and does not need to be preceded by a backslash.</p>\n\n<p>You haven't explained why you need this function, which makes it hard to assess whether it is suitably designed. I'd like to point out that it is possible for multiple input strings to map to the same sanitized output. That might be an undesirable property — in which case you should think of this more as an escaping function than a sanitizing function.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2015-12-03T01:59:11.163", "Id": "112693", "ParentId": "9730", "Score": "0" } } ]
{ "AcceptedAnswerId": "9961", "CommentCount": "4", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-03-05T21:49:54.117", "Id": "9730", "Score": "2", "Tags": [ "ruby", "html", "ruby-on-rails", "regex", "dom" ], "Title": "Sanitize DOM IDs" }
9730
<p>Super-duper javascript noob here. I'm trying to fetch public repos from GitHub, and add them to a dl. I know this won't work on every website due to cross-site scripting, but GitHub offers a JSON-P API. I'm fairly certain that I'm doing this mostly the right way (it works), but the append function looks ugly, and I'm not sure if the way I'm triggering the script is considered best practice.</p> <p>gh-project.js:</p> <pre><code>function get_github_public_repos(username) { var the_url = "https://api.github.com/users/" + username + "/repos" $.ajax({ url: the_url, dataType: 'jsonp', type: 'get', success: function(data) { for(i = 0; i &lt; data.data.length; i++){ var repo = data.data[i]; if (!repo.fork) { $('#gh-projects').append("&lt;dt&gt;&lt;a href='" + repo.url +"' title='" + repo.name + "'&gt;" + repo.name + "&lt;/a&gt;" + "&lt;/dt&gt;" + "&lt;dd class='project-description'&gt;" + repo.description + "&lt;/dd&gt;" ); } } } }); } </code></pre> <p>projects.html:</p> <pre><code> &lt;!-- snip --&gt; &lt;dl class="project-list" id="gh-projects"&gt; &lt;!-- To be filled in by Javascript. Hooray! --&gt; &lt;/dl&gt; &lt;/section&gt; &lt;script src="/js/gh-projects.js"&gt;&lt;/script&gt; &lt;script&gt;get_github_public_repos('gfontenot')&lt;/script&gt; &lt;!-- end of file --&gt; </code></pre> <p>Thanks for the pointers.</p>
[]
[ { "body": "<p>Looks fine dude,</p>\n\n<p>Peronsal pref, although like you I am NO javascript guru, however...</p>\n\n<pre><code>(function($){\n\n var GIt = {\n init: function(){\n this.get_repo_list();\n },\n get_repo_list : function(){\n\n var uri = \"https://api.github.com/users/\", \n loadRepo = function(u){\n var u= (u) ? u: 'default';\n $.ajax({\n url: uri + u + '/repos',\n dataType : 'jsonp',\n type : 'GET',\n success : function(callback){\n var dl = $(\"#gh-projects\"),\n elem = '...';\n\n //Use Jquery tmpl maybe?\n ...dl.append(elem);\n }\n });\n }\n loadRepo('username');\n }\n }\n\n $(function(){\n GIT.init();\n })\n})(jQuery)\n</code></pre>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-03-06T02:20:34.070", "Id": "9733", "ParentId": "9732", "Score": "1" } }, { "body": "<p>Your code looks good, and I'm not going to suggest comestic changes. However:</p>\n\n<ol>\n<li><code>the_url</code> is not informative enough, try to find a variable that conveys that this url will let you fetch the repositories of an user.</li>\n<li>Did you consider that <code>repo.name</code> could contain a <code>'</code> which would cause you to output wrong html? Fortunately, GitHub prevents such things to happen.</li>\n<li>Declare <code>var i;</code> at the top of your <code>success</code> function. <a href=\"https://developer.mozilla.org/en/JavaScript/Reference/Statements/var#var_hoisting\" rel=\"nofollow\">Here's why</a>.</li>\n<li><p>The way you're building your html string is dangerous. It's also hard to read and easy to get wrong.</p>\n\n<p>As Philip suggested, using some sort of template would be a good idea, but there's no way to do this in standard jQuery (<a href=\"http://api.jquery.com/category/plugins/templates/\" rel=\"nofollow\">jQuery templates</a> have been deprecated, and the way forward seems to be <a href=\"https://github.com/BorisMoore/jsrender\" rel=\"nofollow\">JsRender</a> which is not yet Beta). Fortunately, your code is not big enough for you to need that. Instead, use <code>attr()</code>, <code>text()</code> and <code>addClass()</code> wisely:</p>\n\n<pre><code>var dt = $('&lt;dt&gt;').attr('href', repo.url).attr('title', repo.name).text(repo.name);\nvar dd = $('&lt;dd&gt;').addClass('project-description').text(repo.description);\n$('#gh-projects').append(dt).append(dd);\n</code></pre></li>\n</ol>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-03-08T00:39:45.313", "Id": "15540", "Score": "0", "body": "Just realized, the `dt` var doesn't allow for a link. What's the best way to add an `a` tag into that `dt`?" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-03-08T00:46:23.917", "Id": "15541", "Score": "0", "body": "Would `var a = $('<a>').attr('href', repo.url).attr('title', repo.name).text(repo.name);` and then `var dt = $('<dt>').append(a);` be the right way to handle this?" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-03-08T05:53:18.187", "Id": "15552", "Score": "1", "body": "Sounds good! You definitely need an <a>." } ], "meta_data": { "CommentCount": "3", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-03-06T08:41:53.593", "Id": "9740", "ParentId": "9732", "Score": "3" } } ]
{ "AcceptedAnswerId": "9740", "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-03-06T01:54:20.207", "Id": "9732", "Score": "2", "Tags": [ "javascript", "jquery", "ajax" ], "Title": "Fetching data via jquery and adding items to a list" }
9732
<p>I am designing a class which (among other things) acts as a vertex in an undirected graph.</p> <pre><code>#include &lt;iterator&gt; #include &lt;string&gt; class Node { public: explicit Node(const std::string&amp; name); Node(const Node&amp;); Node(Node&amp;&amp;); class iterator : public std::iterator&lt;std::random_access_iterator_tag, const Node&gt; { //... }; class container_proxy { public: iterator begin() const; iterator end() const; private: //... }; container_proxy neighbors() const; add_link(Node&amp; other); //... private: //... }; // to support: for (const Node&amp; neighbor : node.neighbors()) Node::iterator begin(const Node::container_proxy&amp;); Node::iterator end(const Node::container_proxy&amp;); </code></pre> <p>Now I want to define a function <code>link_complete</code> which:</p> <ul> <li>takes any number of arguments</li> <li>allows non-<code>const</code> <code>Node</code> lvalues (parameter type <code>Node&amp;</code>)</li> <li>allows non-<code>const</code> <code>Node</code> rvalues (parameter type <code>Node&amp;&amp;</code>)</li> <li>does not allow any other parameter type.</li> </ul> <p>An example usage:</p> <pre><code>Node ret_by_value(); void example_test(Node&amp; x, Node&amp;&amp; y) { link_complete(x, ret_by_value(), std::move(y), Node("test")); } </code></pre> <p>Here's the solution I came up with:</p> <pre><code>#include &lt;initializer_list&gt; #include &lt;type_traits&gt; class Node { //... public: static void link_complete(std::initializer_list&lt;Node*&gt; node_list); }; template &lt;typename ... Types&gt; struct template_all; // UNDEFINED template &lt;&gt; struct template_all&lt;&gt; : public std::true_type {}; template &lt;typename ... Types&gt; struct template_all&lt;std::false_type, Types...&gt; : public std::false_type {}; template &lt;typename ... Types&gt; struct template_all&lt;std::true_type, Types...&gt; : public template_all&lt;Types...&gt;::type {}; template &lt;typename ... Args&gt; auto link_complete(Args&amp;&amp; ... args) -&gt; typename std::enable_if&lt; template_all&lt; typename std::is_same&lt; typename std::remove_reference&lt;Args&gt;::type, Node &gt;::type ... &gt;::value, void &gt;::type { Node::link_complete( { &amp;args... } ); } </code></pre> <p>It seems to work as required, but I'm wondering if there was a simpler or "prettier" way to do it, or maybe a way to improve that <code>template_all</code> helper type. All C++11, TR1, and Boost features are welcome. I did notice <a href="http://www.boost.org/doc/libs/1_49_0/libs/mpl/doc/refmanual/and.html"><code>boost::mpl::and_</code></a> looks similar to my <code>template_all</code> helper type, but Boost MPL seems like a tricky learning curve and/or overkill for this problem.</p>
[]
[ { "body": "<h1><code>struct</code> has <code>public</code> inheritance</h1>\n\n<p>By default, <code>struct</code> has <code>public</code> inheritance. Therefore, you don't need to manually specify it every time. You can write shorter (and so more readable) code:</p>\n\n<pre><code>template &lt;&gt;\nstruct template_all&lt;&gt;\n : std::true_type {};\n\ntemplate &lt;typename ... Types&gt;\nstruct template_all&lt;std::false_type, Types...&gt;\n : std::false_type {};\n\ntemplate &lt;typename ... Types&gt;\nstruct template_all&lt;std::true_type, Types...&gt;\n : template_all&lt;Types...&gt;::type {};\n</code></pre>\n\n<p>Since type traits generally use many templates, you don't want to add even more extra keywords all over the place.</p>\n\n<h1>Use alias templates</h1>\n\n<p>If you have acces to a compiler that supports some C++14 features, you will probably want to use the alias templates for transformation traits to get rid of many <code>typename</code> and <code>::type</code>. Unfortunately, the alias templates for the query traits (<code>is_*</code>) have not been accepted, so you have to use <code>std::is_same</code>.</p>\n\n<pre><code>template &lt;typename ... Args&gt;\nauto link_complete(Args&amp;&amp; ... args) -&gt;\n std::enable_if_t&lt;\n template_all&lt;\n typename std::is_same&lt;\n std::remove_reference_t&lt;Args&gt;,\n Node\n &gt;...\n &gt;::value,\n void\n &gt;\n{\n Node::link_complete( { &amp;args... } );\n}\n</code></pre>\n\n<h1><code>static_assert</code> is great</h1>\n\n<p>Instead of using SFINAE for <code>link_complete</code>, you should use <code>static_assert</code> since your function does not have any overload. It will allow you to give a meaningful error message instead of a somewhat obscure SFINAE error message:</p>\n\n<pre><code>template &lt;typename ... Args&gt;\nvoid link_complete(Args&amp;&amp; ... args)\n{\n\n static_assert(\n template_all&lt;\n typename std::is_same&lt;\n std::remove_reference_t&lt;Args&gt;,\n Node\n &gt;::type...\n &gt;::value,\n \"link_complete arguments must be of the type Node\"\n );\n\n Node::link_complete( { &amp;args... } );\n}\n</code></pre>\n\n<h1>You may want to use <a href=\"http://en.cppreference.com/w/cpp/types/decay\" rel=\"nofollow\"><code>std::decay</code></a></h1>\n\n<p><code>std::decay</code> calls <code>std::remove_reference</code> and <code>std::remove_cv</code> internally. If needed, it also calls <code>std::remove_extent</code> if <code>T</code> is an array type and calls <code>std::add_pointer</code> if <code>T</code> is a function type. In short:</p>\n\n<blockquote>\n <p>This is the type conversion applied to all function arguments when passed by value.</p>\n</blockquote>\n\n<p>That allows you to check for what we generally think of as \"same types\":</p>\n\n<pre><code>template &lt;typename ... Args&gt;\nvoid link_complete(Args&amp;&amp; ... args)\n{\n\n static_assert(\n template_all&lt;\n typename std::is_same&lt;\n std::decay_t&lt;Args&gt;,\n Node\n &gt;::type...\n &gt;::value,\n \"link_complete arguments must be of the type Node\"\n );\n\n Node::link_complete( { &amp;args... } );\n}\n</code></pre>\n\n<h1>Rethink <code>template_all</code></h1>\n\n<p>All in all, your goal is to test boolean conditions on types. Since the query traits have a <code>static constexpr bool value</code> member, you may want to create a <code>template_all</code> that checks for <code>true</code> and <code>false</code> (like <code>std::enable_if</code> or <code>std::conditional</code>) instead of checking for <code>std::true_type</code> and <code>std::false_type</code>. That would make your intent clearer, but it would be more like a <code>all_true</code> template.</p>\n\n<pre><code>template &lt;bool...&gt;\nstruct all_true; // UNDEFINED\n\ntemplate &lt;&gt;\nstruct all_true&lt;&gt;\n : std::true_type {};\n\ntemplate &lt;bool... Conds&gt;\nstruct all_true&lt;false, Conds...&gt;\n : std::false_type {};\n\ntemplate &lt;bool... Conds&gt;\nstruct all_true&lt;true, Conds...&gt;\n : all_true&lt;Conds...&gt; {};\n\ntemplate &lt;typename ... Args&gt;\nvoid link_complete(Args&amp;&amp; ...)\n{\n static_assert(\n all_true&lt;\n std::is_same&lt;\n std::decay_t&lt;Args&gt;,\n Node\n &gt;::value...\n &gt;::value,\n \"must have Node types\"\n );\n\n Node::link_complete( { &amp;args... } );\n}\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-05-29T18:54:56.397", "Id": "90064", "Score": "0", "body": "Thanks for the detailed look. I specifically don't want to `remove_cv` in this case. Omitting base class access rubs my style-meter the wrong way, but that's mostly preference. I like `all_true` (and can't really remember why I thought using type parameters was a good idea at the time)." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-05-29T18:57:32.667", "Id": "90066", "Score": "0", "body": "@aschepler I tend to consider that `class` or `struct` is enough to document `public`/`private` access, but I have to admit that beginners simply don't know the difference, so explicitly specifying it isn't bad either ^^" } ], "meta_data": { "CommentCount": "2", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-05-23T14:29:09.800", "Id": "51533", "ParentId": "9736", "Score": "6" } } ]
{ "AcceptedAnswerId": "51533", "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-03-06T03:22:44.717", "Id": "9736", "Score": "12", "Tags": [ "c++", "c++11", "graph", "template-meta-programming", "variadic" ], "Title": "Variadic function with restricted types" }
9736
<p>I'm a ruby programmer who's writing Java for university. I'd love to get some feedback on how my Java looks and how to improve it to conform with the norms.</p> <pre><code>import java.util.Set; import java.util.HashSet; import java.util.List; import java.util.ArrayList; public class Cell { private Set&lt;Integer&gt; possibles; private List&lt;CellGroup&gt; groups; public Cell() { this.possibles = new HashSet&lt;Integer&gt;(java.util.Arrays.asList(1,2,3,4,5,6,7,8,9)); this.groups = new ArrayList&lt;CellGroup&gt;(); } public void register_cell_group(CellGroup group) { this.groups.add(group); } public void set(Integer number) { // Make the only possibile the set number this.possibles = new HashSet&lt;Integer&gt;(); this.possibles.add(number); this.inform_groups(); } public void not(Integer number) { this.possibles.remove(number); if (this.possibles.size() == 1) { this.inform_groups(); } } public boolean is_solved() { return this.possibles.size() == 1; } private void inform_groups() { for (int i = 0; i &lt; this.groups.size(); i++) { this.groups.get(i).cell_solved(this, this.possibles.toArray(new Integer[0])[0]); } } } </code></pre>
[ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-03-06T09:04:45.483", "Id": "15439", "Score": "2", "body": "Additionally to Cygal's comments you should stick with Java naming conventions. Especially you should use camelCase for methods (underscores in names are only used in `static final`\"constants\" like `MAX_VALUE`)" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-03-06T11:19:41.577", "Id": "15442", "Score": "0", "body": "Yeah, just getting my head around the new naming conventions." } ]
[ { "body": "<p><em>Edit:</em> As Landei suggested, use camelCase! Thanks Landei.</p>\n\n<ol>\n<li>Your <code>set</code> function does not need to take an Integer. Idiomatic code would only use an <code>int</code>. Autoboxing means you can still add an int to <code>this.possibles</code>.</li>\n<li>Why don't you use <code>is_solved</code> in <code>not</code>?</li>\n<li><code>not</code> is surprising, and I need to read the code to know what it does. I'd suggest naming it <code>remove</code>?</li>\n<li>What about <code>this.possibles.iterator().next()</code> instead of the <code>toArray</code> trick?</li>\n<li><p>Use a for each statement in <code>inform_groups</code>:</p>\n\n<pre><code>for(CellGroup g : this.groups) {\n g.cell_solved(this, this.possibles.iterator().next());\n}\n</code></pre></li>\n</ol>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-03-06T08:52:18.790", "Id": "9741", "ParentId": "9738", "Score": "5" } }, { "body": "<p>I know this is a little bit late but I figured that code reviews never go out of style. Below I have rewritten this class to be slightly more idomatic Java - here are some of the highlights:</p>\n\n<ol>\n<li>Always prefer final variables, hence the set and list being changed to final</li>\n<li>Don't need to use the 'this' keyword as this is the implied scope. Though you should use it if it you have another variable in scope with the same name, as often is the case with setters. Because I edit Java in an IDE and the syntax colorer highlights fields different from other items I find 'this' to be too noisy.</li>\n<li>Camel Cased names that have a noun-verb arrangement. Typically java class methods are of the form verbNoun like setValue.</li>\n<li>Java does have a for-each looping construct so I made use of it in the list traversal in informGroups as it didn't appear that 'i' was used for anything other than list access.</li>\n<li>The only tricky thing I saw was in the inform_groups method which may have indeterminate behavior. Toda you are assuming that in this method that the list size is exactly one. In fact this is a necessary condition for this behavior of this method to be correct. Unfortunately, you call this method from two different places and will undoubtedly come back to this class one day and make a change that will call inform_groups when the possibles set size is > 1. Therefore I would add an assertion at the beginning of the method to document and verify this important precondition. </li>\n</ol>\n\n<p>As a side note, in Java you are not guaranteed the order of the array that is produced to by toArray so the so the 0 index may be different each time you run this. There are ordered sets in Java like TreeSet which can give you better predictability here. </p>\n\n<p>Overall this was a nice simple class and I liked it, your methods are nice and short, and so this class is fairly testable. </p>\n\n<p>You may consider whether or not it is worth passing the possible values into the constructor so as to avoid hardcoding them if you decide to change the range. </p>\n\n<p>Also, in the inform_groups method you are passing two pieces of state to the group, including the cell itself, which begs the question: why not just pass the cell and have a method called getSolvedValue which will return the solved value perhaps then you could get away with implementing a simpler interface? </p>\n\n<p>Finally, it looks like the only use for the group is to call cellSolved and what you really have here is a listener/observer pattern. To avoid passing too much responsibility around in the form of a whole CellGroup, consider having the CellGroup implement an interface like CellSolveListener with exactly one method: cellSolved(Cell cell). And your registration method looks like registerSolveListener(CellSolvedListener listener). This documents clearly the contract between the two Objects, makes sure you are only passing around the responsibility you need and as a bonus Objects other than the CellGroup can now listen for changes.</p>\n\n<pre><code>import java.util.ArrayList;\nimport java.util.Arrays;\nimport java.util.HashSet;\nimport java.util.List;\nimport java.util.Set;\n\npublic class Cell\n{\n private final Set&lt;Integer&gt; possibles = new HashSet&lt;Integer&gt;();\n private final List&lt;CellGroup&gt; groups = new ArrayList&lt;CellGroup&gt;();\n\n public Cell()\n {\n possibles.addAll( Arrays.asList( 1, 2, 3, 4, 5, 6, 7, 8, 9 ) );\n }\n\n public void registerCellGroup( CellGroup group )\n {\n groups.add( group );\n }\n\n public void setValue( Integer number )\n {\n possibles.clear();\n possibles.add( number );\n informGroups();\n }\n\n public void removeValue( Integer number )\n {\n possibles.remove( number );\n\n if ( isSolved() )\n {\n informGroups();\n }\n }\n\n public boolean isSolved()\n {\n return possibles.size() == 1;\n }\n\n private void informGroups()\n {\n assert possibles.size() == 1;\n for ( CellGroup group : groups )\n {\n group.cellSolved( this, possibles.iterator().next()); \n }\n }\n}\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-04-11T19:00:57.067", "Id": "17228", "Score": "0", "body": "Glad I could be of assistance. Good luck learning java!" } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-03-22T16:28:32.820", "Id": "10253", "ParentId": "9738", "Score": "3" } } ]
{ "AcceptedAnswerId": "10253", "CommentCount": "2", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-03-06T08:05:31.843", "Id": "9738", "Score": "2", "Tags": [ "java" ], "Title": "Experienced ruby programmer starting with Java" }
9738
<p>In the following code, <code>checkServerExists</code> function checks if the server exists in the vector. If it does, then the new message is directly pushed in the vector, otherwise a new thread is created and then the message is pushed in the vector.</p> <p>I need to know whether it makes sense to write the code, as I have done.</p> <pre><code>#include &lt;pthread.h&gt; #include &lt;stdio.h&gt; #include &lt;unistd.h&gt; #include &lt;vector&gt; #include &lt;string&gt; #include &lt;iostream&gt; pthread_mutex_t demoMutex = PTHREAD_MUTEX_INITIALIZER; pthread_cond_t conditionVariable = PTHREAD_COND_INITIALIZER; unsigned int condition = 0; struct serverInfo { unsigned int serverId; pthread_t threadId; std :: vector &lt;std :: string&gt; queue; }; std :: vector &lt;serverInfo&gt; serverInfoVector; void * printHello (void* threadId) { pthread_t *my_tid = (pthread_t *)threadId; pthread_mutex_lock (&amp;demoMutex); while (condition == 0) pthread_cond_wait (&amp;conditionVariable, &amp;demoMutex); unsigned int i = 0; char found = false; if (serverInfoVector.size () &gt; 0) { while ((i &lt; serverInfoVector.size ()) &amp;&amp; (found == false)) { if (pthread_equal (pthread_self(), serverInfoVector [i].threadId)) { found = true; break; } else i++; } } while ((found == true) &amp;&amp; (!serverInfoVector [i].queue.empty ())) { std :: cout &lt;&lt; "\nThread: " &lt;&lt; pthread_self () &lt;&lt; ", poped from queue: " &lt;&lt; serverInfoVector [i].queue.front () &lt;&lt; "\n"; serverInfoVector [i].queue.pop_back (); } pthread_mutex_unlock (&amp;demoMutex); pthread_exit (NULL); } void checkServerExists (unsigned int serverNumber, std :: string message) { unsigned int i = 0; char found = false; pthread_mutex_lock (&amp;demoMutex); if (serverInfoVector.size () &gt; 0) { while ((i &lt; serverInfoVector.size ()) &amp;&amp; (found == false)) { if (serverNumber == serverInfoVector [i].serverId) { found = true; break; } else i++; } } if (found == false) { // This server doesn't exist, so create a thread for it, create a queue for it, push the message in the corresponding queue. // Push the server number in the serverNumberArray. // Create a thread for it. pthread_t newThread; int returnValue; if ((returnValue = pthread_create (&amp;newThread, NULL, printHello, (void*) &amp;newThread)) != 0) { printf ("\nerror: pthread_create failed with error number %d", returnValue); } printf ("\nIn checkServerExists ()`: thread id %ld\n", newThread); // Push the message in its queue. serverInfo obj; obj.serverId = serverNumber; obj.threadId = newThread; obj.queue.push_back (message); serverInfoVector.push_back (obj); condition++; pthread_cond_signal (&amp;conditionVariable); pthread_mutex_unlock (&amp;demoMutex); } else { // This server exists, so lookup its thread and queue, push the message in the corresponding queue. printf ("\nIn else ()`: thread id %ld\n", serverInfoVector [i].threadId); serverInfoVector [i].queue.push_back (message); condition++; pthread_cond_signal (&amp;conditionVariable); pthread_mutex_unlock (&amp;demoMutex); } } int main () { checkServerExists (1, "anisha"); checkServerExists (2, "kaul"); checkServerExists (1, "sanjeev"); checkServerExists (2, "sharma"); for (unsigned int i = 0; i &lt; serverInfoVector.size (); i++) pthread_join (serverInfoVector [i].threadId, NULL); return 0; } </code></pre>
[]
[ { "body": "<p>Any function that is a callback from a C library must use the C ABI.<br>\nIf your code is C++ (as this is) then you <strong>MUST</strong> declare the callback function appropriately to make sure the compiler gets the correct ABI:</p>\n\n<pre><code>extern \"C\" void* printHello (void* threadId);\n</code></pre>\n\n<p>Correct usage of the signal:</p>\n\n<pre><code>while (condition == 0)\n pthread_cond_wait (&amp;conditionVariable, &amp;demoMutex);\n</code></pre>\n\n<p>But you never decrement the variable <code>condition</code>. Thus after the first thread is created it will always be true. Thus I would do this:</p>\n\n<pre><code>while (condition == 0)\n{\n // Note I always enclose the statement in {} what happens if pthread_cond_wait()\n // had been a macro? You can never trust all third party libraries so it\n // is better to be safe than struggle to find it with debugger.\n pthread_cond_wait (&amp;conditionVariable, &amp;demoMutex);\n}\n// Once you know it is your decrement.\n--condition;\n</code></pre>\n\n<p>Normally you use <code>pthread_exit();</code> if you are killing the thread deep inside the code. If it is directly inside the callback function then you can just return NULL. Also you must guard against exceptions propagating out of the callback (if they escape the application will terminate (usally: Its actually undefined what happens but I have found it usally terminates the whole application (not just the thread))).</p>\n\n<pre><code>void * printHello (void* threadId)\n{\n void* result = NULL;\n try\n {\n result = // Your code here\n }\n catch(std::exception const&amp; e) // Optional\n {\n // Log Exception\n std::cerr &lt;&lt; \"Exception: \" &lt;&lt; e.what() &lt;&lt; \"\\n\";\n }\n catch(...) // MUST have this one.\n {\n // Log Exception\n std::cerr &lt;&lt; \"Exception: Unknown(...)\\n\";\n }\n return result;\n}\n</code></pre>\n\n<p>You use lock/unlock pairs for the mutex. This is not exception safe. So I would create an object that will do the lock in the constructor and unlock in the destructor then use this to lock your mutexs. This will make your code more exception safe.</p>\n\n<pre><code>class MutexLocker\n{\n pthread_mutex_t&amp; mutex;\n MutextLocker(pthread_mutex_t&amp; mutex)\n : mutex(mutex)\n {\n pthread_mutex_lock(&amp;mutex);\n }\n ~MutexLocker()\n {\n pthread_mutex_unlock(&amp;mutex);\n }\n};\n</code></pre>\n\n<p>Your code may seem threeaded but it is still inherently serial. This is because each thread maintain the mutex for its whole life this it prevents new threads from being created. You should unlock the mutext as soon as you have finished initialization (or just use the lock when accessing global objects that may be mutated by the master thread).</p>\n\n<p>Also on thread startup you spend a lot of time finding your queue. Why not get the master thread to pass a pointer to the threads queue (via the void* parameter). Note the value you pass (the pthread_t pointer is not guranteed to be correctly filled out when the thread starts (it is only guranteed correct after pthread_create() returns which may be after the thread has started so it is not a good object to pass:</p>\n\n<p>What I would have done is:</p>\n\n<pre><code>struct serverInfo\n{\n unsigned int serverId;\n pthread_t threadId;\n\n // Make the queue a pointer\n // So even when this object is copied the queue is unaffected.\n // May want to use a smart pointer or something (needs slightly more thought).\n std::vector&lt;std::string&gt;* queue;\n};\n\n std::auto_ptr&lt;std::vector&lt;std::string&gt;&gt; queue = new std::vector&lt;std::string&gt;();\n // Pass a pointer to the queue to the thread.\n // Now the thread does not need to know or care about serverInfoVector\n // Which is good because this is being mutated by other people.\n pthread_create(&amp;newThread, NULL, printHello, queue.get()); // Add error code\n\n if (/* Everything OK */)\n {\n serverInfoVector.push_back(serverInfo(id, newThread, queue.release());\n }\n</code></pre>\n\n<h3>Minor Comments:</h3>\n\n<p>Add a constructor to you serverInfo class.</p>\n\n<pre><code>struct serverInfo\n{\n unsigned int serverId;\n pthread_t threadId;\n std :: vector &lt;std :: string&gt; queue;\n\n // Add this:\n serverInfo(unsigned int serverId, pthread_t threadId, std::string const&amp; message)\n : serverId(serverId),\n , threadId(threadId)\n {\n queue.push_back(message);\n }\n};\n</code></pre>\n\n<p>This will allow more readable code below.</p>\n\n<p>AS a personal preference I allways have my types begin with an uppercase letter. This helps me distinguish types from data in an easy way that is not intrusive. This becomes more important when you start playing with templates.</p>\n\n<p>Try and limit global variables.</p>\n\n<pre><code>std :: vector &lt;serverInfo&gt; serverInfoVector;\n</code></pre>\n\n<p>Easier to create these at the top level and then pass references to them around. If you have underlying functions that depend on global state it becomes really hard to test the code. In the long run it is best to pass everything as parameters then you can see exactly what the function depends on.</p>\n\n<p>This is a horrible variable name. Try searching for all occurrences of the variable <code>i</code> to see where it is. I understand it short for index. Why not use <code>index</code> or my favorite <code>loop</code>.</p>\n\n<pre><code>unsigned int i = 0;\n</code></pre>\n\n<p>This test seems unnesacery. If size is 0 then the while loop will just fail.</p>\n\n<pre><code>if (serverInfoVector.size () &gt; 0)\n{\n</code></pre>\n\n<p>I don't like the extra space you add around <code>::</code> makes the code seem less readable (probably because I am not used to the style). But I think <code>std::string</code> is just fine.</p>\n\n<p>This bit of code looks very familiar (is this not the same as above)</p>\n\n<pre><code>if (serverInfoVector.size () &gt; 0)\n{\n while ((i &lt; serverInfoVector.size ()) &amp;&amp; (found == false))\n {\n if (serverNumber == serverInfoVector [i].serverId)\n {\n found = true;\n break;\n }\n else\n i++;\n }\n}\n</code></pre>\n\n<p>Refactor common code into a function. This way if there is a bug in your code then you only need to fix the bug in a single location (this prevents cut/paste errors).</p>\n\n<p>Here is the point where the constructor will help:</p>\n\n<pre><code> // Push the message in its queue.\n serverInfo obj;\n obj.serverId = serverNumber;\n obj.threadId = newThread;\n obj.queue.push_back (message);\n serverInfoVector.push_back (obj);\n</code></pre>\n\n<p>This can now be written as:</p>\n\n<pre><code> serverInfoVector.push_back(serverInfo(serverNumber, newThread, message));\n</code></pre>\n\n<p>Seems like you have common code on both sides of the branch.</p>\n\n<pre><code>{\n // STUFF\n\n condition++;\n pthread_cond_signal (&amp;conditionVariable);\n pthread_mutex_unlock (&amp;demoMutex);\n}\nelse\n{\n // STUFF\n\n condition++;\n pthread_cond_signal (&amp;conditionVariable);\n pthread_mutex_unlock (&amp;demoMutex);\n}\n</code></pre>\n\n<p>This should be refactored out of the branches.</p>\n\n<p>You have implemented all this as a function.\nThat is called multiple times and uses some global data.</p>\n\n<pre><code>checkServerExists (1, \"anisha\");\ncheckServerExists (2, \"kaul\");\ncheckServerExists (1, \"sanjeev\");\ncheckServerExists (2, \"sharma\");\n</code></pre>\n\n<p>Personally I would implement this as an object (all the data internal to the object). Then call a method on the object to activate the new thread. This way nobody else can mess around with my data structures.</p>\n\n<pre><code>MultiThreadServer server;\nserver.AddJobToThreadWithID (1, \"anisha\");\nserver.AddJobToThreadWithID (2, \"kaul\");\nserver.AddJobToThreadWithID (1, \"sanjeev\");\nserver.AddJobToThreadWithID (2, \"sharma\");\n</code></pre>\n\n<p>Unfortunately I am not sure this is a good idea.</p>\n\n<pre><code>for (unsigned int i = 0; i &lt; serverInfoVector.size (); i++)\n pthread_join (serverInfoVector [i].threadId, NULL);\n</code></pre>\n\n<p>This is because the threads remove there object from serverInfoVector. There is a race condition here where you might access an element just as a thread removes it from the structure.</p>\n\n<p>Note: main() is special. If you do not provide a <code>return X</code> then C++ will implicitly add a <code>return 0</code> for you. Thus I always leave this out of main. Note: This ONLY applies to main you must return the correct value from all other functions.</p>\n\n<pre><code>return 0;\n</code></pre>\n\n<h3>Answers to follow comments:</h3>\n\n<blockquote>\n <p>you said: \"Normally you use pthread_exit(); if you are killing the thread deep inside the code.\" Why not join? Any special reasons for that?</p>\n</blockquote>\n\n<ul>\n<li>Return (in the callback function) is used when the thread wants to die of old age.</li>\n<li>pthread_exit() is used when a thread wants to commit suicide.</li>\n<li>pthread_join() is when a thread wants to wait for <code>a different</code> thread to die.</li>\n</ul>\n\n<blockquote>\n <p>You said: \"Also you must guard against exceptions propagating out of the callback\" You mean if there are errors the application may terminate, so we should properly handle exceptions?</p>\n</blockquote>\n\n<p>Yes. You must catch <strong>ALL</strong> exceptions before they leave the thread.</p>\n\n<blockquote>\n <p>You said: \"You use lock/unlock pairs for the mutex. This is not exception safe\" Couldn't understand this. You mean that I have written openly the lock API two times in two functions? Why is that not exception safe? – Anisha Kaul 9 hours ago</p>\n</blockquote>\n\n<p>This means there is a potential for your code to leave a mutex locked forever and your application will get stuck.</p>\n\n<pre><code> void myFunc()\n {\n pthread_mutex_lock(mutex)\n\n // WORK\n\n pthread_mutex_unlock(mutex);\n }\n</code></pre>\n\n<p>The above code is not exception safe. If the <code>WORK</code> part throws an exception then <code>mutex</code> will not be unlocked and other threads will become stuck waiting for it. The simple way to solve this is to use RAII (and the class I wrote above).</p>\n\n<pre><code> void myFunc()\n {\n MutexLocker lock(mutex)\n\n // WORK\n }\n</code></pre>\n\n<p>Now the mutex will always be unlocked when this method exits (even if there are exceptions) as the destructor of <code>lock</code> will be called when the function exits and this will unlock the mutex correctly.</p>\n\n<blockquote>\n <p>You said: \"This is because each thread maintain the mutex for its whole life this it prevents new threads from being created. You should unlock the mutext as soon as you have finished initialization (or just use the lock when accessing global objects that may be mutated by the master thread)\" Would you please edit my code to reflect this? AFAIK, we are supposed to keep the locks on till we complete the access to the shared data? So, in the printHello function I have kept the lock on while dealing with the queue. Is there some othe rway of doing the same?</p>\n</blockquote>\n\n<p>Yes <strong>you must</strong> keep the locks on while accessing the shared data.</p>\n\n<p>But you brake your own rules here:</p>\n\n<pre><code>for (unsigned int i = 0; i &lt; serverInfoVector.size (); i++)\n pthread_join (serverInfoVector [i].threadId, NULL);\n</code></pre>\n\n<p>Which as I noted above can lead to race conditions and crashes. But if you do lock it then the the application may never quit. Also your code locks the code so long that only one thread may ever execute at a time (so there seems no point in using threads). Sorry that was over blowing it a bit (you release the lock while waiting on the conditional so that is not completely true).</p>\n\n<p>This is an indication that too much of your data is shared. In my description above I explained how to remove the queue from the shared part of the structure (so each thread only sees the queue) and how <code>serverInfoVector</code> does not even need to be shared with the threads. Re-writting this is a major task and will require some work. Thus you only need a lock when adding/removing work from the queue associated with the thread.</p>\n\n<blockquote>\n <p>Also, in the checkserver function I have used mutex while inserting in the queue. How should I improve this?</p>\n</blockquote>\n\n<p>Just make sure it is exception safe.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-03-08T06:49:30.753", "Id": "15555", "Score": "0", "body": "You said: \"Normally you use pthread_exit(); if you are killing the thread deep inside the code.\" Why not join? Any special reasons for that?" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-03-08T06:53:36.643", "Id": "15556", "Score": "0", "body": "You said: \"Also you must guard against exceptions propagating out of the callback\" You mean if there are errors the application may terminate, so we should properly handle exceptions?" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-03-08T07:13:11.613", "Id": "15557", "Score": "0", "body": "You said: \"You use lock/unlock pairs for the mutex. This is not exception safe\" Couldn't understand this. You mean that I have written openly the lock API two times in two functions? Why is that not exception safe?" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-03-08T07:41:40.843", "Id": "15558", "Score": "0", "body": "You said: \"This is because each thread maintain the mutex for its whole life this it prevents new threads from being created. You should unlock the mutext as soon as you have finished initialization (or just use the lock when accessing global objects that may be mutated by the master thread)\" Would you please edit my code to reflect this? AFAIK, we are supposed to keep the locks on till we complete the access to the shared data? So, in the `printHello` function I have kept the lock on while dealing with the queue. Is there some othe rway of doing the same?" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-03-08T07:44:02.307", "Id": "15559", "Score": "0", "body": "Also, in the `checkserver` function I have used mutex while inserting in the queue. How should I improve this?" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-03-08T18:59:33.857", "Id": "15606", "Score": "0", "body": "@AnishaKaul: While I was refactoring. I notices one other mistake. You get the front_item in the queue with `serverInfoVector [i].queue.front()` but then you remove the last element with `serverInfoVector [i].queue.pop_back()` this will only work if you never have more than one element in the queue (which for this small test is probably true but will not work in real life)." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-03-12T10:12:32.083", "Id": "15779", "Score": "0", "body": "What is an ABI?" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-03-12T10:15:03.187", "Id": "15781", "Score": "0", "body": "You said: \"*But you never decrement the variable condition. Thus after the first thread is created it will always be true*\" but, if we use the broadcast signal and decrement the condition variable (after first thread wakes up) then how will the remaining threads waken up?" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-03-12T10:17:37.410", "Id": "15782", "Score": "0", "body": "Oh or perhaps we can set the condition variable to high number so that when it decrements, it doesn't get to 0 straightaway?" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-03-12T16:23:53.310", "Id": "15807", "Score": "0", "body": "@AnishaKaul: Both the child/master thread must have a lock to be in the region where the wait or the signal happen. Thus only one will be active. Thus when a thread wakes up it decrements the count (potentially to zero) but when the master get the lock it re-increments the counter before calling signal so the next thread will have a non zero counter. If the master does three signals then it will have also incremented counter three times. Thus it will take three threads waking up to decrement it back to zero. Always remember both these regions are protected by a single lock. See `QueInfo` below" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-05-14T10:27:18.160", "Id": "18836", "Score": "0", "body": "I had had to post here again to tell you that you've been too helpful. And I am thankful to you for that. I am yet studying all the things you pointed out. Will follow up here soon." } ], "meta_data": { "CommentCount": "11", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-03-06T18:46:45.430", "Id": "9759", "ParentId": "9739", "Score": "6" } }, { "body": "<p>This is what I would have done:</p>\n\n<pre><code>#include &lt;string&gt;\n#include &lt;map&gt;\n#include &lt;list&gt;\n#include &lt;iostream&gt;\n\n#include &lt;pthread.h&gt;\n</code></pre>\n\n<h3>Mutex Locker</h3>\n\n<p>Generic Exception safe mutext locker/unlocker</p>\n\n<pre><code>class MutextLocker\n{\n pthread_mutex_t&amp; mutex;\n public:\n MutextLocker(pthread_mutex_t&amp; mutex): mutex(mutex)\n {\n pthread_mutex_lock(&amp;mutex);\n }\n ~MutextLocker()\n {\n pthread_mutex_unlock(&amp;mutex);\n }\n};\n</code></pre>\n\n<h3>QueInfo:</h3>\n\n<p>Data used and manipulate by each thread.<br>\nBoth the main thread and the owning thread access this object so all access needs to controlled via locks.</p>\n\n<pre><code>class QueInfo\n{\n public:\n QueInfo()\n : noMoreWork(false)\n , threadStarted(false)\n {\n if (pthread_mutex_init(&amp;mutex, NULL) != 0)\n { throw int(1);\n }\n if (pthread_cond_init(&amp;cond, NULL) != 0)\n {\n pthread_mutex_destroy(&amp;mutex);\n throw int(2);\n }\n }\n ~QueInfo()\n {\n pthread_cond_destroy(&amp;cond);\n pthread_mutex_destroy(&amp;mutex);\n }\n bool getWorkItem(std::string&amp; item)\n {\n MutextLocker lock(mutex);\n\n while ((queue.size() == 0) &amp;&amp; (!noMoreWork))\n {\n pthread_cond_wait (&amp;cond, &amp;mutex);\n }\n bool result = false;\n if (queue.size() != 0)\n {\n item = queue.front();\n queue.pop_front();\n result = true;\n }\n return result;\n }\n void addMessage(std::string const&amp; item)\n {\n MutextLocker lock(mutex);\n queue.push_back(item);\n pthread_cond_signal(&amp;cond);\n }\n void finishedAdding()\n {\n MutextLocker lock(mutex);\n noMoreWork = true;\n pthread_cond_signal(&amp;cond);\n }\n\n // These two are accessed by ServerInfo but\n // never by the thread. This means we do not need\n // to lock on their use. But I am being lazy here \n // leaving them as public members.\n pthread_t threadId; // Being lazy here\n bool threadStarted; // these two are for use by ServerInfo\n private:\n pthread_mutex_t mutex;\n pthread_cond_t cond;\n bool noMoreWork;\n std::list&lt;std::string&gt; queue;\n};\n</code></pre>\n\n<h3>ServerInfo</h3>\n\n<p>Object that controls all threads.<br>\nKeeps a map of QueInfo objects. Each one represents a running thread.<br>\nOnly the main thread sees this data so no locking needed.</p>\n\n<pre><code>class ServerInfo\n{\n public:\n ~ServerInfo()\n {\n for (Cont::iterator loop = queue.begin(); loop != queue.end(); ++loop)\n {\n loop-&gt;second.finishedAdding();\n void* result;\n pthread_join(loop-&gt;second.threadId, &amp;result);\n }\n }\n\n void checkServerExists(unsigned int serverNumber, std::string const&amp; message);\n\n private:\n typedef std::map&lt;unsigned int, QueInfo&gt; Cont;\n Cont queue;\n};\n</code></pre>\n\n<h3>Callback function</h3>\n\n<p>Notice we pass a pointer to its own QueInfo object as a parameter.<br>\nOnly this thread and the main thread can see this object. But all access is guarded.</p>\n\n<pre><code>void* printHello(void* data)\n{\n QueInfo* myQueue = reinterpret_cast&lt;QueInfo*&gt;(data);\n\n std::string workItem;\n while(myQueue-&gt;getWorkItem(workItem))\n {\n std::cout &lt;&lt; \"\\nThread: \" &lt;&lt; pthread_self () &lt;&lt; \", poped from queue: \" &lt;&lt; workItem &lt;&lt; \"\\n\";\n }\n return NULL; // Return NULL on exit.\n}\n</code></pre>\n\n<h3>The main server adding threads.</h3>\n\n<pre><code>void ServerInfo::checkServerExists(unsigned int serverNumber, std::string const&amp; message)\n{\n QueInfo&amp; item = queue[serverNumber]; // If it does not exist it is inserted.\n item.addMessage(message);\n\n if (!item.threadStarted)\n {\n int returnValue;\n if ((returnValue = pthread_create (&amp;item.threadId,\n NULL,\n printHello,\n reinterpret_cast&lt;void*&gt;(&amp;item))) != 0)\n {\n std::cout &lt;&lt; \"\\nerror: pthread_create failed with error number \"&lt;&lt; returnValue;\n queue.erase(serverNumber);\n }\n else\n {\n item.threadStarted = true;\n }\n std::cout &lt;&lt; \"\\nIn checkServerExists ()`: thread id \" &lt;&lt; item.threadId &lt;&lt; \"\\n\";\n }\n else\n {\n std::cout &lt;&lt; \"\\nIn else ()`: thread id \" &lt;&lt; item.threadId &lt;&lt; \"\\n\";\n }\n}\n</code></pre>\n\n<h3>Main</h3>\n\n<p>Main is simplified as it does not even know about the threads.</p>\n\n<pre><code>int main ()\n{\n ServerInfo server;\n server.checkServerExists (1, \"anisha\");\n server.checkServerExists (2, \"kaul\");\n server.checkServerExists (1, \"sanjeev\");\n server.checkServerExists (2, \"sharma\");\n\n // Note ServerInfo destructor will wait for all the threads.\n}\n</code></pre>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-03-08T18:12:04.510", "Id": "9824", "ParentId": "9739", "Score": "1" } } ]
{ "AcceptedAnswerId": "9759", "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-03-06T08:08:03.120", "Id": "9739", "Score": "3", "Tags": [ "c++", "multithreading", "thread-safety", "pthreads" ], "Title": "Thread design for sending data to multiple servers" }
9739
<p>I am new to VB.NET and one of the functions I wrote is below. The idea behind it is to just send a dictionary and table name to the function, get the result and then return.</p> <p>Is this good practice or just silly?</p> <pre><code>Public Function dbInsert(ByRef EntryDetails As Dictionary(Of String, String),ByRef table as String) As Integer Dim command As new SqlCeCommand ' Loop over entries. Dim fieldNames() As String = {} Dim fieldsValues() As String = {} Dim pair As KeyValuePair(Of String, String) For Each pair In EntryDetails ReDim Preserve fieldNames(0 To UBound(fieldNames) + 1) fieldNames(UBound(fieldNames)) = pair.Key command.Parameters.AddWithValue("@" + pair.Key, pair.Value) Next command = New SqlCeCommand("INSERT INTO "+table+" (" + String.Join(",", fieldNames) + ")", connection.DbPublic) Dim newProdID As Int32 = 0 Try command.ExecuteNonQuery() Dim cmd As New SqlCeCommand("SELECT @@IDENTITY", conn) newProdID = Convert.ToInt32(cmd.ExecuteScalar()) 'Console.WriteLine("added: {0}", newProdID) Return newProdID Catch e As Exception Console.WriteLine("Unable to insert: {0}", e.Message) Return 0 End Try End Function </code></pre>
[ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-03-06T17:09:22.177", "Id": "15464", "Score": "2", "body": "Using `byref` parameters when not needed is bad practice." } ]
[ { "body": "<blockquote>\n <p>This approach is not much good, but may be suit your required functionality. The method name is dbInsert and you\n are passing table and data in dictionary. you can make it much better by using better naming convention and parameter types. </p>\n</blockquote>\n\n<p>On the place of this create a method with following parameter as:\n<code>GetIdentityOnInsert(string sqlQuery, CommandType commandType, SqlParameterCollection sqlParameters)</code></p>\n\n<p>query will be: <code>query = \"Insert into tableName value(@param1,@param2);SELECT @@IDENTITY;</code>\"</p>\n\n<hr>\n\n<pre><code>Public Function GetIdentityOnInsert(ByVal sqlQuery as String, ByVal commandType as Commandtype, ByVal sqlParameters as SqlParameterCollection) \nTry\nUsing connection As New SqlConnection(connectionString)\n\n ' Create the command and set its properties.\n Dim command As SqlCommand = New SqlCommand()\n command.Connection = connection\n command.CommandText = sqlQuery\n command.CommandType = commandType\n Dim parameter As New SqlParameter()\n\n For Each parameter In sqlParameters \n command.Parameters.Add(parameter);\n Next \n\n ' Open the connection and execute the reader.\n connection.Open()\n Dim newProdID As Int32 = 0\n ' try ExecuteScalar() if it gives error then replace it to ExecuteNonQuery()\n ' and replace the below code as in your question.\n newProdID = command.ExecuteScalar() \n\n 'Dim cmd As New SqlCeCommand(\"SELECT @@IDENTITY\", conn)\n 'newProdID = Convert.ToInt32(cmd.ExecuteScalar())\n 'Console.WriteLine(\"added: {0}\", newProdID)\n Return newProdID\n\nEnd Using\nCatch e As Exception\n Console.WriteLine(\"Unable to insert: {0}\", e.Message)\n Return 0\nEnd Try\nEnd Function\n</code></pre>\n\n<p>Hope this help you to create you Data Access Layer. you can extend <code>ExecuteNonQuery</code> with the above method.. just you have to customize little bit..</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-03-12T04:47:19.097", "Id": "15774", "Score": "0", "body": "that functionality doesn't work on Compact Edition 3.5" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-03-12T07:19:45.760", "Id": "15775", "Score": "0", "body": "why not.. it works same as i explored through these links: [link1](http://arcanecode.com/2007/01/29/inserting-rows-into-a-sql-server-compact-edition-table-in-c/), [link2](http://www.codeproject.com/Questions/198722/How-to-use-INSERT-statement-in-SQL-server-compact), [msdn link](http://msdn.microsoft.com/en-us/library/ms174633.aspx). this should work well.." } ], "meta_data": { "CommentCount": "2", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-03-06T12:50:19.340", "Id": "9746", "ParentId": "9742", "Score": "1" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "1", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-03-06T09:07:15.200", "Id": "9742", "Score": "1", "Tags": [ "vb.net" ], "Title": "General insert function" }
9742
<p>Here's the exercise in brief:</p> <blockquote> <p>Consider the following file: Code:</p> <p><em>before.csv</em></p> <pre><code>A; ; B; B; A; H; C; ; D; D; C; G; E; D; F; F; E; H; G; D; ; H; G; ; </code></pre> <p>And a modified version of the file: </p> <p><em>after.csv</em></p> <pre><code>A; ; B; B; A; H; C; ; D; D; ; G; E; D; F; F; E; H; G; D; ; K; ; E; </code></pre> <p>The first field of the CSV is a unique identifier of each line. The exercise consists of detecting the changes applied to the file, by comparing before and after.</p> <p>There are 3 types of changes you should detect:</p> <ul> <li>ADDED (line is present in after.csv but not in before.csv)</li> <li>REMOVED (line is present in before.csv but not in after.csv)</li> <li>MODIFIED (line is present in both, but second and/or third field are modified)</li> </ul> <p>In my example, there are three modifications:</p> <ul> <li>ADDED line (K)</li> <li>REMOVED line (H)</li> <li>MODIFIED line (D)</li> </ul> </blockquote> <p>And my code:</p> <pre><code>import collections import csv import sys class P_CSV(dict): '''A P_CSV is a dict representation of the csv file: {"id": dict(csvfile)} ''' fieldnames = ["id", "col2", "col3"] def __init__(self, input): map(self.readline, csv.DictReader(input, self.fieldnames, delimiter=";",\ skipinitialspace=True)) def readline(self, line): self[line["id"]] = line def get_elem(self, name): for i in self: if i == name: return self[i] class Change: ''' a Change element will be instanciated each time a difference is found'''. def __init__(self, *args): self.args=args def echo(self): print "\t".join(self.args) class P_Comparator(collections.Counter): '''This class holds 2 P_CSV objects and counts the number of occurrence of each line.''' def __init__(self, in_pcsv, out_pcsv): self.change_list = [] self.in_pcsv = in_pcsv self.out_pcsv = out_pcsv self.readfile(in_pcsv, 1) self.readfile(out_pcsv, -1) def readfile(self, file, factor): for key in file: self[key] += factor def scan(self): for i in self: if self[i] == -1: self.change_list.append(Change("ADD", i)) elif self[i] == 1: self.change_list.append(Change("DELETE", i)) else: # element exists in two files. Check if modified j = J_Comparator(self.in_pcsv.get_elem(i), self.out_pcsv.get_elem(i)) if len(j) &gt; 0: self.change_list += j class J_Comparator(list): '''This class compares the attributes of two lines and return a list of Changes object for every difference''' def __init__(self, indict, outdict): for i in indict: if indict[i] != outdict[i]: self.append(Change("MODIFY", indict["id"], i, indict[i], "BECOMES", outdict[i])) if len(self) == 0: self = None #Main p = P_Comparator(P_CSV(open(sys.argv[1], "rb")), P_CSV(open(sys.argv[2], "rb"))) p.scan() print "{} changes".format(len(p.change_list)) [c.echo() for c in p.change_list] </code></pre> <p>In real life, the code is supposed to compare two very large files (>6500 lines) with much more fields (>10).</p> <p>How can I improve, both the style of my programming as well as the performance of the script? For the record I'm using <strong>Python2.7</strong></p>
[ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-03-06T13:01:21.813", "Id": "15447", "Score": "0", "body": "Could you realy on the sorting of the `id`s? Because if you can I would suggest a different approach, i.e. parsing the two files side by side." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-03-06T13:09:23.667", "Id": "15448", "Score": "0", "body": "Sure, I'm listening :)" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-03-06T13:14:24.190", "Id": "15449", "Score": "0", "body": "Did you think about using diff?" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-03-06T13:28:06.583", "Id": "15450", "Score": "0", "body": "@rahmu: \"Sure\" means that the lines are sorted by ids?" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-03-06T13:29:43.317", "Id": "15451", "Score": "0", "body": "I would but this is only a part of a larger script I'm working on. I just spent 2 days improving the diff part, although there is so much more to the script. The `Change` class in particular will have multiple methods but that's beyond the scope of this code review. (I'm assuming you meant the Unix `diff` tool. If you meant some Python utility then please show me some link). Maybe you reckon I run `diff` on both files and pipe the output to my script?" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-03-06T13:36:24.573", "Id": "15453", "Score": "0", "body": "@RikPoggi: It means I'm willing to use `sort` on the lists if it improves the code/performance." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-03-06T13:43:01.090", "Id": "15454", "Score": "0", "body": "If the files are already sorted you can parse them line by line without csv and translate to dict only when `line_before != line_after`, then it's just a matter to write the right workflow to see which change difference there is. But if you have to load -> sort -> compare, then no, it would be slower then what you're doing." } ]
[ { "body": "<p>I think that a simpler approach could be using the two files \"indexes\" using list comprehensions. What I would propose:</p>\n\n<p>create an Id list for the before and after file, extracted for the CSV (as you already do)</p>\n\n<p>So you would end up with something like:</p>\n\n<pre><code>before = ['A','B','C','D','E','F','G','H']\nafter = ['A','B','C','D','E','F','G','K']\n</code></pre>\n\n<p>and then you can:</p>\n\n<pre><code>removed = [x for x in before if x not in after]\nadded = [x for x in after if x not in before]\n</code></pre>\n\n<p>Everything else looks well for me. Hope this helps!</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-03-06T12:56:06.493", "Id": "15446", "Score": "0", "body": "This would be perfectly clear, but wouldn't it be super slow? You parse the whole after file for each before entry AND THEN do the same the other way around! In my script you parse each file once and increment/decrement the counter accordingly. If the result is not 0, then you know there was a change." } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-03-06T12:50:14.790", "Id": "9745", "ParentId": "9744", "Score": "0" } }, { "body": "<h2>Implementation</h2>\n\n<ol>\n<li>The P_CSV trick is good idea.</li>\n<li>I don't know if \"input\" is supposed to be a file name, a string, a <code>file</code> object, and so on (this is Python's fault, but still). Please use a better name and document that it is a <code>file</code>.</li>\n<li>What does <code>{\"id\": dict(csvfile)}</code> mean in your docstring?</li>\n<li><code>get_elem</code> could be implemented with <code>return self.get(name, default=None)</code>. The way you're doing it is misleading, since you're relying on the fact that no <code>return</code> means <code>return None</code>.</li>\n<li>This means you can either remove <code>get_elem</code> or find a better name explaining that it's just like <code>get</code> except that it returns <code>None</code> instead of throwing an exception.</li>\n<li>I guess you want to use <code>__str__</code> in <code>Change</code>, and maybe <a href=\"https://stackoverflow.com/questions/1436703/difference-between-str-and-repr-in-python\"><code>__repr__</code></a> (but not <code>echo</code>).</li>\n<li>Do you really need <code>Change</code> as it is? Simply store lists in <code>change_list</code>, instead of <code>Change</code>s.</li>\n<li><code>readfile</code>? I'd say <code>readcsv</code> since it is no longer a file, but a <code>P_CSV</code>. If you have a more descriptive name of what those files contain, then use that instead.</li>\n<li>J_Comparator doesn't work as requested in the exercise, since it also says what columns were modified.</li>\n<li>Setting a list to <code>None</code> is wrong. \"No values\" is the empty list. You can then use <code>self.change_list.extend(j)</code> without needing to worry about the empty list. It's much more elegant.</li>\n<li>Why P and J for the comparators?</li>\n</ol>\n\n<h2>Performance</h2>\n\n<p>Performance is good: you're using a linear algorithm, even though you're going through the files twice. If you're worried about very very larges files that won't hold in memory, you can use the assumption that the files are sorted to advance in both files simultaneously, and make sure to always have the same unique id in both files. I don't think this is needed, 6000 lines is quite small!</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-03-06T13:34:45.603", "Id": "15452", "Score": "0", "body": "Thank you so much! I'll try to make my variable names clearer and more dscriptive. I'll also get rid of the `get_elem` method, I have just realized that P_CSV inherits from `dict` so I can access `in_pcsv[i]` directly. I should also consider raising exceptions in case it's empty. Also thank you for both the `__repr__` and `list.extend()` tips :)" } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-03-06T13:11:05.363", "Id": "9747", "ParentId": "9744", "Score": "2" } }, { "body": "<p>I'll start from the very first method of your code, and then we'll see how everything could be improved.</p>\n\n<p>Let's also start from a matter of syle, this line:</p>\n\n<pre><code>def __init__(self, input):\n map(self.readline, csv.DictReader(input, self.fieldnames, delimiter=\";\",\\\n skipinitialspace=True)) ^\n |\n there's no need for this\n</code></pre>\n\n<p>could just be:</p>\n\n<pre><code>def __init__(self, input):\n map(self.readline, csv.DictReader(input, self.fieldnames, delimiter=\";\",\n skipinitialspace=True))\n</code></pre>\n\n<p>Further style guides can be found in <a href=\"http://www.python.org/dev/peps/pep-0008/\" rel=\"nofollow\">PEP8</a>.<br>\nAlso that use of <code>map</code> seems hackish, it would be more clear this way:</p>\n\n<pre><code>def __init__(self, csvfile):\n for dct in csv.DictReader(csvfile, self.fieldnames, delimiter=\";\",\n skipinitialspace=True)):\n self.readline(dct)\n</code></pre>\n\n<p>I've also changed the argument name to <code>csvfile</code> to state clearer what that argument is and for not shadowing unecessary the built-in <code>input()</code>.</p>\n\n<p>But I'm sure you see that it still looks somehow ugly. Where the reasons are 2:</p>\n\n<ol>\n<li>You don't need the <code>readline</code> method, but the <code>dict</code> __init__</li>\n<li>You've subclassed the wrong dict.</li>\n</ol>\n\n<p>Yes, why don't subclass <code>csv.DictReader</code>? If you go and take a look into the source file <code>csv.py</code> you'll see that <code>DictReader</code> is actually quite a simple class, so maybe you could just copy what you need and write yours. The bare bone could be something like:</p>\n\n<pre><code>class IdDictReader:\n\n def __init__(self, fieldnames, *args, **kwargs):\n self.fieldnames = fieldnames\n self.reader = reader(f, dialect, *args, **kwds)\n self.dialect = dialect\n self.line_num = 0\n\n def __iter__(self):\n return self\n\n def next(self):\n row = self.reader.next()\n self.line_num = self.reader.line_num\n while row == []:\n row = self.reader.next()\n d = {row[0]: zip(self.fieldnames, row[1:]))\n return d\n</code></pre>\n\n<p>In the same way you'll need to write <code>IdDictWriter</code>.</p>\n\n<p>This alone will improve your performance a bit, but we haven't touched the core of you system yet.</p>\n\n<p>Now you should also lose the <code>P_Comparator</code> class, because a <code>Counter</code> seems fragile. I would go with <code>set</code>s.</p>\n\n<p>So let's say that <code>after</code> and <code>before</code> are two <code>dict</code> organaized exactly like you would (thanks to the <code>IdDictReader</code>):</p>\n\n<pre><code>before = {'B': {'col2': 'A', 'col2': 'H'}, ...}\nafter = { ...\nbefore_ids = set(before)\nafter_ids = set(after)\nadded = after_ids - before_ids\ndeleted = before_ids - after_ids\ncommon = before_ids &amp; after_ids\n</code></pre>\n\n<p>Now you'll just need to see which are changed:</p>\n\n<pre><code>for _id in common:\n if before[_id] != after[_id]:\n # ...\n</code></pre>\n\n<p><code>set</code>s in Python are very well implemented, so I'd say that you should see a considerable performance improvement. But when it comes to performances the only thing to do is time it and profile it and see what's best.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-03-07T12:58:31.063", "Id": "15481", "Score": "0", "body": "Thank you. I just replaced the Counter with `set`s. It works like a charm, although for my volume of files (6500+ lines, 10 fields) the performance gain is minimal (~1-2%) on my machine. What's wrong with my use of `map()`?" } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-03-06T14:48:15.820", "Id": "9753", "ParentId": "9744", "Score": "2" } }, { "body": "<p>Based on <a href=\"http://wiki.python.org/moin/TimeComplexity\" rel=\"nofollow\">http://wiki.python.org/moin/TimeComplexity</a> where the theoretical run-time is described as:</p>\n\n<ul>\n<li>List: x in s -> O(n) </li>\n<li>Set: x in s -> O(1) to O(n) # NB! Sets are immutable </li>\n<li>Dict: get item -> O(1) to O(n)</li>\n</ul>\n\n<p>...this is fastest diff function I could come up with, using O(1) as much as possible:</p>\n\n<pre><code>import sys # a bit superfluous if you delete the \"__main__\" part at the bottom.\n\ndef diff(before, after, delimiter=';'):\n # Here I use lists to main the ability to cycle through the set by position.\n oldlist=list(before.split(sep=delimiter))\n newlist=list(after.split(sep=delimiter))\n\n # Here I use sets to benefit from the O(k) lookup time.\n old=set(oldlist)\n new=set(newlist)\n\n inboth = old &amp; new # saves us from looking at a lot of redundant stuff.\n\n unchanged,added,removed,modified={},{},{},{} # I love multiple assignment.\n\n for index in range(len(oldlist)+len(newlist)):\n try:\n if newlist[index] in inboth:\n #print('\\t', newlist[index]) # uncomment to see diff.\n unchanged[index]=newlist[index]\n if newlist[index] not in old:\n #print('+:\\t', newlist[index]) # uncomment to see diff.\n added[index]=newlist[index]\n if oldlist[index] not in new:\n #print('-:\\t', oldlist[index]) # uncomment to see diff.\n removed[index]=oldlist[index]\n if index in added and index in removed:\n modified[index]=str(added.pop(index))+\"--&gt;\"+str(removed.pop(index))\n except IndexError:\n pass\n\n return unchanged,added,removed,modified\n\ndef main():\n if sys.version_info &lt;= (3, 2):\n sys.stdout.write(\"Sorry, requires Python 3.2.x, not Python 2.x\\n\")\n sys.exit(1)\n\n before= \"1;2;Bla;4;5;6;7;Bla2;8\"\n after = \"1;2;Bob;4;5;7;Bob2;8;9;10\"\n # modified Bla -&gt; Bob, Bla2 -&gt; Bob2\n # removed 6\n # added 9, 10\n unchanged, added, removed, modified = diff(before, after)\n print (\"-------------------\\n\",\n \"asis:\\t\",len(unchanged),\"\\n\",\n \"adds:\\t\",len(added),\"\\n\",\n \"rems:\\t\",len(removed),\"\\n\",\n \"mods:\\t\",len(modified))\n\nif __name__ == '__main__':\n main()\n</code></pre>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-03-04T19:45:24.953", "Id": "23454", "ParentId": "9744", "Score": "0" } } ]
{ "AcceptedAnswerId": "9747", "CommentCount": "7", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-03-06T12:14:25.140", "Id": "9744", "Score": "4", "Tags": [ "python", "performance", "python-2.x", "csv" ], "Title": "Comparing 2 CSV files" }
9744
<p>I had an interview recently where I was asked to produce the traditional FizzBuzz solution:</p> <blockquote> <p>Output a list of numbers from 1 to 100.</p> <ul> <li>For all multiples of 3 and 5, the number is replaced with "FizzBuzz"</li> <li>For all remaining multiples of 3, the number is replaced with "Fizz"</li> <li>For all remaining multiples of 5, the number is replaced with "Buzz"</li> </ul> </blockquote> <p>My solution was written in Java because of the role, but this was not a requirement. The interviewer was keen to see some evidence of TDD, so in that spirit I went about producing a FizzBuzz unit test:</p> <pre><code>public class FizzBuzzTest { @Test public void testReturnsAnArrayOfOneHundred() { String[] result = FizzBuzz.getResultAsArray(); assertEquals(100, result.length); } @Test public void testPrintsAStringRepresentationOfTheArray() { String result = FizzBuzz.getResultAsString(); assertNotNull(result); assertNotSame(0, result.length()); assertEquals("1, 2", result.substring(0, 4)); } @Test public void testMultiplesOfThreeAndFivePrintFizzBuzz() { String[] result = FizzBuzz.getResultAsArray(); // Check all instances of "FizzBuzz" in array for (int i = 1; i &lt;= 100; i++) { if ((i % 3) == 0 &amp;&amp; (i % 5) == 0) { assertEquals("FizzBuzz", result[i - 1]); } } } @Test public void testMultiplesOfThreeOnlyPrintFizz() { String[] result = FizzBuzz.getResultAsArray(); // Check all instances of "Fizz" in array for (int i = 1; i &lt;= 100; i++) { if ((i % 3) == 0 &amp;&amp; !((i % 5) == 0)) { assertEquals("Fizz", result[i - 1]); } } } @Test public void testMultiplesOfFiveOnlyPrintBuzz() { String[] result = FizzBuzz.getResultAsArray(); // Check all instances of "Buzz" in array for (int i = 1; i &lt;= 100; i++) { if ((i % 5) == 0 &amp;&amp; !((i % 3) == 0)) { assertEquals("Buzz", result[i - 1]); } } } } </code></pre> <p>My resulting implementation became:</p> <pre><code>public class FizzBuzz { private static final int MIN_VALUE = 1; private static final int MAX_VALUE = 100; private static String[] generate() { List&lt;String&gt; items = new ArrayList&lt;String&gt;(); for (int i = MIN_VALUE; i &lt;= MAX_VALUE; i++) { boolean multipleOfThree = ((i % 3) == 0); boolean multipleOfFive = ((i % 5) == 0); if (multipleOfThree &amp;&amp; multipleOfFive) { items.add("FizzBuzz"); } else if (multipleOfThree) { items.add("Fizz"); } else if (multipleOfFive) { items.add("Buzz"); } else { items.add(String.valueOf(i)); } } return items.toArray(new String[0]); } public static String[] getResultAsArray() { return generate(); } public static String getResultAsString() { String[] result = generate(); String output = ""; if (result.length &gt; 0) { output = Arrays.toString(result); // Strip out the brackets from the result output = output.substring(1, output.length() - 1); } return output; } public static final void main(String[] args) { System.out.println(getResultAsString()); } } </code></pre> <p>Self-examining what I originally submitted: </p> <ul> <li><p>Early on I decided to merge my "multiple of" calculation into the generate() method to avoid over-engineering, which I now think was a mistake</p></li> <li><p>The separate getResultAsArray/generate methods were clearly OTT. </p></li> <li><p>The getResultAsString could also be merged with the main() method, since one just delegates to the other.</p></li> <li><p>@APC on StackOverflow pointed out that my approach is not scalable, perhaps I should have better separated the logic from the string building?</p></li> </ul> <p>I'm still fairly inexperienced with TDD and I feel this may have let me down in this case. <strong>I'm looking for other ways I might have improved on this approach, particularly with regard to TDD practices?</strong></p> <p><em>This is cross-referenced from my <a href="https://stackoverflow.com/questions/9584065/ways-to-improve-my-fizzbuzz-solution-for-a-tdd-role">SO question</a>, since you can't move SO questions to Code Review, and someone pointed out that this is a better forum for this type of request. In retrospect, I should have come here in the first place!</em></p> <hr> <p>Based on the very useful suggestions on StackOverflow, I've reworked my answer to something I now consider would have been more "TDD-friendly". This is my second attempt at a solution:</p> <ul> <li><p>Separated the FizzBuzz logic from the output generation to make the solution more scalable</p></li> <li><p>Just one assertion per test, to simplify them</p></li> <li><p>Only testing the most basic unit of logic in each case</p></li> <li><p>A final test to confirm the string building is also verified</p></li> </ul> <p>The code:</p> <pre><code>public class FizzBuzzTest { @Test public void testMultipleOfThreeAndFivePrintsFizzBuzz() { assertEquals("FizzBuzz", FizzBuzz.getResult(15)); } @Test public void testMultipleOfThreeOnlyPrintsFizz() { assertEquals("Fizz", FizzBuzz.getResult(93)); } @Test public void testMultipleOfFiveOnlyPrintsBuzz() { assertEquals("Buzz", FizzBuzz.getResult(10)); } @Test public void testInputOfEightPrintsTheNumber() { assertEquals("8", FizzBuzz.getResult(8)); } @Test public void testOutputOfProgramIsANonEmptyString() { String out = FizzBuzz.buildOutput(); assertNotNull(out); assertNotSame(0, out.length()); } } public class FizzBuzz { private static final int MIN_VALUE = 1; private static final int MAX_VALUE = 100; public static String getResult(int input) { boolean multipleOfThree = ((input % 3) == 0); boolean multipleOfFive = ((input % 5) == 0); if (multipleOfThree &amp;&amp; multipleOfFive) { return "FizzBuzz"; } else if (multipleOfThree) { return "Fizz"; } else if (multipleOfFive) { return "Buzz"; } return String.valueOf(input); } public static String buildOutput() { StringBuilder output = new StringBuilder(); for (int i = MIN_VALUE; i &lt;= MAX_VALUE; i++) { output.append(getResult(i)); if (i &lt; MAX_VALUE) { output.append(", "); } } return output.toString(); } public static final void main(String[] args) { System.out.println(buildOutput()); } } </code></pre>
[ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-03-08T09:05:01.080", "Id": "15563", "Score": "0", "body": "@Winston: Thanks for the correction, this is probably better - I was originally thinking others would vote up/down my draft revision" } ]
[ { "body": "<ul>\n<li>You can avoid the special case for FizzBuzz</li>\n<li>No need to hard-code the limits </li>\n<li>It's not really <em>bad</em> if you have multiple <code>return</code>s in a short (!) method, but it should be avoided if you have an equally readable solution with only one <code>return</code></li>\n</ul>\n\n<p>I would write it that way:</p>\n\n<pre><code>public class FizzBuzz {\n\n public static String getResult(int input) {\n String result = \"\";\n if (input % 3 == 0) {\n result = \"Fizz\";\n }\n if (input % 5 == 0) {\n result += \"Buzz\";\n }\n return result.isEmpty() ? \"\" + input : result;\n }\n\n public static String buildOutput(int from, int to) {\n StringBuilder output = new StringBuilder();\n for (int i = from; i &lt;= to; i++) {\n if(output.length() &gt; 0) {\n output.append(\", \");\n }\n output.append(getResult(i));\n }\n return output.toString();\n }\n\n public static final void main(String[] args) {\n System.out.println(buildOutput(1, 100));\n }\n}\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-08-07T19:11:15.823", "Id": "107114", "Score": "0", "body": "`\"\" + input` while this works, it's really not obvious what it's doing. Wouldn't using a method from `String` make more sense?" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-08-08T21:46:11.810", "Id": "107384", "Score": "3", "body": "@raptortech97 It's a very common idiom in Java every Java developer should know, so why not use it?" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2018-03-09T08:09:29.130", "Id": "361614", "Score": "0", "body": "I really prefer the earliest return possible. When you're looking through the method and see a return you know exactly that that is the result you're going to get for that case. If you store it into a result you still need to work through the entire method to see if that result variable is modified somewhere in between before the actual return. If you start at the end and see that single return statement you also don't know anything about what the result will be so it doesn't help. So at least in my opinion there's no benefit in only having a single return statement." } ], "meta_data": { "CommentCount": "3", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-03-06T19:25:13.383", "Id": "9763", "ParentId": "9749", "Score": "6" } }, { "body": "<pre><code>public class FizzBuzzTest {\n\n @Test\n public void testMultipleOfThreeAndFivePrintsFizzBuzz() {\n assertEquals(\"FizzBuzz\", FizzBuzz.getResult(15));\n }\n\n @Test\n public void testMultipleOfThreeOnlyPrintsFizz() {\n assertEquals(\"Fizz\", FizzBuzz.getResult(93));\n }\n</code></pre>\n\n<p>This doesn't feel like a TDD test. If you wrote this in a test-first manner I'd expect you to start with 3, not 93. Not that testing 93 is bad, but I'd expect a test for the trivial cases as well.</p>\n\n<pre><code> @Test\n public void testMultipleOfFiveOnlyPrintsBuzz() {\n assertEquals(\"Buzz\", FizzBuzz.getResult(10));\n }\n\n @Test\n public void testInputOfEightPrintsTheNumber() {\n assertEquals(\"8\", FizzBuzz.getResult(8));\n }\n</code></pre>\n\n<p>I'd expect more tests in general. I'd probably consistently test the first 15 numbers. I'd store the correct results in an array and use a loop to assert accuracy in each case.</p>\n\n<pre><code> @Test\n public void testOutputOfProgramIsANonEmptyString() {\n String out = FizzBuzz.buildOutput();\n assertNotNull(out);\n assertNotSame(0, out.length());\n }\n</code></pre>\n\n<p>This test seems inefficient. You check for non-null, non-empty strings, but have no checks to make sure the actual output made any sense. </p>\n\n<pre><code>}\n\npublic class FizzBuzz {\n\n private static final int MIN_VALUE = 1;\n private static final int MAX_VALUE = 100;\n</code></pre>\n\n<p>I'd make these parameters to <code>buildOutput</code> not class constants.</p>\n\n<pre><code> public static String getResult(int input) {\n boolean multipleOfThree = ((input % 3) == 0);\n boolean multipleOfFive = ((input % 5) == 0);\n</code></pre>\n\n<p>I think you can probably get rid of some of those parentheses.</p>\n\n<pre><code> if (multipleOfThree &amp;&amp; multipleOfFive) {\n return \"FizzBuzz\";\n }\n else if (multipleOfThree) {\n return \"Fizz\";\n }\n else if (multipleOfFive) {\n return \"Buzz\";\n }\n return String.valueOf(input);\n</code></pre>\n\n<p>I'd put this in an else, I think it gives a clearer idea of what you are doing and looks more parallel with the rest of the function</p>\n\n<pre><code> }\n\n\n public static String buildOutput() {\n StringBuilder output = new StringBuilder();\n\n for (int i = MIN_VALUE; i &lt;= MAX_VALUE; i++) {\n output.append(getResult(i));\n\n if (i &lt; MAX_VALUE) {\n output.append(\", \");\n }\n }\n\n return output.toString();\n }\n\n public static final void main(String[] args) {\n System.out.println(buildOutput());\n }\n}\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-03-08T09:15:32.817", "Id": "15566", "Score": "0", "body": "An excellent answer, the references to TDD convention were just what I was looking for. It looks like you would recommend something in-between to 2 approaches I made for my tests: **DO** have multiple assertions in the test (in the form of a loop), but **DON'T** let the test contain logic (and use a hand crafted array instead)." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-03-08T09:15:42.207", "Id": "15567", "Score": "0", "body": "I expected the actual output of of my `testOutputOfProgramIsANonEmptyString()` had been already tested by my other tests (beyond the building of a `String`) - but it does make sense to ensure we aren't just printing gobbledygook." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-03-08T17:19:35.937", "Id": "15600", "Score": "0", "body": "@seanhodges, if your testing framework supports it, use data-driven tests rather then the loop I mentioned. Then each item in the array counts as its own test rather then as one giant test. I strongly discourage any sort of logic in the test. Logic is what we get wrong in programs, and we need our tests to be correct. If nothing else, you've never tested your comma logic." } ], "meta_data": { "CommentCount": "3", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-03-07T02:36:23.857", "Id": "9764", "ParentId": "9749", "Score": "6" } } ]
{ "AcceptedAnswerId": "9764", "CommentCount": "1", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-03-06T13:47:00.510", "Id": "9749", "Score": "6", "Tags": [ "java", "unit-testing", "interview-questions", "fizzbuzz" ], "Title": "Ways to improve my coding test FizzBuzz solution for a TDD role?" }
9749
<p>I just started programming in Python this morning, and it is (more or less) my first programming language. I've done a bit of programming before, but never really did much except for "Hello World" in a few languages. I searched around for some Python FizzBuzz solutions, and they all seem significantly more complicated then mine, so I think I must be missing something, even though it works correctly. Could you guys point out any errors I've made, or things I can improve?</p> <pre><code>count = 0 while (count &lt; 101): if (count % 5) == 0 and (count % 3) == 0: print "FizzBuzz" count = count +1 elif (count % 3) == 0: print "Fizz" count = count + 1 elif (count % 5) == 0: print "Buzz" count = count +1 else: print count count = count + 1 </code></pre>
[ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-03-01T09:06:01.113", "Id": "35931", "Score": "3", "body": "Only slightly related to your question but this pages contains a few tricks quite interesting if you are starting to learn Python : http://www.reddit.com/r/Python/comments/19dir2/whats_the_one_code_snippetpython_tricketc_did_you/ . One of them leads to a pretty concise (and quite obscure) solution of the Fizzbuzz problem : `['Fizz'*(not i%3) + 'Buzz'*(not i%5) or i for i in range(1, 100)]`." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2017-03-21T16:45:55.467", "Id": "299827", "Score": "0", "body": "Nice solution! To actually print the items one per line, as most Fizzbuzz questions require, not just show a list of results, this needs to be: `print '\\n'.join(['Fizz'*(not i%3) + 'Buzz'*(not i%5) or str(i) for i in range(1, 101)])`. Also note the 101 - `range(1, 100)` returns 1 to 99." } ]
[ { "body": "<p>Your code looks fine. It certainly works. The only thing I'd say about it is that you are repeating the incrementation in all <code>if</code> blocks. You could just move that out of and after them and you'll achieve the same thing.</p>\n\n<pre><code>if (count % 5) == 0 and (count % 3) == 0:\n print \"FizzBuzz\"\nelif (count % 3) == 0:\n print \"Fizz\"\nelif (count % 5) == 0:\n print \"Buzz\"\nelse:\n print count\ncount = count + 1\n</code></pre>\n\n<p>You could also condense the <code>if</code> conditions a bit if you recognize that values of <code>0</code> are considered <code>False</code> and non-zero is <code>True</code>. You're testing if they're equal to <code>0</code> so you could just write it as </p>\n\n<pre><code>if not(count % 5) and not(count % 3):\n print \"FizzBuzz\"\n</code></pre>\n\n<p>I would however not do your loop like that using a <code>while</code> loop but instead use a <code>for</code> loop. Then you wouldn't even need the increment statement there.</p>\n\n<pre><code>for count in range(0, 101):\n if not(count % 5) and not(count % 3):\n print \"FizzBuzz\"\n elif not(count % 3):\n print \"Fizz\"\n elif not(count % 5):\n print \"Buzz\"\n else:\n print count\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-03-06T14:53:21.303", "Id": "15457", "Score": "0", "body": "Thanks for the help! I'll have to play around with this!" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-03-06T14:56:31.690", "Id": "15458", "Score": "1", "body": "Also one thing I'll include here, your first condition could be replaced checking if the number is a multiple of `15` instead of `5` and `3` separately. But what you have is still perfectly fine as they're both logically equivalent." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-03-06T15:31:01.100", "Id": "15459", "Score": "0", "body": "One quick question that is slightly off-topic: aside from reducing lines-of-code, is there a reason you prefer the 'for' loop rather then my 'while'? Do you find it more readable? Would most experienced programmers prefer your method as more readable? I only ask because to me it seems harder to read, but that could be because it contains concepts I haven't covered yet." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-03-06T16:37:15.200", "Id": "15462", "Score": "0", "body": "Yes it is indeed more readable IMHO. Any programmer should know what a `for` loop is and what it's used for. Given some variable, the body of the loop will be run for every value in a given collection. A `while` loop isn't quite as clear. Given _some_ condition, the body of the loop will be run as long as the condition is met. It isn't as clear whether that condition will be met as it can be affected by a number of factors. It could change at any point within the body. With a `for` loop, there is only one possible way for the \"condition\" to change and that is it reaches the end of the body." } ], "meta_data": { "CommentCount": "4", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-03-06T14:48:16.397", "Id": "9754", "ParentId": "9751", "Score": "7" } }, { "body": "<h2>Lose the useless brackets</h2>\n\n<p>This:</p>\n\n<pre><code>while (count &lt; 101):\n</code></pre>\n\n<p>can just be:</p>\n\n<pre><code>while count &lt; 101:\n</code></pre>\n\n<h2>Increment out of the <code>if</code>s</h2>\n\n<p>Wouldn't be easier to do:</p>\n\n<pre><code>count = 0\nwhile count &lt; 101:\n if count % 5 == 0 and count % 3 == 0:\n print \"FizzBuzz\"\n elif count % 3 == 0:\n print \"Fizz\"\n elif count % 5 == 0:\n print \"Buzz\"\n else:\n print count\n\n count = count + 1 # this will get executed every loop\n</code></pre>\n\n<h2>A <code>for</code> loop will be better</h2>\n\n<pre><code>for num in xrange(1,101):\n if num % 5 == 0 and num % 3 == 0:\n print \"FizzBuzz\"\n elif num % 3 == 0:\n print \"Fizz\"\n elif num % 5 == 0:\n print \"Buzz\"\n else:\n print num\n</code></pre>\n\n<p>I've also renamed <code>count</code> to <code>num</code> since it doesn't count much, is just a number between 1 and 100.</p>\n\n<h2>Let's use only one <code>print</code></h2>\n\n<p>Why do 4 different print, when what is really changing is the printed message?</p>\n\n<pre><code>for num in xrange(1,101):\n if num % 5 == 0 and num % 3 == 0:\n msg = \"FizzBuzz\"\n elif num % 3 == 0:\n msg = \"Fizz\"\n elif num % 5 == 0:\n msg = \"Buzz\"\n else:\n msg = str(num)\n print msg\n</code></pre>\n\n<h2>Light bulb!</h2>\n\n<p><code>\"FizzBuzz\"</code> is the same of <code>\"Fizz\" + \"Buzz\"</code>.</p>\n\n<p>Let's try this one:</p>\n\n<pre><code>for num in xrange(1,101):\n msg = ''\n if num % 3 == 0:\n msg += 'Fizz'\n if num % 5 == 0: # no more elif\n msg += 'Buzz'\n if not msg: # check if msg is an empty string\n msg += str(num)\n print msg\n</code></pre>\n\n<p>Copy and paste this last piece of code <a href=\"http://people.csail.mit.edu/pgbovine/python/tutor.html#mode=edit\">here</a> to see what it does. </p>\n\n<p>Python is a very flexible and powerful language, so I'm sure there could be other hundred and one different possible solutions to this problem :)</p>\n\n<h2>Edit: Improve more</h2>\n\n<p>There's still something \"quite not right\" with these lines:</p>\n\n<pre><code>if not msg:\n msg += str(num)\n</code></pre>\n\n<p>IMHO it would be better to do:</p>\n\n<pre><code>for num in xrange(1,101):\n msg = ''\n if num % 3 == 0:\n msg += 'Fizz'\n if num % 5 == 0:\n msg += 'Buzz'\n print msg or num\n</code></pre>\n\n<p>There! Now with:</p>\n\n<pre><code>print msg or num\n</code></pre>\n\n<p>is clear that <code>num</code> is the default value to be printed.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-03-06T18:04:04.803", "Id": "15467", "Score": "0", "body": "**Let's use only one print** would work well without converting `num` to a string. It's as if you were already anticipating the need for the conversion on **Light bulb!**? Or maybe it was the purity of keeping `msg` a string?" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-03-06T18:11:59.177", "Id": "15468", "Score": "2", "body": "@Tshepang: yeah I know, but it would have been more strange to have a `msg` variable that one time is a `str` and another an `int`. Also it isn't a very good practice to have a variable that could have different types. So I'd say that is the **following of the good practices that will lead you towards the light bulb :)** [Edit: Yes, I'd like to think it was number 2.]" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-10-27T20:04:33.080", "Id": "53404", "Score": "0", "body": "One interesting exercise - what if you want a space between Fizz and Buzz, and no newlines but rather commas. ie `1, 2, fizz, ... 14, fizz buzz, fizz, ...`" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-06-11T00:24:57.590", "Id": "93907", "Score": "1", "body": "You reach the best solution about half way through this post and then start making it cuter and less readable." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2015-05-07T13:44:12.547", "Id": "163295", "Score": "4", "body": "@MikeGraham I disagree. I think the last version is very readable. Honestly I think appending Buzz to Fizz when n is divisible by 3 and 5 is part of the reason it's in the question in the first place, written as it is. The `print msg or num` is very pythonic in terms of \"do this otherwise use the fallback\". If it were another language you might explicitly set the output for msg." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2015-05-18T12:21:04.423", "Id": "165120", "Score": "0", "body": "@JordanReiter, the fact that there is a cutesy solution is an important part of fizzbuzz -- people who avoid it have shown good sense. The \"A for loop will be better\" is plainly more readable than the final solution, which unnecessarily is cute and subtle and less plain. If someone didn't know what the code was supposed to do, they would very, very likely understand precisely what it does quicker reading the \"A for loop will be better\" solution than the final solution. Code should be as simple as possible." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2015-05-18T16:16:38.083", "Id": "165157", "Score": "2", "body": "We'll just have to agree to disagree. If I were interviewing, I'd immediately follow with: \"I've changed my mind. I want 7 instead of 5, and instead of Fizz I want Fooz\". In the loop solution, you have to rewrite 5 lines of code; in the \"custesy\" solution, you only have to rewrite 2 lines of code. The \"straightforward\" solution includes repeating yourself: you check whether something is divisible by 5 twice and you print \"Fizz\" (on its own or as part of another word) twice. Can we at least agree that the \"Let's use only one print\" is *far* better then calling print numerous times?" } ], "meta_data": { "CommentCount": "7", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-03-06T15:04:11.887", "Id": "9755", "ParentId": "9751", "Score": "44" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "2", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-03-06T14:32:50.613", "Id": "9751", "Score": "21", "Tags": [ "python", "beginner", "fizzbuzz" ], "Title": "Ultra-Beginner Python FizzBuzz ... Am I missing something?" }
9751
<p>In current task, I'm refactoring the code of converting JSON file into SQLite database on Android device. Code compliant with Java 6.</p> <p>As a benchmark, grabbing the code from remote server takes <code>~1 second</code>, but parsing it and saving to database takes <code>up to 1 minute</code></p> <p>In file there is approximately 100 branches, where is has 2 services, which is like 300 queries. Each query takes up to <code>100 ms</code></p> <pre><code>JSONObject response = new JSONObject(coupons); JSONArray branches = response.getJSONArray("branches"); String lastTimestamp = ""; for(int i = 0; i &lt; branches.length(); i++){ JSONObject branch = branches.getJSONObject(i); JSONObject b = branch.getJSONObject("Branch"); // add Branch lastTimestamp = b.getString("timestamp"); addBranch( b.getInt("id"), b.getString("longitude"), b.getString("latitude"), b.getString("heading"), b.getString("address"), b.getString("opening_hours"), b.getString("region"), b.getString("country"), b.getString("phone"), b.getString("type"), lastTimestamp ); // add Services JSONArray services = branch.getJSONArray("Service"); for(int o = 0; o &lt; services.length(); o++){ JSONObject s = services.getJSONObject(o); addService( s.getInt("id"), s.getInt("branch_id"), s.getString("name") ); } // end loop adding branches &amp; services } </code></pre> <p>where methods used to insert to database are:</p> <pre><code>private long addBranch( int remote_id, String longitude, String latitude, String heading, String address, String opening_hours, String region, String country, String phone, String type, String timestamp ){ ContentValues values = new ContentValues(); values.put(BranchSQL.COLUMN_REMOTE_ID, remote_id); values.put(BranchSQL.COLUMN_LONGITUDE, longitude); values.put(BranchSQL.COLUMN_LATITUDE, latitude); values.put(BranchSQL.COLUMN_HEADING, heading); values.put(BranchSQL.COLUMN_ADDRESS, address); values.put(BranchSQL.COLUMN_OPENING_HOURS, opening_hours); values.put(BranchSQL.COLUMN_REGION, region); values.put(BranchSQL.COLUMN_COUNTRY, country); values.put(BranchSQL.COLUMN_PHONE, phone); values.put(BranchSQL.COLUMN_TYPE, type); long insertId = getDatabase().insertWithOnConflict(BranchSQL.TABLE_BRANCHES, null, values, SQLiteDatabase.CONFLICT_IGNORE); return insertId; } private long addService(int remote_id, int branch_id, String name){ ContentValues values = new ContentValues(); values.put(BranchSQL.COLUMN_REMOTE_ID, remote_id); values.put(BranchSQL.COLUMN_BRANCH_ID, branch_id); values.put(BranchSQL.COLUMN_NAME, name); long insertId = getDatabase().insertWithOnConflict(BranchSQL.TABLE_SERVICES, null, values, SQLiteDatabase.CONFLICT_IGNORE); return insertId ; } </code></pre> <p>code creating structure of tables:</p> <pre><code>private static final String BRANCHES_CREATE = "create table " + TABLE_BRANCHES + "( " + COLUMN_ID + " integer primary key autoincrement, " + COLUMN_REMOTE_ID + " integer unique, " + COLUMN_LONGITUDE + " text not null, " + COLUMN_LATITUDE + " text not null, " + COLUMN_HEADING + " integer, " + COLUMN_ADDRESS + " text not null, " + COLUMN_OPENING_HOURS + " text not null, " + COLUMN_REGION + " text not null, " + COLUMN_COUNTRY + " text not null, " + COLUMN_PHONE + " text not null, " + COLUMN_TYPE + " text not null, " + COLUMN_TIMESTAMP + " text null);"; private static final String SERVICES_CREATE = "create table " + TABLE_SERVICES + "( " + COLUMN_ID + " integer primary key autoincrement, " + COLUMN_REMOTE_ID + " integer unique, " + COLUMN_BRANCH_ID + " integer, " + COLUMN_NAME + " text not null );"; </code></pre> <p><em>Note that almost all fields in BRANCH type are text, to not slowing down inserting rows by parsing <code>Integer, Double, Date, ...</code> values</em></p> <p>This is probably the simplest way to do it. But it looks like it is also the most in-effective way. </p> <p>Second way, I can think about, is using <a href="http://code.google.com/p/google-gson/" rel="nofollow">Gson</a> or <a href="http://jackson.codehaus.org/" rel="nofollow">Jackson</a> to parse whole branch&amp;services object to Java Object, but this looks to me not very memory/cpu usage friendly.</p> <p>Can I please kindly ask for your optimizing tips?</p>
[]
[ { "body": "<p>You're trying to do a <a href=\"http://en.wikipedia.org/wiki/Bulk_insert\" rel=\"nofollow\">bulk insert</a>, which is notoriously slow on many databases if you're not careful. Indeed, each call to <code>insertWithOnConflict()</code> creates a new transaction, then inserts, then closes the transaction. Instead, use <a href=\"http://developer.android.com/reference/android/database/sqlite/SQLiteDatabase.html#beginTransaction()\" rel=\"nofollow\">beginTransaction()</a> and <a href=\"http://developer.android.com/reference/android/database/sqlite/SQLiteDatabase.html#endTransaction()\" rel=\"nofollow\">endTransaction()</a> to have only a single transaction (the doc explains how to use them with a try/catch block).</p>\n\n<p>Up to API 16, it was possible to use <code>DatabaseUtils.InsertHelper</code>, but this is now deprecated. <a href=\"http://www.outofwhatbox.com/blog/2010/12/android-using-databaseutils-inserthelper-for-faster-insertions-into-sqlite-database/\" rel=\"nofollow\">This blog post</a> uses <code>DatabaseUtils.InsertHelper</code>, which is not a good idea anymore. But it has other interesting performance tweaks you could try out:</p>\n\n<ul>\n<li>Don’t bind empty columns to avoid producing useless SQL. This will lead to a speedup if you often have empty columns. (half of the author columns are empty and he reports a 30% speedup).</li>\n<li>Disable thread locking temporarily: for various reasons, this is <strong>very dangerous</strong>, and should only be attempted if you know the implications, can prove it won't do any harm, and <em>really</em> need the ~30% speedup reported by the author.</li>\n</ul>\n\n<p>Of course, there are probably other optimisations, like trying to do this in a background thread, doing this only once when the user doesn't mind. If the speedups provided by the above solutions really don't help, displaying a progress bar can make your app feel like it's doing something important, which will be less frustrating for the user.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-03-07T15:18:23.557", "Id": "15488", "Score": "0", "body": "Oh gosh, sorry, see code posted under my question. I've took your suggestions and now it takes under 5 seconds whatever :)) Thanks" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2015-06-17T11:14:37.230", "Id": "170846", "Score": "0", "body": "InsertHelper is deprecated now see this [SO answer](http://stackoverflow.com/a/14344928/1665247)" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2015-06-17T16:31:55.320", "Id": "170864", "Score": "0", "body": "Thanks @dvrm, I updated my answer. Feel free to improve it too." } ], "meta_data": { "CommentCount": "3", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-03-07T12:56:09.430", "Id": "9767", "ParentId": "9766", "Score": "7" } } ]
{ "AcceptedAnswerId": "9767", "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-03-07T11:02:17.780", "Id": "9766", "Score": "8", "Tags": [ "java", "parsing", "android", "json", "sqlite" ], "Title": "Optimize JSON insertion to SQLite (insert ... on duplicate key ignore)" }
9766
<p>I have a <code>List&lt;string&gt;</code> being stored in my cache with about 600K members. I want this to act as the backend for an Ajax autocomplete box. It's accessible through my model:</p> <pre><code>public static List&lt;string&gt; GetProducts() { var cached = HttpContext.Current.Cache["MyApp-Products"]; if (cached == null) { UpdateCache(); return GetProducts(); } return ((List&lt;string&gt;)cached); } </code></pre> <p>My ajax call uses this method to get it's data:</p> <pre><code>[HttpPost] public JsonResult ProductSearch(string term) { return Json(MyModel.GetProducts() .Where(s =&gt; s.ToUpper().StartsWith(term.ToUpper())) .OrderBy(s =&gt; s) .Take(5) .ToList&lt;string&gt;() ); } </code></pre> <p>The problem is, this Ajax call to <code>ProductSearch()</code> is waiting 2.09 seconds for a response. I'm doing the same with other objects in my model that have smaller list sizes and they respond in 35-125ms (which is acceptable).</p> <p>So, I believe my performance issue is somewhere in accessing the list. Is there a faster way to access this list besides the Linq code that I'm using, or just a better way to use Linq?</p>
[ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-03-07T17:13:51.553", "Id": "15494", "Score": "0", "body": "Were you aware that the `List<T>` type that you are using as backend is not thread safe? You should really take that into account when attempting to use it in a multi-threaded environment such as ASP.NET." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-03-07T17:39:10.783", "Id": "15499", "Score": "2", "body": "Not sure I'm too keen on the recursion there, even if it should only be a single loop-around. I'd replace `return GetProducts();` with the (also-repeat, might want to DRY it out) `cached = HttpContext.Current.Cache[\"MyApp-Products\"];`." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-03-07T22:06:47.233", "Id": "15537", "Score": "0", "body": "sounds like the perfect use for a http://en.wikipedia.org/wiki/Directed_acyclic_word_graph" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-03-08T02:23:10.013", "Id": "15544", "Score": "0", "body": "@Darin what would be the thread-safe alternative?" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-03-08T13:07:07.010", "Id": "15571", "Score": "1", "body": "A public static List<T> is threadsafe. Instance members are not guaranteed to be. But either way, as long as the collection is not modified during runtime, it does not matter. http://msdn.microsoft.com/en-us/library/6sh2ey19.aspx (see Thread Safety near bottom above Community Content)" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-03-12T09:35:20.037", "Id": "15777", "Score": "3", "body": "@Lars-Erik: You read the specification wrong. The fact that static members of the class (all zero of them) are thread safe doesn't mean that a static variable holding an instance of the class is thread safe. Neither the variable nor the class instance is thread safe." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-03-13T08:48:43.073", "Id": "15847", "Score": "0", "body": "Ah, bummer. Embarrasing. Anyway, the part about modification should still hold true." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-01-05T23:41:18.397", "Id": "64489", "Score": "0", "body": "One thing to watch for using the `HttpContext.Current.Cache` is that there is an overhead as the dictionary populates and depending on the amount of items in your cache that alone can become expensive. You may be better off using something else like Lucene.Net which can store its index in RAM, or even a `static List<string>` that gets repopulated on app recycle." } ]
[ { "body": "<p>A starts-with should be easy enough to store in a pre-sorted list, ideally using a case-insensitive sort comparer rather than applying conversions each sort. Then: use binary search to find the first match, and keep moving forwards until it no longer matches. Should be pretty efficient.</p>\n\n<p>If this needs to be edited in a shared multi-threaded context, be sure to use appropriate synchronization - presumably readers will be more common than writers, so a ReaderWriterLockSlim may be the best option.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-03-08T00:54:48.470", "Id": "15542", "Score": "1", "body": "The binary search will get you to *a* match quickly, not necessarily the first. You'd have to then back up until you find the first match and proceed forward from there. On average I would expect this to be much faster (than iterating through a pre-sorted set), but there are some cases where it could be slower. For example, the case where you end up taking the first 5 elements out of a very large set." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-03-08T06:14:15.633", "Id": "15553", "Score": "0", "body": "@tvanfosson: After finding *a* match, you just treat the match as \"too large\" and continue the binary search. After the binary search has completed fully (i.e., after all log_2(n) steps), you know exactly where the *first* match is located. In other words, instead of searching for \"prefix.*\", you search just for \"prefix\". If you found \"prefix\", you know that this is the first element (since \"prefix<whatever>\" is greater). If you did not find \"prefix\", the end point of your binary search will be right before the first match (or not, if there is no match at all)." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-03-08T13:10:36.747", "Id": "15572", "Score": "0", "body": "@Heinzi you're assuming no duplicates, but I see what you mean. Go until you can't go any more, then check the next element (with special handling for the boundary cases). I'm not sure that's a lot faster than just finding one then going backwards (pushing on a stack) until you find the first non-match, popping the elements off the stack, then continuing at the point after the first match. It *sounds* more complicated. I suppose whether it's worth it depends on whether you expect a large or small number of matches and the size of the data set." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-03-08T14:12:34.527", "Id": "15580", "Score": "0", "body": "@tvanfosson: You are right, the *average-case* performance depends on the actual data. There is a difference in the *worst-case* time compexity, though: The binary-search-till-the-end approach requires at most `O(log n)`, whereas the find-first-match-then-go-backwards method could have `O(n)`." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-03-08T14:47:45.120", "Id": "15584", "Score": "0", "body": "@Heinzi you're only considering the search phase, not the selection phase for your algorithm. Both algorithms are `O(log n) + O(m)` where m is the number of elements selected. If m is large then the difference in the constant on the second term is meaningful." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-03-08T14:53:25.147", "Id": "15585", "Score": "0", "body": "@tvanfosson: Ah, yes, very good point. Thanks!" } ], "meta_data": { "CommentCount": "6", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-03-07T17:16:40.550", "Id": "9774", "ParentId": "9773", "Score": "17" } }, { "body": "<p>You should put your strings in a database.</p>\n\n<pre><code>CREATE TABLE MyStrings\n(\n UpperCaseVersion varchar(8000)\n StringValue varchar(8000)\n PRIMARY KEY(UpperCaseVersion, StringValue)\n)\n</code></pre>\n\n<p>Now it's threadsafe and quickly searchable (via the ordering from the primary key).</p>\n\n<p>This solution will easily scale to 100 Million strings.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-03-07T17:23:07.000", "Id": "15495", "Score": "2", "body": "Wouldn't the database I/O be _slower_ than doing it in memory directly?" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-03-07T17:24:49.187", "Id": "15496", "Score": "0", "body": "@M.Babcock no, the IO is not bad at all because of the clustered index seek." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-03-07T17:54:59.917", "Id": "15503", "Score": "0", "body": "Thanks for the tip, however for reasons beyond my control, I don't have the option of putting this in a db." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-06-04T18:55:33.473", "Id": "19691", "Score": "0", "body": "We could rename CodeReview.Stackexchange.com to ProgrammingHumour.StackExchange.com :))))" } ], "meta_data": { "CommentCount": "4", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-03-07T17:20:18.157", "Id": "9775", "ParentId": "9773", "Score": "4" } }, { "body": "<p>Marc has the best answer but a trivial step in the right direciton would be to drop all the expensive ToUpper calls. Just replace <code>.Where(s =&gt; s.ToUpper().StartsWith(term.ToUpper()))</code> with <code>.Where(s =&gt; s.StartsWith(term, StringComparison.InvariantCultureIgnoreCase)</code></p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-03-07T17:54:14.970", "Id": "15502", "Score": "2", "body": "Thanks! The `StringComparison.InvariantCultureIgnoreCase` actually helped significantly." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-06-04T18:49:24.430", "Id": "19690", "Score": "7", "body": "How much exactly did it help? 10%? 50%? 99%?" } ], "meta_data": { "CommentCount": "2", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-03-07T17:30:29.420", "Id": "9776", "ParentId": "9773", "Score": "16" } }, { "body": "<p>I see that you order the list just to take 5 items. <code>.OrderBy(s =&gt; s).Take(5)</code>. This is an O(n*log(n)) operation. Instead you can find the top most N items in an O(n) time.\nHere is an extension method <code>TakeOrdered</code> ( <a href=\"http://pastebin.com/NHDdrbYV\" rel=\"nofollow noreferrer\">http://pastebin.com/NHDdrbYV</a> ) I wrote some time ago just for this purpose .</p>\n\n<pre><code> return Json(MyModel.GetProducts()\n .Where(s =&gt; s.ToUpper().StartsWith(term.ToUpper()))\n .TakeOrdered(5,s=&gt;s)\n .ToList&lt;string&gt;()\n);\n</code></pre>\n\n<p>you can compare the performance results with a function like below</p>\n\n<pre><code>void PerformanceTest()\n{\n Stopwatch sw = new Stopwatch();\n\n int N = 1000000;\n int M = 10;\n\n //JIT - Warm up\n var seq1 = RandomSequence().Take(10).OrderBy(x =&gt; x).Take(M).ToArray();\n var seq2 = RandomSequence().Take(10).TakeOrdered(M).ToArray();\n\n\n sw.Start();\n seq1 = RandomSequence().Take(N).OrderBy(x =&gt; x).Take(M).ToArray();\n long t1 = sw.ElapsedMilliseconds;\n\n sw.Restart();\n seq2 = RandomSequence().Take(N).TakeOrdered(M).ToArray();\n long t2 = sw.ElapsedMilliseconds;\n\n for (int i = 0; i &lt; seq1.Length; i++) Debug.Assert(seq1[i] == seq2[i]);\n\n Console.WriteLine(t1 + \" \" + t2);\n}\n\npublic IEnumerable&lt;int&gt; RandomSequence()\n{\n Random rnd = new Random(0);\n while (true)\n yield return rnd.Next();\n}\n\n N |.OrderBy.Take .TakeOrdered (in ms.)\n-----+---------------------------\n100K | 65 23\n600K | 578 131\n1M | 1110 224\n10M | 16540 2243\n</code></pre>\n\n<p>And since It doesn't require all items to be kept in memory(for sorting), it consumes much less RAM</p>\n\n<p><strong>PS:</strong>\n<code>TakeOrdered</code> utilizes <a href=\"http://lucene.apache.org/core/old_versioned_docs/versions/3_0_2/api/all/org/apache/lucene/util/PriorityQueue.html\" rel=\"nofollow noreferrer\">PriorityQueue</a> of Lucene.Net internally\n<a href=\"http://lucene.apache.org/core/old_versioned_docs/versions/3_0_2/api/all/org/apache/lucene/util/PriorityQueue.html\" rel=\"nofollow noreferrer\">http://lucene.apache.org/core/old_versioned_docs/versions/3_0_2/api/all/org/apache/lucene/util/PriorityQueue.html</a></p>\n\n<p>Here is more explanation: \n<a href=\"https://stackoverflow.com/questions/7936473/how-can-i-use-lucenes-priorityqueue-when-i-dont-know-the-max-size-at-create-ti\">How can I use Lucene's PriorityQueue when I don't know the max size at create time?</a></p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-03-08T13:15:36.117", "Id": "15574", "Score": "0", "body": "I suspect that the use of the PriorityQueue makes this a non-stable sort. If you need to retain the relative ordering of items with \"equal\" prefixes, you probably shouldn't use this." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-03-08T13:30:03.540", "Id": "15576", "Score": "0", "body": "@tvanfosson If you'd taken a look to `PerformanceTest`(Assert code), you would see that it produces exactly the same output as `OrderBy().Take()`" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-03-08T13:39:58.940", "Id": "15578", "Score": "0", "body": "HeapSort is known to be a non-stable sort. If the priority queue implementation uses the same heap data structure (which the docs seem to suggest), then I would expect that it would have the same characteristics. Note that your test wouldn't detect this as there is no way to tell the difference between identical keys sorted in a different relative way. Attach a bit of unique data to each key and compare the order of those data elements and see if it's still in the same relative order. According to the docs, OrderBy uses a stable sort." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-03-08T13:45:28.653", "Id": "15579", "Score": "0", "body": "@tvanfosson Just forget the implemantation details for now: The idea is: You can find the Max(or Min) item of a List in O(n) time. if you extend this idea to m item(5 in the question), you can get top(or buttom) m items faster then sorting the list(just in one pass on the list + the cost of keeping 5 sorted items)" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-03-08T14:30:04.080", "Id": "15581", "Score": "0", "body": "Right, but consider the case where you have a set of log entries that you know are ordered by time. You want to find the first 5 log entries whose description starts with the word error because you want to see where a problem started. A simple scan is probably the way to do it, but let's say you order them by description and then take the first five. In this case a stable sort is critical because you want to retain the relative ordering by time. I'm not saying that your method is wrong, just that you have to understand whether it's appropriate or not." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-03-08T14:54:27.527", "Id": "15586", "Score": "1", "body": "I should also add that my comment wasn't directed at this particular question, but rather meant as a caveat for anyone who finds this later and is doing a key-based sort rather than sorting on the entire element. I just thought people should know that it's not a drop in replacement IF stability is important." } ], "meta_data": { "CommentCount": "6", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-03-07T17:34:00.523", "Id": "9777", "ParentId": "9773", "Score": "11" } }, { "body": "<p>You're asking the wrong question. You should be asking how to return the results quickly, not how to do it quickly with a particular data structure (a List).</p>\n\n<p>There has been a lot of work done on exactly this sort of problem. I don't know a lot about this, but most likely some sort of tree structure will be much faster. Off the top of my head, I would look into a <a href=\"https://en.wikipedia.org/wiki/Trie\" rel=\"nofollow\">trie</a> structure, which is a particular type of tree. (Yeah, the spelling is confusing.)</p>\n\n<p>But I'm certainly no expert on this, and there might well be better options. You may want to post this question on a board with a more algorithmic focus.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-03-08T17:41:17.977", "Id": "9820", "ParentId": "9773", "Score": "2" } }, { "body": "<p>You can get rid of the OrderBy statement and just make sure that you're filling the cache with an already sorted list - this will not save a lot of time, but should give some improvement. </p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-03-08T23:45:39.740", "Id": "9841", "ParentId": "9773", "Score": "3" } }, { "body": "<p>If you're doing a StartsWith, perhaps you could break the list down into sub-lists, which obviously would take time, but it wouldn't be time that a human would wait on, since it could be done in the background. Then you could have a list for each letter of the alphabet (or break it down more for common letters and group a few common ones together, whatever works to break it down most evenly).</p>\n\n<p>It wouldn't be 'elegant' to have a bunch of switch statements for each starting letter, but you could easily trim the list length from 600k to sort through to 60k or less, which would drastically reduce the time required to return results.</p>\n\n<p>Alternatively, another option would be to change your datatype entirely. You could pre-sort your 600k list into <code>Dictionary&lt;string, List&lt;string&gt;&gt;</code> with the key being a string of the \"StartsWith\" you want to match. Then modify your code to simply pull the list stored as the value in the dictionary that matches your StartsWith. So, if you pre-sort to 2 letters, such as aa, ab, ac, ad, etc etc, once you match that, you get can then sort through a drastically smaller list. You could even pre-sort to 3 letters, such as aaa, aab, aac, and so on, which should result in needing to parse through a list of probably under 1000 elements for the longest list in the dictionary, with many being significantly smaller than 1000. </p>\n\n<p>Using a 3-letter key would result in a dictionary with around 17k keys, which should yield acceptable performance. Accessing the dictionary value should be well under 1ms, then sorting through a list with under 1000 elements should be under 10ms, which should result in your function returning a value in more like 20ms rather than 2 seconds. The downside would be needing to break apart your 600k element list into 17,576 smaller sorted lists, then storing each of those in a dictionary with the appropriate \"StartsWith\" key. This, however, should only take a few seconds and can be done at initialization (and new entries for your list, which I assume isn't static, can be added to the dictionary rather than the jumbo-list, resulting in only needing to sort the list once, ever).</p>\n\n<p>The best bet would be a database, but since that's not an option for you, the second-best thing would be simply reducing the length of your list from 600k down to something much much smaller. </p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-03-13T21:15:41.437", "Id": "9994", "ParentId": "9773", "Score": "0" } } ]
{ "AcceptedAnswerId": "9776", "CommentCount": "8", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-03-07T17:11:42.080", "Id": "9773", "Score": "19", "Tags": [ "c#", "performance", "linq" ], "Title": "Optimizing List<string> performance" }
9773
<p>I have created code to show/hide data from a DB. It works, but as I am new to jQuery, I would like to know if this is a good way.</p> <p><strong>HTML:</strong></p> <pre><code>&lt;li class="devInfo"&gt; &lt;span class="sn_table"&gt;&lt;? echo $sn; ?&gt;&lt;/span&gt; &lt;span class="last_edit_table"&gt;&lt;? echo $last_change; ?&gt;&lt;/span&gt; &lt;span class="comment_table"&gt;&lt;? echo $comment; ?&gt;&lt;/span&gt; &lt;span class="model_table"&gt;&lt;? echo $model_name; ?&gt;&lt;/span&gt; &lt;a class="more" data-name="&lt;? echo $id; ?&gt;" href=""&gt;+&lt;/a&gt; &lt;div class="details"&gt;&lt;/div&gt; &lt;/li&gt; </code></pre> <p><strong>jQuery:</strong></p> <pre><code>$(function () { $(".more").live("click", function () { var onMe =$(this); var detailsConteiner = $(onMe).next('div'); var forLoader = $(onMe).parent("li"); if ($(onMe).text() == "+") { $(devInfo).children("span").css({"text-indent":"", "text-overflow":""}); $(forLoader).fadeIn(400).prepend('&lt;img src="/images/css/loader_small.gif" style="margin-bottom:.25em; margin-left:1.25em; vertical-align:middle;"&gt;'); $(onMe).text("-") $(devInfo).css("background", ""); $(forLoader).css("background", "#d6e5f4"); $(onMe).siblings("span").css({"text-indent":"1000px", "text-overflow":"clip"}); $(detailsConteiner).empty(); $(details).slideUp(1000); var value = $(onMe).attr("data-name"); var dataString = 'deviceId=' + value; $.ajax({ type: "POST", url: "helpers/getDetails.php", data: dataString, cache: false, success: function (html) { $(detailsConteiner).prepend(html).slideDown(500); $(forLoader).children("img").fadeOut(600); } }); return false; } else { $(details).slideUp(700); $(onMe).text("+"); $(forLoader).css("background", ""); $(onMe).siblings("span").css({"text-indent":"", "text-overflow":""}); return false; } }); }); </code></pre> <p><strong>Ajax response:</strong></p> <pre><code>&lt;dl class="details"&gt; &lt;dd&gt;Id: &lt;? echo $id; ?&gt; &lt;/dd&gt; &lt;dd&gt;Serial: &lt;? echo $sn; ?&gt; &lt;/dd&gt; &lt;dd&gt;Model: &lt;? echo $model_name; ?&gt; &lt;/dd&gt; &lt;dd contenteditable data-name="comment"&gt;Comment:&lt;? echo $comment; ?&gt;&lt;/dd&gt; &lt;dd&gt;Last Change&lt;? echo date('d.m.Y', strtotime($last_change)); ?&gt; &lt;/dd&gt; &lt;/dl&gt; </code></pre> <p><strong>CSS:</strong></p> <pre><code>.devInfo img { margin-bottom:.25em; margin-left:1.25em; vertical-align:middle; margin-left:25px; } li.expanded { background-color: #d6e5f4; } li.expanded span { text-indent: -1000px; text-overflow:clip; } </code></pre> <p><strong>JS:</strong></p> <pre><code>*function showDetails() // is not needed as the function insertDetails is doing job function hideRestOfLI() { $(".details").slideUp(1000); } function expand() { hideRestOfLI(); $(".devInfo").removeClass(ExpandClass); $(".more").text(ColapsedChar); $devInfo.addClass(ExpandClass); $moreLink.text(ExpandedChar); } completed: hideLoading // complete: hideLoading </code></pre>
[]
[ { "body": "<ul>\n<li><p><strong><code>.live()</code></strong>: As of jQuery 1.7, the <code>.live()</code> method is deprecated <a href=\"http://api.jquery.com/live/\" rel=\"nofollow\">for various reasons</a>. Users should go for a combination of <a href=\"http://api.jquery.com/on/\" rel=\"nofollow\"><code>.on()</code></a> and <a href=\"http://api.jquery.com/delegate/\" rel=\"nofollow\"><code>.delegate()</code></a>. For this code, you don't need to use <code>.delegate()</code> since <code>a.more</code> is never dynamically modified. Simply use <code>.on()</code> like this:</p>\n\n<pre><code>$(\"a.more\").on(\"click\", function() { ... });\n</code></pre>\n\n<p>(If you were attaching an event on a lot of elements, you would have used another construct, see the <code>.on()</code> doc for details.)</p></li>\n<li><p><strong>Dead code</strong>: </p>\n\n<pre><code>$(devInfo).children(\"span\").css({\"text-indent\":\"\", \"text-overflow\":\"\"});\n</code></pre>\n\n<p>The first time you write this, it seems to have no effect. Remove it if this is the case.</p></li>\n<li><strong>Timeouts</strong>: Whenever you're doing Ajax calls, don't forget that requests could timeout, especially on phones. <code>$.ajax()</code> provides you with a way to handle timeouts, do it, and revert <code>a.more</code> to <code>\"+\"</code>.</li>\n<li>Use <a href=\"https://developer.mozilla.org/en/JavaScript/Reference/Operators/Comparison_Operators\" rel=\"nofollow\">strict equality comparison</a>.</li>\n<li>You could use a switch on <code>$(onMe).text()</code>, with two cases: <code>\"+\"</code> and <code>\"-\"</code>.</li>\n</ul>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-03-07T21:38:22.267", "Id": "15532", "Score": "0", "body": "$(devInfo).children(\"span\").css({\"text-indent\":\"\", \"text-overflow\":\"\"}); // it's not dead, its reset css after it has been clicked on the one of the a.more" } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-03-07T20:28:22.643", "Id": "9786", "ParentId": "9780", "Score": "1" } }, { "body": "<p>There are many changes to the css through jquery that could just be handled by adding a class to devInfo.</p>\n\n<p>I...</p>\n\n<ol>\n<li>Changed some variable names for readability</li>\n<li>Created some variable constants for readability</li>\n<li>Created single responsibility functions for clean code</li>\n<li>Only transformed elements to jQuery once and stored in a variable starting with '$'</li>\n<li>Extracted out the style from js and put it in css</li>\n<li>Prevented the link's default action from going</li>\n<li>Added functionality to add/remove the 'expanded' class</li>\n</ol>\n\n<p>The code is completely untested. So there is probably some syntax issues, but let me know what you think.</p>\n\n<p>CSS</p>\n\n<pre><code>.devInfo a.more img {\n margin-bottom:.25em; \n margin-left:1.25em; \n vertical-align:middle;\n}\n\n.devInfo.expanded a.more {\n background-color: #d6e5f4;\n}\n\n.devInfo.expanded {\n background: url();\n}\n\n.devInfo.expanded .span {\n text-indent: 1000px;\n text-overflow: clip;\n}\n</code></pre>\n\n<p>JS</p>\n\n<pre><code>$(function () {\n var ExpandedChar = \"-\",\n ColapsedChar = \"+\",\n ExpandClass = 'expanded';\n\n var toggleDetails = function(event) { \n event.preventDefault();\n\n var $moreLink = $(this),\n $details= $moreLink.next('.details'), \n $devInfo = $moreLink.closest('.devInfo');\n\n var displayLoading = function() {\n $devInfo.prepend(buildLoadImage()).fadeIn(400);\n };\n\n var hideLoading = function() {\n $devInfo.children(\"img\").fadeOut(600);\n };\n\n var insertDetails = function(html) { \n $details.prepend(html).slideDown(500); \n };\n\n var getDetailsFor = function(deviceId) {\n $.ajax({\n type: \"POST\",\n url: \"helpers/getDetails.php\",\n data: {deviceId: deviceId},\n cache: false,\n beforeSend: displayLoading,\n success: insertDetails,\n completed: hideLoading\n });\n }\n\n if (isColapsed()) {\n expand();\n getDetailsFor($moreLink.attr(\"data-name\")); \n } else {\n colapse();\n } \n\n function expand() {\n $devInfo.addClass(ExpandClass);\n $moreLink.text(ExpandedChar);\n showDetails();\n }\n\n function showDetails() {\n $details.slideUp(1000);\n }\n\n function colapse() {\n $devInfo.removeClass(ExpandClass);\n $moreLink.text(ColapsedChar);\n hideDetails();\n }\n\n function hideDetails() {\n $details.slideUp(700);\n }\n\n function isColapsed() {\n return $moreLink.text() == ColapsedChar;\n }\n\n function buildLoadImage() {\n return $('&lt;img /&gt;').attr('src', '/images/css/loader_small.gif');\n }\n }\n\n $(\".more\").live(\"click\", toggleDetails);\n});\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-03-08T05:50:35.053", "Id": "15550", "Score": "0", "body": "collapse has two l and you still use .live() but I like it." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-03-08T20:01:04.117", "Id": "15614", "Score": "0", "body": "Thank you very much for your code review, you show me complitly different way how to structure code, I learned a lot. Its took a lot of time to understand/debug the code but with a few changes i make it works, please see the EDIT" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-03-09T00:10:15.160", "Id": "15629", "Score": "0", "body": "@Cygal ha! I thought that the spelling was off! I guess I should have looked it up." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-03-09T00:13:24.573", "Id": "15630", "Score": "0", "body": "@Cygal I thought of using `delegate` or `on` (and use `prop` or `data` instead of `att`r) but I didn't know what version of jQuery was being used. So I decided to stick with what I saw." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-03-09T00:15:34.533", "Id": "15631", "Score": "0", "body": "@InTry Glad I could help. It is also good exercise for me. :) The edit only contains a few lines. Did it cut you off?" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-03-09T07:56:51.507", "Id": "15658", "Score": "0", "body": "I just posted/edited parts that I had to change in order to make it works." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-03-09T08:06:13.650", "Id": "15659", "Score": "0", "body": "@natedavisolds Actually, `.live()` is not needed at all AFAIK." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-03-09T08:47:37.140", "Id": "15662", "Score": "0", "body": "And thanks for `.prop()`, I didn't know about it. Since it's 1.6+, I think it's safe to recommend it now." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-03-10T20:00:46.457", "Id": "15735", "Score": "0", "body": "question, is it really needed/faster to use function if you use it just once, eg. buildLoadImage function? (somehow I have feeling that my old code was faster ;) )" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-03-10T23:45:26.970", "Id": "15743", "Score": "0", "body": "@InTry for me using buildLoadImage is for readability. It helps me understand what the code is doing when I return after some time away from it. I do this because I believe that maintaining code has the greatest cost. There is probably quite a few ways to improve the speed of this code. I'm not sure if the difference is noticable we could test it of course... or fine tune it." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-03-11T13:12:09.657", "Id": "15750", "Score": "0", "body": "indeed that's big advantage." } ], "meta_data": { "CommentCount": "11", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-03-08T03:51:33.817", "Id": "9800", "ParentId": "9780", "Score": "2" } } ]
{ "AcceptedAnswerId": "9800", "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-03-07T19:24:59.803", "Id": "9780", "Score": "2", "Tags": [ "javascript", "jquery", "beginner", "html", "css" ], "Title": "Query, populate, show, hide data" }
9780
<p>This code feels like it goes through too many conversions to accomplish my goal:</p> <blockquote> <p>based on an IEnumerable of ids get those objects from a data store and set their <code>DisplayOrder</code> property to the position of the associated id.</p> </blockquote> <p>Is there a more elegant solution that I'm missing?</p> <pre><code>public void ReorderElements(IEnumerable&lt;int&gt; elementSks) { var elementsToReorder = GetSession().QueryOver&lt;DocumentElement&gt;() .WhereRestrictionOn(de =&gt; de.DocumentElementSk).IsIn(elementSks.ToArray()).List(); var elementOrder = elementSks.Select((sk, i) =&gt; new { Sk = sk, Order = i }) .ToDictionary(p =&gt; p.Sk, p =&gt; p.Order); elementsToReorder.ToList() .ForEach(e =&gt; e.DisplayOrder = elementOrder[e.DocumentElementSk]); this.Save(elementsToReorder); } </code></pre>
[ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-03-07T19:55:05.303", "Id": "15511", "Score": "0", "body": "Are the elementSks in any particular order when the enter the method?" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-03-07T21:40:46.460", "Id": "15534", "Score": "0", "body": "@sgriffinusa The ids are posted in order from a web page and then sent to this repository method." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-03-07T21:43:07.223", "Id": "15535", "Score": "0", "body": "Sorry, I should have been more specific, what I want to know is if they are sorted." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-03-07T21:46:49.630", "Id": "15536", "Score": "0", "body": "@sgriffinusa yes the ids are in the order I want them in. The elements retrieved from the data store are ordered by their primary key. So I have to update them based on the position of the ids in `elementSks`." } ]
[ { "body": "<p>If the list on input is going to be short, or if performance doesn't matter to you, you can simplify the code by using <code>IndexOf()</code> instead of the dictionary:</p>\n\n<pre><code>public void ReorderElements(IEnumerable&lt;int&gt; elementSks)\n{\n var elementsToReorder = GetSession().QueryOver&lt;DocumentElement&gt;()\n .WhereRestrictionOn(de =&gt; de.DocumentElementSk).IsIn(elementSks.ToArray()).List();\n\n var elementOrder = elementSks.ToList();\n\n foreach(var element in elementsToReorder)\n element.DisplayOrder = elementOrder.IndexOf(element.DocumentElementSk);\n\n this.Save(elementsToReorder);\n}\n</code></pre>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-03-07T20:57:57.040", "Id": "9789", "ParentId": "9782", "Score": "2" } }, { "body": "<p>Please try this. I wrote this without testing or even compiling.</p>\n\n<pre><code>public void ReorderElements(IEnumerable&lt;int&gt; elementSks)\n{\n var skToElementsToReorder = GetSession().QueryOver&lt;DocumentElement&gt;()\n .WhereRestrictionOn(de =&gt; de.DocumentElementSk).IsIn(elementSks.ToArray())\n .ToDictionary(el =&gt; el.DocumentElementSk, el =&gt; el);\n\n int index = 0;\n foreach(int sk in elementSks)\n {\n // Assumes that the key exists - the .IsIn restriction right before helps\n skToElementsToReorder[sk].DisplayOrder = index++;\n }\n\n this.Save(elementsToReorder);\n}\n</code></pre>\n\n<p>Somehow I think that this can help: <a href=\"http://code.msdn.microsoft.com/101-LINQ-Samples-3fb9811b\" rel=\"nofollow noreferrer\">http://code.msdn.microsoft.com/101-LINQ-Samples-3fb9811b</a> (as long as you can zip elementSks together with an index. Let me try a simpler version:</p>\n\n<pre><code>public class /* or struct ? */Element \n{\n public string name;\n public in sk;\n public int index;\n}\n\n// I am not fluent in LINQ, but Linq.Zip might help to generate these?\npublic class SkTuple\n{\n int sk;\n int index;\n}\n\n// Now you have an `IEnumerable` of each somehow, and you want to do an update at the same time as you do a join ... like this? \n</code></pre>\n\n<p><a href=\"https://stackoverflow.com/questions/709560/linq-in-line-property-update-during-join\">https://stackoverflow.com/questions/709560/linq-in-line-property-update-during-join</a></p>\n\n<p>This kind of got me thinking that maybe SQL is king after all - perhaps you want to just save this list of ids into a temp table where table id will be the index, and then call a stored procedure which will use a join and an update like this one:</p>\n\n<p><a href=\"http://geekswithblogs.net/faizanahmad/archive/2009/01/05/join-in-sql-update--statement.aspx\" rel=\"nofollow noreferrer\">http://geekswithblogs.net/faizanahmad/archive/2009/01/05/join-in-sql-update--statement.aspx</a></p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-03-08T03:43:28.207", "Id": "15548", "Score": "0", "body": "The linq to retrieve `elementsToReorder` is NHibernate's new QueryOver syntax. It's just a rehashing of their ICriteria expression syntax. It boils down to SQL and doesn't have that much affect on performance. Everything after the object retrieval is what I'm most worried about." } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-03-08T01:48:58.623", "Id": "9799", "ParentId": "9782", "Score": "1" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "4", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-03-07T19:41:36.667", "Id": "9782", "Score": "5", "Tags": [ "c#", "linq" ], "Title": "Reorder objects based on provided enumerable order" }
9782
<p>I'm trying to make an audio file tag editor, but I ran into some serious performance issues. Here's my method for loading files:</p> <pre><code>private void LoadFiles(params string[] fileNames) { foreach (string fileName in fileNames) { string path = fileName; if (loadedSongs.ContainsKey(path)) continue; new Thread(new ThreadStart(() =&gt; { using (TagFile file = TagFile.Create(path)) { Song song = new Song() { Album = file.Tag.Album, AlbumArtists = file.Tag.AlbumArtists, Artists = file.Tag.Performers, BeatsPerMinute = (file.Tag.BeatsPerMinute != 0 ? (uint?)file.Tag.BeatsPerMinute : null), // ...snip... }; lock (this.loadedSongs) { this.loadedSongs.Add(path, song); } this.Invoke((MethodInvoker)delegate { int rowId = songDataGrid.Rows.Add(); DataGridViewRow row = songDataGrid.Rows[rowId]; UpdateRow(row, song); }); } })).Start(); } } </code></pre> <p>So I have a <code>Song</code> class defined which is really just a container for the various tags that <code>TagLib.File</code> provides, so I don't need to keep a handle on the file.</p> <p>I have a few problems with this function though:</p> <ul> <li><p>It is incredibly slow. Even with threading, it takes about 12 seconds before the DataGridView even <em>updates and adds the first rows</em> if I load 2GB of files (on my machine).<br> That may not seem long, but imagine if a user adds 10 or 20GB of music - they could be waiting several minutes before they can use the application.</p></li> <li><p>The <code>songDataGrid.Rows.Add()</code> call doesn't seem to execute immediately - it seems to do it in "batches." I don't know if the problem is the TagLib Sharp library or with the DataGridView control, or if I'm just imagining things. It's probably the fact that the <code>TagLib.File.Create()</code> function finishes on all the Threads at the same time, then the rest of the code is fast.</p></li> <li><p>This takes up a LOT of memory - once this runs, my app has over 1GB of memory in use until the garbage collector is run (at which point it dwindles down to ~80k, which is alright). I believe this is because TagLib loads the entire file into memory. I am disposing the file properly, as far as I know.</p></li> </ul> <p>I don't know if my issues are because of limitations of TabLib or it's something in my code.</p> <p>Note that I don't really care that much if it takes several seconds/minutes to load several gigabytes worth of files. What I really want is to curb memory usage as well as immediate addition into the DataGridView so that the user can at least edit the first few rows of the grid while the rest of the application is loading. </p> <p>What can I change?</p> <hr> <p><strong>Update</strong> I know that in my personal research of the subject, I noticed a lot of people complaining that TagLib is kind of slow. It's mostly likely because of your code (as it was in my situation). I've alleviated some of the problems, so in case someone else stumbles on this post with a similar issue, I'll give a quick update on my predicament. </p> <p>Thanks to Dan Lyons, I've refactored my code to use a different threading and update model, which makes the method much snappier. </p> <p>It was slow for two reasons: because I was locking access to a Dictonary plus invoking a UI update, and the fact that I was parsing the album art images in the method itself.</p> <ul> <li><p>To fix the locking/UI issue, I used a BackgroundWorker and did the updates on the RunWorkerCompleted event, which is called on the UI thread, so no invocation is necessary. Doing this was orders of magnitudes more efficient than blindly running my own Thread.</p></li> <li><p>If you're using TagLib for dealing with album art, it can spike your memory through the roof if handled poorly. If you're showing the art to the user at all, I would advise against storing the full ByteVector worth of data in memory, and instead convert it to a resized Bitmap and store <em>that</em> in memory. If the user wishes to modify or export the artwork, reload the file. I was able to get my app down to ~60k memory maximum with 2GB of songs + album art.</p></li> </ul>
[]
[ { "body": "<p>There are a couple suggestions:</p>\n\n<ul>\n<li>First, you do not need to use your path variable - it is simply fileName re-packaged. This is probably of negligible impact, but there's no reason to keep the extra string around, either.</li>\n<li>Next, a filesystem is not going to give you much in the way of performance gains by multi-threading access. In fact, if you're doing this on a spindle drive, you are probably making things worse. Instead of generating threads for every file, toss your entire loop into a separate async method and have the loop run on a single thread. You still get the UI responsiveness of it being a background task this way.</li>\n<li>You may want to avoid hand-building threads. It is generally preferable to use one of the other mechanisms in the language instead, such as ThreadPool, Task&lt;T&gt;, or even BeginAsync or BackgroundWorker (since you seem to be in a UI).</li>\n<li>Consider having your async loop build its own collection and doing a batch add to loadedSongs later. This removes the need to synchronize access to loadedSongs until the very end and the corresponding locking overhead.</li>\n<li>Finally, I would suspend layout on your grid until the update is complete. DataGridView is pretty poor at updating itself quickly. You almost <em>always</em> win by suspending, making all your updates in a batch, and then resuming layout.</li>\n</ul>\n\n<p>However, my suspicion is that the biggest gain you will get is implementing your own tag reader library rather than using TagLib, assuming you are correct that it reads the entire file. I/O is one of the most expensive things you can do on a computer. ID3v1 and ID3V2 tags should generally appear in the first X bytes of the file, so you only have to read until the end of the tag, rather than the entire file.</p>\n\n<p>As with any performance issue, though, <strong>you need to run this through a profiler</strong>. The results may very well point you in a completely different direction. For example, it may reveal that TagLib isn't actually reading the entire file. At the very least, it provides baselines to use in determining if you are making meaningful gains.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-03-09T19:02:16.627", "Id": "15693", "Score": "0", "body": "Thanks for the suggestions. This is actually very helpful, particularly the idea of processing first, updating last. Only one caveat - the reason I am duplicating the path variable is because of the [outer variable trap](http://stackoverflow.com/a/3416792/152698) that occurs because of the fact that I am using a lambda expression." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-03-09T20:27:48.503", "Id": "15702", "Score": "0", "body": "Wow, just from doing two of those things (point 3 & 4, using BackgroundWorker and removing the need for syncronization), this method is magnitudes faster, and it took very little code to do so." } ], "meta_data": { "CommentCount": "2", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-03-09T18:49:31.080", "Id": "9864", "ParentId": "9785", "Score": "4" } } ]
{ "AcceptedAnswerId": "9864", "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-03-07T19:25:42.787", "Id": "9785", "Score": "5", "Tags": [ "c#" ], "Title": "Adding many items generated from Taglib# is incredibly slow and expensive, how can I increase the performance?" }
9785
<p>I'm new to rails. I am using Redis instead of something backed w/ ActiveRecord. I need to validate the presence of location, categories, start_date, and end_date. I then need to check that start_date and end_date are valid dates, that start_date comes before end_date. And that location matches a regex [A-Za-z_]. And that categories.length > 0. Since the start_date and end_date parameters in my model's setters are Date objects, should I check for valid dates and convert them in my controller. Then have my model's setters take care of the rest of the validation? </p> <p>I just don't know where to put the validations: in my model or controller?</p> <p>Model:</p> <pre><code>class MyThingie def self.set_x(location, categories, start_date, end_date, value) updates = {} for date in (start_date .. end_date) # ... end $redis.mset(*updates.flatten) end def self.set_y(location, categories, default) updates = {} for category in categories # ... end $redis.mset(*updates.flatten) end def self.set_z(location, categories, start_date, end_date, block) if block updates = {} for date in (start_date .. end_date) # ... end $redis.mset(*updates.flatten) else deletes = [] for date in (start_date .. end_date) # ... end $redis.del(*deletes) end end end </code></pre> <p>Controller:</p> <pre><code>class MyThingieController &lt; ApplicationController # ... def create begin method = params[:method] location = params[:location] categories = params[:categories] s_start_date = params[:start_date] s_end_date = params[:end_date] if method == "normal" value = params[:value] start_date = Date.strptime(s_start_date, "%m/%d/%Y") end_date = Date.strptime(s_end_date, "%m/%d/%Y") MyThingie.set_x(location, categories, start_date, end_date, value) elsif method == "default" default = params[:default] MyThingie.set_y(location, categories, default) elsif method == "block" block = params[:block] start_date = Date.strptime(s_start_date, "%m/%d/%Y") end_date = Date.strptime(s_end_date, "%m/%d/%Y") MyThingie.set_z(location, categories, start_date, end_date, block) else raise "Invalid form submit" end rescue Exception =&gt; e errors = [e.message] respond_to do |format| format.json do json = Jsonify::Builder.new json.errors errors a = json.compile! render :status =&gt; 400, :json =&gt; a end end else respond_to do |format| format.json do json = Jsonify::Builder.new json.msg "Update successful." a = json.compile! render :json =&gt; a end end end end </code></pre> <p>Here the keys are like</p> <p>mythingie:location:date = value</p> <p>mythingie:location:default = default</p> <p>mythingie:location:date:z = "true"</p>
[]
[ { "body": "<p>You should not validate your model in controller.\nImagine situation, where you need to create another controller, for example it will be the API controller with same logic. What you will do? Copy your code and paste?\nAnd what about unit testing? ;)</p>\n\n<p><a href=\"http://www.sitepoint.com/10-ruby-on-rails-best-practices/\" rel=\"nofollow\">http://www.sitepoint.com/10-ruby-on-rails-best-practices/</a></p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-03-09T15:38:14.767", "Id": "9856", "ParentId": "9788", "Score": "0" } }, { "body": "<p>In your model.</p>\n\n<p>You can include ActiveModel::Validations directly in your model without relying on ActiveRecord for persistence.</p>\n\n<p>See <a href=\"http://api.rubyonrails.org/classes/ActiveModel/Validations.html\" rel=\"nofollow\">ActiveModel::Validations</a> &amp; the <a href=\"http://rubygems.org/gems/date_validator\" rel=\"nofollow\">date_validator gem</a></p>\n\n<p>A quick example more relevant to you;</p>\n\n<pre><code>class MyThingie\n\n include ActiveModel::Validations\n\n validates :start_date, :presence =&gt; true \n validates :end_date, :presence =&gt; true \n\n # Check out the date_validator gem, it allows things like \n validates_date_of :end_date, :after =&gt; :start_date\n\n validates_format_of :location, :with =&gt; /[A-Za-z]/\n\n # ... \nend\n</code></pre>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-03-13T12:37:18.133", "Id": "9962", "ParentId": "9788", "Score": "4" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-03-07T20:57:31.067", "Id": "9788", "Score": "3", "Tags": [ "ruby", "ruby-on-rails" ], "Title": "Rails and Redis: how should I handle validation here?" }
9788
<p>I tried to solve one <a href="http://www.spoj.pl/problems/PALIN/" rel="nofollow" title="problem">SPOJ problem</a>. I wrote one program in Python, however, it got accepted by the SPOJ judges, but its total execution time is 2.88s. The same algorithm used in C language having execution time 0.15s.</p> <p>Please offer suggestions on improving this approach.</p> <pre><code>def tempPalindrome(inputString): """ Code for finding out temporary palindrome. used by nextPalindrome function""" inputList = list(inputString) length = len(inputList) halfL = inputList[:length/2] halfL.reverse() if (length % 2) == 0: inputList = inputList[:length&gt;&gt;1] + halfL else: inputList = inputList[:(length&gt;&gt;1)+1] + halfL #if new palindrome is greater than given number then return otherwise increment it if ''.join(inputList) &gt; inputString.zfill(length): return inputList else: position = length &gt;&gt; 1 if length %2 == 0: position-=1 for i in range(position, -1, -1): if inputList[i] == '9': inputList[i] = '0' else: inputList[i] = chr(ord(inputList[i]) + 1) break if (i == 0) and (inputList[i] == '0'): inputList = ['1'] + inputList length += 1 halfL = inputList[:length/2] halfL.reverse() if (length % 2) == 0: inputList = inputList[:length&gt;&gt;1] + halfL else: inputList = inputList[:(length&gt;&gt;1)+1] + halfL return inputList return None def nextPalindrome(): """ Take an input from user and find next palindrome""" inputs = list() noOfCases = int(raw_input()) for i in range(noOfCases): inputs.append(raw_input()) for inputString in inputs: inputList = tempPalindrome(inputString) print ''.join(inputList) return None if __name__ == '__main__': nextPalindrome() </code></pre> <p>By profiling this code using cProfile profiler, I get the following output:</p> <blockquote> <pre class="lang-none prettyprint-override"><code> &gt;&gt;&gt; 1 99 101 119 function calls in 3.111 CPU seconds Ordered by: standard name ncalls tottime percall cumtime percall filename:lineno(function) 1 0.000 0.000 3.111 3.111 &lt;string&gt;:1(&lt;module&gt;) 2 0.000 0.000 0.000 0.000 AsyncFile.py:107(flush) 4 0.000 0.000 0.000 0.000 AsyncFile.py:121(fileno) 4 0.000 0.000 0.000 0.000 AsyncFile.py:16(AsyncPendingWrite) 2 0.000 0.000 0.000 0.000 AsyncFile.py:160(readline_p) 4 0.000 0.000 0.000 0.000 AsyncFile.py:261(write) 6 0.000 0.000 0.000 0.000 AsyncFile.py:55(__checkMode) 6 0.000 0.000 0.000 0.000 AsyncFile.py:67(__nWrite) 8 0.000 0.000 0.000 0.000 AsyncFile.py:88(pendingWrite) 2 0.000 0.000 0.000 0.000 AsyncIO.py:44(readReady) 2 0.000 0.000 3.111 1.555 DebugClientBase.py:318(raw_input) 2 0.000 0.000 3.111 1.555 DebugClientBase.py:34(DebugClientRawInput) 2 0.000 0.000 0.000 0.000 DebugClientBase.py:374(handleLine) 2 0.000 0.000 0.000 0.000 DebugClientBase.py:965(write) 2 0.000 0.000 3.110 1.555 DebugClientBase.py:987(eventLoop) 1 0.000 0.000 0.000 0.000 nextPalindrome.py:24(tempPalindrome) 1 0.000 0.000 3.111 3.111 nextPalindrome.py:65(nextPalindrome) 7 0.000 0.000 0.000 0.000 socket.py:223(meth) 2 0.000 0.000 0.000 0.000 utf_8.py:15(decode) 2 0.000 0.000 0.000 0.000 {_codecs.utf_8_decode} 7 0.000 0.000 0.000 0.000 {getattr} 7 0.000 0.000 0.000 0.000 {len} 1 0.000 0.000 0.000 0.000 {method 'append' of 'list' objects} 2 0.000 0.000 0.000 0.000 {method 'decode' of 'str' objects} 1 0.000 0.000 0.000 0.000 {method 'disable' of '_lsprof.Profiler' objects} 1 0.000 0.000 0.000 0.000 {method 'encode' of 'str' objects} 2 0.000 0.000 0.000 0.000 {method 'encode' of 'unicode' objects} 4 0.000 0.000 0.000 0.000 {method 'fileno' of '_socket.socket' objects} 2 0.000 0.000 0.000 0.000 {method 'find' of 'str' objects} 6 0.000 0.000 0.000 0.000 {method 'find' of 'unicode' objects} 2 0.000 0.000 0.000 0.000 {method 'join' of 'str' objects} 4 0.000 0.000 0.000 0.000 {method 'recv' of '_socket.socket' objects} 2 0.000 0.000 0.000 0.000 {method 'reverse' of 'list' objects} 2 0.000 0.000 0.000 0.000 {method 'rfind' of 'str' objects} 6 0.000 0.000 0.000 0.000 {method 'rfind' of 'unicode' objects} 3 0.000 0.000 0.000 0.000 {method 'sendall' of '_socket.socket' objects} 1 0.000 0.000 0.000 0.000 {method 'zfill' of 'unicode' objects} 2 0.000 0.000 0.000 0.000 {range} 2 3.110 1.555 3.110 1.555 {select.select} </code></pre> </blockquote>
[ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-03-06T17:52:43.090", "Id": "15465", "Score": "0", "body": "Could you also provide the timing enviroment? Otherwise we'll have to set it up on our own, it could give different result, we're lazy, etc... etc... :)" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-03-06T18:03:50.427", "Id": "15466", "Score": "0", "body": "Actually when I submitted on spoj then it is showing total execution time as 2.88s. Do you need profiled environment or something else." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-03-06T18:53:51.027", "Id": "15469", "Score": "1", "body": "I tried to time `tempPalindrome` building a random number with `num = ''.join(random.choice('0123456789') for _ in xrange(1000000))` and the [ipython](http://ipython.org/) timeit I got `~ 680ms`. Sorry, but I'm not able to reproduce that 2.88s." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-03-06T19:26:12.507", "Id": "15471", "Score": "0", "body": "@RikPoggi The SPOJ machines are very old and slow." } ]
[ { "body": "<pre><code>def tempPalindrome(inputString):\n</code></pre>\n\n<p>Python convention is to name function lowercase_with_underscores. Also what is temporary about this palindrome?</p>\n\n<pre><code> \"\"\" Code for finding out temporary palindrome. used by nextPalindrome function\"\"\"\n inputList = list(inputString)\n</code></pre>\n\n<p>Don't use lists. You shouldn't need to convert into lists, and it'll be faster if you avoid that.</p>\n\n<pre><code> length = len(inputList)\n halfL = inputList[:length/2]\n halfL.reverse()\n</code></pre>\n\n<p>You can reverse a string by using <code>string[::-1]</code>. </p>\n\n<pre><code> if (length % 2) == 0:\n inputList = inputList[:length&gt;&gt;1] + halfL\n else:\n inputList = inputList[:(length&gt;&gt;1)+1] + halfL\n</code></pre>\n\n<p>I suggest not using <code>&gt;&gt; 1</code> to divide the length in half. Its not going to give you a speed advantage in python, and makes it difficult to read.</p>\n\n<pre><code> #if new palindrome is greater than given number then return otherwise increment it\n if ''.join(inputList) &gt; inputString.zfill(length):\n</code></pre>\n\n<p>Since you derived <code>length</code> from the length of <code>inputString</code>, why are you zfilling it? Also, not the extra work required to convert back from the list to a string</p>\n\n<pre><code> return inputList\n else:\n\n position = length &gt;&gt; 1\n if length %2 == 0:\n position-=1\n for i in range(position, -1, -1):\n if inputList[i] == '9':\n inputList[i] = '0'\n else:\n inputList[i] = chr(ord(inputList[i]) + 1)\n break\n</code></pre>\n\n<p>You are basically reimplementing the process of incrementing a number. Instead, convert your string an actual integer, and then add one to it. <strong>EDIT</strong> I was wrong. If your numbers are very large converting back and between integers and strings of the numbers will be expensive. For that reason you shouldn't do it. But this for loop is a bad plan because its depends on python's loop mechanism not a c loop.</p>\n\n<pre><code> if (i == 0) and (inputList[i] == '0'):\n</code></pre>\n\n<p>You don't need any of those parens.</p>\n\n<pre><code> inputList = ['1'] + inputList\n length += 1\n\n halfL = inputList[:length/2]\n halfL.reverse()\n if (length % 2) == 0:\n inputList = inputList[:length&gt;&gt;1] + halfL\n else:\n inputList = inputList[:(length&gt;&gt;1)+1] + halfL\n return inputList\n</code></pre>\n\n<p>You've done this before. Write a function that handles the logic.</p>\n\n<pre><code> return None\n</code></pre>\n\n<p>Seeing as you should never reach this, why have you included it?</p>\n\n<pre><code>def nextPalindrome():\n \"\"\" Take an input from user and find next palindrome\"\"\"\n inputs = list()\n noOfCases = int(raw_input())\n for i in range(noOfCases):\n inputs.append(raw_input())\n for inputString in inputs:\n inputList = tempPalindrome(inputString) \n print ''.join(inputList)\n</code></pre>\n\n<p>I'm not sure why you are storing the data in a list, and then process it in another loop. Just process the data as you read it. </p>\n\n<pre><code> return None\n\nif __name__ == '__main__':\n nextPalindrome()\n</code></pre>\n\n<p>Here is my reworking of your code</p>\n\n<pre><code>def make_palindrome(number, odd):\n text = str(number)\n if odd:\n return text + text[::-1][1:]\n else:\n return text + text[::-1]\n\n\ndef palindrome(inputString):\n \"\"\" Code for finding out temporary palindrome. used by nextPalindrome function\"\"\"\n\n # handle the case that increases the input length as a special case\n if inputString.count('9') == len(inputString):\n return '1' + '0' * (len(inputString) - 1) + '1'\n\n if len(inputString) % 2 == 0:\n odd = False\n number = int(inputString[:len(inputString)/2])\n else:\n odd = True\n number = int(inputString[:len(inputString)/2 + 1])\n\n current = make_palindrome(number, odd)\n if current &gt; inputString:\n return current\n else:\n return make_palindrome(number + 1, odd)\n\ndef main():\n \"\"\" Take an input from user and find next palindrome\"\"\"\n noOfCases = int(raw_input())\n for i in range(noOfCases):\n print palindrome(raw_input()) \n return None\n\nif __name__ == '__main__':\n main()\n</code></pre>\n\n<p>I've managed to make it simpler, mostly by using appropriate data types i.e. strings and ints rather then lists. Because it does less, it should also be faster. I haven't done extensive testing, so it may not handle all cases correctly.</p>\n\n<p><strong>EDIT</strong></p>\n\n<p>Better version stealing from Rok Poggi</p>\n\n<pre><code>def make_palindrome(text, odd):\n return text + text[- odd - 1::-1]\n\ndef upped(match):\n content = match.group(0)\n return chr( ord(content[0]) + 1 ) + '0' * (len(content) - 1)\n\ndef palindrome2(inputString, extract = re.compile(r'[^9]9*$')):\n \"\"\" Code for finding out temporary palindrome. used by nextPalindrome function\"\"\"\n\n # handle the case that increases the input length as a special case\n if all(letter == '9' for letter in inputString):\n return '1' + '0' * (len(inputString) - 1) + '1'\n\n length = len(inputString)\n odd = length % 2\n number = inputString[:length/2 + odd]\n\n current = make_palindrome(number, odd)\n if current &gt; inputString:\n return current\n else:\n number = extract.sub(upped, number) \n return make_palindrome(number, odd)\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-03-07T16:58:55.447", "Id": "15493", "Score": "0", "body": "thanks for explaining stepwise, i got your point. it's working fine with quite less execution time." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-03-07T20:14:56.420", "Id": "15512", "Score": "0", "body": "I don't think it was a bad idea to reimplement the process of incrementing a number, mainly because he'll be working on long integers and the convertion back and forth will take some time. I explained that better in my answer. I've also borrowed the barebone of your rewrite to write my solution, I hope it's ok :)" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-03-08T09:07:18.077", "Id": "15564", "Score": "0", "body": "It does look nicer :) From a quick timing it seems though that `extract.sub` is 19:1 slower than `extract.search`. In the other scenario I got the same performances. Without the `middle` charachter you're also bound to to check for 9 in the whole string, and `all()` is almost 44 times slower than `.count()`, but again the odds are 1 to ∞" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-03-08T17:28:29.700", "Id": "15601", "Score": "0", "body": "@RikPoggi, I'm not sure that comparing `extract.sub` and `extract.search` is fair because `extract.sub` does a lot more work then `extract.search`. I'm not following you on the `middle` character. I'm sure that I could optimize the `9999999` check, but since, as you mention, its highly unlikely to check more then a few characters I didn't bother. My own performance testing shows very similiar timings between the two functions." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-03-09T09:09:45.427", "Id": "15664", "Score": "0", "body": "@Win: I didn't compare them directly. I compared the whole funcions, if I used a 1000000 digits random number that executes those else sentences (in both mine and yours) and I got 19.5 *ms* with yours against 1.1 *ms* with mine. That's why I said that `search` seems to be better than `sub`. I don't know either what's that `middle` nonsense ;) Anyway except for that case, I got similar performances too." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-03-09T18:11:23.153", "Id": "15687", "Score": "0", "body": "@RikPoggi, I see. Probably I'm paying large penalty because of the function call." } ], "meta_data": { "CommentCount": "6", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-03-06T19:13:27.877", "Id": "9760", "ParentId": "9790", "Score": "4" } }, { "body": "<p>I won't give you the full answer of how to make your code faster, but <a href=\"https://stackoverflow.com/questions/843671/profiling-in-python-who-called-the-function\">this helpful stackoverflow</a> post shows a nice tool to visualize your code (that has been profiled). In order to profile I made the following change:</p>\n\n<pre><code>noOfCases = 10\ninputs = ['50','20','100','20','30','40','50','80','10','1004']\n#for i in range(noOfCases):\n# inputs.append(raw_input())\n</code></pre>\n\n<p>The command I used to profile was:</p>\n\n<pre><code>python -m cProfile -o output.pstats ./yourScript\n</code></pre>\n\n<p>And then created ( I renamed your script foobar.py ):<img src=\"https://i.stack.imgur.com/iGMgh.png\" alt=\"enter image description here\"></p>\n\n<p>with the following command(assuming you have download gprof2dot.py from <a href=\"http://code.google.com/p/jrfonseca/source/browse/gprof2dot.py?repo=gprof2dot\" rel=\"nofollow noreferrer\">here</a>:</p>\n\n<pre><code>gprof2dot.py -f pstats output.pstats | dot -Tpng -o output.png\n</code></pre>\n\n<p>From this visualization you can see which calls take up the most time, so you can focus your efforts there. Then you can compare new results with old results, slow refining your calculation times! </p>\n\n<p>Profiling is a keep step in analyzing were to focus attention when redesigning (with respect to execution time) - hope this helps.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-03-07T00:56:46.043", "Id": "15479", "Score": "0", "body": "-1, I'm sorry but this is code review. Not tell people how to profile their code. (Nice use of graphs though)" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-03-07T17:28:43.490", "Id": "15497", "Score": "0", "body": "@MarmOt Good, This approach helped me quite a lot. thanks" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-03-08T13:10:50.987", "Id": "15573", "Score": "0", "body": "@WinstonEwert That's a bit unfair. The question was posted to Stack Overflow. This answer was posted there was and was directly relevant to the question as asked. The question only migrated to Code Review 16 hours ago. Perhaps the question should not have been migrated, but this remains a helpful answer that I would not like to see deleted for fear of downvotes. (That said, it would be more helpful if it profiled with representative data, i.e. with tens of thousands of digits.)" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-03-08T13:30:59.443", "Id": "15577", "Score": "0", "body": "@Weeble I won't delete it (maybe someone else will) - I responded here ( for some reason this site doesn't get the 'migrated from' date correct... this was posted a while ago ) it is possibly not enough to qualify as a code review - when I have time I'll update it to show some specific things he can change to improve the execution time" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-03-08T14:33:11.413", "Id": "15582", "Score": "0", "body": "Ah, sorry, I read the question before it was migrated and then when I came back I assumed the timestamps were accurate." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-03-08T17:13:30.500", "Id": "15598", "Score": "0", "body": "@Weeble, actually the original poster asked his question on stackoverflow, then reasked on code-review, then the original question got migrated, and finally both questions were merged. Hence the confusion about where the answers were posted." } ], "meta_data": { "CommentCount": "6", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-03-06T19:25:03.713", "Id": "9762", "ParentId": "9790", "Score": "1" } }, { "body": "\n\n<h2>Review</h2>\n\n<p>I'm not going in details, since <a href=\"https://codereview.stackexchange.com/a/9760/10415\"><em>@Winston Ewert</em></a> already coverd pretty much everything (but I disagree on one point):</p>\n\n<ul>\n<li>There's no need to use lists, strings are iterable too.</li>\n<li>There's no need for bitwise operations <code>&gt;&gt;</code>, just divide by two ig that's what you need.</li>\n<li>Explicitly call the floor division <code>//</code> (see <a href=\"http://www.python.org/dev/peps/pep-0238/\" rel=\"nofollow noreferrer\">PEP238</a>), this will give you compatibility with Python 3.</li>\n<li>Follow <a href=\"http://www.python.org/dev/peps/pep-0008/\" rel=\"nofollow noreferrer\">PEP8</a> and its naming convention.</li>\n<li>It was a <strong>good idea to reimplement the incrementing process</strong>. The reason is that you have long integers, and a whole conversion would be slower.</li>\n<li>But you <strong>definetly need to do that better!</strong></li>\n</ul>\n\n<h2><a href=\"http://docs.python.org/library/functions.html#all\" rel=\"nofollow noreferrer\"><code>all</code></a> instead of <a href=\"http://docs.python.org/library/stdtypes.html#str.count\" rel=\"nofollow noreferrer\"><code>count</code></a></h2>\n\n<p>This:</p>\n\n<pre class=\"lang-py prettyprint-override\"><code>if inputString.count('9') == len(inputString):\n</code></pre>\n\n<p>aside than the fact that it could work on the first half of the string (moving the check a little later in the work-flow):</p>\n\n<pre class=\"lang-py prettyprint-override\"><code>if half.count('9') == len(half):\n</code></pre>\n\n<p>has its advantage: for a given length will always took the same amount of time. But what are the odds of having a very very long string of '9' only? Very small, so I think it would be better a different approach:</p>\n\n<pre class=\"lang-py prettyprint-override\"><code>if all(digit == '9' for digit in half):\n</code></pre>\n\n<p>This will take considerably more for special cases full of '9', but at the meantime considerably less in all the other (that are more). Furthermore if you have a special case the execution is going to end the very next line, so it's alreay a \"fast\" case. I think the code should be improved for all the others.</p>\n\n<h2>The full power of <code>%</code></h2>\n\n<p>There shouldn't be need for <code>True</code> and <code>False</code> booleans, there's already:</p>\n\n<pre class=\"lang-py prettyprint-override\"><code>odd = length % 2\n</code></pre>\n\n<p>That will be <code>1</code> or <code>0</code>. Also this <code>1</code> or <code>0</code> will very useful later.</p>\n\n<h2>Odd and even should be more similar</h2>\n\n<p>The algorithm should be improved to treat odd and even string length at the same way, or in a very similar way.</p>\n\n<p>This can be done with:</p>\n\n<pre class=\"lang-py prettyprint-override\"><code>def rik_make_palindrome(half, middle, odd):\n return (middle*(2-odd)).join((half,half[::-1]))\n</code></pre>\n\n<h2>Building the palindrome</h2>\n\n<p>If the first palindrome was too small, all you need to is to:</p>\n\n<pre class=\"lang-py prettyprint-override\"><code>if middle != '9':\n middle = str(int(middle) + 1)\n</code></pre>\n\n<p>increment the middle value (if the middle value is not <code>9</code>). Otherwise:</p>\n\n<pre class=\"lang-py prettyprint-override\"><code>sub = re.search(r'[^9]9*$', half)\nsub = str(int(sub.group()[0]) + 1) + '0' * (len(sub.group()) -1)\nhalf,middle = half[:-len(sub)] + sub, '0'\n</code></pre>\n\n<p><code>sub</code> will always match, since you'll get here only if you passed the <code>all</code> check. And this would be the \"wiser\" way to increment of one a very very long number.</p>\n\n<p>Note: I don't know if <em>regex</em> are allowed, otherwise you'll have to extract parse the string from the end and find the first non-9 digit. It wouldn't be hard to write in \"pure\" Python, just slower to run.</p>\n\n<h2>Final code</h2>\n\n<p>Let's put everything together:</p>\n\n<pre class=\"lang-py prettyprint-override\"><code>def rik_make_palindrome(half, middle, odd):\n return (middle*(2-odd)).join((half,half[::-1]))\n\ndef rik_palindrome(input_string, extract=re.compile(r'[^9]9*$')):\n length = len(input_string)\n odd = length % 2\n half,middle = input_string[:length // 2 + odd -1], input_string[length // 2]\n\n temp = rik_make_palindrome(half, middle, odd)\n if temp &gt; input_string:\n result = temp\n elif middle == '9' and all(digit == '9' for digit in half):\n result = '1' + '0' * (length - 1) + '1'\n else:\n if middle != '9':\n middle = str(int(middle) + 1)\n else:\n sub = extract.search(half)\n sub = str(int(sub.group()[0]) + 1) + '0' * (len(sub.group()) -1)\n half,middle = half[:-len(sub)] + sub, '0'\n\n result = rik_make_palindrome(half, middle, odd)\n return result\n</code></pre>\n\n<h2>Timing</h2>\n\n<p>This is <code>get_num()</code>:</p>\n\n<pre class=\"lang-py prettyprint-override\"><code>def get_num(digits=1000000):\n return ''.join(random.choice('0123456789') for _ in xrange(digits))\n</code></pre>\n\n<p>Where 1000000 is the maximum number of digits (from the <a href=\"http://www.spoj.pl/problems/PALIN/\" rel=\"nofollow noreferrer\">spoj</a> site).</p>\n\n<p>Small number of random digits:</p>\n\n<pre class=\"lang-py prettyprint-override\"><code>*** n = get_num(digits=1000) ***\n6.59 us -- rik_palindrome(n)\n17.1 us -- palindrome(n)\n51.4 us -- sus_palindrome(n)\n\n*** n = get_num(digits=1000-1) ***\n3.94 us -- rik_palindrome(n)\n17.3 us -- palindrome(n)\n51.4 us -- sus_palindrome(n)\n</code></pre>\n\n<p>Maximum number of randomr digits:</p>\n\n<pre class=\"lang-py prettyprint-override\"><code>*** n = get_num(digits=1000000) ***\n1.99 ms -- rik_palindrome(n)\n68.2 ms -- sus_palindrome(n)\n7.63 s -- palindrome(n)\n\n*** n = get_num(digits=1000000-1) ***\n1.98 ms -- rik_palindrome(n)\n80.2 ms -- sus_palindrome(n)\n13.2 s -- palindrome(n)\n</code></pre>\n\n<p>Any further test or improvement is more than welcome!</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-03-07T20:22:31.993", "Id": "15513", "Score": "0", "body": "It seems to me that you are incorrect for \"9992\"" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-03-07T20:42:40.490", "Id": "15516", "Score": "0", "body": "@WinstonEwert: Good call, Thanks! I was wondering if I had to move the all-9-check later, and it seems I should've. I just edited my answer and fixed it :)" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-03-08T01:14:21.033", "Id": "15543", "Score": "0", "body": "This answer reads more like a review of my answer then a review of the original code. You do make good points, and your technique for implementing the increment is very nice. But overall your version seems messier then it needs to be. See my updated post for a new version which steals your good ideas." } ], "meta_data": { "CommentCount": "3", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-03-07T20:11:52.583", "Id": "9783", "ParentId": "9790", "Score": "2" } }, { "body": "<p>You're copying a lot of lists. This is probably the root of your problem. </p>\n\n<p>Learn about the difference between <code>+</code>, <code>+=</code> and <code>append</code>, and consider that this may be implemented more efficiently either by working with list indices or slice objects, or by using generator sequences (see <code>itertools</code>).</p>\n\n<p>Also, your implementation looks really complex. Try something like this:</p>\n\n<pre><code>from itertools import ifilter, count\ndef ispalindrome(num): \n strnum = str(num)\n return strnum[::-1] == strnum\n\ndef nextpalindrome(num):\n return next(ifilter(ispalindrome, count(num+1)))\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-03-06T17:55:33.080", "Id": "15519", "Score": "0", "body": "there is a need to change in string frequently so i am changing it to list. And I have tried all the possible list elimination from my side but got failed. Is there another way to do this efficiently. And here how can I use itertools." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-03-06T18:11:23.930", "Id": "15520", "Score": "0", "body": "@SushantJain You have clearly not understood a word I wrote. Learn about the things I have told you to learn about." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-03-06T18:13:58.560", "Id": "15521", "Score": "0", "body": "Here i can't use this code because input number can be 10,000 digits long as specified in problem. So it will take so much time." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-03-06T18:20:19.343", "Id": "15522", "Score": "0", "body": "@SushantJain Good. Understand the things I wrote in my answer." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-03-06T18:20:27.200", "Id": "15523", "Score": "0", "body": "I think it is showing time limit exceeded. Look again" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-03-06T22:30:01.203", "Id": "15524", "Score": "1", "body": "This recommended implementation is inadequate for the specified range of inputs. With a million digit input this could end up going through 10^500000 iterations to find the next palindrome. This computation will not complete with all the resources in the universe." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-03-06T22:35:36.660", "Id": "15525", "Score": "0", "body": "@Weeble: It's not \"recommended\" for production use. It's an example of much simpler code." } ], "meta_data": { "CommentCount": "7", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-03-06T17:39:02.903", "Id": "9791", "ParentId": "9790", "Score": "2" } }, { "body": "<p>Generally the approach to finding out why code is so is to <a href=\"http://en.wikipedia.org/wiki/Profiling_%28computer_programming%29\" rel=\"nofollow\">profile</a> it.</p>\n\n<p>There's a module in the standard library called <a href=\"http://docs.python.org/library/profile.html\" rel=\"nofollow\"><code>profile</code></a>, which is easy to use. I've applied it to your code and I'm not sure why you're getting such slow speeds:</p>\n\n<pre><code>daenyth@Bragi tmp $ python2 palindrome.py \n1\nracecar\nracfcar\n 17 function calls in 2.796 seconds\n\n Ordered by: standard name\n\n ncalls tottime percall cumtime percall filename:lineno(function)\n 1 0.000 0.000 2.796 2.796 &lt;string&gt;:1(&lt;module&gt;)\n 1 0.000 0.000 0.000 0.000 palindrome.py:1(tempPalindrome)\n 1 0.000 0.000 2.796 2.796 palindrome.py:42(nextPalindrome)\n 1 0.000 0.000 0.000 0.000 {chr}\n 1 0.000 0.000 0.000 0.000 {len}\n 1 0.000 0.000 0.000 0.000 {method 'append' of 'list' objects}\n 1 0.000 0.000 0.000 0.000 {method 'disable' of '_lsprof.Profiler' objects}\n 2 0.000 0.000 0.000 0.000 {method 'join' of 'str' objects}\n 2 0.000 0.000 0.000 0.000 {method 'reverse' of 'list' objects}\n 1 0.000 0.000 0.000 0.000 {method 'zfill' of 'str' objects}\n 1 0.000 0.000 0.000 0.000 {ord}\n 2 0.000 0.000 0.000 0.000 {range}\n 2 2.796 1.398 2.796 1.398 {raw_input}\n\n\ndaenyth@Bragi tmp $ echo -e \"2\\nracecar\\nfoobarbazzabrabfoo\" | python2 palindrome.py \nracfcar\nfoobarbazzabraboof\n 25 function calls in 0.000 seconds\n\n Ordered by: standard name\n\n ncalls tottime percall cumtime percall filename:lineno(function)\n 1 0.000 0.000 0.000 0.000 &lt;string&gt;:1(&lt;module&gt;)\n 2 0.000 0.000 0.000 0.000 palindrome.py:1(tempPalindrome)\n 1 0.000 0.000 0.000 0.000 palindrome.py:42(nextPalindrome)\n 1 0.000 0.000 0.000 0.000 {chr}\n 2 0.000 0.000 0.000 0.000 {len}\n 2 0.000 0.000 0.000 0.000 {method 'append' of 'list' objects}\n 1 0.000 0.000 0.000 0.000 {method 'disable' of '_lsprof.Profiler' objects}\n 4 0.000 0.000 0.000 0.000 {method 'join' of 'str' objects}\n 3 0.000 0.000 0.000 0.000 {method 'reverse' of 'list' objects}\n 2 0.000 0.000 0.000 0.000 {method 'zfill' of 'str' objects}\n 1 0.000 0.000 0.000 0.000 {ord}\n 2 0.000 0.000 0.000 0.000 {range}\n 3 0.000 0.000 0.000 0.000 {raw_input}\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-03-06T18:10:11.387", "Id": "15526", "Score": "0", "body": "Have u changed anything in my code because i am getting quite different profiler(cProfile) output shown in my edited question." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-03-06T18:12:12.053", "Id": "15527", "Score": "0", "body": "@SushantJain: I only ran it on a small number since I didn't have a data set handy. That's probably why." } ], "meta_data": { "CommentCount": "2", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-03-06T17:58:27.633", "Id": "9792", "ParentId": "9790", "Score": "0" } }, { "body": "<p>Here are a few thoughts:</p>\n\n<ol>\n<li><p>Don't bother to store the inputs in a list, just convert and print as you go. (This saves memory, but not processing time)</p></li>\n<li><p>Converting strings to lists and back again is costing you a lot of time.</p></li>\n<li><p>Looping over all characters is slow, better to use a built-in function if possible. \nYour main loop seems to be discarding lots of '9' characters so in this case you can use <code>rstrip</code> to do this much faster.</p></li>\n<li><p>I suspect a string functions will be faster than list functions (e.g. I would expect reversing a string to be faster than reversing a list of characters)</p></li>\n</ol>\n\n<p>In this case, the main optimisation is therefore to keep the processing based on strings rather than lists of characters. </p>\n\n<p>Testing with a million character strings containing all 9s in Python 2.7, the code below is 28 times faster:</p>\n\n<pre><code>def tempPalindrome(inputString):\n inputList = inputString\n length = len(inputList)\n halfL = inputList[:length/2][::-1] \n inputList = inputList[:(length+1)&gt;&gt;1] + halfL\n\n if inputList &gt; inputString.zfill(length):\n return inputList\n\n position = (length-1) &gt;&gt; 1\n i = len(inputList[:position+1].rstrip('9'))-1\n num9s = position-i \n if i&gt;=0:\n inputList = inputList[:i]+chr(ord(inputList[i]) + 1)+'0'*num9s+inputList[position+1:]\n else:\n inputList = '1' + '0'*num9s+inputList[position+1:]\n length += 1\n\n halfL = inputList[:length/2][::-1]\n return inputList[:(length+1)&gt;&gt;1] + halfL\n\ndef nextPalindrome():\n noOfCases = int(raw_input())\n for i in xrange(noOfCases):\n print tempPalindrome(raw_input())\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-03-06T22:40:12.993", "Id": "15528", "Score": "0", "body": "Good answer. I was going to post an answer, but I don't think there's much I can add to this." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-03-07T15:03:32.447", "Id": "15529", "Score": "0", "body": "@Peter Thanks, your approach will be quite helpful for enhancing my programming skills. Only one problem is with point 1, here i have to take all inputs first then print output as a string so any good approach you can suggest so i need not have to store it first in list." } ], "meta_data": { "CommentCount": "2", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-03-06T20:49:19.367", "Id": "9793", "ParentId": "9790", "Score": "4" } } ]
{ "AcceptedAnswerId": "9793", "CommentCount": "4", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-03-06T17:34:48.673", "Id": "9790", "Score": "1", "Tags": [ "python", "performance", "beginner", "programming-challenge", "palindrome" ], "Title": "The Next Palindrome - reducing total execution time" }
9790
<p>I'm attempting to escape ampersands from a string before passing to PHP's <code>SimpleXMLElement-&gt;addChild()</code> for use with some SOAP webservices, but I don't want to double escape them. I'm getting these strings from a variety of sources so I can't count on them not being escaped already. <code>&amp;amp;amp;</code> or <code>&amp;amp;</code> should be untouched but <code>&amp;</code> or <code>&amp;blah blah blah</code> should not.</p> <pre><code>&lt;?php $s = preg_replace('/&amp;([^; ]*)( |$)/','&amp;amp;$1$2',$s) </code></pre>
[]
[ { "body": "<p>Your code is hard to read, and a few test cases would be nice to know what this should handle. For example, do you want to allow multiple lines? Do you want to replace things that are not \"amp\", like <code>&amp;gt;</code>? Are you sure this will correctly sanitize your inputs?</p>\n\n<p>It seems to me that you only want to replace <code>&amp;</code> (ampersand + space) by <code>&amp;amp;</code>. </p>\n\n<p>This version works:</p>\n\n<ol>\n<li>for any kind of whitespace </li>\n<li>across <a href=\"http://www.php.net/manual/en/reference.pcre.pattern.modifiers.php\" rel=\"nofollow noreferrer\">multiple lines</a>:</li>\n</ol>\n\n<hr>\n\n<pre><code>$s = preg_replace('/&amp;(\\s)/m', '/&amp;amp;$1/', $s);\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-03-14T16:21:05.173", "Id": "15955", "Score": "0", "body": "I'm specifically trying to escape any ampersands that are not already part of an escape sequence. SimpleXMLElement will complain about an unterminated escape. So `&gt;` should be untouched, but `&&gt;` should result in `&amp;&gt;`" } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2012-03-08T08:10:48.437", "Id": "9802", "ParentId": "9796", "Score": "3" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2012-03-08T00:27:51.567", "Id": "9796", "Score": "2", "Tags": [ "php", "regex", "xml" ], "Title": "Escaping XML to be used with SOAP" }
9796
<p>I have the following function for validating users facebook information against the rules setup in the database for users. Its working fine but i need to know if it can be more optimized. Few things that you need to know are: </p> <ol> <li>There is a possibility that particular rule would not exists in db.</li> <li>But if exists and does not match with user details it must redirect to error page.</li> <li>it is also possible that user has not set the information in their profile so in this case it should redirect to error page.</li> <li><p>my dbdetails array has following structure is </p> <p>Array( ['Demography'] => Array( ['Rule'] => Array( [0] => 'Some Value' [1] => 'Some Value'... ) ['Value'] => Array( [0] => 'Some Value' [1] => 'Some Value' ) ) )</p></li> </ol> <p>And the fbdata is exactly same what facebook returns when user visits the page after allowing the application. Here is my function which validates/</p> <pre><code>private function validate_demographics($dbDetails, $fbData) { $this-&gt;load-&gt;library('facebook', array('appId' =&gt; APP_ID, 'secret' =&gt; APP_SECRET)); //Is page like restriction is there if( in_array('People Who Like My Page', $dbDetails['Demography']['Value']) ) { //Checks whether user has liked the page or not if( !$fbData['page']['liked'] ) { //If user has not liked the page set the network flag to 1. redirect('viewer/demographics_not_match/1'); } } if( in_array('Age', $dbDetails['Demography']['Rule']) ) { $ageInd = array_search('Age', $dbDetails['Demography']['Rule']); $validAge = explode('-', $dbDetails['Demography']['Value'][$ageInd]); $userBirthdate = explode('/',$this-&gt;viewer_fb_data['birthday']); $userAge = date('Y') - $userBirthdate[2]; if( $userAge &gt;= $validAge[0] &amp;&amp; $userAge &lt;= $validAge[1] ) { return true; } else { redirect('viewer/demographics_not_match/2'); } } if( in_array('High-School', $dbDetails['Demography']['Rule']) or in_array('College', $dbDetails['Demography']['Rule']) ) { //Checks whether user has set his educational details on facebook if( array_key_exists('education', $this-&gt;viewer_fb_data) ) { foreach( $this-&gt;viewer_fb_data['education'] as $userEducation ) { if( in_array($userEducation['school']['name'], $dbDetails['Demography']['Value']) ) { return true; } } } else { redirect('viewer/demographics_not_match/3'); } } if( in_array('City', $dbDetails['Demography']['Rule']) or in_array('State', $dbDetails['Demography']['Rule']) or in_array('Country', $dbDetails['Demography']['Rule']) ) { //Checks whether user has set his location on facebook if( array_key_exists('location', $this-&gt;viewer_fb_data) ) { $userLocation = explode(',', $this-&gt;viewer_fb_data['location']['name']); if( in_array($userLocation[0], $dbDetails['Demography']['Value']) ) { return true; } } else { redirect('viewer/demographics_not_match/5'); } } if( in_array('Work-Place', $dbDetails['Demography']['Rule']) ) { //Checks whether user has set his work details on facebook if( array_key_exists('work', $this-&gt;viewer_fb_data) ) { $workInd = array_search('Work-Place', $dbDetails['Demography']['Rule']); $workPlaces = explode(',', $dbDetails['Demography']['Value'][$workInd]); foreach( $this-&gt;viewer_fb_data as $fbWork ) { if( in_array($fbWork['employer']['name'], $workPlaces) ) { return true; } } } else { redirect('viewer/demographics_not_match/4'); } } return false; } </code></pre>
[ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-03-08T09:03:38.120", "Id": "15562", "Score": "0", "body": "Hi! Thanks for your question. You're asking for a performance improvement, but you didn't say how slow it was, and where you think the issue is. \"Premature optimization is the root of all evil.\" Did you consider using software like XDebug too locate possible bottlenecks? If you also want a more traditional code review, then ask for it. :)" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-03-08T09:08:26.273", "Id": "15565", "Score": "0", "body": "i haven't face any issue yet. Just need senior advise if anything i have missed or is there any overhead i have created in this code. Since this code needs to handle around 10,000 users simultaneously when the project goes live so i dont how it behaves at that time." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-03-08T17:55:03.693", "Id": "15604", "Score": "0", "body": "Your controller seems to be doing an awful lot of work, this is often indicative that you're implementing business logic in a controller. This is an antipattern known as \"fat controller\". Business logic belongs in your models, the controllers should only really contain glue logic and be \"thin\" (They just pass user input to the model and model output to the view without making any business-logic decisions)." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-03-09T06:28:00.947", "Id": "15650", "Score": "0", "body": "yeah i have often heard that apply the business logic in a model. But i dont find any disadvantages of doing that if you can point out then please let me know...." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-03-09T07:40:57.270", "Id": "15653", "Score": "0", "body": "@ShayanHusaini If the business logic is in the model, then the model becomes easy to reuse as it's pretty much stand-alone. You can plug it into any controller and action you want. If a big chunk of the business logic is in the controller then the model can't be reused without copying and pasting code from its associated controller. Besides, semantically speaking it's the model's job to implement business logic because a model embodies a thing or a concept in your system and it should know in what ways it can be expected to be used." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-03-09T07:55:55.003", "Id": "15657", "Score": "0", "body": "but dont you think it would slow down the application little bit since the data is passed from the view to controller then controller passed it to model and if data is not valid as per business logic it returns the error to controller and then controller passed it to view. Using the business logic in controller would shorten this process as controller checks the business logic and didn't passed it to model if it is not valid" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-03-14T09:37:35.720", "Id": "15933", "Score": "0", "body": "@ShayanHusaini 1/ Consider [accepting](http://meta.stackexchange.com/questions/5234/how-does-accepting-an-answer-work) my answer if it answered your question. 2/ You shouldn't worry about performance when \"passing data\". It's really fast, and if you ever **measure** a performance degradation, you can always [pass by reference](http://www.php.net/manual/en/language.references.pass.php) which will avoid any copy but will also modify the variable in the caller scope." } ]
[ { "body": "<p>The code looks OK, and what is probably going to take you time is the call to the Facebook API, which means there's no need to optimize that snippet.</p>\n\n<p>I also have two unimportant remarks:</p>\n\n<ul>\n<li>Your function either returns true/false, or redirects to another page. There is no reasonable way to guess that (given a name such as <code>validate_demographics</code>). You should be careful when you are redirecting in some cases but not all of them. This is a lack of consistency that could prove dangerous afterwards (eg. if you put a redirect after this is executed, it won't work in every case).</li>\n<li>The validation method is a bit surprising: as soon as you found a rule that is validated, your return <code>TRUE</code>. Don't you want to check that <em>all</em> the rules match?</li>\n</ul>\n\n<hr>\n\n<p>You want to consider it valid when one of the rules matches, and invalid when all them don't match. If nothing matches, where do you want to redirect the user? #1? #4?</p>\n\n<p>To solve the \"does one rule match?\" problem, I would set a variable <code>$nothing_matches</code> to <code>TRUE</code> at the beginning of the function, and change every <code>return TRUE</code> to <code>$nothing_matches = FALSE</code>. You can simply <code>return $nothing_matches;</code> at the end of the function.</p>\n\n<p>Now, if nothing matched (`$nothing_matched is TRUE) you can hardcode the rule you want to redirect to, since there's no better way to choose the rule.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-03-08T13:06:05.453", "Id": "15570", "Score": "0", "body": "currently the scenario is if any of the information is matched with the given criteria then user will be supposed as valid user." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-03-08T13:20:05.087", "Id": "15575", "Score": "0", "body": "Not really. If the first one is wrong, it redirects, and the others won't be evaluated (since [`redirect()` calls `exit;`](https://github.com/EllisLab/CodeIgniter/blob/develop/system/helpers/url_helper.php#L520). You might want to remember what has been validated and what has not, and then act accordingly at the end of the function. If it's OK to stop after finding out that the first one doesn't match, then that's fine." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-03-09T06:40:32.883", "Id": "15652", "Score": "0", "body": "Hey @Cygal you are right that if first one is wrong then others wont be evaluated. So tell me how can i fix that is it good to use a variable with value 0 if matched, non-zero if not matched and in last redirects the user checking the variables value?" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-03-09T07:48:49.867", "Id": "15656", "Score": "0", "body": "Yes, that would work. I'll edit my answer to explain it a bit more." } ], "meta_data": { "CommentCount": "4", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-03-08T12:59:49.917", "Id": "9806", "ParentId": "9803", "Score": "1" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "7", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-03-08T08:32:42.823", "Id": "9803", "Score": "2", "Tags": [ "php", "codeigniter" ], "Title": "Controller method optimization" }
9803
<p>I have the following loop which uses Idiorm to write to a table from a PHP Slim application:</p> <pre><code>foreach($jobs-&gt;get_items() as $job) { echo $job-&gt;get_title().'&lt;br /&gt;'; $jobRow = ORM::for_table('jobs')-&gt;create(); $jobRow-&gt;guid = $job-&gt;get_id(TRUE); $jobRow-&gt;url = $job-&gt;get_link(); $jobRow-&gt;description = $job-&gt;get_description(); $jobRow-&gt;pubdate = $job-&gt;get_date(); echo $job-&gt;get_date(); try { $jobRow-&gt;save(); } catch (exception $e) { continue; } } </code></pre> <p>It feels a bit hacky to be using continue in a try/ catch block. Is there a better way to avoid a MYSQL constraint violation without having to query the table? get_id() returns an md5 hash of the guid in an rss feed which is actually a unqiue URL. I have a UNIQUE index on that field in my table.</p>
[]
[ { "body": "<p>How exceptional is this error? What do you want to do when this happens?</p>\n\n<p>If it's rare and you don't want to do anything, then:</p>\n\n<ul>\n<li>Only catch the actual exception (maybe it's <code>PDOException</code>).</li>\n<li>Remove the <code>continue</code> which serves no purpose here and could confuse the reader.</li>\n<li>Make sure you don't fail silently when the error is not a violation error.</li>\n</ul>\n\n<p>Your code will look like this:</p>\n\n<pre><code>try {\n $jobRow-&gt;save();\n} catch (PDOException $e) {\n if(!isAnExpectedViolation()) {\n // I still need to do something about it!\n }\n}\n</code></pre>\n\n<p>If it's really frequent, you may want to check if it's going to violate the constraint before running the query. If it's frequent and you want to tell about it to the user, put it into an <code>if</code> and act accordingly.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-03-08T12:38:33.533", "Id": "15569", "Score": "1", "body": "Note that you don't need to agree on the \"exceptions are exceptional\" policy, but it's important not to catch every kind of exception that could be thrown." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-03-29T07:44:34.287", "Id": "16641", "Score": "0", "body": "Just getting round to looking at this again. The exception will happen alot as the data is coming from a feed which may well have duplicates of existing data. I'm hashing a URL to generate a guid and if there is a row with the same hash the exception will get thrown." } ], "meta_data": { "CommentCount": "2", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-03-08T11:11:41.473", "Id": "9805", "ParentId": "9804", "Score": "1" } }, { "body": "<p>You really really REALLY don't want to hide errors like this. It will come back to haunt you when in 18 months you're asked to update the script or debug it and you do something that triggers an error condition but nothing to alert you to the fact ever happens. </p>\n\n<p>I've had many jobs where debugging some code was made far harder than it needed to be because someone had tried to just sweep errors under the carpet with an @ operator or by catching an exception and doing nothing with it. </p>\n\n<p>I know that doesn't answer your question. But I thought it was important to point that out. </p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-03-08T17:51:11.263", "Id": "9822", "ParentId": "9804", "Score": "1" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-03-08T10:55:49.917", "Id": "9804", "Score": "1", "Tags": [ "php", "mysql" ], "Title": "Is there a cleaner way to ensure I am not writing duplicate data?" }
9804
<p>I had a requirement where I need to create object using same interface but one derived class expects simple data and other array of type. Here is solution I came up with:</p> <p>I had two questions:</p> <ol> <li>As you can see I am converting <code>IEquatable&lt;T&gt;</code> into <code>T</code>. In my testing so far I did not see any disasters. Can you think of any from top off your head?</li> <li>Is there a way I can change constraint in <code>ArrayExpectant::CloneFromMe</code> to <code>ArrayWrapper</code> instead of <code>IEquatable</code>?</li> </ol> <pre><code>public class ArrayWrapper&lt;T&gt; : IEquatable&lt;T&gt; { public T[] Array { get; set; } public bool Equals(T other) { return false; } public bool Equals(T[] other) { return Array == other; } public bool Equals(ArrayWrapper&lt;T&gt; other) { return Array == other.Array; } } public interface ICreationByCloning { ICreated CloneFromMe&lt;TClone&gt;(IEquatable&lt;TClone&gt; t) where TClone : IEquatable&lt;TClone&gt;; } public interface ICreated { } public class Simpleton&lt;T&gt; : ICreated, ICreationByCloning { public Simpleton(T t) { } public ICreated CloneFromMe&lt;TClone&gt;(IEquatable&lt;TClone&gt; t) where TClone : IEquatable&lt;TClone&gt; { return new Simpleton&lt;TClone&gt;((TClone)t); } } public class ArrayExpectant&lt;T&gt; : ICreated, ICreationByCloning where T : IEquatable&lt;T&gt; { T[] Data { get; set; } public ArrayExpectant(T[] t) { Data = t; } public ICreated CloneFromMe&lt;TClone&gt;(IEquatable&lt;TClone&gt; t) where TClone : IEquatable&lt;TClone&gt; { TClone[] array = (t as ArrayWrapper&lt;TClone&gt;).Array; return new ArrayExpectant&lt;TClone&gt;(array); } } </code></pre>
[ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-03-08T13:21:25.383", "Id": "15583", "Score": "1", "body": "If you are building the interface, why not build always an array and check for the quantity of data?" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-03-08T15:58:25.103", "Id": "15588", "Score": "0", "body": "I'm not sure what are you trying to achieve with this code. Could you show us, how would you use it with both `Simpleton` and `ArrayExpectant`?" } ]
[ { "body": "<p>I'm not completely sure what are you trying to accomplish, but I think this is bad and very confusing code.</p>\n\n<p>You seem to be using the interface <code>IEquatable&lt;T&gt;</code> to mean “<code>T</code>, or a type that has some relation to <code>T</code>”. That's not what it's meant for at all!</p>\n\n<p>Also, the point of interfaces is to be able to use different types in the same way. For example, if I have a <code>IEnumerable&lt;string&gt;</code>, I know I can iterate over it using a <code>foreach</code> and process the <code>string</code>s it gives me.</p>\n\n<p>But that does not apply to your interface. I have to know whether I have have <code>Simpleton&lt;T&gt;</code> (I have to pass <code>T</code> to it) or <code>ArrayExpectant&lt;T&gt;</code> (I have to pass <code>ArrayWrapper&lt;T&gt;</code> to it).</p>\n\n<p>Because of this, I would suggest you to drop the interface completely, I don't see any benefit of having it.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-03-08T20:00:25.627", "Id": "9832", "ParentId": "9808", "Score": "1" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "2", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-03-08T13:19:11.763", "Id": "9808", "Score": "1", "Tags": [ "c#" ], "Title": "Arrays, inheritance, generics" }
9808
<p>In a data processing and analysis application I have a dataCleaner class that conducts a series of functions that help me to clean raw time series data. </p> <p>One of the problems I see in my data is that they often include large gaps at the beginning and end. This is due to the occasional corruption of the timestamp, a behaviour that I cannot influence but can lead to arbitrary timings of individual data records. </p> <p>Imagine an hourly dataset covering November 2011. Sometimes one of the timestamps is corrupted and may end up recording a date of January 2011. Since the data are sorted by date this puts a point at the beginning which needs to be removed. It is possible that this corruption can occur more than once in any given dataset. I need to detect and remove these outliers if they exist.</p> <p>So I designed this function to trim off contiguous values at each end of the data if the time gap is considered large. My data arrive into this function in the form of two numpy arrays (timestamps and values) and must be filtered together.</p> <pre><code>@staticmethod def _trimmed_ends(timestamps, values, big_gap = 60*60*24*7): """ Uses timestamps array to identify and trim big gaps at either end of a dataset. The values array is trimmed to match. """ keep = np.ones(len(timestamps), dtype=bool) big_gaps = (np.diff(timestamps) &gt;= big_gap) n = (0, 0) for i in xrange(len(keep)): if big_gaps[i]: keep[i] = False n[0] += 1 else: break for i in xrange(len(keep)): if big_gaps[::-1][i]: keep[::-1][i] = False n[1] += 1 else: break if sum(n) &gt; 0: logging.info("%i points trimmed (%i from beginning, %i from end)" % (sum(n), n[0], n[1])) else: logging.info("No points trimmed") return timestamps[keep], values[keep] </code></pre> <p>Is this a pythonic way to do this? I have been advised that I might want to convert this into an iterator but I'm not sure it that is possible, let alone desirable. As I understand it, I need to attack the array twice, once forwards and once backwards in order to achieve the desired result.</p>
[]
[ { "body": "<p>Firstly, a loopless solution (not actually tested)</p>\n\n<pre><code>big_gaps = np.diff(timestamps) &gt;= big_gap\n</code></pre>\n\n<p>As you did</p>\n\n<pre><code>front_gaps = np.logical_and.accumulate(big_gaps)\n</code></pre>\n\n<p>This produces an array which is <code>True</code> until the first <code>False</code> in big_gaps. </p>\n\n<pre><code>end_gaps = np.logical_and.accumulate(big_gaps[::-1])[::-1]\n</code></pre>\n\n<p>We do the same thing again, but this time we apply on the reversed array.</p>\n\n<pre><code>big_gaps = np.logical_or(front_gaps, end_gaps)\n</code></pre>\n\n<p>Now that we have arrays for the front and end portions, combine them</p>\n\n<pre><code>n = np.sum(front_gaps), np.sum(end_gaps)\n</code></pre>\n\n<p>Take the sums of the gaps arrays, 1 = <code>True</code>, 0 = <code>False</code> to figure out the values for <code>n</code></p>\n\n<pre><code>keep = np.logical_not(big_gaps)\n</code></pre>\n\n<p>Invert the logic to figure out which ones to keep</p>\n\n<pre><code>return timestamps[keep], values[keep]\n</code></pre>\n\n<p>Produce your actual values</p>\n\n<p>A few comments on pieces of your code</p>\n\n<pre><code>@staticmethod\ndef _trimmed_ends(timestamps, values, big_gap = 60*60*24*7):\n</code></pre>\n\n<p>I'd make a constant: <code>ONE_WEEK = 60*60*24*7</code>, as I think it would make this clearer</p>\n\n<pre><code>big_gaps = (np.diff(timestamps) &gt;= big_gap)\n</code></pre>\n\n<p>You don't need those parens</p>\n\n<pre><code>n = (0, 0)\n</code></pre>\n\n<p>This is a tuple here, but you modify it later. That won't work.</p>\n\n<p>And finally, no you shouldn't use an iterator, for the reasons you mention.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-03-08T19:39:59.803", "Id": "15610", "Score": "0", "body": "thanks This is great. From looking at it I think it does the job nicely and without a loop. Now to test it. (I probably should have written a test first and posted that with my code)." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-03-08T20:54:58.453", "Id": "15616", "Score": "0", "body": "There is a slight problem, the np.diff leads to big_gaps being one element shorter than timestamps. This propagates through and leads to at least one point being trimmed every time." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-03-08T21:02:31.093", "Id": "15619", "Score": "0", "body": "This works: `front_gaps, end_gaps = np.logical_and.accumulate(np.append(big_gaps, False)), np.logical_and.accumulate(np.append(False, big_gaps)[::-1])[::-1]`" } ], "meta_data": { "CommentCount": "3", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-03-08T17:53:05.817", "Id": "9823", "ParentId": "9809", "Score": "2" } } ]
{ "AcceptedAnswerId": "9823", "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-03-08T15:12:22.633", "Id": "9809", "Score": "0", "Tags": [ "python" ], "Title": "Pythonic data processing? Should I use an iterator?" }
9809
<p>I had a need to isolate some long-running blocking calls in a background thread of my app. I also needed to keep this thread running indefinitely, because COM would complain if some object I created in that thread were accessed from another thread. I then needed to control what these objects did from my main UI thread, in a guaranteed-FIFO manner.</p> <p>The solution I came up with was kind of ActiveObject-reminiscent; a polling loop running as the DoWork handler of a BackgroundWorker, which accepted encapsulated Command objects representing the work to perform from a thread-safe ConcurrentQueue. Here's the vitals:</p> <pre><code>//basic implementation of the Command pattern; no serialization/persistence needed, //just need to be able to encapsulate some work and defer it. internal class Command { private Action action; public Command(Action action) { this.action = action; } protected Command() { } public virtual void Execute() { action(); } } //Generic variation accepts a single parameter internal class Command&lt;T&gt;:Command { private T param; private Action&lt;T&gt; action; public Command(Action&lt;T&gt; action, T param) { this.action = action; this.param = param; } public override void Execute() { action(param); } } ... //event handlers run in the UI thread will Enqueue() Command objects //containing the delegates that should be run in the background thread ConcurrentQueue&lt;Command&gt; queuedCommands = new ConcurrentQueue&lt;Command&gt;(); //The BGW DoWork handler; runs indefinitely until the UI that needs it is Dispose()d private void MainBackgroundLoop(object sender, System.ComponentModel.DoWorkEventArgs e) { Command command; bool commandAvailable; do { commandAvailable = queuedCommands.TryDequeue(out command); if (commandAvailable) command.Execute(); else Thread.Sleep(100); //&lt;-- Here's your code smell } while (!e.Cancel); } </code></pre> <p>Now, this functions beautifully. But, the use of Thread.Sleep() in any SO/CR post usually gets called out as a code smell. I get why; this loop requires CPU to try to pull commands out of the queue at least 10 times a second, which will eat CPU for an "idle" thread. But, given there are other reasons why the thread has to keep running, this seems acceptable.</p> <p>Thoughts?</p>
[ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-03-08T17:34:53.117", "Id": "15602", "Score": "0", "body": "Shouldn't you be using `delegate`s or `Task`s? Or even `event`s?" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-03-08T18:02:13.587", "Id": "15605", "Score": "0", "body": "I am using delegates. `Action` is a particular-system defined delegate type, as is `Action<T>`. I encapsulate these in Command objects because an `Action<T>` isn't an `Action`, and to avoid external closures (referencing variables that may, and in fact will, go out of scope before the delegate is evaluated)." } ]
[ { "body": "<p>You're right, most of the time, you shouldn't use polling like this. You should instead block the thread indefinitely if there is no work and wake it up when it's needed.</p>\n\n<p>Fortunately, the same namespace that contains the <code>ConcurrentQueue&lt;T&gt;</code> you use also has the solution you need: <code>BlockingCollection&lt;T&gt;</code>. The collection has methods that will always return an item, and block if none are available, which is exactly what you need. Using that class, I would rewrite your code like this:</p>\n\n<pre><code>BlockingCollection&lt;Command&gt; queuedCommands = new BlockingCollection&lt;Command&gt;();\n\nprivate void MainBackgroundLoop(object sender, DoWorkEventArgs e)\n{\n do\n {\n Command command;\n bool commandAvailable = queuedCommands.TryTake(out command, Timeout.Infinite);\n if (commandAvailable)\n command.Execute();\n } while (commandAvailable);\n}\n</code></pre>\n\n<p>Because the collection doesn't know about your <code>DoWorkEventArgs</code>, you have take care of ending the loop in some other way. In the code above, if you call <code>queuedCommands.CompleteAdding()</code>, it will make sure remaining items are processed and then it will shut down, because <code>TryTake()</code> will return <code>false</code>. Another option for cancellation is to use an overload of <code>TryTake()</code> that takes a <code>CancellationToken</code> and use that to cancel the operation.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-03-08T20:58:46.537", "Id": "15618", "Score": "0", "body": "That's beautiful; +1 for the built-in solution. Now, it will block my user code, but behind the scenes it will still use some polling mechanism to keep track of the timeout and/or cancellation. I guess I should trust that it's CPU-efficient, but \"just because you can't see the implementation's complexity doesn't mean it's free\". I'm guessing it uses threading with WaitHandles." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-03-08T21:14:30.697", "Id": "15620", "Score": "0", "body": "One more question; how's the FIFO nature of this? Order of operations can sometimes be important, so if I put in commands 1, 2, and 3, I need to get them back in that order." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-03-08T21:27:14.207", "Id": "15621", "Score": "0", "body": "Never mind the follow-up Q; I found on another answer that a BlockingCollection uses a ConcurrentQueue by default, and can be told to use any IProducerConsumerCollection implementation. So, I can specify once and for all that it uses a ConcurrentQueue, and TryTake will dequeue the items FIFO." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-03-09T00:27:35.027", "Id": "15632", "Score": "0", "body": "@KeithS, yes exactly, `ConcurrentQueue<T>` is used by default, but you can switch it if you want." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-05-22T00:25:07.157", "Id": "19206", "Score": "2", "body": "WOW, this simple example gave me a great start on a solution that's much more effective. I never understood the blocking nature of the BlockingCollection, and it was a perfect solution to getting rid of my Thread.Sleep message loop. Thanks a LOT!!!" } ], "meta_data": { "CommentCount": "5", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-03-08T20:16:59.517", "Id": "9833", "ParentId": "9812", "Score": "15" } } ]
{ "AcceptedAnswerId": "9833", "CommentCount": "2", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-03-08T15:59:36.640", "Id": "9812", "Score": "5", "Tags": [ "c#", "multithreading" ], "Title": "Polling loop - Always a bad decision?" }
9812
<p>The code follows the requested format of the output exactly for my assignment. But, for my own personal reference, is there a better way that I could have done anything? Are there any additional tips? Maybe some simple ways that I could gold plate against exceptions or errors? I know how <code>try</code>, <code>catch</code> and <code>throw</code> exceptions work. My instructor doesn't check for it, though, so I wasn't going to spend time on it.</p> <pre><code>class Money { public static void main(String[] args){ //Variable and Constant Declaration int price,amountpaid,dollars,quarters,dimes,nickels,change,remainder = 0; Scanner sc = new Scanner(System.in); DecimalFormat df = new DecimalFormat("#0.00"); //Input System.out.println("Please enter the purchase price in cents: "); price = sc.nextInt(); System.out.println("Please enter the amount tendered in cents: "); amountpaid = sc.nextInt(); //Calculations remainder = amountpaid - price; change = remainder; dollars = remainder / 100; remainder = remainder % 100; quarters = remainder / 25; remainder = remainder % 25; dimes = remainder / 10; remainder = remainder % 10; nickels = remainder / 5; remainder = remainder % 5; pennies = remainder; //Output System.out.println("Purchase Price:\t $" + df.format((double)price/100) + "\nAmount Tendered: $" + df.format((double)amountpaid/100) + "\n \nYour Change is: $" + df.format((double)change/100) + "\n \n \t \t " + dollars + " one-dollar bills(s)\n \t \t " + quarters + " quarter(s)\n \t \t " + dimes + " dime(s)\n \t \t " + nickels + " nickle(s)\n \t \t " + remainder + " penn(y/ies)"); System.out.println("\nThank you for your business. Come back soon."); } // End Main } //End Class </code></pre>
[ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-03-09T00:43:25.383", "Id": "15635", "Score": "1", "body": "Use `System.out.format`." } ]
[ { "body": "<p>There is a general purpose guideline - the Single Responsibility Principle. For a given procedure/function you should be able to write a simple statement \"This code does X.\" If you find yourself writing \"This code does X and Y.\" then you should consider breaking the code up into pieces - one piece that does X and one piece that does Y.</p>\n\n<p>The code above does three things - reads input, calculates change, writes output. Those three pieces are candidates for creating separate functions.</p>\n\n<p>I say candidates because there is always a trade-off. When you extract some code into a new function/method then you also have to be able to communicate input to the new function/method as well as for it to communicate back its results. Your code is fairly simple and straightforward as is. Even though it has three different parts and is longer than would be preferred for a single function, splitting it up wouldn't improve it that much while at the same time adding extra complication/overhead in the method calls and returns.</p>\n\n<p>However, that said, if this code became the basis for a more advanced assignment, one thing that you could do would be to create a Change or Payment class something like I have shown below. It encapsulates two parts of the functionality in your code in a simple and direct way that provides a basis for adding additional features.</p>\n\n<p>For example, if you needed to calculate the amount tendered from counts of coins and bills, you could add a function that reads a count of coins tendered and another that calculates the total value.</p>\n\n<pre><code>class Payment {\n int dollars = 0;\n int quarters = 0;\n int dimes = 0;\n int nickels = 0;\n int pennies = 0;\n\n public payment(int value) {\n int remainder = value;\n\n dollars = remainder / 100; \n remainder = remainder % 100; \n\n quarters = remainder / 25; \n remainder = remainder % 25; \n\n dimes = remainder / 10; \n remainder = remainder % 10;\n\n nickels = remainder / 5; \n remainder = remainder % 5; \n\n pennies = remainder; \n }\n\n public writeOutput(PrintStream out) {\n out.println(\"\\t \\t \" + dollars + \" one-dollar bills(s)\\n \\t \\t \" \n + quarters + \" quarter(s)\\n \\t \\t \" + dimes + \n \" dime(s)\\n \\t \\t \" + nickels + \" nickle(s)\\n \\t \\t \" + \n pennies + \" penn(y/ies)\");\n\n }\n}\n</code></pre>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-03-08T17:33:06.193", "Id": "9819", "ParentId": "9814", "Score": "7" } } ]
{ "AcceptedAnswerId": "9819", "CommentCount": "1", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-03-08T16:25:39.833", "Id": "9814", "Score": "4", "Tags": [ "java", "homework", "finance" ], "Title": "Money class for handling calculations with coins" }
9814
<p>I am busy creating a basic php mailer script to post to _self and email to a address.</p> <p>Is the script secure?</p> <p>How can I avoid someone clicking on submit the whole time, to spam the mailbox, with minimal extra code</p> <pre><code>&lt;?php //Mail header removal function remove_headers($string) { $headers = array( "/to\:/i", "/from\:/i", "/bcc\:/i", "/cc\:/i", "/Content\-Transfer\-Encoding\:/i", "/Content\-Type\:/i", "/Mime\-Version\:/i" ); $string = preg_replace($headers, '', $string); return strip_tags($string); } $to = "email@tosendto.com"; $subject = "Sent from site"; $uname = remove_headers($_POST['fname']); $uemail = remove_headers($_POST['femail']); $umessage = remove_headers($_POST['fmessage']); $umessage = "Name : " . $uname . " Email : " . $uemail . " Message : " . $umessage; if(isset($_POST['submit'])) { mail($to, $subject, $umessage, "From: page@website.com"); } ?&gt; &lt;div id="mailer" &gt; &lt;h1&gt;Message&lt;/h1&gt; &lt;form name="test" action="&lt;?php echo htmlentities($_SERVER['PHP_SELF']); ?&gt;" method="post"&gt; &lt;p&gt;Your Name:&lt;/p&gt; &lt;input type="text" size="20" name="fname"&gt;&lt;br&gt;&lt;br&gt; &lt;p&gt;Your Email:&lt;/p&gt; &lt;input type="text" size="20" name="femail"&gt;&lt;br&gt;&lt;br&gt; &lt;p&gt;Your Message:&lt;/p&gt; &lt;textarea name="fmessage" rows="4" cols="20"&gt;&lt;/textarea&gt;&lt;br&gt;&lt;br&gt; &lt;input type="submit" name="submit" value="Send Message"&gt; &lt;/form&gt; &lt;?php if(isset($_POST['submit'])) { echo "&lt;p&gt;Sent. We will be in contact shortly.&lt;/p&gt;"; } ?&gt; &lt;/div&gt; </code></pre>
[]
[ { "body": "<p>Your using the <strong>email</strong> sanitize filter on each field, you need to use <code>FILTER_SANITIZE_STRING</code> for the name and <code>FILTER_SANITIZE_FULL_SPECIAL_CHARS</code> for the message field.</p>\n\n<p>Sanitizing is not the same as validating...</p>\n\n<p><a href=\"http://www.php.net/manual/en/filter.filters.validate.php\" rel=\"nofollow\">VALIDATE Filters</a></p>\n\n<p><a href=\"http://www.php.net/manual/en/filter.filters.sanitize.php\" rel=\"nofollow\">SANITIZE filters</a></p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-03-09T05:52:47.337", "Id": "15649", "Score": "0", "body": "If I understand correctly. I only want sanitize. Dont care about validation for now." } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-03-09T01:18:02.693", "Id": "9848", "ParentId": "9827", "Score": "2" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-03-08T19:17:48.160", "Id": "9827", "Score": "2", "Tags": [ "php", "html" ], "Title": "Creating a basic secure php mailer" }
9827
<p>I'm a fairly new programmer (just started yesterday!). I decided to tackle Project Euler #2 today, as I did #1 yesterday without many problems. I came up with what seems to me to be a working solution, but I feel like I did it in an exceedingly ugly way. Could anyone suggest improvements to my code and/or logic?</p> <blockquote> <p>Each new term in the Fibonacci sequence is generated by adding the previous two terms. By starting with 1 and 2, the first 10 terms will be:</p> <p>1, 2, 3, 5, 8, 13, 21, 34, 55, 89, ...</p> <p>By considering the terms in the Fibonacci sequence whose values do not exceed four million, find the sum of the even-valued terms.</p> </blockquote> <pre><code>fib = 1 fib2 = 2 temp = 0 total = 0 while temp &lt;=4000000: temp = fib2 if temp % 2 == 0: total += temp temp = fib + fib2 fib = fib2 fib2 = temp print total </code></pre> <p>I just sort of used my <code>temp</code> variable as a holding ground for the results, and then juggled some variables around to make it do what I wanted... Seems like quite a mess. But it does result in <code>4613732</code>, which seems to be correct!</p>
[]
[ { "body": "<p>I would use separately Fibonacci generator</p>\n\n<pre><code>def even_fib(limit):\n a, b = 0, 1\n while a &lt; limit:\n if not a % 2: \n yield a\n a, b = b, a + b\n</code></pre>\n\n<p>And <code>sum</code> function to calculate sum of items</p>\n\n<pre><code>print sum(even_fib(4000000))\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-03-09T07:41:18.657", "Id": "15654", "Score": "1", "body": "+1. Aside from the use of a generator, this refactor has two improvements that bear mentioning explicitly. The first is tuple assignment to drop `temp` - another way to achieve the same is: `a = a + b; b = a + b`, but the tuple assignment logic is much more straightforward. The other one is `if not a%2` is, at least arguably, better than comparing against zero." } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-03-09T07:23:06.527", "Id": "9849", "ParentId": "9830", "Score": "14" } }, { "body": "<p>First of all, I'd like to tell you that the fibonnaci series starts at 1 and the second number is 1, because 1+0=1, so a fibonacci series starts like this: <code>[1, 1, 2, 3, 5, 8...]</code></p>\n\n<p>I know you can say it's kind of cheatting but anyways: Fibonacci series follows a pattern, because to get an even number out of a sum you'll need 2 even or 2 odd numbers(3+3=6, 6 is even; 3+5=8; 2+8=10). Starting at 1 (odd) it follows this pattern: <code>[odd, odd, even, odd, odd, even...]</code>.</p>\n\n<p>Cheating or not this is my solution:</p>\n\n<pre><code>def generate_fib(max_value):\n series = [1, 1]\n while True:\n next_last = series[-1] + series[-2]\n if next_last &gt; max_value:\n break\n series.append(next_last)\n return series\n\nseries = generate_fib(4000000)\nevens = [series[x] for x in range(2, len(series), 3)]\nprint(sum(evens))\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-04-21T18:26:35.710", "Id": "83796", "Score": "0", "body": "If you solve it and look at the corresponding solution pdf (note the checkmark, pdf, and person icons to the right of the Solved By column) you will see an even more optimized solution that isn't 'cheating' but rather recommended." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-08-06T01:18:59.773", "Id": "106563", "Score": "0", "body": "Saying that the Fibonacci sequence starts at zero does not break the algorithm. It's completely reasonable to believe that it *does* start at zero." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-08-07T18:59:25.183", "Id": "107109", "Score": "0", "body": "@ckuhn203 actually it can't start at zero because the next number is defined by the sum of the two preceding numbers, so if you start at zero you'll have `[0]` the second number will be the first number plus zero because you still don't have 2 numbers, and it'll become `[0, 0]`, then the third will be 0, the forth, the fifth all of them will be equal to zero... that's why you can't start the fibonacci series at zero." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-08-07T19:20:00.987", "Id": "107121", "Score": "1", "body": "Some say that the [Fibonacci Sequence](http://en.wikipedia.org/wiki/Fibonacci_number) is 0, 1, 1, 2, …; other say it is 1, 1, 2, …. Either way, it makes no difference if you just want to find the sum of the even entries." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-08-07T19:26:12.490", "Id": "107122", "Score": "0", "body": "@200_success Ok ok, but it just don't make sense for me to start it with zero because the whole sequence would zeroes." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-08-07T19:30:45.393", "Id": "107124", "Score": "1", "body": "It takes two fixed consecutive entries to uniquely define a Fibonacci-type sequence. The zero-based definition just says that it starts with 0, 1, …. A silly definition of 0, 0, … would, of course, result in all zeroes." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-08-07T19:34:10.900", "Id": "107125", "Score": "0", "body": "@200_success The wikipedia entry you just linked, says that you can start with either `[1, 1]` or `[0, 1]`." } ], "meta_data": { "CommentCount": "7", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-04-21T18:21:17.450", "Id": "47810", "ParentId": "9830", "Score": "3" } }, { "body": "<p>I'm also a fellow newbie but the way I would approach it is to first create a separate function for calculating the value for a given nth term in the Fibonacci sequence. Here's my solution:</p>\n\n<pre><code>def fibonacci(n):\n if n == 1:\n return 1\n elif n == 2:\n return 1\n else:\n return fibonacci(n-2) + fibonacci(n-1)\n\ntotal = 0\ni = 1\nwhile fibonacci(i) &lt;= 4000000:\n if fibonacci(i) % 2 == 0:\n total += fibonacci(i)\n i += 1\nprint(total)\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-08-06T00:09:51.680", "Id": "106558", "Score": "1", "body": "Very clean solution, but I will point out that the recursive solution becomes exponentially slower as `n` becomes large." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-08-07T19:17:09.470", "Id": "107120", "Score": "0", "body": "As @ckuhn203 said, this solution is too slow man, recursion is not a good way to handle this, compared to my solution I'm in the speed of light, haha just kidding... or not..." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2016-05-15T03:58:51.590", "Id": "240095", "Score": "0", "body": "It is massive compute since for every value of i we are recomputing fibonacci. Instead computing fibonacci(4000000) would be better in single go and computing sum" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2017-12-15T15:14:16.180", "Id": "347914", "Score": "0", "body": "The problem with this answer is not that it's recursive; it's that every iteration, it recalculates the entire fibonacci sequence. A recursive solution that yields the even integers each iteration is about as fast as the generator solution submitted by @San4ez. I can't submit the code because I don't have enough rep, however for me the generator clocks at 13 s and the recursive at 16 s for 10^6 calculations." } ], "meta_data": { "CommentCount": "4", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-08-05T23:54:06.943", "Id": "59183", "ParentId": "9830", "Score": "5" } }, { "body": "<p>@San4ez gave you a good solution, I would use the Single Responsability principle and define:</p>\n\n<pre><code>def fibs(limit):\n a, b = 0, 1\n while a &lt; limit:\n yield a\n a, b = b, a + b\n\nprint(sum(i for i in fib(4000000) if i % 2 == 0))\n</code></pre>\n\n<p>so that the <code>fibs</code> function does not check evenness</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2016-04-02T08:48:09.843", "Id": "232213", "Score": "0", "body": "Please explain the downvote, what is the problem of this answer." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2017-12-15T14:56:46.537", "Id": "347912", "Score": "1", "body": "I don't know why they downvoted, but your solution takes about 50% more time to compute. Efficiency isn't everything though and separation of responsibility is important." } ], "meta_data": { "CommentCount": "2", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2015-06-17T13:01:06.263", "Id": "93863", "ParentId": "9830", "Score": "3" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-03-08T19:40:36.567", "Id": "9830", "Score": "12", "Tags": [ "python", "beginner", "project-euler", "fibonacci-sequence" ], "Title": "Python Solution for Project Euler #2 (Fibonacci Sums)" }
9830
<p>I've been trough a few css tutorials. I've also been using basic css for a while now.</p> <p>My question, How do you decide witch css to use. For instance. If you want a div box to show on the left. You can either use.</p> <pre><code>float: left; </code></pre> <p>or</p> <pre><code>position: absolute; </code></pre> <p>Another one would be, if you have a paragraph tag inside a div and you want to set its width or height. Do you use</p> <pre><code>width: auto; height: auto; </code></pre> <p>or</p> <pre><code>width: 100%; height: 100%; </code></pre> <p>or</p> <pre><code>padding: 5px; </code></pre>
[]
[ { "body": "<p>I'm afraid that there's no 'good' answer here. There are many ways to achieve a certain effect, but they are dependent on the context.</p>\n\n<p>Floated containers differ from the ones that are positioned absolutely. An absolutely positioned container is 'taken out of the layout' - that means e.g. that if you have 2 divs in a parent div and you set position absolute on one, the other one is going to fill the whole parent and the absolutely positioned one is going to be 'on top' of it (provided it has a width &amp; height set, has a higher z-index or is placed last in DOM, but that's another story). If in the same situation you float one of the divs (and it has width set), the other one will 'stick' to it, but again, it (the second div) has to fulfill some criteria (e.g. if it has width set to 100% or 'clear' property set to both or left/right, it will not stick to the other one)</p>\n\n<p>As for width - if an element is a block element or it has display:block set, width: 100% will expand it to be as wide as the closest ancestor that has position:relative or position:absolute set (this might be a little tricky), whereas width:100% on inline elements will not do anything.</p>\n\n<p>width:100% will probably not work as you expect if you have padding set on the element (element will be to wide).</p>\n\n<p>width:auto behaves differently on floated an non floated, block elements...</p>\n\n<p>There are just too many variations. The same solution works in some cases, but doesn't work in others. It's rarely possible to say 'this is just going to work' if you don't look at what's happening to the rest of the page.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-03-09T00:09:21.880", "Id": "9843", "ParentId": "9831", "Score": "1" } }, { "body": "<p>As Chris' long-winded answer demonstrates, deciding between <code>float</code> and <code>absolute</code> positioning depends on the circumstances.</p>\n\n<p><code>padding</code> works really well with <code>p</code> tags because it adapts regardless of the amount of text.</p>\n\n<p>I recommend this:</p>\n\n<pre><code>p {padding: 8px;}\n</code></pre>\n\n<p>or this:</p>\n\n<pre><code>p {padding: 1em;}\n</code></pre>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-03-09T00:48:33.470", "Id": "9846", "ParentId": "9831", "Score": "0" } } ]
{ "AcceptedAnswerId": "9843", "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-03-08T19:45:54.413", "Id": "9831", "Score": "1", "Tags": [ "css" ], "Title": "CSS layout basics to follow" }
9831
<p>I am creating a site that is very heavily relying on Ajax. To stop major spamming on my site, I decided to implement a PHP system that checks how many actions have been made in the last 5 minutes. I wrote this fairly quickly and I was wondering if there are any major issues with my code. Read the footnote as to why I can't test this. If you see any major errors here, please let me know. Also, spelling errors would be the fault of auto-correct.</p> <pre><code>&lt;?php session_start(); require_once(".conf.php"); //Main config $verification = $_GET['verification_token']; $requestactions = $_GET['request_actions']; $username = $_SESSION['username']; $login = $_SESSION['login']; $ip = $_SERVER['SERVER_ADDR']; //Set up config $maxactions = 40; $maxactionserror = 'Hmm, it seems you exceded the max actions allowed here. Try again in a few, Thank you!'; $actiontable = 'actions' $currentactions = 0; $timeout = 1; $cookieexpire = 600 //Time in MS $blockreason = 'exceeded action requests'; //Query config $firstquery = mysql_query("SELECT * FROM '$actiontable' WHERE username = '$username'"); $rows = mysql_num_rows($firstquery); function check() { if ($rows) { if ($rows &gt;= $maxactions) { setcookie['reasonblocked', $blockreason, time() + $cookieexpire); setcookie['ipblocked', $ip, time() + $cookieexpire); setcookie['blockfinished', 'timestamp', time() + $cookieexpire); $blockquery = mysql_query("INSERT INTO '$actiontable'('eligible') VALUES ('0') WHERE 'username' = '$username'"); echo $maxactionserror; unset($login); unset($username); session_destroy(); } else { while ($get = mysql_fetch_array($firstquery)) { $currentactions = $get['cactions']; $newactions = $currentactions++; $secondquery = mysql_query("INSERT INTO '$actiontable'('username', 'auth_token', 'cactions', 'userip') VALUES ('$username', '$verification', '$newactions', '$ip')"); echo 'success'; check(); } } } else { $secondquery = mysql_query("INSERT INTO '$actiontable'('username', 'auth_token', 'cactions') VALUES ('$username', '$verification', '1')"); echo 'success'; } } ?&gt; </code></pre> <hr> <p>PS. I am on vacation so I am unable to test this. That is why I posted on here.</p>
[]
[ { "body": "<p>Okay, so the first thing here: prevent yourself from SQL injections. Of course you can escape your parameters but parametrized queries with PDO or so would be much better. You can also use mysqli - <a href=\"http://www.php.net/manual/de/mysqli.prepare.php\" rel=\"nofollow noreferrer\">here</a>'s an example: </p>\n\n<p>Also this won't execute since you have syntax errors in there (ie a missing <code>;</code> here: <code>$cookieexpire = 600 //Time in MS</code>).</p>\n\n<p>Also, don't rely on cookies for this. If someone really wants to spam, it is really easy just to delete your cookies or just return them in a valid state... store the ipaddress (or ipaddr and the browser-string) and then save that in a database (or something like redis).</p>\n\n<p>There is much more to talk about here, but this would be a good start.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-03-13T21:08:24.193", "Id": "15926", "Score": "0", "body": "Ok thanks. I noticed those few errors specifically the `missing ;` after I posted and I never fixed here. I **am** inserting the ip into a database. I don't know why I didn't post that here. Hmm. What else is wrong here?" } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-03-13T07:14:00.067", "Id": "9951", "ParentId": "9834", "Score": "2" } } ]
{ "AcceptedAnswerId": "9951", "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-03-08T20:55:54.153", "Id": "9834", "Score": "1", "Tags": [ "php", "ajax" ], "Title": "PHP Action Verification" }
9834
<p>I've tried to write a simple timer class that could later be used in games, such as for updating the screen every second. Problem is, I read <code>gettimeofday()</code> was UNIX-specific and unsafe to use as well (that last one I'm not sure about). I know C has a <code>clock()</code> function, but it only has second precision.</p> <p>Is there a way to get time in a cross-platform way that has millisecond precision at the very least? I know Boost and other libraries exist, but I prefer not to use them for various reasons.</p> <pre><code>class Timer { private: bool m_isRunning; int m_startTime; int m_delayAmount; double m_initialDelay; public: Timer(int delayAmount, double initialDelay = 0.0) { m_delayAmount = delayAmount * 1000; m_initialDelay = initialDelay/1000; } void start() { m_startTime = getMilliseconds(); clock_t endwait = clock() + m_initialDelay * CLOCKS_PER_SEC; while (clock() &lt; endwait); m_isRunning = true; } void stop() { m_isRunning = false; } bool isRunning() { return m_isRunning; } bool hasTicked() { if (getMilliseconds() - m_startTime &gt; m_delayAmount) { m_startTime = getMilliseconds(); return true; } else { return false; } } int getMilliseconds() const { timeval t; gettimeofday(&amp;t, NULL); return (t.tv_sec * 1000000) + t.tv_usec; } }; </code></pre> <p>This is kinda how you would use it. The program just prints a message every second after an initial delay of 3 seconds.</p> <pre><code>int main (int argc, char * const argv[]) { Timer timer(1000, 3000); timer.start(); int i = 1; while (timer.isRunning()) { if (timer.hasTicked()) { cout &lt;&lt; "tick " &lt;&lt; i++ &lt;&lt; endl; } } } </code></pre>
[ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-03-08T21:40:41.523", "Id": "15622", "Score": "0", "body": "Busy waits are not a good idea. `while (clock() < endwait);`. It will basically burn your CPU out as it goes to 100% utilization in a tight loop. Your timer may work for this scenario but overall not that useful. I would expect it to take an initial delay, a recurring delay and `function`. Then the function is automatically called each time the time out period is reached. Here you have to actually check to see to see if the timer has gone off." } ]
[ { "body": "<p>It is not clear why one is multiplied by 1000 and the other divided by a thousand (nor why one is an integer and the other a double).</p>\n\n<pre><code> m_delayAmount = delayAmount * 1000; \n m_initialDelay = initialDelay/1000;\n</code></pre>\n\n<p>This just detects if the delay has been exceeded:</p>\n\n<pre><code> if (getMilliseconds() - m_startTime &gt; m_delayAmount)\n</code></pre>\n\n<p>Not that we have gone twice since it happened (that may be useful to know). Also if you fail to call it for 5 minutes the next one is still 3 seconds away. I would like the ability to to call my function for each alarm it had missed or if this delay was 4.5 seconds then I wan the next one to be 1.5 seconds away (rather than 3).</p>\n\n<p>Should this not be private?</p>\n\n<pre><code>int getMilliseconds() const\n</code></pre>\n\n<p>It does not seem this needs to be part of the interface.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-03-08T21:45:34.263", "Id": "9836", "ParentId": "9835", "Score": "1" } }, { "body": "<p>I think you should take a look at <code>std::chrono</code> and <code>std::thread</code>.</p>\n\n<p>If you want to replicate, say, a VB timer or whatever (something that calls a function every second), you can do this:</p>\n\n<pre><code>template&lt;typename Func&gt;\nvoid timer(Func func, unsigned interval)\n{\n while(true)\n {\n std::this_thread\n\n std::this_thread::sleep_for(;\n std::chrono::milliseconds(interval)); \n func();\n }\n}\n</code></pre>\n\n<p>Of course, you can change that into a functor and give it a <code>bool</code> for start and stop.</p>\n\n<p>if you just want to measure the elapsed time then just use chrono</p>\n\n<pre><code>std::chrono::system_clock::time_point start=std::chrono::system_clock::now(); \n//start timer \n//do stuff\nstd::chrono::duration&lt;double&gt; time_taken=std::chrono::system_clock::now() - start;\n</code></pre>\n\n<p>Don't reinvent the wheel. If you don't have access to C++11, then all of this functionality can be used from Boost.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-03-10T17:27:12.430", "Id": "9886", "ParentId": "9835", "Score": "4" } }, { "body": "<p>The <code>clock()</code> function in C standard library measures the <strong><em>approximation of the spent CPU time of the process</em></strong> - it does not count real wall-clock time. As such don't use it for timing.</p>\n\n<p>On Unix-based systems(or any system conforming to SUSv2 and POSIX.1-2001 standards), please take a look at <code>clock_gettime()</code> and <code>CLOCK_MONOTONIC</code> - both found in <em>time.h</em>. The Unix manpage for covers the function quite well. :)</p>\n\n<p>On Unix-based machines you might want to set an <strong>interval timer</strong> by using the <code>setitimer()</code> function from <em>sys/time.h</em> to return a <em>signal</em> to the process which you then handle accordingly. Again, the Unix manpages are the most precise, easily accessible source of information on the matter.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-03-12T02:40:26.620", "Id": "9906", "ParentId": "9835", "Score": "1" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "1", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-03-08T21:27:06.283", "Id": "9835", "Score": "2", "Tags": [ "c++", "timer" ], "Title": "Timer class for games" }
9835
<p>Let's say I want to create dynamic documentation of functions I wrote, without using the <code>help()</code> function (I don't want the user to care about arguments accepted by my function, nor get cluttered with other stuff like the copyright info, or other stuff that aren't functions). </p> <p>Here's an attempt:</p> <pre><code>import inspect def foo(): """Return 'foo' string""" return "foo" def user_defined_functions(): """Return names of user-defined functions""" for name in globals(): if inspect.isfunction(eval(name)): docstring = eval(name + ".__doc__") print("{}:\n {}".format(name, docstring)) </code></pre> <p>And here's the pretty result:</p> <pre><code>&gt;&gt;&gt; import test &gt;&gt;&gt; test.user_defined_functions() user_defined_functions: Return names of user-defined functions foo: Return 'foo' string </code></pre> <p>If I had just used the help function I could have gotten extra stuff I don't need (I'm not writing a library, so the user doesn't need all of this):</p> <pre><code>Help on module test: NAME test FUNCTIONS foo() Return 'foo' string user_defined_functions() Return names of user-defined functions FILE /home/wena/src/utils/test.py </code></pre>
[ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-03-09T09:50:12.023", "Id": "15666", "Score": "0", "body": "It's not clear how could you use this function on user defined funtions. The users are going to edit this file? Are you going to import their module? Are you forcing them to import `user_defined_function`? Would you care to explain better?" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-03-09T14:48:41.737", "Id": "15673", "Score": "0", "body": "I was concerned by the term I chose to use, `user-defined-functions`, due to a lack of a better one in my head. What I meant by it is functions that aren't built into Python. I am maintaining a CLI application (http://code.google.com/p/wajig/) where there are a bunch of functions in a single file, and each of those represent a subcommand. I need this functionality so that when a user types `wajig commands`, all functions in that file would get displayed with their docstrings." } ]
[ { "body": "<p>Use <code>for name, value in globals().items():</code> then you don't need to use <code>eval</code></p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-03-08T23:13:03.453", "Id": "9840", "ParentId": "9837", "Score": "5" } }, { "body": "<p>Peeking inside the source code you linked I'd say that what you need is some sort of <code>command</code> table: a dictiony with all the commands and their aliases should do.</p>\n\n<p>To suggest that, other then the fact that you'll need it for what you asked, is that it's almost already written. It's in that ugly <code>if/elif</code> into the <code>help</code> function, but it's almost already there :)</p>\n\n<p>At the beginning of the file:</p>\n\n<pre><code>COMMANDS_TABLE = {\"autoalts\": [\"autoalternatives\"],\n \"builddeps\": [\"builddepend\", \"builddepends\", \"builddeps\"], \n #....\n</code></pre>\n\n<p>With this table your <code>help</code> function will more or less look like:</p>\n\n<pre><code>def help(args):\n # ...\n for command in in args[1:]:\n for func_name,aliases in COMMANDS_TABLE.items():\n if command in aliases:\n command = func_name\n break\n # ...\n</code></pre>\n\n<p>And your <code>listcommands</code> could be:</p>\n\n<pre><code>def listcommands(args):\n for func_name in sorted(COMMANDS_TABLE):\n print globals()[func_name].__doc__\n</code></pre>\n\n<p>But this still looks like a hack, and the reason is that a good command table should map the function themselves not their name:</p>\n\n<pre><code>COMMANDS_TABLE = {autoalts: [\"autoalternatives\"],\n builddeps: [\"builddepend\", \"builddepends\", \"builddeps\"], \n #....\n</code></pre>\n\n<p>Everything will be a lot easier, because once you get the function, you can ask whatever you want:</p>\n\n<pre><code>def listcommands(args):\n for func in sorted(COMMANDS_TABLE, key=operator.attrgetter('__name__')):\n print func.__doc__\n</code></pre>\n\n<p>Now, this is a good design! You could later on transform those functions into callables and this code will still work :)</p>\n\n<p>In the source code you linked, there's also a <code>util.help()</code> function, that might need the same kind of changes.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-03-09T18:04:12.520", "Id": "15682", "Score": "0", "body": "Thanks for taking the time to go as far as looking at that ugly code, especially because that was beyond the scope of the original question." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-03-09T18:05:41.397", "Id": "15684", "Score": "0", "body": "I don't understand the last paragraph: what `eats function name` and `which one is the better choice`." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-03-09T18:12:55.303", "Id": "15688", "Score": "0", "body": "@Tshepang: Oh, I deleted that... Let's [continue in chat](http://chat.stackexchange.com/rooms/2733/discussion-from-displaying-user-defined-functions) if you want, because is not strictly related to your question and I took just a quick look at your code, so I wasn't sure." } ], "meta_data": { "CommentCount": "3", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-03-09T17:41:38.197", "Id": "9862", "ParentId": "9837", "Score": "2" } } ]
{ "AcceptedAnswerId": "9840", "CommentCount": "2", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-03-08T21:47:03.683", "Id": "9837", "Score": "1", "Tags": [ "python" ], "Title": "Displaying user-defined functions and their docstrings" }
9837
<p><strong>Intention:</strong> Automatically scroll the window to the top of a DOM element when the document is loaded. </p> <hr> <p><strong>via JavaScript:</strong></p> <pre class="lang-js prettyprint-override"><code>window.onload = function(){ document.getElementById('foo').scrollIntoView(true); }; </code></pre> <p><strong>Questions and Concerns:</strong></p> <ul> <li>Is there a more compact and/or smarter technique?</li> <li>Does this technique pose issues or potential conflicts?</li> <li>With the above said, should it matter where on the document it's loaded? If so, what's the best location? I've already studied <a href="https://stackoverflow.com/questions/5329807/benefits-of-loading-js-at-the-bottom-as-opposed-to-the-top-of-the-document">this question and its references</a> closely and I'm led to believe it's best to have this kind of script located toward the bottom the document.</li> </ul>
[]
[ { "body": "<p>Three concerns:</p>\n\n<ol>\n<li><p>Error if there is not element called 'foo'</p></li>\n<li><p>I have no idea what that boolean in the function is for. Passing booleans at parameters is very bad. I have no idea what happens if I were to pass it false or any other value. Not scroll into view? I know that it is for topAlign but why not leave it out.</p></li>\n<li><p>you can't use the <code>onload</code> event again without messing it up.</p></li>\n</ol>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-03-09T00:31:07.423", "Id": "15633", "Score": "1", "body": "\"If true, the scrolled element is aligned with the top of the scroll area. If false, it is aligned with the bottom.\" [source](https://developer.mozilla.org/en/DOM/element.scrollIntoView)" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-03-09T00:32:03.910", "Id": "15634", "Score": "0", "body": "Obviously, the element won't be called 'foo' in production. Where would the second `onload` event be placed and why is it an improvement?" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-03-09T01:03:28.753", "Id": "15637", "Score": "0", "body": "'foo' by any other name.. is still 'foo'... you are chaining behavior when it could break your code. I am recommending doing a bit of checking like: ` if (el = document.getElementById('foo')) el.scrollIntoView();" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-03-09T01:08:21.513", "Id": "15638", "Score": "0", "body": "@gmeben it is topAligned by default... that is my point." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-03-09T02:09:02.567", "Id": "15640", "Score": "1", "body": "I feel adding a conditional to test for a single element that's known to exist is a bit overkill. Compactness is one of my goals. My concerns for potential conflict comes down to whether or not `scrollIntoView` or the way I'm initializing the script is known to cause behavior issues, and if so, is there an alternative method?" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-03-09T02:11:27.617", "Id": "15641", "Score": "0", "body": "I should've known that I could strip out the boolean value being passed to make this more compact. Thanks for pointing that out." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-03-09T02:16:44.100", "Id": "15642", "Score": "0", "body": "Still, I'd be interested to see how `onload` could be used again for this script. Unless you meant that `onload` could be used again _elsewhere_ in the document without worrying about conflict." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-03-09T03:46:47.293", "Id": "15643", "Score": "0", "body": "@gmeben apologies I meant \"you can't use the onload event again without messing it up.\"" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-03-09T03:48:46.213", "Id": "15644", "Score": "0", "body": "@gmeben I can see how the conditional test can seem overkill. Just a concern for me." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-03-09T03:48:59.990", "Id": "15645", "Score": "0", "body": "That's what I figured. Excellent" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-03-09T03:50:55.243", "Id": "15646", "Score": "0", "body": "If I were applying this to an array of DOM elements, then I could definitely see the conditional being a practical and thing to implement and worthy of sacrificing a bit of the conciseness of the script." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-03-09T03:58:22.160", "Id": "15647", "Score": "0", "body": "Also, I edited your post to show the final answer for people who show up here in the future, but it won't be shown until it's 'peer reviewed,' whatever that means..." } ], "meta_data": { "CommentCount": "12", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-03-09T00:27:01.750", "Id": "9845", "ParentId": "9838", "Score": "4" } } ]
{ "AcceptedAnswerId": "9845", "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-03-08T23:09:14.510", "Id": "9838", "Score": "3", "Tags": [ "javascript" ], "Title": "Scroll to the top of an element when document is loaded" }
9838
<p>I wish to create a database for a webpage where users are able to add their own events to a timetable. Users will be able to decide if the events should be recurring (weekly) or not. Users should be able to query other groups of users to organize a time for a meeting. That is it.</p> <p>What I have so far is as follows:</p> <pre><code>Users ( userID INT NOT NULL AUTO_INCREMENT, username VARCHAR(80), PRIMARY KEY (user_id) ); Groups { GroupID INT NOT NULL AUTO_INCREMENT, GroupName NVARCHAR(100) private BOOLEAN } Membership { UserID (FOREIGN KEY, UNIQUE), GroupID( FOREIGN KEY, UNIQUE) } Events ( event_id INT NOT NULL AUTO_INCREMENT, title VARCHAR(80) NOT NULL, description VARCHAR(200), start_time DATETIME, end_time DATETIME, group_id INT NOT NULL, recurring BOOLEAN ); Group ( group_id INT NOT NULL, user_id INT NOT NULL ); </code></pre> <p>When a user wants to arrange a meeting using my database, I will be forced to use 3 queries and 2 loops, is there a better way than this? It all seems extremely complicated.</p> <pre><code>int i = 0; String[] names = { Request.Form["usernames"]Split(' ') }; //retrieving names from form List&lt;int&gt; user_ids = new List&lt;int&gt;(); foreach(string name in names){ int user_id = db.QueryValue("SELECT user_id FROM users WHERE username = name"); user_ids.Add(user_id); //now I have a list of all user_ids } db.Execute("INSERT INTO group(groupName) values(Request.Form["Group name"])"); int groupID = db.QueryValue("SELECT groupid from group where groupname="Request.Form["Group name "]"); foreach (string user_id in user_ids) { db.Execute("INSERT INTO membership(userid,groupid) values(user_id, groupID);" } </code></pre>
[ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-03-08T22:32:41.543", "Id": "15625", "Score": "2", "body": "This should probably be moved to Code Review..." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-03-08T22:40:43.770", "Id": "15626", "Score": "0", "body": "Do you mean you will create a new group for every event? If so, why not have a EventUsers table instead of groups and memberships? Also, if you change recurring to an int, positive values can imply number of days between events while -1 can mean monthly, -2 can mean every second months and so on. More dynamic and allows for yearly recurrances" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-03-08T22:50:29.883", "Id": "15627", "Score": "0", "body": "No, I will not create a new group for every event. I will allow the users to choose from existing groups or to create their own group! Many thanks for the suggestion about recurrences, I will bear that in mind. Any other thoughts?" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-03-08T22:58:22.780", "Id": "15628", "Score": "0", "body": "Ok, but if I create a group and create events for that ten times and then add a user to the group, she will seem to have been in those first events too. Thus you still need the EventUsers table to track the group members for the actual event" } ]
[ { "body": "<p>From looking at your database description . . .</p>\n\n<ul>\n<li>No unique constraint on <code>Users.username</code>. You can have 1000 users named \"Fred\".</li>\n<li>No unique constraint on <code>Groups.groupname</code>. You can have 1000 groups named \"Hamburger\". You probably don't want to allow that.</li>\n<li>If you intend to build Membership like <code>UserID integer not null unique references Users (userID)</code>, and <code>GroupID integer not null unique references Groups (GroupID)</code> then each user and each group can appear in that table only once. That means that if <em>I</em> have membership in the group <code>Hamburger</code>, you cannot also have membership in the group <code>Hamburger</code>. I think you probably want to drop the <code>UNIQUE</code> constraint from both those clauses, and add <code>PRIMARY KEY (UserID, GroupID)</code>.</li>\n<li>It's not clear what the difference is between the two tables Membership and Group.</li>\n</ul>\n\n<p>From looking at your code . . .</p>\n\n<ul>\n<li><code>db.QueryValue(\"SELECT user_id FROM users WHERE username = name\");</code> You're selecting user identifiers given the users' names. But names aren't unique in your database. If I select one \"Fred\", and there are 1000 Freds in your database, I'm going to end up with 1000 different user identifiers. You probably don't want to do this.</li>\n<li><code>db.Execute(\"INSERT INTO group(groupName)</code> There's no column named \"groupname\" in that table.</li>\n<li><code>int groupID = db.QueryValue(\"SELECT groupid from group where groupname =</code> You're selecting group identifiers given the group's name. Same problem as with selecting user identifiers above.</li>\n</ul>\n\n<p>Unless I misunderstand you, and that's always possible, you should be able to insert existing users and existing groups into <code>Memberships</code> with a single <code>INSERT</code> statement.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-03-09T00:17:57.733", "Id": "9844", "ParentId": "9839", "Score": "4" } }, { "body": "<p>To handle the complexity issue create <em>business objects</em>. For example, a <code>User</code> class that has an <code>Events</code> collection. That is, classes that reflect the <em>real world</em> relationships you're modeling.</p>\n\n<p>Think of a tiered code structure here. Your <code>client</code> object(s) (i.e. layer) manipulates your <code>business</code> object(s) (i.e. layer). <code>DataAccess</code> objects (i.e. layer) moves data between the business objects and your database using the <code>Database</code> functionality.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-03-09T18:27:05.933", "Id": "9863", "ParentId": "9839", "Score": "0" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "4", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-03-08T22:26:08.723", "Id": "9839", "Score": "1", "Tags": [ "c#", "sql", "asp.net", "sql-server" ], "Title": "Users' timetable database" }
9839
<p>Here's a messy C# method used to calculate some business logic.</p> <p>Does anybody have any suggestions on how I can optimise this code? I'm asking in case there are bad practices, improvements or functions within .NET/LINQ which I'm missing.</p> <pre><code>private static decimal GetRecurringCostEquiv(List&lt;QuotationItemViewModel&gt; items) { var discVal = GetDiscounts(items, (int)RecordEnums.ProductClassification.Service); decimal? currentRecurringCosts = GetRecurringCost(items).Value; decimal? result = 0.00M; decimal highestContractTerm = items.Where(x =&gt; x.ProductTypeId == (int)RecordEnums.ProductClassification.Service).Select(y =&gt; y.RecurringTerm).Max() ?? 0; if ((discVal &gt; 0) &amp;&amp; (highestContractTerm &gt; 0)) { var calc = items.Where(x =&gt; x.ProductTypeId == (int)RecordEnums.ProductClassification.Service).Select(y =&gt; y.RecurringCostCore * y.Quantity); decimal total = calc.Sum() ?? 0; decimal totalOverTerm = total * highestContractTerm; decimal totalOverTermMinusDiscounts = totalOverTerm - discVal; result = totalOverTermMinusDiscounts / highestContractTerm; } else { result = currentRecurringCosts; } return result ?? 0.00M; } </code></pre>
[ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-03-09T14:33:43.650", "Id": "15671", "Score": "0", "body": "It would help to know what these other methods are and what they return. `GetDiscounts()`, `GetRecurringCost()`" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-03-09T14:45:05.703", "Id": "15672", "Score": "0", "body": "@JeffMercado These are just decimal values." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-03-09T14:49:56.643", "Id": "15674", "Score": "0", "body": "`GetRecurringCost()` returns a decimal?" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-03-09T16:23:39.753", "Id": "15679", "Score": "0", "body": "I'm guessing it returns a `decimal?`." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-03-09T20:14:11.237", "Id": "15701", "Score": "0", "body": "Amongst other comments I would perhaps look at changing the method name from GetRecurringCostEquiv() to GetRecurringCostEquivalent() to be more specific and staying away from non-standard abrev. Unless Equiv is a standard in your business domain I guess. Just a minor thing." } ]
[ { "body": "<p>There's two things that I'm seeing right off the bat.</p>\n\n<ol>\n<li><p>Don't use \"magic integers\" where you can be using Enums. <code>GetDiscounts</code> should probably receive an enum, not an int:</p>\n\n<p><code>var discVal = GetDiscounts(items, RecordEnums.ProductClassification.Service);</code></p></li>\n<li><p>You don't need to <code>Select</code> then <code>Max</code>. Just using <code>Max</code> will give you the desired outcome.</p>\n\n<p><code>decimal highestContractTerm = items.Where(x =&gt; x.ProductTypeId == (int)RecordEnums.ProductClassification.Service).Max(y =&gt; y.RecurringTerm ?? 0;</code></p></li>\n</ol>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-03-09T14:47:20.437", "Id": "9853", "ParentId": "9852", "Score": "1" } }, { "body": "<p>It is not bad. Here is my shot at it:</p>\n\n<pre><code>private static decimal GetRecurringCostEquiv(List&lt;QuotationItemViewModel&gt; items)\n{\n var discVal = GetDiscounts(items, (int)RecordEnums.ProductClassification.Service);\n\n // This can be calculated using its own small function\n // Consider using SQL-like LINQ syntax and split it into multiple lines. \n decimal highestContractTerm = items.Where(x =&gt; x.ProductTypeId == (int)RecordEnums.ProductClassification.Service).Select(y =&gt; y.RecurringTerm).Max() ?? 0;\n\n if (discVal &lt;= 0 || highestContractTerm &lt;= 0)\n {\n return GetCurrentRecurringCosts(items);\n }\n\n // The following 2 lines could be its own function.\n // Again, consider splitting LINQ into multiple lines.\n var calc = items.Where(x =&gt; x.ProductTypeId == (int)RecordEnums.ProductClassification.Service).Select(y =&gt; y.RecurringCostCore * y.Quantity);\n decimal total = calc.Sum() ?? 0;\n\n // Get rid of the totalOverTerm variable and bring its value into the second line\n decimal totalOverTerm = total * highestContractTerm;\n decimal totalOverTermMinusDiscounts = totalOverTerm - discVal;\n\n // Do this instead:\n // return Coalesce(totalOverTermMinusDiscounts / highestContractTerm);\n\n decimal? result = totalOverTermMinusDiscounts / highestContractTerm;\n return result ?? 0.00M;\n}\n\n// Consider using this function\npublic static decimal Coalesce(decimal? nullableValue, decimal valueIfNull = Decimal.Zero)\n{\n if (nullableValue.HasValue)\n {\n return nullableValue.Value;\n }\n\n return valueIfNull;\n}\n</code></pre>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-03-09T14:49:09.177", "Id": "9854", "ParentId": "9852", "Score": "1" } }, { "body": "<p>Try this. There are several areas that are hard to comment on due to the null-based nature of several of the variables you are utilizing. Also the static helper methods on the bottom need to be refactored/replaced to conform with the methods you already have.</p>\n\n<pre><code> private static decimal GetRecurringCostEquiv(this List&lt;QuotationItemViewModel&gt; items)\n {\n\n #region Variable Acquisition\n\n var products = items.Where(q=&gt; q.ProductTypeId == (int)RecordEnums.ProductClassification.Service);\n var highestContractTerm = products.Max(q =&gt; q.RecurringTerm).Normalize();\n var discounts = items.GetDiscounts();\n\n var hasContractTerm = highestContractTerm &gt; 0;\n var hasDiscounts = discounts &gt; 0;\n\n #endregion\n\n if (hasDiscounts &amp;&amp; hasContractTerm)\n {\n decimal cost = products.Sum(q =&gt; q.RecurringCostCore * q.Quantity).Normalize();\n\n return ((cost * highestContractTerm) - discounts) / highestContractTerm;\n }\n else \n {\n return items.GetRecurringCost().Normalize();\n }\n }\n\n\n private static decimal? GetRecurringCost(this List&lt;QuotationItemViewModel&gt; items)\n {//TODO: should be reviewed/refactored according to the base function\n return GetRecurringCost(items).Value;\n }\n\n private static int GetDiscounts(this List&lt;QuotationItemViewModel&gt; items)\n {//TODO: should be reviewed/refactored according to the base function\n var discounts = 0; //Do Stuff\n\n return discounts &gt; 0 ? discounts : 0;//ensure discount value compliance\n }\n\n\n private static decimal Normalize(this decimal? value) { return (decimal)value; }\n\n private static decimal Normalize(this int? value) { return (int)value; }\n</code></pre>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-03-09T19:24:46.820", "Id": "9867", "ParentId": "9852", "Score": "0" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "5", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-03-09T14:13:03.530", "Id": "9852", "Score": "2", "Tags": [ "c#", "linq" ], "Title": "Calculating business logic" }
9852
<p>Here's a trivial example:</p> <pre><code>if type(length) != int: length = 16 </code></pre> <p>as opposed to:</p> <pre><code>try: len_mod = (length + 33) / 32 + 1 except TypeError: #recover here somehow, over-ride input? len_mod = (16 + 33) / 32 + 1 </code></pre> <p>I don't need an <em>authoritative</em> answer, but some opinion on this approach would be fine.</p> <p>Some info about the surrounding code, as it stands now:</p> <ol> <li>I don't expect anything but an <code>int</code> for <code>length</code>. I will never expect anything else.</li> <li>There's no purpose in showing an error message (this is a stand-alone method)</li> <li>There's no harm in suppressing the error (for now, nothing else uses this method)</li> </ol> <p>With that information, is it still alright to hijack (albeit, bad) user input and suppress the resulting error by replacing it with what <em>would</em> have been the default value in the function? </p> <p>I ask because I've never read anyone else's code where this happens, and I have wondered if there was a reason for that I'm missing.</p> <p>Feel free to invent some cases where I might regret this decision, or any other points you'd like to highlight for the sake of example.</p> <p>Thanks.</p> <h1>EDIT</h1> <p>Another angle: my goal is to make a useful, single serving website, quite similar to tinyurl. I tested their site using a similar bit of invalid data, and it didn't report anything back to me. It just let me be stupid:</p> <p><img src="https://i.stack.imgur.com/PwSnZ.png" alt="tiny url giving me a crap tinyurl link like it&#39;s nothing big"></p> <p>They didn't check if my site matched a regex for syntactically valid domains, they didn't even bother mentioning that my original link was 6 characters <em>shorter</em> than what they gave back. I think this is a good thing, from a user's perspective. Why tell me what the site can and can't do?</p> <p>I understand that this code, being for a stand-alone, single-serving application, may or may not be subject to some of the same rules as other, more modular functions are. Given the circumstances, how do I write my code to suffer fools lightly, and still be durable and extendable? So far, I'm quite happy with the short, direct <code>try:except</code> block acting as a guardian.</p>
[ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-03-09T18:15:59.450", "Id": "15689", "Score": "1", "body": "Where did length come from? You've said it was user input, but was it read from a file? raw_input? the python interpreter?" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-03-10T00:02:16.273", "Id": "15703", "Score": "0", "body": "`def myfunc(start_string, length=16, random_seed=1, ...)`. It'll be used as input from a user once the UI is incorporated. For now, I suppose it's *develoeper* input? If that makes sense?" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-03-10T00:12:33.657", "Id": "15705", "Score": "1", "body": "Then it is *NOT* user input, and the answers given thus far are predicated on a false understanding of what you are doing. Handling input from the user is a completely different scenario then handling the data a programmer passes your function." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-03-10T00:36:15.453", "Id": "15708", "Score": "0", "body": "I don't understand. What difference does it make if it came from `raw_input`, or a form on a website? Both come from users." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-03-10T00:53:18.987", "Id": "15710", "Score": "1", "body": "you stated that it came from a developer, i.e. not the user. The deal is this, I'm confused on what circumstances you might be passed either an int or something else. If its coming directly from user input, then it should always be a string. Or it should have already been converted to an int, and thus the problem should have been solved before coming to this function." } ]
[ { "body": "<p>Why don't you check <code>length</code> type when you get value from user input?</p>\n\n<pre><code>try:\n length = int(user_input)\nexcept (ValueError, TypeError):\n length = DEFAULT_LENGTH\n</code></pre>\n\n<p>Also, I think it's not good to compare type of variable <code>type(length) != int</code>. Length could be <code>long</code> type and it would not harm to your program (more likely).</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-03-09T15:53:17.540", "Id": "15675", "Score": "0", "body": "After sanitizing user input you will use `length` as you like: `len_mod = (length + 33) / 32 + 1`" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-03-09T18:04:38.507", "Id": "15683", "Score": "1", "body": "Alright, so it's not anything unusual to look at user input and say, \"Hey, this person must be confused\" and replace it with an acceptable answer vs. explicitly reminding the user to read the docstring or something. That was more of my concern." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-03-09T18:11:17.727", "Id": "15686", "Score": "1", "body": "Both variants are possible and depend on your program" } ], "meta_data": { "CommentCount": "3", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-03-09T15:52:10.633", "Id": "9857", "ParentId": "9855", "Score": "2" } }, { "body": "<p>Don't give into that temptation.</p>\n\n<p>Suppose that the user inputs an invalid number say \"45a\", and then the default is taken. What happens? In the best case its obvious the user that something went wrong. However, its probably not obvious exactly what went wrong. However, your program knows exactly what went wrong, but chose not to tell the user. You've just made things harder for the user. Even worse, what if the user doesn't notice that something is wrong. The user assumes that his input was read correctly and takes the program's output as accurate and acts on it. Now they have incorrect information, and don't know it!</p>\n\n<p>As far as I'm concerned nothing good can happen from ignoring invalid user input. Tell the user they goofed. </p>\n\n<p><strong>EDIT</strong></p>\n\n<p>Firstly, there is a very large important difference between tinyurl and your function. Tinyurl never overrides the user input with defaults. It doesn't try and guess what you really meant when you give it nonsense. Your function overrides user input and tries to guess what the user really wanted. Its the guessing and overriding that is a really bad idea. The only effect of doing those is to mask bugs.</p>\n\n<p>Secondly, while tinyurl can get away with it as a website, I don't think \"suffering fools lightly\" is a good idea. We all play the fool occasionally, and when that happens I want my programs to slap me in the face, not play along. When I introduce a bug in my program, I want that bug to manifest itself as close as possible to point where I introduced it. That way I should have the easiest time tracing the problem. What your method does is prevent function from dying because I passed it the wrong types, but then exhibits incorrect behavior later on. As far as I can tell, there are no circumstances in which that will be helpful to me. </p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-03-10T00:11:41.893", "Id": "15704", "Score": "0", "body": "Let me show you something...I'm editing my question in light of your response. Please weigh in." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-03-10T00:52:08.957", "Id": "15709", "Score": "0", "body": "@Droogans, updated my answer" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-03-10T04:35:03.207", "Id": "15712", "Score": "0", "body": "What you've done here is clearly separated the line between developer versus user input, and how \"the principle of least astonishment\" differs from those two groups. I'm going to restructure tomorrow; a clean, tight, modular core, and an idiot proof wrapper for directing user input into. I've been stuck thinking I couldn't have one without the other." } ], "meta_data": { "CommentCount": "3", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-03-09T19:30:25.460", "Id": "9868", "ParentId": "9855", "Score": "4" } } ]
{ "AcceptedAnswerId": "9868", "CommentCount": "5", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-03-09T15:04:56.217", "Id": "9855", "Score": "0", "Tags": [ "python", "casting" ], "Title": "Over-Riding User Input" }
9855
<p>Have some code that I wrote to parse a flat file of IP address and other junk unwanted information. Just wanting to see if there was any way to make shorter or better. </p> <pre><code>#!/usr/bin/perl use strict; use warnings; #opening the access_log flat file that contains a list of ip addresses with unwanted information after, and contains duplicate IPs #example, "203.151.232.51 - - DateTime Junk URL Information" open (YYY, "/home/access_log"); #assigning flat file to an array my @incomingarray=&lt;YYY&gt;; my $value = 0; #splitting up the array and assigning variables to the pairs foreach my $pair(@incomingarray) { (my $ip, my $junk) = split(/ - - /, $pair); $incomingarray[$value] = $ip; #autoincrementing the scalar $value++; } close (YYY); #print @incomingarray; #creating a hashlist from the array and using the map function to remove duplicates my %IPlist = map { $_ =&gt; 1 } @incomingarray; #creating a new array by using the keys function to loop through the hash list my @distinctIP = keys %IPlist; foreach (@distinctIP) { print "$_\n"; } </code></pre>
[ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-03-09T16:35:14.270", "Id": "15680", "Score": "0", "body": "Can you please put the code in the question. This way we will never loose the code that is associated with any responses." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-03-09T19:57:17.577", "Id": "15698", "Score": "0", "body": "use perlcrtic on your code" } ]
[ { "body": "<p>You should probably close the file as soon as you are finished.<br />\nDivorcing the open() and close() makes it harder to see maintain.<br />\nMove close() to here (just after you finish using the file).</p>\n<pre><code>open (YYY, &quot;/home/access_log&quot;);\n#assigning flat file to an array\nmy @incomingarray=&lt;YYY&gt;;\nclose (YYY);\n</code></pre>\n<p>In the main loop you add overwriten the current values with just the IP address I would not consider this good practice (though it works here because of the simplicity of the program). And since your next step is to convert the array into a hash why not do so directly in the loop.</p>\n<pre><code> $incomingarray[$value] = $ip;\n</code></pre>\n<p>Why not just do:</p>\n<pre><code> $IPlist{$ip} ++; // Increment the count that way you can count each IP.\n</code></pre>\n<p>There is no need to create a new array just to loop over them. You can use the keys directly in the foreach statement to loop over the hash.</p>\n<pre><code>my @distinctIP = keys %IPlist;\nforeach (@distinctIP) {\n print &quot;$_\\n&quot;;\n}\n</code></pre>\n<p>Just as easy to write:</p>\n<pre><code>foreach (keys %IPlist) {\n print &quot;$_\\n&quot;;\n}\n</code></pre>\n<h3>Two things no note about variables.</h3>\n<p>Using the automatic variables $_ and @_ make writing the code easier but (in my opinion) also can make the code harder to read and maintain (if overused). This is why perl has got the reputation of being a write once never read or understand again language. So please try and be explicit.</p>\n<p>Also all the variables you declare are global scope (you seem to have fixed this). I know for this short program it does not make any difference but a habit you should get into is declaring variables with <code>my</code>. This scopes the variable to the current block (thus making them behave like variables in most other modern languages). By doing this you reduce problems associated with modifying global state accidentally and when you do drop <code>my</code> you know it is on purpose and thus affecting the global version.</p>\n<h3>Loading the whole array.</h3>\n<p>Personally I would not have loaded the file into the array and parse it. I would have just read the file line by line and done the appropriate parsing:</p>\n<pre><code>#!/usr/bin/perl\n\nuse strict;\nuse warnings;\n\nmy %IPList ;\nopen(YYY, &quot;access_log&quot;);\nwhile(my $line = &lt;YYY&gt;)\n{\n chomp $line;\n (my $ip, my $junk) = split(/ - - /, $line);\n\n $IPList{$ip}++;\n}\nclose(YYY);\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-03-09T18:09:28.967", "Id": "15685", "Score": "0", "body": "I like the approach you outlined about not loading the whole array and just trying to read it instead. I have tried to implement this but I first get a global variable warning,then after I fixed that I keep getting syntax errors for this line of code. $IPList{$ip}++;" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-03-09T18:19:14.930", "Id": "15690", "Score": "0", "body": "@Salmonerd: Fixed the syntax errors." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-03-10T00:14:20.783", "Id": "15706", "Score": "0", "body": "@LokiAstari is right about the whole-array point. But since this is Code Review, let's be explicit. The reason for processing each line of the file separately is because the file could have billions or trillions of lines, and you can't load a file that won't fit into memory. It's bad enough you're keeping a list of all the IPs, but presumably you need to use them in some follow-on code you haven't show us. In other words, you should always think in terms of enormous data." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-03-10T00:27:42.577", "Id": "15707", "Score": "0", "body": "@Loki Astari: Works pretty good" } ], "meta_data": { "CommentCount": "4", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-03-09T16:51:52.767", "Id": "9861", "ParentId": "9859", "Score": "3" } }, { "body": "<p>As Loki Astari already mentioned you should not read in the file at once. But there are also several other issues with your file handling:</p>\n\n<ul>\n<li>You should use <strong>three argument version</strong> of open</li>\n<li>You should use <strong>lexical filehandles</strong> </li>\n<li>You should add <strong>error handling</strong></li>\n</ul>\n\n<p>So just the file opening part could be written as:</p>\n\n<pre><code>open my $filehandle , '&lt;' , 'access_log' or die \"Cannot open 'access_log'.\" ;\nwhile( my $line = &lt;$filehandle&gt; ) {\n # work with $line\n}\nclose $filehandle ;\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-04-10T09:24:42.700", "Id": "17146", "Score": "1", "body": "I recommend the changes stated above as it follows Perl Best Practices. I don't have a good link in PBP but you can use always google." } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-03-26T20:25:34.263", "Id": "10348", "ParentId": "9859", "Score": "2" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "2", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-03-09T16:09:11.443", "Id": "9859", "Score": "3", "Tags": [ "perl" ], "Title": "parsing a flat file and removing duplicates" }
9859
<p>This is a simple sort of array. The array (in fact I used <code>ArrayList</code>) is stored in <code>default_list.txt</code> file on server, all changes to it are made using servlets.</p> <p><strong>Add.java:</strong></p> <pre><code>import java.io.BufferedReader; import java.io.File; import java.io.FileReader; import java.io.FileWriter; import java.io.IOException; import java.util.ArrayList; import java.util.Collections; import java.util.List; import javax.servlet.RequestDispatcher; import javax.servlet.ServletException; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import javax.servlet.http.HttpSession; public class Add extends HttpServlet { protected void processRequest(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { addNumber(request); goToPage("/index.jsp", request, response); } private void goToPage(String address, HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { RequestDispatcher dispatcher = getServletContext() .getRequestDispatcher(address); dispatcher.forward(request, response); } public static void addNumber(HttpServletRequest request) { try { HttpSession session = request.getSession(true); String path = session.getServletContext().getRealPath("/") + "default_list.txt"; String path2 = session.getServletContext().getRealPath("/") + "sorted_list.txt"; int numbers = Integer.parseInt(request.getParameter("textarea1")); FileWriter writer = new FileWriter(path, true); writer.write(numbers + "\n"); writer.flush(); writer.close(); List&lt;String&gt; buf = new ArrayList&lt;String&gt;(); File sorted_list = new File(path2); sorted_list.delete(); ArrayList&lt;Integer&gt; arr = new ArrayList&lt;Integer&gt;(); FileReader filereader = new FileReader(path); BufferedReader br = new BufferedReader(filereader); String eachLine = br.readLine(); while (eachLine != null) { arr.add(Integer.parseInt(eachLine)); eachLine = br.readLine(); } filereader.close(); long timeout = System.currentTimeMillis(); Collections.sort(arr); timeout = System.currentTimeMillis() - timeout; writer = new FileWriter(path2, true); for (int i = 0; i &lt; arr.size(); ++i) buf.add(arr.get(i) + "\n"); for (String record : buf) { writer.write(record); } if (arr.size() &gt; 0) { writer.write("Sort method executed in " + timeout + " ms.\n"); } writer.flush(); writer.close(); } catch (Exception e) { } } protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { processRequest(request, response); } protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { processRequest(request, response); } } </code></pre> <p><strong>Delete.java:</strong></p> <pre><code>import java.io.BufferedReader; import java.io.File; import java.io.FileReader; import java.io.FileWriter; import java.io.IOException; import java.util.ArrayList; import java.util.Collections; import java.util.List; import javax.servlet.RequestDispatcher; import javax.servlet.ServletException; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import javax.servlet.http.HttpSession; public class Delete extends HttpServlet { protected void processRequest(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { addNumber(request); goToPage("/index.jsp", request, response); } private void goToPage(String address, HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { RequestDispatcher dispatcher = getServletContext() .getRequestDispatcher(address); dispatcher.forward(request, response); } public static void addNumber(HttpServletRequest request) { try { HttpSession session = request.getSession(true); List&lt;String&gt; buf = new ArrayList&lt;String&gt;(); List&lt;String&gt; buf2 = new ArrayList&lt;String&gt;(); String path = session.getServletContext().getRealPath("/") + "default_list.txt"; String path2 = session.getServletContext().getRealPath("/") + "sorted_list.txt"; ArrayList&lt;Integer&gt; arr = new ArrayList&lt;Integer&gt;(); FileReader filereader = new FileReader(path); BufferedReader br = new BufferedReader(filereader); String eachLine = br.readLine(); while (eachLine != null) { arr.add(Integer.parseInt(eachLine)); eachLine = br.readLine(); } filereader.close(); if (arr.size() &gt; 0) { arr.remove(arr.size() - 1); File path_buf = new File(path); path_buf.delete(); FileWriter writer = new FileWriter(path, true); for (int i = 0; i &lt; arr.size(); ++i) buf.add(arr.get(i) + "\n"); for (String record : buf) { writer.write(record); } buf.clear(); arr.clear(); writer.flush(); writer.close(); } File sorted_list = new File(path2); sorted_list.delete(); filereader = new FileReader(path); br = new BufferedReader(filereader); eachLine = br.readLine(); while (eachLine != null) { arr.add(Integer.parseInt(eachLine)); eachLine = br.readLine(); } filereader.close(); long timeout = System.currentTimeMillis(); Collections.sort(arr); timeout = System.currentTimeMillis() - timeout; FileWriter writer = new FileWriter(path2, true); for (int i = 0; i &lt; arr.size(); ++i) buf.add(arr.get(i) + "\n"); for (String record : buf) { writer.write(record); } if (arr.size() &gt; 0) { writer.write("Sort method executed in " + timeout + " ms.\n"); } writer.flush(); writer.close(); } catch (Exception e) { } } protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { processRequest(request, response); } protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { processRequest(request, response); } } </code></pre> <p><strong>Erase.java:</strong></p> <pre><code>import java.io.File; import java.io.FileWriter; import java.io.IOException; import javax.servlet.RequestDispatcher; import javax.servlet.ServletException; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import javax.servlet.http.HttpSession; public class Erase extends HttpServlet { protected void processRequest(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { addNumber(request); goToPage("/index.jsp", request, response); } private void goToPage(String address, HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { RequestDispatcher dispatcher = getServletContext() .getRequestDispatcher(address); dispatcher.forward(request, response); } public static void addNumber(HttpServletRequest request) { try { HttpSession session = request.getSession(true); String path = session.getServletContext().getRealPath("/") + "default_list.txt"; File list = new File(path); list.delete(); FileWriter writer = new FileWriter(path, true); writer.flush(); writer.close(); path = session.getServletContext().getRealPath("/") + "sorted_list.txt"; list = new File(path); list.delete(); writer = new FileWriter(path, true); writer.flush(); writer.close(); } catch (Exception e) { } } protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { processRequest(request, response); } protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { processRequest(request, response); } } </code></pre> <p><strong>Generate.java:</strong></p> <pre><code>import java.io.BufferedReader; import java.io.File; import java.io.FileReader; import java.io.FileWriter; import java.io.IOException; import java.util.ArrayList; import java.util.Collections; import java.util.List; import java.util.Random; import javax.servlet.RequestDispatcher; import javax.servlet.ServletException; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import javax.servlet.http.HttpSession; public class Generate extends HttpServlet { protected void processRequest(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { addNumber(request); goToPage("/index.jsp", request, response); } private void goToPage(String address, HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { RequestDispatcher dispatcher = getServletContext() .getRequestDispatcher(address); dispatcher.forward(request, response); } public static void addNumber(HttpServletRequest request) { try { HttpSession session = request.getSession(true); List&lt;String&gt; buf = new ArrayList&lt;String&gt;(); String path = session.getServletContext().getRealPath("/") + "default_list.txt"; String path2 = session.getServletContext().getRealPath("/") + "sorted_list.txt"; try { short amount = Short.parseShort(request .getParameter("textarea2")); Random randomGenerator = new Random(); FileWriter writer = new FileWriter(path, true); for (int i = 0; i &lt; amount; ++i) buf.add(randomGenerator.nextInt(100) + "\n"); for (String record : buf) { writer.write(record); } writer.flush(); writer.close(); buf.clear(); File sorted_list = new File(path2); sorted_list.delete(); ArrayList&lt;Integer&gt; arr = new ArrayList&lt;Integer&gt;(); FileReader filereader = new FileReader(path); BufferedReader br = new BufferedReader(filereader); String eachLine = br.readLine(); while (eachLine != null) { arr.add(Integer.parseInt(eachLine)); eachLine = br.readLine(); } filereader.close(); long timeout = System.currentTimeMillis(); Collections.sort(arr); timeout = System.currentTimeMillis() - timeout; FileWriter writer2 = new FileWriter(path2, true); for (int i = 0; i &lt; arr.size(); ++i) buf.add(arr.get(i) + "\n"); for (String record : buf) { writer2.write(record); } if (arr.size() &gt; 0) { writer2.write("Sort method executed in " + timeout + " ms.\n"); } writer2.flush(); writer2.close(); } catch (Exception e) { } ; } catch (Exception e) { } } protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { processRequest(request, response); } protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { processRequest(request, response); } } </code></pre> <p><strong>index.jsp:</strong></p> <pre class="lang-xml prettyprint-override"><code>&lt;%@ page import="java.util.*" %&gt; &lt;%@ page import="java.io.*" %&gt; &lt;HTML&gt; &lt;HEAD&gt; &lt;TITLE&gt;Sample sort&lt;/TITLE&gt; &lt;/HEAD&gt; &lt;BODY&gt; &lt;H1&gt;JSP/Servlet sorting sample.&lt;/H1&gt; &lt;FORM ACTION="list.add" METHOD="POST"&gt; Input a number: &lt;input type="text" name="textarea1"&gt; &lt;INPUT TYPE="SUBMIT" VALUE="Add"&gt; &lt;/form&gt; &lt;FORM ACTION="list.gen" METHOD="POST"&gt; Enter amount of numbers to generate: &lt;input type="text" name="textarea2"&gt; &lt;input type="SUBMIT" value="Generate"&gt; &lt;/FORM&gt; &lt;table&gt; &lt;tr&gt; &lt;td&gt;&lt;form action="list.del" method="POST"&gt; &lt;input type="SUBMIT" value="Delete last"&gt; &lt;/form&gt;&lt;/td&gt; &lt;td&gt;&lt;form action="list.erase" method="POST"&gt; &lt;input type="SUBMIT" value="Clear"&gt; &lt;/form&gt;&lt;/td&gt; &lt;/tr&gt; &lt;/table&gt; &lt;table width="500"&gt; &lt;tr&gt; &lt;td width="250"&gt; Your list: &lt;br&gt; &lt;br&gt; &lt;% String file = application.getRealPath("/") + "default_list.txt"; FileReader filereader = new FileReader(file); BufferedReader br = new BufferedReader(filereader); String eachLine = br.readLine(); while (eachLine != null) { out.println(eachLine); out.println("&lt;br&gt;"); eachLine = br.readLine(); } filereader.close(); %&gt; &lt;/td&gt; &lt;td width="250"&gt; Sorted list: &lt;br&gt; &lt;br&gt; &lt;% String file2 = application.getRealPath("/") + "sorted_list.txt"; FileReader filereader2 = new FileReader(file2); BufferedReader br2 = new BufferedReader(filereader2); String eachLine2 = br2.readLine(); while (eachLine2 != null) { out.println(eachLine2); out.println("&lt;br&gt;"); eachLine2 = br2.readLine(); } filereader2.close(); %&gt; &lt;/td&gt; &lt;/tr&gt; &lt;/table&gt; &lt;/BODY&gt; &lt;HTML&gt; </code></pre> <p>Alternatively the whole project is <a href="http://www.mediafire.com/?" rel="nofollow">here</a>.fcjrg5nms979in9</p> <p>What I am asking for is:</p> <ol> <li>Did I do it overally properly? Some big mistakes here and there maybe?</li> <li>What would you advice me to change to make it better? (safer, faster, simpler)</li> </ol>
[]
[ { "body": "<p>Browsed quickly and here are a few pointers</p>\n\n<p>1) Separation of Concerns (SoC). Let your view (jsp) handle the rendering, Controller (servlet) handle the flow of the application, and all your processing in another set of classes. This would be the basics of MVC. \nHere is the <a href=\"http://en.wikipedia.org/wiki/Model%E2%80%93view%E2%80%93controller\" rel=\"nofollow noreferrer\">wikipedia</a> definition for a simple layout.</p>\n\n<blockquote>\n <p>Model - The model is a collection of Java classes that form a software\n application intended to store, and optionally separate, data. A single\n front end class that can communicate with any user interface (for\n example: a console, a graphical user interface, or a web application).</p>\n \n <p>View - The view is represented by a Java Server Page, with data being\n transported to the page in the HttpServletRequest or HttpSession.</p>\n \n <p>Controller - The Controller servlet communicates with the front end of\n the model and loads the HttpServletRequest or HttpSession with\n appropriate data, before forwarding the HttpServletRequest and\n Response to the JSP using a RequestDispatcher.</p>\n</blockquote>\n\n<p>2) In your JSP don't use scriptlets. Consider learning jstl before you get in the habit of using scriptlets. Why are scriptlets bad? <a href=\"https://stackoverflow.com/a/3180202/425406\">Read this detailed answer</a></p>\n\n<p>3) All of your servlets have the methods goToPage(), doGet(), doPost(), and ProcessRequest(). This is a lot to re-write each time you create a new servlet. Consider creating an abstract class between your servlets and HttpServlet which defines these methods.</p>\n\n<pre><code>public abstract class BaseServlet extends HttpServlet{\n //You must define this \n protected abstract void processRequest(HttpServletRequest request,\n HttpServletResponse response) throws ServletException, IOException;\n\n protected void goToPage(String address, HttpServletRequest request,\n HttpServletResponse response) throws ServletException, IOException {\n RequestDispatcher dispatcher = getServletContext().getRequestDispatcher(address);\n dispatcher.forward(request, response);\n\n }\n\n protected void doGet(HttpServletRequest request,\n HttpServletResponse response) throws ServletException, IOException {\n processRequest(request, response);\n }\n\n protected void doPost(HttpServletRequest request,\n HttpServletResponse response) throws ServletException, IOException {\n processRequest(request, response);\n }\n}\n</code></pre>\n\n<p>Now all you have to do is extend BaseServlet instead of HttpServlet and you have the methods available to you without the need to re-write. If you were to find a bug later, or want to rewrite this now you only have to look in one place instead of changing it in each servlet.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-03-08T15:42:47.443", "Id": "15694", "Score": "0", "body": "Thanks, very very big thanks! I simply cant have any more questions now :) Thanks again!" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-03-09T09:11:54.480", "Id": "15695", "Score": "1", "body": "@Chelios: If the answer has helped or solved your problem. It is suggested to Mark as Answered." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-03-09T12:13:21.183", "Id": "15696", "Score": "0", "body": "Uhm, sorry but how do I do it?" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-03-09T13:30:37.500", "Id": "15697", "Score": "0", "body": "http://meta.stackexchange.com/questions/5234/how-does-accepting-an-answer-work" } ], "meta_data": { "CommentCount": "4", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-03-08T14:16:26.787", "Id": "9866", "ParentId": "9865", "Score": "2" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-03-08T13:35:33.213", "Id": "9865", "Score": "2", "Tags": [ "java", "jsp", "servlets" ], "Title": "Tomcat/JSP/servlets web-project" }
9865
<p>Im starting with MVC and I'd like you to see my code. Am I doing right? What can I improve in my classes? </p> <h2>Controller</h2> <pre><code>class Logar extends Controller { private $view; private $modelDAO; function __construct() { $this-&gt;modelDAO = new LogarModel(); $this-&gt;view = new LogarView(); } public function Login() { if ($this-&gt;modelDAO-&gt;Login($_POST['funcionario'], $_POST['senha'])) { $idFuncionario = $this-&gt;modelDAO-&gt;rows['idFuncionario']; parent::redirect("view/funcionario/index.php"); } else { $this-&gt;view-&gt;show("Funcionario nao cadastrado"); } } } class controller { function redirect($url){ header("location: {$url}"); } } </code></pre> <h2>Model</h2> <pre><code>class LogarModel extends Model { function __construct() { $this-&gt;conectar(); } function Login($funcionario, $senha) { $sql = "select * from funcionario where login = ? and senha = ? "; $this-&gt;read($sql); $this-&gt;bindar(1, $funcionario, PDO::PARAM_STR); $this-&gt;bindar(2, $senha, PDO::PARAM_STR); $this-&gt;executar(); $this-&gt;contar(); $this-&gt;pegar_dados(); $this-&gt;desconectar(); if ($this-&gt;linhas == 1) { return true; } else { return false; } } } class model { function conectar(){ $this-&gt;conn = new Connection(); } function read($readQuery){ $this-&gt;stm = $this-&gt;conn-&gt; prepare($readQuery); } function bindar($n,$var,$extensao){ $this-&gt;stm-&gt;bindparam($n,$var,$extensao); } function contar(){ $this-&gt;linhas = $this-&gt;stm-&gt;rowcount(); } function pegar_dados(){ while($this-&gt;rows = $this-&gt;stm-&gt;fetch()){ return $this-&gt;rows; } } function executar(){ $this-&gt;stm-&gt;execute(); } function desconectar(){ $this-&gt;conn = null; } } </code></pre> <h2>View</h2> <pre><code>class LogarView extends view { function __construct(){ } function mostrarlogado(){ } } class view { function view(){ } function get_var($var,$value){ $this-&gt;var = $value; } function show($value){ $this-&gt;value = $value; echo $this-&gt;value; } function alertar($value){ echo "&lt;script&gt;alert('{$value}')&lt;/script&gt;"; } } </code></pre> <p>So, how am I going?</p>
[]
[ { "body": "<p>Yes, you understood how MVC works, and you are doing it right. The helper functions such as <code>redirect()</code> are in the correct classes. A few comments on the code itself:</p>\n\n<ol>\n<li>I'd recommend to add an <code>exit;</code> statement after sending headers in <code>redirect()</code>. It will be easier to understand the code, since you can now think of the <code>redirect()</code> as a <code>return</code>, which will help you avoid mistakes.</li>\n<li><a href=\"https://stackoverflow.com/questions/1054022/best-way-to-store-password-in-database\">Don't store your password in plain text</a>.</li>\n<li>Symply use <code>return $this-&gt;linhas == 1;</code> at the end of your login function.</li>\n<li>Your <code>model</code> class simply translates the PDO interface into Portuguese, this is not an interesting layer of abstraction in my book. :)</li>\n<li>Declare the variables you use, eg. <code>$this-&gt;stm</code> or <code>$this-&gt;conn</code>.</li>\n<li>You are probably going to want an easier way to make requests when you will have dozens of them, but right now it's OK.</li>\n</ol>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-03-15T21:09:45.080", "Id": "16026", "Score": "0", "body": "how a redirect will help me to avoid mistakes? i did not understand." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-03-16T07:33:39.760", "Id": "16040", "Score": "0", "body": "If there is no `exit()` in the redirect method, then the script will continue to execute. The server won't close the connection, and the client will wait for some other info. If you print anything afterwards, the client will probably never see it, since you issued a redirection. Stating that a redirect() contains an exit makes it clear that nothing can happen after a redirect. It works for your code since you don't do anything in Login() after calling redirect(), but if you were, it wouldn't work. I'd be glad to explain a bit more." } ], "meta_data": { "CommentCount": "2", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-03-12T07:58:51.903", "Id": "9908", "ParentId": "9871", "Score": "1" } }, { "body": "<p>I think you have to use for Redirection</p>\n\n<p>// in controller class</p>\n\n<pre><code>public function redirect($url) {\n// $url =&gt; array('controller' =&gt; 'goto_controller', 'action' =&gt; 'action_of_the_controller')\n if (is_array($url)) {\n debug($url);\n } else {\n\n// login or /home/login or /admin/projects/add etc.\n debug($url);\n }\n }\n</code></pre>\n\n<p>if you want to redirect to the controller then use proper way for MVC. \nIf you want with custom redirect then in same controller or in any other custom location you can goto with without array, you can set redirect from out of project using without array.\nthe Redirection method is upto you. \nYou can redirect with\n - Location:\n - using javascript:\nbut if you are using <code>header(\"Location: url\");</code> method you must have to add \"exit()\" after using the Location header.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-08-26T08:37:26.723", "Id": "110795", "Score": "1", "body": "You're doing the same thing no matter if $url is an array or not, why not simply do `debug($url);` ?" } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-08-26T08:32:01.323", "Id": "61056", "ParentId": "9871", "Score": "0" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-03-09T21:53:19.927", "Id": "9871", "Score": "2", "Tags": [ "php" ], "Title": "Starting MVC PHP - am I doing it right?" }
9871
<p>My classmates and I were given an assignment to make a 'Paint' application (similar to Microsoft Paint).</p> <p>There is a color selection JSlider with a connected textbox to each. My code works fine, but it has some bugs in it. Whenever I draw a shape on the panel and change its color, the background of the panel changes to the JSlider panel.</p> <pre><code>import javax.swing.*; import javax.swing.event.*; import java.awt.*; import java.awt.event.*; import java.util.*; public class MyColorChoose extends JFrame implements ChangeListener, KeyListener, ActionListener, MouseListener, MouseMotionListener { JLabel red, green, blue; JTextField TRed, TGreen, TBlue; JMenu men = new JMenu("File"); JMenu op = new JMenu("Options"); JRadioButton square, oval, tri, rect; JMenuItem close = new JMenuItem("Exit"); JMenuBar mBar = new JMenuBar(); int px, py, rx, ry; ColorChooseRectangle sh = new ColorChooseRectangle(); public int rvalue = 0, gvalue = 0, bvalue = 0; public int minR = 0, minG = 0, minB = 0; public int setR = 127, setG = 127, setB = 127; public int maxR = 255, maxG = 255, maxB = 255; Color fill; JPanel panel = new JPanel(); JSlider SRed = new JSlider(JSlider.HORIZONTAL, minR, maxR, setR); JSlider SGreen = new JSlider(JSlider.HORIZONTAL, minG, maxG, setG); JSlider SBlue = new JSlider(JSlider.HORIZONTAL, minB, maxB, setB); public MyColorChoose() { close.setMnemonic(KeyEvent.VK_X); close.addActionListener(this); men.add(close); mBar.add(men); SRed.setPaintTicks(true); SRed.setMinorTickSpacing(1); SRed.setMajorTickSpacing(50); SRed.setPaintLabels(true); SGreen.setPaintTicks(true); SGreen.setMinorTickSpacing(1); SGreen.setMajorTickSpacing(50); SGreen.setPaintLabels(true); SBlue.setPaintTicks(true); SBlue.setMinorTickSpacing(1); SBlue.setMajorTickSpacing(50); SBlue.setPaintLabels(true); red = new JLabel("Red"); green = new JLabel("Green"); blue = new JLabel("Blue"); TRed = new JTextField(10); TGreen = new JTextField(10); TBlue = new JTextField(10); TRed.setText(Integer.toString(SRed.getValue())); TRed.addKeyListener(this); TBlue.setText(Integer.toString(SBlue.getValue())); TBlue.addKeyListener(this); TGreen.setText(Integer.toString(SGreen.getValue())); TGreen.addKeyListener(this); fill = new Color(SRed.getValue(), SGreen.getValue(), SBlue.getValue()); sh.setChange(fill); JPanel PRed = new JPanel(new GridLayout(3,1)); PRed.add(red); PRed.add(TRed); PRed.add(SRed); JPanel PGr = new JPanel(new GridLayout(3,1)); PGr.add(green); PGr.add(TGreen); PGr.add(SGreen); JPanel PBlue = new JPanel(new GridLayout(3,1)); PBlue.add(blue); PBlue.add(TBlue); PBlue.add(SBlue); JPanel left = new JPanel(new GridLayout(3,1)); left.add(PRed); left.add(PGr); left.add(PBlue); sh.addMouseListener(this); sh.addMouseMotionListener(this); add(mBar, BorderLayout.NORTH); add(left, BorderLayout.WEST); add(sh, BorderLayout.CENTER); SRed.addChangeListener(new ChangeListener() { public void stateChanged(ChangeEvent e) { TRed.setText(String.valueOf(SRed.getValue())); gvalue = Integer.parseInt(TGreen.getText()); bvalue = Integer.parseInt(TBlue.getText()); fill = new Color(SRed.getValue(), gvalue, bvalue); sh.setChange(fill); } }); SGreen.addChangeListener(new ChangeListener() { public void stateChanged(ChangeEvent e) { TGreen.setText(String.valueOf(SGreen.getValue())); rvalue = Integer.parseInt(TRed.getText()); bvalue = Integer.parseInt(TBlue.getText()); fill = new Color(rvalue, SGreen.getValue(), bvalue); sh.setChange(fill); } }); SBlue.addChangeListener(new ChangeListener() { public void stateChanged(ChangeEvent e) { TBlue.setText(String.valueOf(SBlue.getValue())); rvalue = Integer.parseInt(TRed.getText()); gvalue = Integer.parseInt(TGreen.getText()); fill = new Color(rvalue, gvalue, SBlue.getValue()); sh.setChange(fill); } }); } public void stateChanged(ChangeEvent e){} //KEYBOARD LISTENER public void keyTyped(KeyEvent e) { if(e.getKeyCode() == KeyEvent.VK_ENTER) { rvalue = Integer.parseInt(TRed.getText()); gvalue = Integer.parseInt(TGreen.getText()); bvalue = Integer.parseInt(TBlue.getText()); SRed.setValue(rvalue); SGreen.setValue(gvalue); SBlue.setValue(bvalue); fill = new Color(rvalue, gvalue, bvalue); sh.setChange(fill); } } public void keyPressed(KeyEvent e) { if(e.getKeyCode() == KeyEvent.VK_ENTER) { rvalue = Integer.parseInt(TRed.getText()); gvalue = Integer.parseInt(TGreen.getText()); bvalue = Integer.parseInt(TBlue.getText()); SRed.setValue(rvalue); SGreen.setValue(gvalue); SBlue.setValue(bvalue); fill = new Color(rvalue, gvalue, bvalue); sh.setChange(fill); } } public void keyReleased(KeyEvent e){} //ACTION LISTENER public void actionPerformed(ActionEvent e) { Object sel = e.getSource(); if(sel == close) System.exit(0); } //MOUSE LISTENER public void mouseClicked(MouseEvent e){} public void mouseEntered(MouseEvent e){} public void mouseExited(MouseEvent e){} public void mouseMoved(MouseEvent e){} public void mousePressed(MouseEvent e) { px = e.getX(); py = e.getY(); } public void mouseDragged(MouseEvent e) { rx = e.getX(); ry = e.getY(); int w = rx - px; int h = ry - py; sh.setSize(px, py, w, h); } public void mouseReleased(MouseEvent e) { rx = e.getX(); ry = e.getY(); int w = rx - px; int h = ry - py; sh.setSize(px, py, w, h); } public static void main(String[] args) { MyColorChoose m = new MyColorChoose(); m.setSize(600,440); m.setVisible(true); m.setDefaultCloseOperation(m.EXIT_ON_CLOSE); m.setLocationRelativeTo(null); } } </code></pre> <p><strong>Drawing class:</strong></p> <pre><code>import java.awt.*; import javax.swing.*; public class ColorChooseRectangle extends JPanel { public Color change; private int X, Y, W, H; public void paint(Graphics g) { g.setColor(change); g.drawRect(X,Y,W,H); g.fillRect(X,Y,W,H); } public void setChange(Color c) { change = c; repaint(); } public void setSize(int x, int y, int w, int h) { this.X = x; this.Y = y; this.W = w; this.H = h; repaint(); } } </code></pre> <p>Some initialized variables are not yet used, but I will use them.</p>
[]
[ { "body": "<p>I ran your exact code on my computer, I'm a little confused on what your actual problem is, but if you're trying to \"clear\" the panel every time you draw a new shape the code for that would be:</p>\n\n<pre><code>public void paint(Graphics g) \n{\n g.clearRect(0,0,getWidth(),getHeight());\n g.setColor(change);\n g.drawRect(X,Y,W,H);\n g.fillRect(X,Y,W,H);\n}\n</code></pre>\n\n<p>If this isn't what you are looking for, please explain your problem in more detail.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-03-11T11:40:12.577", "Id": "15747", "Score": "0", "body": "No, actually, i want the frame to retain the shapes I Draw.. anyway, here's the full detail of my problem,\n\nI Have drawn a shape on my drawing panel,\nnow, whenever I change the color on the jsliders, \nthe JSlider and its textbox partner appear on the upper left side of the drawing panel,.. Even funny was, whenever I adjust the jslider, the value on the textbox which is adjusting, is also adjusting on the drawing panel! I don't know what is the problem of my code, please help me sir.." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-03-11T17:39:08.477", "Id": "15756", "Score": "1", "body": "Without very good reasons you shouldn't overwrite `paint` in Swing, but overwrite `paintComponent` instead." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-03-12T04:02:14.947", "Id": "15772", "Score": "0", "body": "ohhh so you dont want the color on the JPanel to change when you move the slider??? you only want the slider to effect shapes that are about to be drawn?" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-03-12T04:03:15.367", "Id": "15773", "Score": "0", "body": "@Lanei you are correct, some people override paint() but it is better to override paintComponent() i agree with you and i know that is correct" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-03-12T14:47:50.820", "Id": "15794", "Score": "0", "body": "NO, what I meant is my drawing panel gets messed up by some parts of my frame, (example, I Have drawn a shape, now, whenever i slide the jslider, the jslider image(the slider itself) gets on the drawing panel. how do i fix that?" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-03-12T15:01:36.420", "Id": "15797", "Score": "0", "body": "anyway, here are some screenshots of what I meant with my problem\nhttp://www.mediafire.com/download.php?84k49zcxbzmf8d3" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-03-12T21:26:56.567", "Id": "15828", "Score": "0", "body": "I couldn't open your .rar file, can you just update your question and put the images on your update?" } ], "meta_data": { "CommentCount": "7", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-03-11T01:51:13.607", "Id": "9896", "ParentId": "9875", "Score": "1" } }, { "body": "<p>Some notes:</p>\n\n<ul>\n<li>Access static fields and methods statically. That means instead of using <code>m.EXIT_ON_CLOSE</code> use <code>JFrame.EXIT_ON_CLOSE</code></li>\n<li>Separate the event handler from the gui. JFrame and JPanel subclasses should not implement listeners.</li>\n<li>Try to keep the scope of your variables as small as possible. If you can make them local variables, do so.</li>\n<li>Try to keep the access modifiers of your variables as limited as possible. If you can make them private, do so. Getters and setters maintain encapsulation.</li>\n<li>JFrame has a <code>setJMenuBar(JMenuBar)</code> function that you should use for your menu bar.</li>\n<li><p>For extendability, subclass the content pane rather than the top level container like this:</p>\n\n<pre><code>public class MyColorChoose extends JPanel {\n\n // all the stuff from MyColorChoose\n\n public static void main(String[] args) {\n JFrame frame = new JFrame();\n frame.setJMenuBar(initMenuBar());\n frame.setContentPane(new MyColorChoose());\n frame.pack();\n frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);\n frame.setLocationRelativeTo(null);\n frame.setVisible(true);\n }\n\n }\n</code></pre>\n\n<p>That way if you suddenly decide to make it an applet, you don't have to duplicate much code. You can also separate out the main function into another class. I'd rather not create the menu bar in the content pane class.</p></li>\n<li>NO magic numbers EVER! That means <code>new JPanel(new GridLayout(3, 1))</code> is unacceptable. Constants are your friends.</li>\n<li>Use the <code>@Override</code> annotation when overriding methods.</li>\n<li><p>Favor key bindings over key listeners. Key listeners are low level,while key bindings are high level. Key bindings look like this:</p>\n\n<pre><code>component.getInputMap().put(Keystroke.getKeystroke(\"P\"), \"pause\");\n// if an Action pauseAction has been defined, we can do this:\ncomponent.getActionMap().put(\"pause\", pauseAction);\n</code></pre></li>\n<li><p><code>JTextField</code>s fire action events when the enter key is pressed. Register an action listener with each of your fields instead of using key listener on them.</p></li>\n<li>You panels containing sliders have duplicate code. Refactor them into methods.</li>\n</ul>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-07-01T09:31:45.290", "Id": "13234", "ParentId": "9875", "Score": "1" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-03-10T08:57:37.297", "Id": "9875", "Score": "2", "Tags": [ "java", "swing", "image" ], "Title": "Shape-drawing using JavaX Swing" }
9875
<p>I am parsing a response from server, and in case it contains the fields "chunk_number"(<code>J_ID_CHUNK_NUMBER</code>) and "total_chunk_number"(<code>J_ID_CHUNK_TOTAL</code>), I want to check whether I should request another chunk or not. Not a complicated task. Yet I doubt what would be a better way to implement?</p> <p>Option 1 - using try catch:</p> <pre><code>private int getNextChunkNumber(JSONObject jUpdate) { try { int current; int total; current = jUpdate.getInt(J_ID_CHUNK_NUMBER); total = jUpdate.getInt(J_ID_CHUNK_TOTAL); if (current &lt; total) { return current + 1; } } catch(JSONException e) { // This is an empty exception because it merges with the default result (-1) } return -1; } </code></pre> <p>Option 2 - using the <code>has</code> method:</p> <pre><code>private int getNextChunkNumber(JSONObject jUpdate) { int current; if (jUpdate.has(J_ID_CHUNK_NUMBER) &amp;&amp; jUpdate.has(J_ID_CHUNK_TOTAL)) { current = jUpdate.getInt(J_ID_CHUNK_NUMBER); if (current &lt; jUpdate.getInt(J_ID_CHUNK_TOTAL)) { return current + 1; } } return -1; } </code></pre>
[]
[ { "body": "<p>I would recommend that you use option 2, especially since you have the ability to avoid the exception (by using the has method).</p>\n\n<p>Exceptions should be used in exceptional circumstances (e.g. You might expect getInt to throw an exception if J_ID_CHUNK_TOTAL exists but does not contain a character which can be parsed to an integer). In which case you would want to wrap the call to that in a catch.</p>\n\n<p>I would also suggest that you do a null check against the jUpdate object before using it.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-03-10T09:36:30.803", "Id": "15715", "Score": "0", "body": "Thanks. My idea is to catch an exception if the API is violated in the response (jUpdate), so if `J_ID_CHUNK_NUMBER` or `J_ID_CHUNK_TOTAL` don't exist or if they are not `int`, it's the same for me. Regarding the check for null - it is done in the caller method. Do you think an exceptional circumstance is only `String` instead of `int` or also the absence of the field?" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-03-10T10:27:09.470", "Id": "15716", "Score": "0", "body": "That depends on your business rules, can the code which calls this continue or not if the data is invalid. That will determine whether the routine should exit with a -1 or should it throw an exception." } ], "meta_data": { "CommentCount": "2", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-03-10T09:28:32.740", "Id": "9877", "ParentId": "9876", "Score": "8" } }, { "body": "<p>I strongly recommend option 2. Like Trevor said, exceptions should only be used to handle exceptional or more or less unexpected conditions. That is not the case.</p>\n\n<p>Then, in version 1, you need to explain <em>why</em> that JSONException was thrown/catched and that it is perfectly OK to not handle it.</p>\n\n<p>My suggestion is a modified version of Option 2:</p>\n\n<pre><code>private int getNextChunkNumber(JSONObject jUpdate) {\n int current;\n if (hasNextChunk(jUpdate)) { // &lt;- new method for if condition\n current = jUpdate.getInt(J_ID_CHUNK_NUMBER);\n if (current &lt; jUpdate.getInt(J_ID_CHUNK_TOTAL)) {\n return current + 1;\n } \n }\n return NO_NEXT_CHUNK; // a static int with value -1\n}\n\nprivate boolean hasNextChunk(JSONObject jUpdate) {\n return jUpdate.has(J_ID_CHUNK_NUMBER) &amp;&amp;\n jUpdate.has(J_ID_CHUNK_TOTAL); \n}\n</code></pre>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-03-10T09:36:15.237", "Id": "9878", "ParentId": "9876", "Score": "5" } } ]
{ "AcceptedAnswerId": "9877", "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-03-10T09:10:15.087", "Id": "9876", "Score": "6", "Tags": [ "java", "json" ], "Title": "Check if a value exists or catch an exception" }
9876
<p>This is a simple Python program I wrote. I hope some one could help me optimize this program. If you found any bad habits, please tell me.</p> <pre><code>#!/usr/bin/python import urllib2 def GetURLs(srcURL=""): if srcURL == "": return -1 Content = urllib2.urlopen(srcURL, None, 6) oneLine = Content.readline() while oneLine: print oneLine oneLine = Content.readline() Content.close() return 0 GetURLs("http://www.baidu.com") </code></pre>
[ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-03-10T12:55:58.290", "Id": "15718", "Score": "1", "body": "For starters, dont start your method name with capital letters.Try getURLS() instead of GetURLs same goes for Content (begins with capital letter). In general class names start with capital letters not method or variable names. And I am not sure what are you trying to do with while online: routine. Try to read this book\nhttp://www.amazon.com/Code-Complete-Practical-Handbook-Construction/dp/0735619670 for best practices in programming." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-03-10T13:03:21.983", "Id": "15719", "Score": "0", "body": "yes, maybe I should follow your advice.Thx" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-03-10T13:04:15.087", "Id": "15720", "Score": "7", "body": "You should really follow PEP 8: http://www.python.org/dev/peps/pep-0008/" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-03-10T13:11:42.213", "Id": "15721", "Score": "2", "body": "One piece of 'non-pythonic' code is the guard clause. While often good practice in other languages in python exceptions are light weight and recommended practice. So rather than checking if the url=='' just pass it the urllib2 and deal with the exception using try: except:" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-03-20T23:23:41.113", "Id": "16220", "Score": "1", "body": "@DavidHall: In all honesty, I wouldn't call guard clauses 'non-pythonic', and furthermore I wouldn't call throwing exceptions as being Pythonic, necessarily. It's more of a matter of preference, one of which has a distinct (but insignificant) performance advantage. Here's the [case for guard clauses](http://blog.mafr.de/2009/06/12/a-case-for-guard-clauses/), although, granted, it does not discuss Python directly. Above all, though, if you're working on an existing project, maintaining consistency with the existing convention should be the number one priority." } ]
[ { "body": "<p>You can shorten your code by optimizing iteration over the lines. <code>urlopen()</code> returns a file-like object that allows direct iteration:</p>\n\n<pre><code>content = urllib2.urlopen(srcURL, None, 6)\nfor line in content:\n print line\n\ncontent.close()\n</code></pre>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-03-10T12:55:58.883", "Id": "9880", "ParentId": "9879", "Score": "5" } }, { "body": "<p>You asked for comments on coding style, so here goes:</p>\n\n<ul>\n<li><p>It's <a href=\"http://www.python.org/dev/peps/pep-0008/\" rel=\"nofollow noreferrer\">Python style</a> to use CapitalizedNames for classes and lower_case_names for functions, methods and variables.</p></li>\n<li><p>Functions should have docstrings that describe their arguments and what they do.</p></li>\n<li><p>Names starting with \"get\" are normally used for functions that return the value they get. Your function <em>prints</em> the content at the URL, so it would be better to call it something like <code>print_url</code>.</p></li>\n<li><p>The value of 6 for the <code>timeout</code> argument to <a href=\"http://docs.python.org/library/urllib2.html#urllib2.urlopen\" rel=\"nofollow noreferrer\"><code>urlopen</code></a> seems arbitrary. It would be better either to leave this out (the caller can always use <a href=\"http://docs.python.org/library/socket.html#socket.setdefaulttimeout\" rel=\"nofollow noreferrer\"><code>socket.setdefaulttimeout</code></a> if they need to set a timeout), or to allow the caller to pass it as a keyword argument.</p></li>\n<li><p>You can pass the <code>timeout</code> argument as a keyword argument to avoid having to specify <code>None</code> for the <code>data</code> argument.</p></li>\n<li><p>Having a default value for <code>srcURL</code> is pointless, especially since it's an invalid value! Omit this.</p></li>\n<li><p>The return value is useless: it's -1 if the argument was an empty string, or 0 if it wasn't. If the caller needs to know this, they can look at the argument they are about to supply. (Or they can catch the <code>ValueError</code> that <code>urlopen</code> raises if passed an empty string.)</p></li>\n<li><p>The <code>Content</code> object does not get closed if the <code>readline</code> function raises an error. You can ensure that it gets closed by using Python's <code>try: ... finally: ...</code> statement. (Or <a href=\"http://docs.python.org/library/contextlib.html#contextlib.closing\" rel=\"nofollow noreferrer\"><code>contextlib.closing</code></a> if you prefer.)</p></li>\n</ul>\n\n<p>Applying all of these improvements, plus the <a href=\"https://stackoverflow.com/a/9646592/68063\">one suggested by Lev</a>, yields this function:</p>\n\n<pre><code>def print_url(url, timeout=6):\n \"\"\"\n Print the content at the URL `url` (but time out after `timeout` seconds).\n \"\"\"\n content = urllib2.urlopen(url, timeout=timeout)\n try:\n for line in content:\n print line\n finally:\n content.close()\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-03-10T14:52:24.847", "Id": "15722", "Score": "0", "body": "Can't you just use a `with`-block to handle closing? I.e. never mind `contextlib.closing`; doesn't the object returned by `urllib2.urlopen` already implement the context-manager protocol?" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-03-10T15:35:52.800", "Id": "15723", "Score": "0", "body": "@Karl: try it and see!" } ], "meta_data": { "CommentCount": "2", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-03-10T13:32:27.843", "Id": "9881", "ParentId": "9879", "Score": "16" } }, { "body": "<p>This solution is a bit more idiomatic:</p>\n\n<pre><code>def getURLs(srcURL=\"\"):\n if not srcURL:\n return -1\n content = urllib2.urlopen(srcURL, None, 6)\n try:\n for oneLine in content:\n print oneLine\n finally:\n content.close()\n return 0\n</code></pre>\n\n<p>Notice that by convention, function names start with lower-case. I simplified the test condition at the beginning, and more importantly, the iteration can be written in a simpler way. And as a good practice, resources should be closed in a <code>finally</code> block.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-03-10T13:35:29.767", "Id": "9882", "ParentId": "9879", "Score": "1" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "5", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-03-10T12:49:17.887", "Id": "9879", "Score": "8", "Tags": [ "python", "url" ], "Title": "Function for getting URLs" }
9879
<p>I'm new to C++ and decided to have a go at the spotify challenges on their website, <a href="http://www.spotify.com/uk/jobs/tech/best-before/">http://www.spotify.com/uk/jobs/tech/best-before/</a></p> <p>I have now finished but I get the feeling my code is just terrible, I'm guessing it would be very hard for someone else to read and I feel like there are much better ways to code this. If someone could kindly have a look and help me improve my code I would be very thankful.</p> <p>Here is my code for the best before puzzle: </p> <pre><code>#include &lt;iostream&gt; #include &lt;string&gt; #include &lt;sstream&gt; #include &lt;iomanip&gt; using namespace std; int Year; int Month; int Day; bool loop=true; int date[4]; bool DateFound=false; stringstream ss; string input; string in; void Check_date(); void Check_date() { if(DateFound==false) { //Check if valid Year if (date[1]&lt;2999 &amp;&amp; date[1]&gt;0 &amp;&amp; date[2]&gt;0 &amp;&amp; date[3]&gt;0) { //check months &amp; days are valid if(date[2]==1 || date[2]==3 || date[2]==5 || date[2]==7 || date[2]==8 || date[2]==10 || date[2]==12){if(date[3]&lt;=31){DateFound=true;}} if(date[2]==4 || date[2]==6 || date[2]==9 || date[2]==11){if(date[3]&lt;=30){DateFound=true;}} //Check For Leap Year if (date[2]==2){ if(date[3]&lt;28)DateFound=true; if(date[1]%4==0 &amp;&amp; date[3]&lt;=29)DateFound=true; if(date[1]%100==0 &amp;&amp; date[1]%400!=0 &amp;&amp; date[3]&gt;28)DateFound=false; } } if(DateFound==true) { Year=date[1]; Month=date[2]; Day=date[3]; if(Year&lt;1000)Year=Year+2000; } } } void SwitchDate(){int temp; temp=date[2]; date[2]=date[3]; date[3]=temp; Check_date();}; void ShiftDate(int places) { if(places==1) { int temp; temp=date[3]; date[3]=date[2]; date[2]=temp; temp=date[1]; date[1]=date[2]; date[2]=temp; Check_date(); } if(places==2) { int temp; temp=date[1]; date[1]=date[2]; date[2]=temp; temp=date[2]; date[2]=date[3]; date[3]=temp; Check_date(); } }; </code></pre> <p>And Main</p> <pre><code>int main () { //Main Loop while(loop==true) { cout &lt;&lt;"Please Enter a date \n"; cin&gt;&gt;input; cout&lt;&lt;endl; for (int x=0, y=1; y&lt;=3; y++, x++) { while (input[x] !='/' &amp;&amp; x !=input.length()) ss&lt;&lt;input[x++]; ss&gt;&gt; date[y]; ss.clear(); } //order small medium large for (int x=3, temp; x!=0; x--) { if (date[x] &lt; date[x-1]) { temp=date[x-1]; date[x-1]=date[x]; date[x]=temp; } if (x==1 &amp;&amp; (date[2] &gt; date[3] )) { temp=date[3]; date[3]=date[2]; date[2]=temp; } } Check_date(); SwitchDate(); ShiftDate(1); SwitchDate(); ShiftDate(2); SwitchDate(); //PRINT if(DateFound==true) { cout &lt;&lt;"The smallest valid date is: "; cout &lt;&lt;setw(2)&lt;&lt;setfill('0')&lt;&lt;Year; cout&lt;&lt;"-"; cout &lt;&lt;setw(2)&lt;&lt;setfill('0')&lt;&lt;Month; cout&lt;&lt;"-" ; cout &lt;&lt;setw(2)&lt;&lt;setfill('0')&lt;&lt;Day; cout&lt;&lt;endl; } else cout&lt;&lt;date[1]&lt;&lt;"/"&lt;&lt;date[2]&lt;&lt;"/"&lt;&lt;date[3]&lt;&lt;" Is illegal \n"; DateFound=false; cout &lt;&lt;"Again? 'Y' or 'N' \n"; cin &gt;&gt;in; cout &lt;&lt; endl; if(in=="y" || in=="Y"){loop=true;} if(in=="n" || in=="N"){loop=false;} }//End of Loop } </code></pre>
[ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-03-10T17:26:16.373", "Id": "15725", "Score": "2", "body": "Proper indentation would be nice!" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-03-10T17:30:54.603", "Id": "15727", "Score": "0", "body": "Fixed formatting and added one '}' so that it compiles." } ]
[ { "body": "<p>Here is my incomplete answer, this will tell you is you date is valid in any way but won't currently handle 2 figure years, it will print out all of the combinations not just the lowest, but the lowest will be the first. (note mine uses the British date format because it is the best :D, it is trivail to change that)</p>\n\n<pre><code>#include &lt;algorithm&gt;\n#include &lt;iterator&gt;\n#include &lt;iostream&gt;\n#include &lt;iosfwd&gt;\n#include &lt;deque&gt;\n#include &lt;array&gt;\n\nstruct date{\n std::array&lt;int, 3&gt; val;\n};\n//stream operations\nstd::istream&amp; operator&gt;&gt;(std::istream&amp; is, date&amp; d) {\n char t;\n return is &gt;&gt; d.val[0] &gt;&gt; t &gt;&gt; d.val[1] &gt;&gt; t &gt;&gt; d.val[2]; \n}\nstd::ostream&amp; operator&lt;&lt;(std::ostream&amp; os, const date&amp; d) {\n return os &lt;&lt; d.val[0] &lt;&lt; '-' &lt;&lt; d.val[1] &lt;&lt; '-' &lt;&lt; d.val[2];\n}\n//for sort\nbool date_comp(const date&amp; d1, const date&amp; d2)\n{\n //a reverse iterator could be used here, probably better\n for(size_t i=2; i!=0; --i)\n {\n if(d1.val[i] &lt; d2.val[i])\n return true;\n if(d1.val[i] &gt; d2.val[i])\n return false;\n }\n return false; //they are the same\n}\n\nint days_in_month(int m, int y) {\n switch(m){\n default: return 31;\n case 2: \n if((year % 4 == 0 \n &amp;&amp; year % 100 != 0) \n || (year % 400 == 0))\n return 29\n return 28;\n case 9: case 6: \n case 11: case 4:\n return 30;\n }\n}\n\nbool is_date(const date&amp; d) {\n int day=d.val[0], month=d.val[1], year=d.val[2];\n //it is often easier to say what isn't true rather than what is\n if(month&gt;12 || month&lt;1\n || year&lt;2000 || year&gt;2999\n || day &lt; 0 || day &gt; days_in_month(month, year))\n return false;\n return true;\n}\n\nint main()\n{\n date d;\n std::cin &gt;&gt; d;\n std::deque&lt;date&gt; valid;\n std::sort(d.val.begin(), d.val.end());\n do\n {\n if(is_date(d))\n valid.push_back(d);\n\n }while(std::next_permutation(d.val.begin(), d.val.end()));\n\n std::sort(valid.begin(), valid.end(), &amp;date_comp);\n\n if(valid.empty())\n {\n std::cerr &lt;&lt; d &lt;&lt; \" Illegal\" &lt;&lt; std::endl;\n return 1;\n }\n\n std::copy(valid.begin(), valid.end(),\n std::ostream_iterator&lt;date&gt;(std::cout, \"\\n\"));\n return 0;\n}\n</code></pre>\n\n<p>I belive my version to be better than your because it heavily relises on the standard library to do the heavy lifting, the std lib is a lot better tested than my code so is a lot less likely to fail as well as being well documented.</p>\n\n<p>Further more my code has better data encapsulation, the data elements are encapsulated in a struct and the instances are own by the stack rather than being global data.</p>\n\n<p>EDIT: added sort before perm</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-03-10T17:25:18.450", "Id": "15724", "Score": "2", "body": "The point of this forum is to provide feedback on the code provided." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-03-10T17:28:10.853", "Id": "15726", "Score": "0", "body": "@LokiAstari and? there was a lot wrong with it, my solution shows another way of solving the problem: I genuinely believe the best way to learn is to see it done differently." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-03-10T18:19:37.183", "Id": "15729", "Score": "0", "body": "@LokiAstari I said it was incomplete, any way I fixed it now." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-03-10T18:25:57.890", "Id": "15730", "Score": "1", "body": "Yes I believe your solution is better. But code review is not about providing a better solution (that does not help people see their mistakes). You need to point out the weaknesses in their design and then from their give alternative approaches were possible. PS. Need work on your leap year calculation." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-03-10T18:32:18.823", "Id": "15731", "Score": "0", "body": "@LokiAstari I understand that, I personally I learn by seeing how it can be done in a different way and if further questions rises they can be asked. Some people learn differently. Perhaps I'll do it differently next time however for now the OP can choose to ignore my answer however I think it might be of use." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-03-10T23:59:06.117", "Id": "15744", "Score": "2", "body": "Showing how it can be done better is good. I do it in most of my answers. But you should also really include comments pointing out the flaws in the original approach as well." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-03-11T13:00:18.577", "Id": "15748", "Score": "0", "body": "Yes thank you for the help, I belive seeing it done better can help as long as I can understand why it is better." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-03-11T13:02:50.383", "Id": "15749", "Score": "0", "body": "@Scott and can you? if not feel free to ask question about it, that is personally how I learn the most efficently." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-03-11T13:18:51.417", "Id": "15751", "Score": "0", "body": "thank you for the help, I belive seeing it done better or different does help, It also helps me identify what actually makes a piece of code good or bad.\n@LokiAstari Did you mean my leap year caculation needs work?" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-03-11T13:30:12.250", "Id": "15752", "Score": "0", "body": "yes I can see a few things, I can defo learn alot from the way the both codes are formatted :) I don't get why using std:: is better than just using using namespace std; ?" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-03-11T13:37:16.347", "Id": "15753", "Score": "0", "body": "ah wait someone above has allready explained that" } ], "meta_data": { "CommentCount": "11", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-03-10T16:56:59.877", "Id": "9884", "ParentId": "9883", "Score": "0" } }, { "body": "<h3>Initial comments on just reading:</h3>\n\n<p>Don't do this</p>\n\n<pre><code>using namespace std;\n</code></pre>\n\n<p>Yes every crappy book on C++ has this line.<br>\nOnce you get past 5 lines programs it becomes a nuisance (technical term <code>polluting the global namespace</code>). So get in to the habbit of not using it. There are a couple alternatives (read other C++ posts on this forum) personally I prefix anything in standard with std:: (i.e. std::cout)</p>\n\n<p>Global Variables are not a good idea.</p>\n\n<pre><code>int Year;\nint Month;\nint Day;\n\nbool loop=true;\nint date[4];\nbool DateFound=false;\nstringstream ss;\nstring input;\nstring in;\n</code></pre>\n\n<p>They bind your code to global state which makes modify your code relly hard and writting unit tests and validation code next to imposable. The best practice is a function/methods should not use any external objects. It either is in the scope of the function/method or is passed as a parameter.</p>\n\n<p>Get into the habit of breaking really long lines into small chunks to make it more readable. Also you nested if and its sub-statement all on the same line are a real no-no. It is very hard to read.</p>\n\n<pre><code> if(date[2]==1 || date[2]==3 || date[2]==5 || date[2]==7 || date[2]==8 || date[2]==10 || date[2]==12){if(date[3]&lt;=31){DateFound=true;}}\n /// --&gt; comment this way ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^\n</code></pre>\n\n<p>Better would have been:</p>\n\n<pre><code> if(date[2]==1 || date[2]==3 || date[2]==5 || date[2]==7 || date[2]==8 || date[2]==10 || date[2]==12)\n {\n if(date[3]&lt;=31)\n { DateFound=true;\n }\n }\n</code></pre>\n\n<p>Even better would have been:</p>\n\n<pre><code> if(date[2]==1 || date[2]==3 || date[2]==5 || date[2]==7 ||\n date[2]==8 || date[2]==10 || date[2]==12)\n {\n if(date[3]&lt;=31)\n { DateFound=true;\n }\n }\n</code></pre>\n\n<p>Also notice:</p>\n\n<pre><code> if(date[3]&lt;=31)\n { DateFound=true;\n }\n</code></pre>\n\n<p>Can be written as:</p>\n\n<pre><code> DateFound = date[3]&lt;=31;\n</code></pre>\n\n<p>There are lots of standard function that can make life easier:</p>\n\n<p>Examples:<br>\nHere you are doing a swap</p>\n\n<pre><code>void SwitchDate(){int temp; temp=date[2]; date[2]=date[3]; date[3]=temp; Check_date();};\n</code></pre>\n\n<p>Try:</p>\n\n<pre><code> void SwitchDate(){std::swap(date[2],date[3]); Check_date();};\n</code></pre>\n\n<p>Next you are implementing a simple bubble sort:</p>\n\n<pre><code> //order small medium large\n for (int x=3, temp; x!=0; x--)\n {\n if (date[x] &lt; date[x-1])\n { temp=date[x-1];\n date[x-1]=date[x];\n date[x]=temp;\n }\n if (x==1 &amp;&amp; (date[2] &gt; date[3] ))\n {\n temp=date[3];\n date[3]=date[2];\n date[2]=temp;\n }\n }\n</code></pre>\n\n<p>Try:</p>\n\n<pre><code>std::sort(&amp;date[0], &amp;data[3]);\n</code></pre>\n\n<p>Next you are implementing a sort of rotation threw the different combinations (using switchDate() and ShiftDate()). This functionality can be achieved using <code>std::next_permutation</code>.</p>\n\n<p>Look here for a list of standard functions:</p>\n\n<ul>\n<li><a href=\"http://www.sgi.com/tech/stl/stl_index.html\">index</a></li>\n<li><a href=\"http://www.sgi.com/tech/stl/table_of_contents.html\">table of content</a></li>\n<li><a href=\"http://www.sgi.com/tech/stl/swap.html\">std::swap</a></li>\n<li><a href=\"http://www.sgi.com/tech/stl/sort.html\">std::sort</a></li>\n<li><a href=\"http://www.sgi.com/tech/stl/next_permutation.html\">std::next_permutation</a></li>\n</ul>\n\n<p>With boolean expressions there is no point in testing a boolean against true/false. The point in making the variable boolean is so that it can be used directly and it should be named appropriately so that it's meaning is clear.</p>\n\n<p>This is fine:</p>\n\n<pre><code>if(DateFound==false)\n</code></pre>\n\n<p>But a lot of people find the more succinct style more readable:</p>\n\n<pre><code>if(!DateFound)\n</code></pre>\n\n<p>As with the if statement above:</p>\n\n<pre><code>while(loop==true)\n</code></pre>\n\n<p>More concisely written as:</p>\n\n<pre><code>while(loop)\n</code></pre>\n\n<p>Not sure why you are writing the endl after reading the input.</p>\n\n<pre><code> cout &lt;&lt;\"Please Enter a date \\n\";\n cin&gt;&gt;input;\n cout&lt;&lt;endl; \n</code></pre>\n\n<p>All it does is flush the output buffer. Which has already been flushed (because cin/cout are tied by magic that makes sure the user can read the question before answering).</p>\n\n<p>You want to read three numbers divided by a slash?</p>\n\n<pre><code> for (int x=0, y=1; y&lt;=3; y++, x++)\n { \n while (input[x] !='/' &amp;&amp; x !=input.length()) ss&lt;&lt;input[x++];\n ss&gt;&gt; date[y];\n ss.clear();\n } \n</code></pre>\n\n<p>The stream operators can do much of the work for you. Basically it looks like this:</p>\n\n<pre><code>std::cin &gt;&gt; date[0] &gt;&gt; std::noskipws &gt;&gt; sep[0] &gt;&gt; date[1] &gt;&gt; sep[1] &gt;&gt; date[2];\n</code></pre>\n\n<p>Notice that your inner while loop has been replaced by a single read:</p>\n\n<pre><code>while (input[x] !='/' &amp;&amp; x !=input.length()) ss&lt;&lt;input[x++];\n\n// can be written as:\n\nstd::cin &gt;&gt; number;\n</code></pre>\n\n<p>But to take into account error detection and correction a bit of extra work is needed. So this is how I would do it. (Note its the comments that make it so big).</p>\n\n<pre><code> // Read one line of user input\n // I always read a line of user input into a string then parse the string\n // This makes error detection and recovery easier as the input stream is never\n // in a bad state or needs to be reset. Also it swallows the new line character\n // that can cause problems if you are not being careful.\n std::string line;\n std::getline(std::cin, line);\n\n // Now that I have a lone of input I want parse it.\n std::stringstream linestream(line);\n int date[3]; // I want three numbers\n char sep[2]; // Seporated by '/'\n\n // Try and read the values you want.\n linestream &gt;&gt; date[0] &gt;&gt; std::noskipws &gt;&gt; sep[0] &gt;&gt; date[1] &gt;&gt; sep[1] &gt;&gt; date[2];\n if (!linestream || sep[0] != '/' || sep[1] != '/')\n {\n // linestream will be bad if reading any of the numbers failed.\n // When linsestream is bad !linestream will return true.\n //\n // So this block is entered if reading the number failed or either of the\n // separators is not a '/' character.\n // Failed.\n throw int(1); // Or whatever is appropriate\n }\n</code></pre>\n\n<h3>Comments on algorithm</h3>\n\n<p>You testing for a valid day in a month is very hard to read:</p>\n\n<pre><code> if(date[2]==1 || date[2]==3 || date[2]==5 || date[2]==7 || date[2]==8 || date[2]==10 || date[2]==12){if(date[3]&lt;=31){DateFound=true;}}\n if(date[2]==4 || date[2]==6 || date[2]==9 || date[2]==11){if(date[3]&lt;=30){DateFound=true;}}\n //Check For Leap Year\n if (date[2]==2){\n if(date[3]&lt;28)DateFound=true;\n if(date[1]%4==0 &amp;&amp; date[3]&lt;=29)DateFound=true;\n if(date[1]%100==0 &amp;&amp; date[1]%400!=0 &amp;&amp; date[3]&gt;28)DateFound=false;\n }\n</code></pre>\n\n<p>A typical solution is to use an array of values and then look up the correct size:</p>\n\n<pre><code>int daysInMonth[2][] = { {31,28,31,30,31,30,31,31,30,31,30,31},\n {31,29,31,30,31,30,31,31,30,31,30,31} };\n\nbool isLeapYear = date[1]%400==0 || (date[1]%4==0 &amp;&amp; date[1]%100!=0);\nbool dateFound = date[3] &lt;= daysInMonth[isLeapYear][date[2]];\n</code></pre>\n\n<h3>Comments on encapsulation</h3>\n\n<p>You wrote your program very serially. Basically what you wrote was C code (you just happen to use some basic C++ constructs, this does not make the code C++ (C++ has a style that is distinct from C)).</p>\n\n<p>What you should have done is encapsulate the date in a class of its own.<br>\nThen you can write an input method that read data from a stream so that the object initializes itself and can also print itself.</p>\n\n<p>The main should have looked like this:</p>\n\n<pre><code>int main()\n{\n bool finished = false;\n do\n {\n doTest();\n cout &lt;&lt;\"Again? 'Y' or 'N' \\n\";\n // Need a loop to test for valid value.\n // Declare variables as close to the point of use as possible.\n // No point in declaring them before you need them.\n std::string line;\n do\n {\n std::getline(cin, line);\n }\n while(line != \"y\" &amp;&amp; line != \"Y\" &amp;&amp; line != \"N\" &amp;&amp; line != \"n\");\n\n finished = (line==\"N\" || line==\"n\");\n }\n while(!finished);\n}\n</code></pre>\n\n<p>Then we can write a nice test function that does the work.</p>\n\n<pre><code>void doTest()\n{\n std::cout &lt;&lt;\"Please Enter a date \\n\";\n\n try\n {\n MyDateObject date;\n\n std::cin &gt;&gt; date; // Date knows how to read itself from input\n std::cout &lt;&lt; date; // Date knows how to serialize itself to output.\n }\n catch(...)\n {\n std::cout &lt;&lt; \"Invalid Date\\n\";\n }\n}\n</code></pre>\n\n<p>Now all you need to do is encapsulate the date functionality into a class call MyDateObject.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-03-10T18:08:56.680", "Id": "9887", "ParentId": "9883", "Score": "18" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "2", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-03-10T15:55:56.863", "Id": "9883", "Score": "10", "Tags": [ "c++" ], "Title": "Best Before puzzle" }
9883
<p>I have the following jQuery plugin that binds touch events and moves an element.</p> <p>In the functions <code>moveMe</code> and <code>snap</code>, there is duplicate code doing the same thing because I couldn't figure out how to refactor the scope of the functions to only do this once.</p> <pre><code>$.fn.draggable = function(limit) { var offset = null; var start = function(e) { var orig = e.originalEvent; var pos = $(this).position(); offset = { x: orig.changedTouches[0].pageX - pos.left, //y: orig.changedTouches[0].pageX - pos.top }; $(this).stop(true,false); }; var moveMe = function(e) { e.preventDefault(); $('body').css('overflow-x','hidden'); var orig = e.originalEvent; var touchX = orig.changedTouches[0].pageX; var difference = touchX - offset.x; var move; if (difference &gt;= limit) { move = limit; } else if (difference &lt;= 0) { move = 0; } else { move = difference; } $(this).css({ left: move, //left: orig.changedTouches[0].pageX - offset.x }); }; var snap = function(e) { var orig = e.originalEvent; var touchX = orig.changedTouches[0].pageX; var difference = touchX - offset.x; var threshold = limit*0.75; if (difference &gt;= limit) { move = limit; } else if (difference &lt;= 0) { move = 0; } else { move = difference; } if (threshold &gt; (limit-move)) { $(this).animate({ left : limit }); } else { $(this).animate({ left : 0 }); } }; this.bind("touchstart", start); this.bind("touchmove", moveMe); this.bind("touchend", snap); }; $("#container").draggable(200); </code></pre>
[]
[ { "body": "<p>Could you write something like this?</p>\n\n<pre><code>var limited = function( value, limit ){\n if (value &gt;= limit) { \n return limit; \n } else if (value &lt;= 0) { \n return 0; \n } else { \n return value; \n } \n}\n</code></pre>\n\n<p>then, when you need to work out <code>move</code>, just write <code>move = limited( difference, limit );</code></p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-03-11T06:16:11.717", "Id": "9897", "ParentId": "9885", "Score": "2" } } ]
{ "AcceptedAnswerId": "9897", "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-03-10T17:18:29.507", "Id": "9885", "Score": "0", "Tags": [ "javascript", "jquery", "plugin" ], "Title": "Binding touch events and moving an element" }
9885
<p>Can anyone help me improve my <code>instr()</code> function?</p> <pre><code>int myInstr(wchar_t *str, wchar_t c, int start, int dir){ int pos = 0, result = 0, len; wchar_t *p1; //Left if(dir == 0) { p1 = str; len = lstrlen(str); while(pos &lt; len) { if(*p1 == c) { result = pos; return result; } p1++; pos++; } } else { //Right pos = len = lstrlen(str); p1 = str; p1 += len; while(pos &gt;= 0) { if(*p1 == c) { result = pos; return result; } p1--; pos--; } } return 0; } </code></pre>
[ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-03-10T20:39:14.580", "Id": "15739", "Score": "1", "body": "What is start for?" } ]
[ { "body": "<pre><code>int myInstr(wchar_t *str, wchar_t c, int start, int dir){\nint pos = 0, result = 0, len;\nwchar_t *p1;\n</code></pre>\n\n<p>Names like p1 are best avoided. Its hard to guess what p1 might be for.</p>\n\n<pre><code>//Left\nif(dir == 0)\n{\n p1 = str;\n len = lstrlen(str);\n while(pos &lt; len)\n</code></pre>\n\n<p>There is not a whole lot of point in storing the length in a variable only to use it once</p>\n\n<pre><code> { \n if(*p1 == c) \n {\n result = pos;\n return result;\n</code></pre>\n\n<p>Just <code>return pos</code></p>\n\n<pre><code> }\n p1++;\n pos++;\n</code></pre>\n\n<p>You are keeping track of the same information twice. If you can just keep track of it once.</p>\n\n<pre><code> }\n}\nelse\n{\n //Right\n pos = len = lstrlen(str);\n p1 = str;\n p1 += len;\n while(pos &gt;= 0)\n {\n if(*p1 == c) \n {\n result = pos;\n return result;\n }\n p1--;\n pos--;\n }\n</code></pre>\n\n<p>This is very similiar to the other cases. See if you can't combine the cases.</p>\n\n<pre><code>}\nreturn 0;\n</code></pre>\n\n<p>This seems a poor choice to indicate failure to find. What if it was found at position 0?</p>\n\n<p>Here is my untested version of your code:</p>\n\n<pre><code>int myInstr(wchar_t *str, wchar_t c, int start, int dir){\n int step;\n wchar_t * position;\n wchar_t * end;\n\n if(dir == 0)\n {\n position = str;\n end = str + lstrlen(str);\n step = 1;\n }\n else\n {\n position = str + lstrlen(str) - 1;\n end = str;\n step = -1;\n }\n\n while(position != end)\n {\n if(*position == c)\n {\n return position - str;\n }\n position += step;\n }\n\n return -1;\n}\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-03-11T03:04:50.177", "Id": "15745", "Score": "0", "body": "Reverse direction may need a tweek. 1) position/end identical 2) reading one past the end (on first element)." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-03-11T14:14:37.890", "Id": "15754", "Score": "0", "body": "@LokiAstari, corrected. But of course anybody who pulls my untested code deserves what they get." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-03-20T15:54:03.020", "Id": "16194", "Score": "0", "body": "\"`There is not a whole lot of point in storing the length in a variable only to use it once`\" Yes there is, readability. The result of strlen() will have to be stored _somewhere_, either in your explicitly declared variable or in an invisible temporary one sneaked into the machine code by the compiler. The machine code will be the same in both cases, so by omitting the variable you haven't optimized a thing. Actually, I bet you only make things worse by calling the function inside both if and else, depending on how CPU branch prediction works." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-03-20T16:03:14.113", "Id": "16195", "Score": "0", "body": "@Lundin, I don't think you gain you readability by doing that. In my view local variables improve readability in three ways: Firstly, by providing an informative name for a value. Secondly, by splitting complex expressions up into multiple pieces. Thirdly, by replacing a non-trivial expression used multiple times." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-03-20T16:08:24.310", "Id": "16196", "Score": "0", "body": "To my mind, the first doesn't apply because the name doesn't tell me anything `strlen` doesn't. The second doesn't apply because the expression is still pretty simple. The third doesn't apply because the expression being replaced is non-trivial. The code would not be any shorter using a shared variable." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-03-20T16:11:56.707", "Id": "16197", "Score": "0", "body": "I'm certainly not attempting to optimize anything by avoiding local variables. I just don't think it helps readability. As for the performance, I wouldn't be surprised if compilers manage to hoist the strlen out the if blocks. The optimizations compilers manage are very impressive. I'm not sure how branch prediction comes into this. But certainly there could be a speed penalty for doing it in both branches." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-03-20T16:40:25.440", "Id": "16198", "Score": "0", "body": "Alright... anyway, it not only helps branch prediction if the function is only called once, but it also helps readability. Since strlen must be called every time no matter if/else, it should be outside the if statement regardless of optimization issues. See my own answer for a suggestion how to do it differently." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-03-20T16:53:52.880", "Id": "16199", "Score": "0", "body": "@Lundin, rather then just restating that it helps readability, could you explain where you disagree with my analysis of the issue? Quote frankly, I find the version you posted much less readable then mine." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-03-20T22:13:21.667", "Id": "16218", "Score": "0", "body": "@WinstonEwert I suspect that my code will be more efficient, but that does of course depend a lot on the target architecture. As for readability, for loops are generally regarded as easier to read than while ones (and may be easier for the compiler to optimize). Multiple return statements are generally regarded as bad practice (although I don't always agree there). Those opinions aren't just mine, you can read them in coding standards such as MISRA." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-03-20T23:28:12.733", "Id": "16221", "Score": "0", "body": "@Lundin, I'll agree that a for loop would have been a better choice here. Because the initialization step was separate from the loop I didn't think to use it. While many standards disapprove of multiple returns I don't find their reasons convincing. There are cases where that's a good idea but I don't think this one of them. As for performance, benchmarks or there is no difference. ;)" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-03-21T08:52:27.527", "Id": "16231", "Score": "0", "body": "@WinstonEwert Ok so now I did a rough benchmark on both our codes and their execution times were pretty much identical (GCC/Mingw, Windows XP, 10 million function calls measured with QueryPerformanceCounter). I did however manage to speed up both versions significantly by getting rid of the dir variable, which I suppose shouldn't come as much of a surprise." } ], "meta_data": { "CommentCount": "11", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-03-10T19:29:54.397", "Id": "9892", "ParentId": "9888", "Score": "2" } }, { "body": "<p>Here are my comments:</p>\n\n<p>Functionality:</p>\n\n<ul>\n<li>Remove the superfluous start parameter.</li>\n<li>Remove all needlessly complex (and slow) pointer arithmetic.</li>\n<li>Use the standard wcslen() function from wchar.h</li>\n<li>Position 0 is a valid array index, replace it with an invalid one if value not found.</li>\n</ul>\n\n<p>Performance:</p>\n\n<ul>\n<li>Only call the strlen function once.</li>\n<li>Minimize the code inside the if/else statement.</li>\n</ul>\n\n<p>Readability and style:</p>\n\n<ul>\n<li>str isn't modified by the function, so make it const (const correctness).</li>\n<li>Rewrite the loop to a conventional one.</li>\n<li>Only return once from a function.</li>\n<li>Replace all \"magic numbers\" with constants or enums.</li>\n</ul>\n\n<p>-</p>\n\n<pre><code>#include &lt;stddef.h&gt;\n#include &lt;wchar.h&gt;\n#include &lt;stdio.h&gt;\n\ntypedef enum\n{\n DIR_POS,\n DIR_NEG \n} dir_t;\n\n\n#define NOT_FOUND -1\n\n\nint myInstr (const wchar_t* str,\n wchar_t c,\n dir_t dir)\n{\n int start;\n int end;\n int step;\n int length;\n int i;\n int result = NOT_FOUND;\n\n length = wcslen(str);\n\n if(dir == DIR_POS)\n {\n start = 0;\n end = length;\n step = 1;\n }\n else /* if (dir == DIR_NEG) */\n {\n start = length - 1;\n end = -1;\n step = -1;\n }\n\n for(i=start; i!=end; i+=step)\n {\n if(str[i] == c)\n {\n result = i;\n break;\n }\n }\n\n return result;\n}\n\n\nint main()\n{\n wchar_t str [] = L\"1234567890\";\n\n printf(\"%d\\n\", myInstr(str, '3', DIR_POS)); // prints 2\n printf(\"%d\\n\", myInstr(str, '6', DIR_NEG)); // prints 5\n printf(\"%d\\n\", myInstr(str, 'X', DIR_POS)); // prints -1\n}\n</code></pre>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-03-20T16:37:30.590", "Id": "10188", "ParentId": "9888", "Score": "4" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "1", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-03-10T19:00:25.717", "Id": "9888", "Score": "1", "Tags": [ "c", "strings" ], "Title": "Finding one string located in another" }
9888
<p>I have been learning PHP and wanted to see if I could make a very simple slot machine game. Everything works, but I'm sure this is not the best way to do this. Please let me know how you would do this and what I can do to improve.</p> <pre><code>&lt;?php $num1 = rand(1, 5); $num2 = rand(1, 5); $num3 = rand(1, 5); $result = $num1.' | '.$num2.' | '.$num3; // Read points from file $filename = 'points.txt'; $handle = fopen($filename, 'r'); $current = fread($handle, filesize($filename)); fclose($handle); if ($num1 == $num2 &amp;&amp; $num2 == $num3) { $status = '&lt;big&gt;You are a winner!&lt;/big&gt;'; $add_points = $current + 10; // Add points to file $handle = fopen($filename, 'w'); $current_points = fwrite($handle, $add_points); fclose($handle); } else { $status = 'please try again!'; } ?&gt; &lt;html&gt; &lt;head&gt; &lt;title&gt;Slot Machine Game!&lt;/title&gt; &lt;/head&gt; &lt;body&gt; &lt;center&gt;&lt;big&gt;&lt;?php echo $result; ?&gt;&lt;/big&gt;&lt;/center&gt; &lt;br /&gt; &lt;br /&gt; &lt;center&gt;&lt;big&gt;&lt;?php echo $status; ?&gt;&lt;/big&gt;&lt;/center&gt; &lt;br /&gt; &lt;br /&gt; &lt;center&gt;&lt;big&gt;&lt;?php echo 'You have &lt;strong&gt;'.$current.'&lt;/strong&gt; points!'; ?&gt;&lt;/big&gt;&lt;/center&gt; &lt;/body&gt; &lt;/html&gt; </code></pre>
[ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-03-10T19:13:37.107", "Id": "15732", "Score": "0", "body": "Bah: you deleted your question on Stack Overflow whilst I was writing out my answer, so I had to create an account here so as not to waste it! Once a question is asked, it is good practice not to delete it yourself - let a mod migrate it if necessary." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-03-10T19:18:25.940", "Id": "15734", "Score": "0", "body": "To add to what halfer said, if you put your question on the wrong site, please wait for it to be migrated or closed by the moderator. They can usually transfer the question to the correct site for you saving everybody effort." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-03-10T20:19:45.420", "Id": "15736", "Score": "0", "body": "Oh okay, sorry about that." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-03-22T10:48:08.130", "Id": "16304", "Score": "0", "body": "Wouldn't hurt to put an `srand()` in before you start using `rand()`" } ]
[ { "body": "<p>Looks good. Few initial things:</p>\n\n<ul>\n<li>Indent inside control structures, so everything inside your <code>if()</code> statement would be prefixed by one tab. (You can use a fixed number of spaces, but that can cause problems if you share your code with people who use a different tab-spacing system).</li>\n<li>It is a really good idea to split out your code into logic (or \"controller\") and template (or \"view\"). Your html would then go in a different file and be loaded by your PHP file - a good first step with this sort of thing is Smarty. From there you can progress to a proper PHP framework such as Symfony or Zend (but be aware the learning curve is steep).</li>\n<li>Tags such as <code>&lt;center&gt;</code> and <code>&lt;big&gt;</code> tend to be discouraged - use CSS instead.</li>\n<li>Keep your PHP statements in your view as small as possible. For example I'd rewrite your score thus:</li>\n</ul>\n\n<blockquote>\n<pre><code>&lt;div class=\"points\"&gt;\n You have &lt;strong&gt;&lt;?php echo $current ?&gt;&lt;/strong&gt; points!\n&lt;/center&gt;\n</code></pre>\n</blockquote>\n\n<p>You'll need to define a CSS class called 'points', of course.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-03-10T20:23:33.263", "Id": "15738", "Score": "0", "body": "Yeah, if I was writing this seriously I would have taken all those steps but I just threw it together for the sake of example so it was easier to understand on your guys end, but thanks for all the feedback!" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-03-10T20:44:27.227", "Id": "15740", "Score": "2", "body": "Oh dear - after all my effort, and you didn't really need the feedback? </depressed>" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-03-10T20:52:39.123", "Id": "15741", "Score": "0", "body": "Well im new to PHP but I have been doing HTML and CSS for a couple years now so I knew some of that stuff but I was just trying to confirm that this was written okay or if there was another way I could do it like save it in a cookie instead of a flat file, this is the only way i know. I have looked at MVC frameworks but don't completely understand them yet, the only things I have used are Wordpress and Drupal" } ], "meta_data": { "CommentCount": "3", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-03-10T19:16:07.603", "Id": "9890", "ParentId": "9889", "Score": "3" } }, { "body": "<pre><code>&lt;?php\n\n$num1 = rand(1, 5);\n$num2 = rand(1, 5);\n$num3 = rand(1, 5);\n\n$result = $num1.' | '.$num2.' | '.$num3;\n\n// Read points from file\n$filename = 'points.txt';\n$handle = fopen($filename, 'r');\n$current = fread($handle, filesize($filename));\n</code></pre>\n\n<p>current is kinda vauge as a name. Is there something better you can call it.</p>\n\n<pre><code>fclose($handle);\n</code></pre>\n\n<p>Php has a function <code>file_get_contents</code> which will do those last four lines for you.</p>\n\n<pre><code>if ($num1 == $num2 &amp;&amp; $num2 == $num3) {\n$status = '&lt;big&gt;You are a winner!&lt;/big&gt;';\n</code></pre>\n\n<p>Please indent inside of braces. It makes code way easier to read!</p>\n\n<pre><code>$add_points = $current + 10;\n</code></pre>\n\n<p>Why not simple add to <code>$current</code>?</p>\n\n<pre><code>// Add points to file\n$handle = fopen($filename, 'w');\n$current_points = fwrite($handle, $add_points);\nfclose($handle);\n</code></pre>\n\n<p>use <code>file_put_contents</code></p>\n\n<pre><code>} else {\n$status = 'please try again!';\n}\n\n?&gt;\n&lt;html&gt;\n&lt;head&gt;\n&lt;title&gt;Slot Machine Game!&lt;/title&gt;\n&lt;/head&gt;\n&lt;body&gt;\n\n&lt;center&gt;&lt;big&gt;&lt;?php echo $result; ?&gt;&lt;/big&gt;&lt;/center&gt;\n&lt;br /&gt;\n&lt;br /&gt;\n&lt;center&gt;&lt;big&gt;&lt;?php echo $status; ?&gt;&lt;/big&gt;&lt;/center&gt;\n&lt;br /&gt;\n&lt;br /&gt;\n&lt;center&gt;&lt;big&gt;&lt;?php echo 'You have &lt;strong&gt;'.$current.'&lt;/strong&gt; points!'; ?&gt;&lt;/big&gt;&lt;/center&gt;\n</code></pre>\n\n<p>Why not:</p>\n\n<pre><code>&lt;center&gt;&lt;big&gt;You have &lt;strong&gt;&lt;?php echo $current; ?&gt;&lt;/strong&gt; points!&lt;/big&gt;&lt;/center?\n</code></pre>\n\n<p>It seems easier to follow.</p>\n\n<pre><code>&lt;/body&gt;\n&lt;/html&gt;\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-03-10T20:22:31.907", "Id": "15737", "Score": "0", "body": "Yeah my indenting is totally wrong on here because I was a little confused about how to insert the code on here, it looks better in my code editor. Yeah I went back and looked for what I could do better and I made the those changes, I had no idea what file_get_contents did but now I do, thanks!" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-03-10T23:32:45.620", "Id": "15742", "Score": "0", "body": "@NickMeagher, the indenting issue was because you used tab characters. Your editor should have an option to use spaces which will make copy/pasting into places like this easier." } ], "meta_data": { "CommentCount": "2", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-03-10T19:17:00.980", "Id": "9891", "ParentId": "9889", "Score": "3" } }, { "body": "<p>Maybe you know but this game can only be played by one player at a time. Also there is no way for that player to restart there game.</p>\n\n<p>As you are using this to learn exercise I would suggest your next step would be to use <a href=\"http://www.php.net/manual/en/book.session.php\" rel=\"nofollow\">PHP sessions</a> to store the players score. Then give the user the ability to start a new game. </p>\n\n<p>It would also be nice to add a \"Play Again\" button and play again only if that button was click. If the user just refreshed try to have it not play again.</p>\n\n<p>If you decide to go that way then you could have a new player welcome message for users who have not started to play yet.</p>\n\n<p>Good luck.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-03-23T14:56:05.147", "Id": "10281", "ParentId": "9889", "Score": "-1" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "4", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-03-10T19:02:57.537", "Id": "9889", "Score": "2", "Tags": [ "php", "beginner", "game" ], "Title": "Basic slot machine game" }
9889
<p>I use DMD 1.056 with Tango 0.99.9 to build a GPX document using API. I am a beginner in D language.</p> <hr> <p>Usage DMD 1.056 with Tango 0.99.9 is compulsory as a requirement</p> <p>The GPX data are here hardcoded but my intent is to write a more high level GPX builder code using appropriate API.</p> <hr> <p><strong>The piece of code to refactor:</strong></p> <pre><code>module SwathGen; import tango.io.Stdout, tango.text.xml.Document, tango.text.xml.DocPrinter; void main(char[][] args) { auto gpxdoc = new Document!(char); gpxdoc.header; gpxdoc.tree .element(null,"gpx") .attribute (null,"xmlns","http://www.topografix.com/GPX/1/1") .attribute (null,"version","1.1") .attribute (null,"creator","SwathGen") .attribute (null,"xmlns:xsi","http://www.w3.org/2001/XMLSchema-instance") .attribute (null,"xsi:schemaLocation","http://www.topografix.com/GPX/1/1 http://www.topografix.com/GPX/1/1/gpx.xsd http://www.topografix.com/GPX/gpx_style/0/2 http://www.topografix.com/GPX/gpx_style/0/2/gpx_style.xsd http://www.topografix.com/GPX/gpx_overlay/0/3 http://www.topografix.com/GPX/gpx_overlay/0/3/gpx_overlay.xsd") ; gpxdoc.elements .element (null,"metadata") .element(null,"name","JobDef.gpx") .parent .element(null,"desc","Spray Job") .parent .element(null,"author") .element (null,"name","izylay") .parent .element (null,"email") .attribute (null,"id","izylay") .attribute (null,"domain","ary.com") .parent .parent .element(null,"copyright") .attribute (null,"author","izylay") .element (null,"year","2011") .parent .parent .element(null,"time","2011-10-10T08:19:50Z") .parent .element(null,"keywords","ULM, J300, Aerial Spraying, Locust") .parent .element (null,"bounds") .attribute (null,"minlat","-18.85522622") .attribute (null,"minlon","47.37275913") .attribute (null,"maxlat","-18.82044444") .attribute (null,"maxlon","47.39838002") ; gpxdoc.elements .element(null,"wpt") .attribute (null,"lat","-18.85522622") .attribute (null,"lon","47.39173757") .element (null,"name","A000") .parent .element (null,"sym","Waypoint") ; gpxdoc.elements .element(null,"rte") .element (null,"name","Spray Job") // .parent .element(null,"rtept") .attribute (null,"lat","-18.85522610") .attribute (null,"lon","47.39838002") .element (null,"name","Entry point") .parent .element (null,"sym","Dot") .parent .parent .element(null,"rtept") .attribute (null,"lat","-18.85522525") .attribute (null,"lon","47.37275913") .element (null,"name","B000") .parent .element (null,"sym","Dot") .parent .parent .element(null,"rtept") .attribute (null,"lat","-18.85387012") .attribute (null,"lon","47.37275913") .element (null,"name","B001") .parent .element (null,"sym","Dot") .parent .parent .element(null,"rtept") .attribute (null,"lat","-18.85387109") .attribute (null,"lon","47.39173757") .element (null,"name","A001") .parent .element (null,"sym","Dot") .parent .parent .element(null,"rtept") .attribute (null,"lat","-18.85251596") .attribute (null,"lon","47.39173757") .element (null,"name","A002") .parent .element (null,"sym","Dot") .parent .parent .element(null,"rtept") .attribute (null,"lat","-18.85251499") .attribute (null,"lon","47.37275913") .element (null,"name","B002") .parent .element (null,"sym","Dot") .parent .parent .element(null,"rtept") .attribute (null,"lat","-18.85115986") .attribute (null,"lon","47.37275913") .element (null,"name","B003") .parent .element (null,"sym","Dot") .parent .parent .element(null,"rtept") .attribute (null,"lat","-18.85116082") .attribute (null,"lon","47.39173757") .element (null,"name","A003") .parent .element (null,"sym","Dot") .parent .parent .element(null,"rtept") .attribute (null,"lat","-18.84980569") .attribute (null,"lon","47.39173757") .element (null,"name","A004") .parent .element (null,"sym","Dot") .parent .parent .element(null,"rtept") .attribute (null,"lat","-18.84980472") .attribute (null,"lon","47.37275913") .element (null,"name","B004") .parent .element (null,"sym","Dot") .parent .parent .element(null,"rtept") .attribute (null,"lat","-18.84844959") .attribute (null,"lon","47.37275913") .element (null,"name","B005") .parent .element (null,"sym","Dot") .parent .parent .element(null,"rtept") .attribute (null,"lat","-18.84845056") .attribute (null,"lon","47.39173757") .element (null,"name","A005") .parent .element (null,"sym","Dot") .parent .parent .element(null,"rtept") .attribute (null,"lat","-18.84709543") .attribute (null,"lon","47.39173757") .element (null,"name","A006") .parent .element (null,"sym","Dot") .parent .parent .element(null,"rtept") .attribute (null,"lat","-18.84709446") .attribute (null,"lon","47.37275913") .element (null,"name","B006") .parent .element (null,"sym","Dot") .parent .parent .element(null,"rtept") .attribute (null,"lat","-18.84573933") .attribute (null,"lon","47.37275913") .element (null,"name","B007") .parent .element (null,"sym","Dot") .parent .parent .element(null,"rtept") .attribute (null,"lat","-18.84574029") .attribute (null,"lon","47.39173757") .element (null,"name","A007") .parent .element (null,"sym","Dot") .parent .parent .element(null,"rtept") .attribute (null,"lat","-18.84438516") .attribute (null,"lon","47.39173757") .element (null,"name","A008") .parent .element (null,"sym","Dot") .parent .parent .element(null,"rtept") .attribute (null,"lat","-18.84438419") .attribute (null,"lon","47.37275913") .element (null,"name","B008") .parent .element (null,"sym","Dot") .parent .parent .element(null,"rtept") .attribute (null,"lat","-18.84302906") .attribute (null,"lon","47.37275913") .element (null,"name","B009") .parent .element (null,"sym","Dot") .parent .parent .element(null,"rtept") .attribute (null,"lat","-18.84303003") .attribute (null,"lon","47.39173757") .element (null,"name","A009") .parent .element (null,"sym","Dot") .parent .parent .element(null,"rtept") .attribute (null,"lat","-18.84167489") .attribute (null,"lon","47.39173757") .element (null,"name","A010") .parent .element (null,"sym","Dot") .parent .parent .element(null,"rtept") .attribute (null,"lat","-18.84167393") .attribute (null,"lon","47.37275913") .element (null,"name","B010") .parent .element (null,"sym","Dot") .parent .parent .element(null,"rtept") .attribute (null,"lat","-18.84031879") .attribute (null,"lon","47.37275913") .element (null,"name","B011") .parent .element (null,"sym","Dot") .parent .parent .element(null,"rtept") .attribute (null,"lat","-18.84031976") .attribute (null,"lon","47.39173757") .element (null,"name","A011") .parent .element (null,"sym","Dot") .parent .parent .element(null,"rtept") .attribute (null,"lat","-18.83896463") .attribute (null,"lon","47.39173757") .element (null,"name","A012") .parent .element (null,"sym","Dot") .parent .parent .element(null,"rtept") .attribute (null,"lat","-18.83896366") .attribute (null,"lon","47.37275913") .element (null,"name","B012") .parent .element (null,"sym","Dot") .parent .parent .element(null,"rtept") .attribute (null,"lat","-18.83760852") .attribute (null,"lon","47.37275913") .element (null,"name","B013") .parent .element (null,"sym","Dot") .parent .parent .element(null,"rtept") .attribute (null,"lat","-18.83760949") .attribute (null,"lon","47.39173757") .element (null,"name","A013") .parent .element (null,"sym","Dot") .parent .parent .element(null,"rtept") .attribute (null,"lat","-18.83625436") .attribute (null,"lon","47.39173757") .element (null,"name","A014") .parent .element (null,"sym","Dot") .parent .parent .element(null,"rtept") .attribute (null,"lat","-18.83625339") .attribute (null,"lon","47.37275913") .element (null,"name","B014") .parent .element (null,"sym","Dot") .parent .parent .element(null,"rtept") .attribute (null,"lat","-18.83489825") .attribute (null,"lon","47.37275913") .element (null,"name","B015") .parent .element (null,"sym","Dot") .parent .parent .element(null,"rtept") .attribute (null,"lat","-18.83489922") .attribute (null,"lon","47.39173757") .element (null,"name","A015") .parent .element (null,"sym","Dot") .parent .parent .element(null,"rtept") .attribute (null,"lat","-18.83354409") .attribute (null,"lon","47.39173757") .element (null,"name","A016") .parent .element (null,"sym","Dot") .parent .parent .element(null,"rtept") .attribute (null,"lat","-18.83354312") .attribute (null,"lon","47.37275913") .element (null,"name","B016") .parent .element (null,"sym","Dot") .parent .parent .element(null,"rtept") .attribute (null,"lat","-18.83218798") .attribute (null,"lon","47.37275913") .element (null,"name","B017") .parent .element (null,"sym","Dot") .parent .parent .element(null,"rtept") .attribute (null,"lat","-18.83218895") .attribute (null,"lon","47.39173757") .element (null,"name","A017") .parent .element (null,"sym","Dot") .parent .parent .element(null,"rtept") .attribute (null,"lat","-18.83083382") .attribute (null,"lon","47.39173757") .element (null,"name","A018") .parent .element (null,"sym","Dot") .parent .parent .element(null,"rtept") .attribute (null,"lat","-18.83083285") .attribute (null,"lon","47.37275913") .element (null,"name","B018") .parent .element (null,"sym","Dot") .parent .parent .element(null,"rtept") .attribute (null,"lat","-18.82947771") .attribute (null,"lon","47.37275913") .element (null,"name","B019") .parent .element (null,"sym","Dot") .parent .parent .element(null,"rtept") .attribute (null,"lat","-18.82947868") .attribute (null,"lon","47.39173757") .element (null,"name","A019") .parent .element (null,"sym","Dot") .parent .parent .element(null,"rtept") .attribute (null,"lat","-18.82812355") .attribute (null,"lon","47.39173757") .element (null,"name","A020") .parent .element (null,"sym","Dot") .parent .parent .element(null,"rtept") .attribute (null,"lat","-18.82812258") .attribute (null,"lon","47.37275913") .element (null,"name","B020") .parent .element (null,"sym","Dot") .parent .parent .element(null,"rtept") .attribute (null,"lat","-18.82676744") .attribute (null,"lon","47.37275913") .element (null,"name","B021") .parent .element (null,"sym","Dot") .parent .parent .element(null,"rtept") .attribute (null,"lat","-18.82676841") .attribute (null,"lon","47.39173757") .element (null,"name","A021") .parent .element (null,"sym","Dot") .parent .parent .element(null,"rtept") .attribute (null,"lat","-18.82044444") .attribute (null,"lon","47.39173757") .element (null,"name","Exit point") .parent .element (null,"sym","Dot") .parent ; gpxdoc.elements .element(null,"extensions") .element(null,"polyline") .attribute(null,"xmlns","http://www.topografix.com/GPX/gpx_overlay/0/3") .element(null,"points") // .element(null,"pt") .attribute (null,"lat","-18.85522622") .attribute (null,"lon","47.37275913") .parent .element(null,"pt") .attribute (null,"lat","-18.85522622") .attribute (null,"lon","47.39838002") .parent .element(null,"pt") .attribute (null,"lat","-18.82044444") .attribute (null,"lon","47.39838002") .parent .element(null,"pt") .attribute (null,"lat","-18.82044444") .attribute (null,"lon","47.37275913") .parent .element(null,"pt") .attribute (null,"lat","-18.85522622") .attribute (null,"lon","47.37275913") // ; auto print = new DocPrinter!(char); Stdout(print(gpxdoc)).newline; } </code></pre> <hr> <p><strong>Question:</strong></p> <p>How could it be improved ?</p>
[ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-03-13T04:18:23.243", "Id": "15842", "Score": "1", "body": "why are you building this XML file in D, rather then loading it?" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-03-13T09:10:01.713", "Id": "15849", "Score": "0", "body": "@Winston Ewert: You are right. Load and parse is the best way to go given an XML file, But I am begining D1/Tango and try to devise a way to build XML using API manipulation and must recognize that hardcoding it as I did is misleading." } ]
[ { "body": "<p>Store this data in an XML file and parse it using <a href=\"http://dlang.org/phobos/std_xml.html\" rel=\"nofollow\">std.xml</a>.</p>\n\n<p>Tango also has had an <a href=\"http://www.dsource.org/projects/tango/wiki/TutXmlPath\" rel=\"nofollow\">XML parser</a> for years which is <a href=\"http://dotnot.org/blog/archives/2008/03/12/why-is-dtango-so-fast-at-parsing-xml/\" rel=\"nofollow\">reputed</a> to be <a href=\"http://dotnot.org/blog/archives/2008/03/10/xml-benchmarks-parsequerymutateserialize/\" rel=\"nofollow\">very fast</a>. Use that instead. :)</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-03-13T03:53:37.803", "Id": "15839", "Score": "0", "body": "Thank you for answering. I forgot to mention it and I have to make an edit: I must stick to the Tango library." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-03-13T04:08:51.123", "Id": "15841", "Score": "0", "body": "I want to devise something building a GPX document using API but not parsing a GPX file." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-03-13T07:36:16.637", "Id": "15844", "Score": "0", "body": "Tango also has an XML parser. I can't recommend enough to use that instead." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-03-13T09:03:47.980", "Id": "15848", "Score": "0", "body": "Tango's XML parser is defined in the module `tango.text.xml.Document` and I already use it in my piece of code." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-03-13T10:00:38.047", "Id": "15851", "Score": "0", "body": "Yeah, but you can use Document.parse and tango.io.device.File to get the tango document from an actual file. Do you understand what I mean? If you don't want to do it, that's fine, but I'd like to make sure my answer was clear." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-03-13T10:12:14.493", "Id": "15854", "Score": "1", "body": "Your answer is clear indeed: You suggest me to load and parse a file so as to build an XML document in memory but that will defeat my intent seeking for code allowing me to build in memory an XML Document using API manipulation (presumably without a prior XML file as you assumed). Maybe hardcoding the GPX data in my piece of code is misleading and I have to recognize that." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-03-13T10:24:08.953", "Id": "15856", "Score": "0", "body": "Thanks for the clarification. Yes, I think it is misleading, and it's difficult to answer without knowing about what the API gives you. :( Maybe this approach is perfect with the API, maybe it's not: hard to tell!" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-03-13T10:55:20.897", "Id": "15859", "Score": "0", "body": "+1: I end up succeeding parsing the content of a GPX file casting it beforehand >>> `auto gpxcontent = cast(char[]) file.load(file)` <<<. Enfin un petit progrès pour moi même si c'est dans une autre direction. Merci bien, j'apprécie votre aide" } ], "meta_data": { "CommentCount": "8", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-03-12T12:16:49.110", "Id": "9914", "ParentId": "9898", "Score": "1" } }, { "body": "<p>Hm, there is a lot of data in your program. As Cygal points out, you should put this where it belongs - in a data file.</p>\n\n<p>Other than that, there are lots of this instructions in your code:</p>\n\n<pre><code> .element(null,\"rtept\")\n .attribute (null,\"lat\",\"-18.82812258\")\n .attribute (null,\"lon\",\"47.37275913\")\n .element (null,\"name\",\"B020\")\n .parent\n .element (null,\"sym\",\"Dot\")\n .parent\n</code></pre>\n\n<p>I would put that in a single function.</p>\n\n<pre><code>.append(createDot(gpxdoc, \"-18.82812258\", \"47.37275913\", \"B020\")).parent\n.append(createDot(gpxdoc, \"-18.82676744\", \"47.37275913\", \"B021\")).parent\n</code></pre>\n\n<p>Since I've never used this language I leave the implementation of the <code>createDot</code> function to you.</p>\n\n<p><strong>Edit</strong>: Now I understand your intent a little better. You want to do something like this:</p>\n\n<pre><code>auto gpxdoc = new GPXDocument;\n\ngpxdoc\n .setDesc(\"Spray Job\")\n .setAuthor(\"izylay\", \"izylay@ary.com\")\n .setCopyright(\"izylay\", \"2011\")\n .setKeywords(\"ULM\", \"Aerial Spraying\", \"Locust\")\n .setBounds(\"-18.85522622\", \"47.37275913\", \"-18.82044444\", \"47.39838002\")\n\n .addWaypoint(\"A000\", \"-18.85522622\", \"47.39173757\")\n\n .addEntrypoint(\"-18.85522610\", \"47.39838002\")\n\n .addPoint(\"B000\", \"-18.85522525\", \"47.37275913\")\n .addPoint(\"B001\", \"-18.85387012\", \"47.37275913\")\n</code></pre>\n\n<p>You can inherit the Document object and add all these methods just to be wrappers around normal node manipulation.</p>\n\n<p>The thing with fluent interfaces is that they may maintain state (that's why you need a <code>parent</code> method, for example.) I'm not familiar with the gpx format, but I wouldn't be surprised if you can create groups of points. For that case, you just need to store a \"state\" reference. For the top-level attributes or elements (description, etc.) you can store references to the appropriate node.</p>\n\n<p>Hope this points you to the right direction.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-03-13T04:06:46.193", "Id": "15840", "Score": "0", "body": "+1: Thank you for pointing mee to this direction. Now, I think of extending the Document class and try to find a way to include a kind of createdoc using fluent interface." } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-03-12T14:09:36.723", "Id": "9927", "ParentId": "9898", "Score": "1" } } ]
{ "AcceptedAnswerId": "9927", "CommentCount": "2", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-03-11T06:35:09.403", "Id": "9898", "Score": "0", "Tags": [ "d" ], "Title": "How code be this piece of code be refactored?" }
9898
<p>I'm looking for a review of my macros. I have these in the project pre-compile header. I tent to copy them into all my new projects as well, unless its a very simple project.</p> <pre><code>#ifdef __APPLE__ #import &lt;TargetConditionals.h&gt; #endif // turn on or off different types of logging. ALog() is always logged. #define LOG_D // Turn on standard debug messages DLog(); #define LOG_N // Turn on network debug messages NLog(); #define LOG_DB // Turn on database debug messages DBLog(); #undef LOG_V // Turn off verose debug messages VLog(); #undef LOG_UI // Turn off popup messages UILog(); // -- You should not have to mess with anything below this line -- // Be safe, start with all things defined #define DEBUGLOG(...) do {} while (0) #define ALERTLOG(...) do {} while (0) #define ALWAYSLOG(...) do {} while (0) // Define three basic debug types, DEBUGLOG, ALERTLOG and ALWAYSLOG // These macros generally should not be called directly // DEBUGLOG - show a message only when compiled for debugging // ALERTLOG - show a popup window message only when compile for debugging // ALWAYSLOG - show a message debugging and release #ifdef __APPLE__ #ifdef DEBUG #undef DEBUGLOG #define DEBUGLOG(type, fmt, ...) NSLog((@"%@: %s [Line %d] " fmt), type, __PRETTY_FUNCTION__, __LINE__, ##__VA_ARGS__) #undef ALERTLOG #if TARGET_OS_MAC #define ALERTLOG(fmt, ...) DEBUGLOG(@"I", fmt, ##__VA_ARGS__) #else #define ALERTLOG(fmt, ...) { UIAlertView *alert = [[UIAlertView alloc] initWithTitle:[NSString stringWithFormat:@"%s\n [Line %d] ", __PRETTY_FUNCTION__, __LINE__] message:[NSString stringWithFormat:fmt, ##__VA_ARGS__] delegate:nil cancelButtonTitle:@"Ok" otherButtonTitles:nil]; [alert show]; } #endif #endif #undef ALWAYSLOG #define ALWAYSLOG(type, fmt, ...) NSLog((@"%@: %s [Line %d] " fmt), type, __PRETTY_FUNCTION__, __LINE__, ##__VA_ARGS__) #endif // Create some standard logging macros #ifdef LOG_D #define DLog(fmt, ...) DEBUGLOG(@"D", fmt, ##__VA_ARGS__) #else #define DLog(...) do {} while (0) #endif #ifdef LOG_N #define NLog(fmt, ...) DEBUGLOG(@"Net", fmt, ##__VA_ARGS__) #else #define NLog(...) do {} while (0) #endif #ifdef LOG_DB #define DBLog(fmt, ...) DEBUGLOG(@"DB", fmt, ##__VA_ARGS__) #else #define DBLog(...) do {} while (0) #endif #ifdef LOG_V #define VLog(fmt, ...) DEBUGLOG(@"V", fmt, ##__VA_ARGS__) #else #define VLog(...) do {} while (0) #endif #ifdef LOG_UI #define UILog(fmt, ...) ALERTLOG(fmt, ##__VA_ARGS__) #else #define UILog(...) do {} while (0) #endif #define ALog(fmt, ...) ALWAYSLOG(@"V", fmt, ##__VA_ARGS__) </code></pre>
[]
[ { "body": "<p>One comment: don't define / undefine the flags that switch logging on or off in the file. That stops you from defining them on the compiler command line. The way you have things now, if you want to make a release build (with no debug logging at all), you have to change the source code.</p>\n\n<p>Another minor point: consider using a logging framework. There are a couple of Objective-C logging frameworks available that will allow you to turn logging on or off without recompiling at all.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-04-17T17:13:25.580", "Id": "17414", "Score": "1", "body": "Actually the above will have all debugging off in a release build. There is a `#ifdef debug` which is compiler controlled around the loggin functions. The inline defines control how much and what kind of logging you want to see when you are in debug mode." } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-04-17T09:23:09.437", "Id": "10951", "ParentId": "9899", "Score": "0" } }, { "body": "<ol>\n<li><p>At very least, DO NOT copy-paste your macros directly into .pch file</p>\n\n<blockquote>\n <p>A PCH file is, by definition, a project specific precompiled header.\n It really shouldn't be used beyond the context of the project and it\n really shouldn't contain anything but #includes/#imports.</p>\n</blockquote>\n\n<p>As <a href=\"https://stackoverflow.com/a/2846425\">suggested by an Apple engineer</a>, you <em>should</em> make a separate file with your macros e.g. Defines.h, and just put #import Defines.h into .pch file.</p></li>\n<li>I would suggest re-thinking you logging strategy. If it is not absolutely necessary (e.g. you do not have access to production instance of your app), you should log only the critical errors. Abundance of logging code decreases its readability/maintainability and can even CAUSE bugs. I recommend <a href=\"http://www.codinghorror.com/blog/2008/12/the-problem-with-logging.html\" rel=\"nofollow noreferrer\">an excellent blog post on this matter from co-founder of Stack Overflow</a>.</li>\n</ol>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-12-08T12:57:21.837", "Id": "19402", "ParentId": "9899", "Score": "1" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-03-11T11:18:21.603", "Id": "9899", "Score": "2", "Tags": [ "objective-c", "macros" ], "Title": "Objective-C debug macros" }
9899
<p>I have a <code>Queue</code> class that is basically a single linked list. It has 2 remove methods. What would be the cleanest way to avoid duplication of the code? Only the comparisons in methods are different.</p> <pre><code>int Queue::remove(const string&amp; substring) { // Loop through the queue list size_t found; found = current_job-&gt;description.find(substring) if (found != string::npos) { // Remove job. } // Return the amount of removed jobs. } int Queue::remove(int priority) { // Loop through the queue list if (current_job-&gt;priority == priority) { // Remove job. } // Return the amount of removed jobs. } </code></pre> <p>I thought a template solution as answered <a href="https://stackoverflow.com/a/9411448">here</a>, but in this case, the comparison function has different arguments.</p>
[]
[ { "body": "<p>You can abstract out the thing that changes, the comparison expression, into a predicate for a template function.</p>\n\n<pre><code>class PriorityMatch\n{\n int priority_;\npublic:\n explicit PriorityMatch(int priority)\n : priority_(priority) {}\n\n bool operator()(const Job&amp; job)\n {\n return job-&gt;priority == priority_;\n }\n};\n\nclass DescriptionMatch\n{\n std::string substring_;\npublic:\n explicit DescriptionMatch(const std::string&amp; substring)\n : substring_(substring) {}\n\n bool operator()(const Job&amp; job)\n {\n return job-&gt;description.find(substring_) != std::string::npos;\n }\n};\n\ntemplate&lt;class Predicate&gt;\nint Queue::remove(Predicate predicate)\n{\n // Loop through the queue list\n if (predicate(current_job)) {\n // Remove job.\n }\n // Return the amount of removed jobs. \n}\n\nint Queue::remove(const string&amp; substring)\n{\n return remove(DescriptionMatch(substring));\n}\n\nint Queue::remove(int priority)\n{\n return remove(PriorityMatch(substring));\n}\n</code></pre>\n\n<p>Or in C++11:</p>\n\n<pre><code>template&lt;class Predicate&gt;\nint Queue::remove(Predicate predicate)\n{\n // Loop through the queue list\n if (predicate(current_job)) {\n // Remove job.\n }\n // Return the amount of removed jobs. \n}\n\nint Queue::remove(const string&amp; substring)\n{\n return remove([](const Job&amp; job){\n return job-&gt;description.find(substring) != std::string::npos;\n });\n}\n\nint Queue::remove(int priority)\n{\n return remove([](const Job&amp; job){\n return job-&gt;priority == priority;\n });\n}\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-03-11T17:00:08.363", "Id": "15755", "Score": "0", "body": "+1. The only difference; I usually make simple functors like `PriorityMatch` and `DescriptionMatch` private member `structures` rather than `classes`. This is because I do not seem them as real object but rather as `property bags` that are used to transport information to a call site." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-03-11T19:25:55.890", "Id": "15757", "Score": "0", "body": "@LokiAstari: What do you mean? The `struct` and `class` keywords are almost synonyms." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-03-11T22:31:10.833", "Id": "15758", "Score": "0", "body": "@AntonGolov: I use struct for property bags. Its not anything major just a stylistic thing that I have adopted." } ], "meta_data": { "CommentCount": "3", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-03-11T16:19:15.280", "Id": "9901", "ParentId": "9900", "Score": "11" } }, { "body": "<p>Just to add a comment, I think that renaming both member functions to <code>Queue::removeBySubstring</code> and <code>Queue::removeByPriority</code> could improve code readability at the client side.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-05-17T20:55:02.577", "Id": "11851", "ParentId": "9900", "Score": "0" } } ]
{ "AcceptedAnswerId": "9901", "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-03-11T13:05:04.420", "Id": "9900", "Score": "8", "Tags": [ "c++", "queue" ], "Title": "Singly linked list queue class" }
9900
<p>I made this little library for personal use to make javascripting faster and easier. I would like to know if there are any inefficiencies in it (in size and performance) and possibly if there is a feature you think is missing that would be useful.</p> <pre><code>//PUT ALL CODE AT THE END OF THE PAGE!!!!!! THIS IS UBER IMPORTANT //document shorthand doc=document //querySelectorAll shorthand function $q(a){return doc.querySelectorAll(a)} //returns specific element function $(a,b){return $q(a)[b||0]} //function to set properties in a chainable manner Element.prototype.$p=function(a){for(b in a)this[b]=a[b];return this} //creates a class that hides elements (notice the use of the function above) $("head").appendChild(doc.createElement("style").$p({"innerHTML":".wqh{display:none}"})) Element.prototype.$p({ "removeClass":function(a){this.classList.remove(a)}, "addClass":function(a){this.classList.add(a)}, "hide":function(){this.addClass("wqh")}, "show":function(){this.removeClass("wqh")}, //loads content of a file inside the element, example: element.load("random file.txt") "load":function(a,b,c){c=this;b=new XMLHttpRequest;b.open("GET",a,!0);b.send();b.onreadystatechange=function(){c.innerHTML=b.responseText}} }) </code></pre> <p>Example of its uses:</p> <pre><code>$(".test").addClass("red") $(".test",1).removeClass("big") $(".test",2).hide() for(a in b=$q("p")) b[a].style.fontFamily="serif", b[a].style.color="blue", b[a].style.fontSize="20px"; </code></pre> <p>More readable version of the $p() function:</p> <pre><code>//function to set properties in a chainable manner Element.prototype.$p = function(proplist){ var property; for(property in proplist){this[property] = proplist[property]} return this; } </code></pre>
[ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-03-12T00:00:09.630", "Id": "15759", "Score": "1", "body": "1) There shouldn't be a requirement to load it at the end of the body. What if you want to use it before then? 2) The whitespace is really ugly, maybe run it through a linter or beautifier. 3) `$` is already used by other libraries. It is also a meaningless name for a function. Please choose something else. 4) `querySelectorAll` is really slow, and missing from old browsers. You can actually get better performance by writing your own selector routine. 5) Adding properties to built-in constructors is a bad practice. See prototype.js." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-03-12T00:17:54.797", "Id": "15761", "Score": "0", "body": "1) It is good practice to put code at the end of the page because it runs the code after the dom is ready and before images are loaded 2) it's made to be compact 3) I rarely use any other library so I don't care 4) I doubt that I can make a perfect copy of queyselectorall that isn't like 100k big and allot slower than the original 5) I could bind these functions to $(), but it wouldn't be as powerful. I want my library to be versatile :)" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-03-12T00:26:19.927", "Id": "15763", "Score": "0", "body": "I thought you might say something like that, that's why I didn't bother to make this an answer. Still: 1) Maybe for your own scripts, not for a library you expect anyone else to use. 2) minify it. 3) If it's only for your own use, okay. But if you're going to make something like this, why not make it generally useful? 4) You don't want a perfect copy, you want tag names, ids, and class names (in any combination). The rest of the stuff leads to bad coding practices. 5) Again, it comes down to whether you're making this only for yourself, or as a generally useful thing." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-03-12T00:41:18.590", "Id": "15767", "Score": "0", "body": "I'm making it for personal use, I don't expect anyone to use it, and I will only use it if I have a big project to do 4)I really like the flexibility of queryselectorall, if I need a part of code to be fast, I'll just use getelementbyid or something..." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-03-12T10:10:35.780", "Id": "15778", "Score": "0", "body": "@GGG answers should not be posted as comments. Then you cause huge comment threads to appear... like this one. Comments are for clarifications, remarks, \"comments\". Not for answering." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-03-12T10:12:45.593", "Id": "15780", "Score": "0", "body": "@williammalo being a bit more authoritative than I should, it is no longer good practice to put code at the end of the page: read on properties `async` and `defer` for the [script tag](http://developers.whatwg.org/scripting-1.html#the-script-element)" } ]
[ { "body": "<p>Problems with it : </p>\n\n<ul>\n<li>in the global namespace</li>\n<li>use of innerHTML</li>\n<li>no cross-compatibility </li>\n<li>messing with object prototypes</li>\n<li>quite useless</li>\n</ul>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-03-12T00:24:37.847", "Id": "15762", "Score": "0", "body": "Where is there a global variable leak? What do you suggest I replace innerHTML with?" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-03-12T00:28:20.517", "Id": "15764", "Score": "2", "body": "@williammalo `doc=document` for one. Not only does it put `doc` in the global scope, there is no `var` keyword so this will cause an error in strict mode." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-03-12T00:33:56.570", "Id": "15765", "Score": "0", "body": "That is intended, I want to use doc as a shorthand everywhere, not just in the library itself. Are there any others? I want to make sure I iron them out." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-03-12T00:37:25.320", "Id": "15766", "Score": "0", "body": "@williammalo try writing code that's readable. That's the major problem with it" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-03-12T00:45:49.257", "Id": "15768", "Score": "0", "body": "@Raynos I'm sorry if it's hard to read, I write my code real compact because I don't trust minifiers." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-03-12T00:50:16.260", "Id": "15769", "Score": "1", "body": "@williammalo , isn't that what gzip is for?" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-03-12T01:53:43.467", "Id": "15770", "Score": "2", "body": "@williammalo \"don't trust minifiers\" ... You suffer a severe case of paranoia, the solution to not trusting minifiers is writing your own minifier" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-03-12T14:50:39.090", "Id": "15795", "Score": "0", "body": "@Raynos the solution is writing efficient code staight up so that you don't even need minifiers." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-03-12T14:58:21.530", "Id": "15796", "Score": "3", "body": "There is nothing \"efficient\" about your code. Compared with properly formatted code it's harder to read, doesn't run faster and it probably won't load noticeably faster when using gzip." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-03-12T15:15:20.180", "Id": "15800", "Score": "1", "body": "@williammalo , if you cannot take criticism, then you should not try to brag about your code. You have turned this into \"why are you so mean\" discussion." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-03-12T16:33:59.397", "Id": "15808", "Score": "0", "body": "@teresco I mainly want to know if I can make my code smaller and if there are any performance bottlenecks. I seriously don't know why everyone talks about readability, it's not what I want criticism about." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-03-13T10:24:14.883", "Id": "15857", "Score": "1", "body": "But why do want to make the code smaller? There is no advantages to it being smaller, only disadvantages. And the whole point of code review it to spot potential bugs, and bad readability leads to bugs." } ], "meta_data": { "CommentCount": "12", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-03-12T00:20:19.233", "Id": "9904", "ParentId": "9902", "Score": "6" } }, { "body": "<p>Going off a little on what others have mentioned, I have a couple of main criticisms:</p>\n\n<ol>\n<li>Manually minified -- it's really difficult to get an idea of what you're really trying to do here. I understand that you don't trust minifiers, but the reason people use those instead of always just writing small code by hand is so that they (and other developers) can make sense of the code when they're working on it, and yet still provide an optimized version for production.</li>\n<li>The use of <code>doc</code> as your shorthand -- general concerns about global variables aside, that's just a bad name for a library shortcut variable. What if someone using your library needs a variable named <code>doc</code>, to represent something the user uploads (for example)? Sure they can sort it all out using correct scoping rules, but it'd be too easy for them to forget about it, maybe put their own variable in the global namespace, and then either their code breaks or your library breaks. If you create a namespace for your library, then you can isolate <code>doc</code> from the user's code, and you'll be fine.</li>\n<li>Modifying existing object prototypes -- really, I could go either way on this. I've used the Prototype library, which did a lot of that, and it was really nice. I'm also aware that it can really confuse developers, and it can even cause problems. It's generally frowned upon by most \"best practices\" lists I've seen, so while I wouldn't avoid it completely, I'd recommend using it gently when it makes more sense than creating a wrapper. That's probably one of the bigger selling points jQuery offers -- it creates a wrapper object instead of working with the direct JS object prototypes, so code that's expecting the additional functionality can use it, and code that might somehow rely on the original implementation won't know the difference.</li>\n</ol>\n\n<p>I'd really like to see the code in a non-minified, at least somewhat commented/documented format -- especially <code>Element.prototype.$p</code>. That function looks interesting, but I'm having a hard time following along with it as a one-liner with arguments simply named <code>a</code> and <code>b</code>. Especially the <code>for .. in</code> condition -- <code>a in b=a</code>? I've never come across an assignment used like that before. I'm not saying it's wrong by any means, and maybe it's really common and I just missed it in my journeys, but it doesn't seem very intuitive or easily understandable; that would definitely be worth a couple of comments explaining what it does.</p>\n\n<p>Hope this helps -- or at least makes sense even if it doesn't.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-03-13T18:19:23.717", "Id": "15919", "Score": "0", "body": "Thanks for the constuctive answer. I don't quite understand what you mean about the doc variable, doesnt it have to be global? If it's not global, how could I use it everywhere? Could you elaborate on that... I'll work on making a more readable version and I'll post it later." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-03-13T18:24:00.357", "Id": "15920", "Score": "0", "body": "Also, like I said before, I put my code here hoping that people could find ways to make it smaller. My goal is to make it as ubersmall as possible, js1k style :D. (I'm still going to make a readable version tho, don't worry)" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-03-13T18:42:47.680", "Id": "15922", "Score": "0", "body": "I made a more readable version of the $p() function for you. It is in the op." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-03-14T18:24:39.763", "Id": "15959", "Score": "0", "body": "Okay, $p makes much more sense now :)" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-03-14T18:32:57.833", "Id": "15960", "Score": "0", "body": "My main point about \"doc\" wasn't so much that it's global - most libraries use at least _some_ kind of global variable. My suggestion about that is mostly about the variable name. It's too easy for \"doc\" to clash with someone else's variable name, whereas jQuery (for example) uses the name of the library (\"jQuery\") or \"$\" for shorthand. Not a lot of people are going to use \"$\" as an identifier, and if you include jQuery in your project, then you'll avoid using \"jQuery\" as an identifier unless you're intentionally trying to screw things up. (Sorry - not used to commenting on here)." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-03-14T18:39:21.773", "Id": "15961", "Score": "0", "body": "As for shrinking your code, while that's a worth-while goal, it's more important to get it functioning correctly, then efficiently (code wise, not size), and _then_ perhaps worry about size. If you're really concerned about code size, you may consider looking into how minifiers work, what they do, how they do it, etc. That could alleviate your concerns, or at least give you insight on what you can do yourself to shrink your code. Just keep in mind that most devs aren't great at reading min'ed code, so try and either comment it or keep a readable version somewhere." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-03-14T19:14:42.213", "Id": "15967", "Score": "0", "body": "I already passed my code through closure compiler advanced, and it didnt make it smaller... I don't think there is a better minifier than that." } ], "meta_data": { "CommentCount": "7", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-03-13T17:23:00.353", "Id": "9990", "ParentId": "9902", "Score": "4" } }, { "body": "<p>The only thing that I can see is that <code>b</code> is escaping into the global scope in <code>$p()</code>. However, <code>b</code> doesn't seem to be accessed globally anywhere else in the code you have posted so I only mention it as something to be careful of for future expansion.</p>\n\n<p>You can avoid this without having to use a <code>var</code> statement by including a parameter <code>b</code> to <code>$p</code> and never passing a value for it:</p>\n\n<pre><code>Element.prototype.$p=function(a,b){for(b in a)this[b]=a[b];return this}\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-03-17T01:31:59.940", "Id": "16071", "Score": "0", "body": "Doesnt putting \"b\" in the \"for\" loop make it local?" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-04-11T18:48:00.310", "Id": "17227", "Score": "0", "body": "I ran the code from your question in the Chrome console and then queried the value of b. This is what I got:\n\n > b\n \"load\"\n > window['b']\n \"load\"\n\nSo it seems that b is escaping into the global namespace." } ], "meta_data": { "CommentCount": "2", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-03-15T19:56:01.640", "Id": "10050", "ParentId": "9902", "Score": "1" } }, { "body": "<p>For returning a specific element I would recommend using document.queryselector when no index is provided as it would be more apt.</p>\n\n<p>This might be especially appropriate in the edge case that a very large list could be returned. querySelector could also be optimised by the browser.</p>\n\n<p>For example <code>if($('li')) { ... }</code> to check if a list item is present at all within the page.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-10-30T17:53:24.980", "Id": "33529", "ParentId": "9902", "Score": "0" } }, { "body": "<p>Others have commented on the general idea of this library, I agree. You should only use this for one-man projects.</p>\n\n<p>Still,</p>\n\n<p><code>function $q(a){return doc.querySelectorAll(a)}</code></p>\n\n<p>could be simply <code>$q = doc.querySelectorAll;</code></p>\n\n<p>Also this seems overkill:</p>\n\n<pre><code>//creates a class that hides elements (notice the use of the function above)\n$(\"head\").appendChild(doc.createElement(\"style\").$p({\"innerHTML\":\".wqh{display:none}\"}))\n</code></pre>\n\n<p>It just makes much more sense to have this in a css file and give it a proper name like <code>hidden</code>.</p>\n\n<p>Finally, if you are going for short, you might as well use <code>d</code> instead of <code>doc</code>.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-10-31T14:18:19.863", "Id": "33583", "ParentId": "9902", "Score": "0" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "6", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-03-11T23:48:35.113", "Id": "9902", "Score": "1", "Tags": [ "javascript", "optimization", "library" ], "Title": "Any criticism on my JavaScript micro-library?" }
9902
<p>I would like any advice on how to improve this code. To clarify what this code considers an intersection to be, the intersection of [3,3,4,6,7] and [3,3,3,6,7] is [3,6,7]. I would appreciate any improvements to make the code more readable or perform faster.</p> <pre><code>public ArrayList&lt;Integer&gt; findIt (int[] a, int[] b){ ArrayList&lt;Integer&gt; result = new ArrayList&lt;Integer&gt;(); Arrays.sort(a); Arrays.sort(b); int i = 0; int j = 0; while(i &lt; a.length &amp;&amp; j &lt; b.length){ if(a[i]&lt;b[j]) ++i; else if (a[i] &gt; b[j]) ++j; else{ if (!result.contains(a[i])) result.add(a[i]); ++i; ++j; } } return result; } </code></pre>
[ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-03-12T10:26:44.887", "Id": "15783", "Score": "1", "body": "Examples of given arrays are already sorted. Are all given arrays sorted? If result ArrayList can not contain duplicate elements, maybe Set would be better?" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-03-13T09:42:50.427", "Id": "15850", "Score": "0", "body": "Since the answers are using `List`s instead of arrays as input, I'll ask directly: Any special reason you are using arrays? It's very unusual to use arrays in Java, because `List`s are much more flexible. Generally, unless you need to optimize extremely for speed, you should reconsider using arrays at all." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-03-13T13:26:41.333", "Id": "15876", "Score": "2", "body": "You mean \"intersection\"." } ]
[ { "body": "<h2>Algorithm</h2>\n\n<p>You're using a O(n log(n)) algorithm here, which could be O(n²) for difficult cases since <code>contains()</code> is O(n) and is called in a loop. Instead, use the property of <code>HashSet</code>: access is O(1), which means you can achieve this in O(n) time. My algorithm below simply keeps track of what it can add to the result. I can add everything that exists in the first list, but I should not add an item I already added.</p>\n\n<p>See my tested code for my implementation:</p>\n\n<pre><code>public static List&lt;Integer&gt; intersection(List&lt;Integer&gt; a, List&lt;Integer&gt; b){\n Set&lt;Integer&gt; canAdd = new HashSet&lt;Integer&gt;(a);\n List&lt;Integer&gt; result = new ArrayList&lt;Integer&gt;();\n\n for (int n: b) {\n if(first.contains(n)) {\n result.add(n);\n // we wish to add only one n\n canAdd.remove(n);\n }\n }\n\n return result;\n}\n</code></pre>\n\n<h2>Comments on your code</h2>\n\n<ol>\n<li>You should return a <code>List</code>, not an <code>ArrayList</code> since it's an implementation detail. Using an <code>ArrayList</code> is OK here since adding at the end of it has O(1) amortized complexity. Otherwise, lists should be <code>LinkedList</code> (when adding to the beginning, not to the end, as @Landei points out).</li>\n<li>Be careful about the names you choose. <code>findIt</code> doesn't seem to be appropriate, but <code>removeDuplicates</code> or <code>intersection</code> describes what the code does.</li>\n</ol>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-03-12T15:18:18.790", "Id": "15801", "Score": "1", "body": "I agree with everything except with the `LinkedList` comment. Benchmarks show that `ArrayList` is almost always preferable. See e.g. http://www.javaspecialists.eu/archive/Issue111.html" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-03-12T16:07:32.253", "Id": "15806", "Score": "0", "body": "You use a reference `first`, but it isn't defined (your code won't compile). If it's `a` or `b`, you have a nasty side-effect." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-03-12T16:53:22.883", "Id": "15809", "Score": "0", "body": "@Landei Oops, I meant to use addFirst. Since it's not always available in the `List` interface, I'll switch back to ArrayList. @X-Zero Opps, that's `canAdd`, I forgot to change that one." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-03-13T17:25:25.857", "Id": "15916", "Score": "0", "body": "@seand Haha, so this is why I couldn't understand what an \"interception\" was." } ], "meta_data": { "CommentCount": "4", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-03-12T10:53:32.507", "Id": "9911", "ParentId": "9909", "Score": "8" } }, { "body": "<p>What about ? It's clean.</p>\n\n<pre><code>public static List&lt;Integer&gt; intersection(List&lt;Integer&gt; a, List&lt;Integer&gt; b){\n List&lt;Integer&gt; result = new ArrayList&lt;Integer&gt;();\n\n for(int v : a) {\n if(b.contains(v) &amp;&amp; !result.contains(v)) {\n result.add(v);\n }\n }\n\n // sort if you need\n Collections.sort(result); \n\n return result;\n}\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-03-13T10:05:06.560", "Id": "15853", "Score": "0", "body": "It's simply a performance issue: `List.contains` takes a lot of time compared to `HashSet.contains()`: O(1) vs O(n). Otherwise, it's nice and easy to read, here's an upvote. :)" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-03-15T06:19:00.793", "Id": "15992", "Score": "0", "body": "Side note: you should use `for (Integer` instead of `for (int` because you're unnecessarily boxing and unboxing as a result." } ], "meta_data": { "CommentCount": "2", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-03-13T09:30:08.397", "Id": "9955", "ParentId": "9909", "Score": "3" } }, { "body": "<p>@Cygal : Assuming that HashSet.contains() is really faster than the List one, this could be the ultimate code :-)</p>\n\n<pre><code>public static List&lt;Integer&gt; intersection(List&lt;Integer&gt; a, List&lt;Integer&gt; b) {\n Set&lt;Integer&gt; aSet = new HashSet&lt;Integer&gt;(a);\n Set&lt;Integer&gt; bSet = new HashSet&lt;Integer&gt;(b);\n\n for(Iterator&lt;Integer&gt; it = aSet.iterator(); it.hasNext();) {\n if(!bSet.contains(it.next())) it.remove();\n }\n\n return new ArrayList&lt;Integer&gt;(aSet);\n}\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-03-13T13:03:07.010", "Id": "15871", "Score": "0", "body": "The `new HashSet` trick is nice, but [The behavior of an iterator is unspecified if the underlying collection is modified while the iteration is in progress in any way other than by calling `remove()`.](http://docs.oracle.com/javase/7/docs/api/java/util/Iterator.html#remove()). Bien tenté!" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-03-13T13:15:29.783", "Id": "15872", "Score": "0", "body": "'aSet' is a local variable so it cannot be modified from anywhere else. It should be good :-) Merci !" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-03-13T13:22:01.970", "Id": "15873", "Score": "0", "body": "I don't know if this is about concurrent accesss or \"removing while doing a for loop\". Maybe this works and is specified, but I would not do this in production code unless I was sure. (That's forbidden in C++, by the way.)" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-03-13T13:30:07.797", "Id": "15878", "Score": "1", "body": "In Java, the only way to remove an Object from a collection is to use an Iterator. This note is applicable only if there is a concurrent access. Trust me, it works well ;-)" } ], "meta_data": { "CommentCount": "4", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-03-13T12:50:32.750", "Id": "9963", "ParentId": "9909", "Score": "3" } }, { "body": "<p>You can use <code>CollectionUtils</code> utility in <a href=\"http://commons.apache.org/collections/\" rel=\"nofollow\">Apache Commons Collection</a>. There is <code>intersection</code> method in this class. I will write my utility for your case in following:</p>\n\n<pre><code>public &lt;T&gt; Collection&lt;T&gt; intersection(T[] one, T[] two)\n{\n List&lt;T&gt; list_one = Arrays.asList(one);\n List&lt;T&gt; list_two = Arrays.asList(two);\n\n List&lt;T&gt; intersection = (List&lt;T&gt;) org.apache.commons.collections\n .CollectionUtils.intersection(list_one, list_two);\n\n return intersection;\n}\n</code></pre>\n\n<p>I hope my answer will useful for you.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-03-18T10:42:28.580", "Id": "10121", "ParentId": "9909", "Score": "0" } } ]
{ "AcceptedAnswerId": "9911", "CommentCount": "3", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-03-12T10:01:16.913", "Id": "9909", "Score": "7", "Tags": [ "java", "optimization", "array" ], "Title": "Finding the Intersection of Arrays" }
9909
<p>This <code>HostResolve</code> procedure runs on a thread separately, to not interrupt other working functions. I would like to ask here if this procedure is correctly written or not?</p> <p>Any recommendations and improvements, if any one willing to help?</p> <pre><code>Procedure HostResolve(); const URL : array[1..4] of String =('facebook.com', 'google.com', 'yahoo.com', 'gmail.com'); var IP:String; IsConnected:Boolean; i:integer; begin IsConnected := false; While true do begin if IsConnectedToInternet then begin if IsConnected = false then begin // for i := Low(URL) to High(URL) do begin if HostToIp(URL[i], IP) then begin ShowMessage(IP); IsConnected := true; Break; end; end; // end; end else begin IsConnected := false; end; Sleep(1000); end; end; Function IsConnectedToInternet: Boolean; var dwConnectionTypes: DWORD; begin dwConnectionTypes := INTERNET_CONNECTION_MODEM + INTERNET_CONNECTION_LAN + INTERNET_CONNECTION_PROXY; Result := InternetGetConnectedState(@dwConnectionTypes, 0); end; Function HostToIP(sHost: string; var sIP: string):Boolean; var aHostName: array[0..255] of Char; pcAddr : PChar; HostEnt : PHostEnt; wsData : TWSAData; begin WSAStartup($0101, wsData); try GetHostName(aHostName, SizeOf(aHostName)); StrPCopy(aHostName, sHost); hostEnt := GetHostByName(aHostName); if Assigned(HostEnt) then if Assigned(HostEnt^.H_Addr_List) then begin pcAddr := HostEnt^.H_Addr_List^; if Assigned(pcAddr) then begin sIP := Format('%d.%d.%d.%d', [Byte(pcAddr[0]), Byte(pcAddr[1]), Byte(pcAddr[2]), Byte(pcAddr[3])]); Result := True; end else Result := False; end else Result := False else begin Result := False; end; finally WSACleanup; end; end; </code></pre>
[ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2015-02-19T08:12:24.370", "Id": "147380", "Score": "0", "body": "@Greenonline do not edit code unless you are sure this is due to copy and paste errors." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2015-02-19T08:15:33.143", "Id": "147381", "Score": "0", "body": "Ok, sorry. I was just trying to indent so as to make the code a bit more readable. The _begin_s and _end_s didn't line up correctly, and made it a bit hard to read. As were the blank lines. I hoped that it would help someone to provide an answer. :-)" } ]
[]
{ "AcceptedAnswerId": null, "CommentCount": "2", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-03-12T11:24:08.050", "Id": "9912", "Score": "1", "Tags": [ "delphi" ], "Title": "Internet Connectivty and Resolve host" }
9912
<p>I'm new To C++ and decided to have a go at the <a href="https://labs.spotify.com/puzzles/" rel="nofollow">Spotify challenges</a> on their website.</p> <p>I have now finished but I get the feeling my code is just terrible. I'm guessing it would be very hard for someone else to read and I feel like there are much better ways to code this.</p> <p>Their "Best Before" puzzle asks: Given a possibly ambiguous date written in "A/B/C" format, where A,B,C are integers between 0 and 2999, interpret them as M/D/Y or D/M/Y or whatever common date format. Pick the interpretation that yields the earliest possible legal date between Jan 1, 2000 and Dec 31, 2999 (inclusive) in "YYYY-MM-DD" format. If the string cannot be interpreted as a valid date, state so.</p> <p>Here is my code for the best before puzzle:</p> <pre><code>#include &lt;iostream&gt; #include &lt;string&gt; #include &lt;sstream&gt; #include &lt;iomanip&gt; using namespace std; int Year; int Month; int Day; stringstream ss; string input; string in; bool loop=true; int date[4]; bool DateFound=false; void Check_date(); void Check_date() { if(DateFound==false) { //Check if valid Year if (date[1]&lt;2999 &amp;&amp; date[1]&gt;0 &amp;&amp; date[2]&gt;0 &amp;&amp; date[3]&gt;0) { //check months &amp; days are valid if(date[2]==1 || date[2]==3 || date[2]==5 || date[2]==7 || date[2]==8 || date[2]==10 || date[2]==12){if(date[3]&lt;=31){DateFound=true;}} if(date[2]==4 || date[2]==6 || date[2]==9 || date[2]==11){if(date[3]&lt;=30){DateFound=true;}} //Check For Leap Year if (date[2]==2) { if(date[3]&lt;28)DateFound=true; if(date[1]%4==0 &amp;&amp; date[3]&lt;=29)DateFound=true; if(date[1]%100==0 &amp;&amp; date[1]%400!=0 &amp;&amp; date[3]&gt;28)DateFound=false; } } if(DateFound==true){Year=date[1]; Month=date[2]; Day=date[3];if(Year&lt;1000){Year=Year+2000;} if(Month&lt;10){}} } } void SwitchDate(){int temp; temp=date[2]; date[2]=date[3]; date[3]=temp; Check_date();}; void ShiftDate(int places) { if(places==1) { int temp; temp=date[3]; date[3]=date[2]; date[2]=temp; temp=date[1]; date[1]=date[2]; date[2]=temp; Check_date(); } if(places==2) { int temp; temp=date[1]; date[1]=date[2]; date[2]=temp; temp=date[2]; date[2]=date[3]; date[3]=temp; Check_date(); } }; int main () { //Main Loop while(loop==true) { cout &lt;&lt;"Please Enter a date \n"; cin&gt;&gt;input; cout&lt;&lt;endl; for (int x=0, y=1; y&lt;=3; y++, x++) { while (input[x] !='/' &amp;&amp; x !=input.length()) ss&lt;&lt;input[x++]; ss&gt;&gt; date[y]; ss.clear(); } //order small medium large for (int x=3, temp; x!=0; x--) { if (date[x] &lt; date[x-1]) { temp=date[x-1]; date[x-1]=date[x]; date[x]=temp; } if (x==1 &amp;&amp; (date[2] &gt; date[3] )) { temp=date[3]; date[3]=date[2]; date[2]=temp; } } Check_date(); SwitchDate(); ShiftDate(1); SwitchDate(); ShiftDate(2); SwitchDate(); //PRINT if(DateFound==true) { cout &lt;&lt;"The smallest valid date is: "; cout &lt;&lt;setw(2)&lt;&lt;setfill('0')&lt;&lt;Year; cout&lt;&lt;"-"; cout &lt;&lt;setw(2)&lt;&lt;setfill('0')&lt;&lt;Month; cout&lt;&lt;"-" ; cout &lt;&lt;setw(2)&lt;&lt;setfill('0')&lt;&lt;Day; cout&lt;&lt;endl; } else cout&lt;&lt;date[1]&lt;&lt;"/"&lt;&lt;date[2]&lt;&lt;"/"&lt;&lt;date[3]&lt;&lt;" Is illegal \n"; DateFound=false; cout &lt;&lt;"Again? 'Y' or 'N' \n"; cin &gt;&gt;in; cout &lt;&lt; endl; if(in=="y" || in=="Y"){loop=true;} if(in=="n" || in=="N"){loop=false;} }//End of Loop } </code></pre>
[]
[ { "body": "<ol>\n<li><p>You should avoid using global variables. If you import this code into a future project it might cause problems -- name conflicts etc.</p>\n\n<p>If you must do this, put them in an anonymous namespace so that they're only in scope for this file:</p>\n\n<pre><code>namespace\n{\n int my;\n int globals;\n int defined;\n int here;\n}\n</code></pre></li>\n<li><p>The declaration of <code>Check_date()</code> is not necessary here:</p>\n\n<pre><code>void Check_date();\nvoid Check_date()\n{\n</code></pre></li>\n<li><p>This could perhaps written better:</p>\n\n<pre><code>for (int x=0, y=1; y&lt;=3; y++, x++)\n{\n while (input[x] !='/' &amp;&amp; x !=input.length()) ss&lt;&lt;input[x++];\n ss&gt;&gt; date[y];\n ss.clear();\n}\n</code></pre>\n\n<p>There is little point using x in the for loop as you don't have an exit condition for it. Also, I would prefer a more meaningful name.</p>\n\n<p>Instead, perhaps:</p>\n\n<pre><code>int inputPos = 0;\nfor(int dateIndex = 1; dateIndex &lt;= 3; ++dateIndex)\n{\n while(input[inputPos] != '/' &amp;&amp; inputPos != input.length()) \n {\n ss &gt;&gt; date[dateIndex];\n ss.clear();\n }\n ++inputPos;\n}\n</code></pre></li>\n<li><p>More generally you've written this in a very C-like style -- I would have defined a type (class) for <code>Date</code>, which would have month and day members. Then the logic for whether month lengths are valid can be encapsulated properly.</p>\n\n<p>You could also encapsulate the read-from-stream code using an <a href=\"http://www.cplusplus.com/istream::operator%3E%3E\" rel=\"nofollow\" title=\"C++ extractor\">iostreams extractor</a>.</p></li>\n</ol>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-03-12T13:16:31.530", "Id": "9917", "ParentId": "9915", "Score": "4" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-03-10T15:43:47.167", "Id": "9915", "Score": "6", "Tags": [ "c++", "beginner", "parsing", "programming-challenge", "datetime" ], "Title": "\"Best before\" puzzle" }
9915
<p>I'm new to AJAX and am trying to learn by myself with a small test:</p> <p>It's a survey with 3 questions. I would like to know if I'm using AJAX the correct way, before starting bigger projects.</p> <p>Here is the question.xhtml page:</p> <pre class="lang-xml prettyprint-override"><code>&lt;?xml version='1.0' encoding='UTF-8' ?&gt; &lt;!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"&gt; &lt;html xmlns="http://www.w3.org/1999/xhtml" xmlns:p="http://primefaces.org/ui" xmlns:f="http://java.sun.com/jsf/core" xmlns:h="http://java.sun.com/jsf/html"&gt; &lt;h:head&gt; &lt;title&gt;Question page&lt;/title&gt; &lt;/h:head&gt; &lt;h:body&gt; &lt;h1&gt;Question page&lt;/h1&gt; &lt;h3&gt;Regular HTML Form&lt;/h3&gt; &lt;h:form id="survey"&gt; Over: &lt;h:outputText value="#{generalController.over}" id="testover"/&gt;&lt;br/&gt; &lt;h:outputText id="question" value="#{generalController.getQuestion()}"/&gt; &lt;p:inputText id="answer" value="#{generalController.answer}"/&gt;&lt;br/&gt; &lt;h:commandButton id="submit" value="Next" rendered="#{!generalController.last}"&gt; &lt;f:ajax execute="answer" render="survey"/&gt; &lt;/h:commandButton&gt; &lt;h:commandButton id="done" value="Finish" rendered="#{generalController.last}" action="end"/&gt; &lt;/h:form&gt; &lt;br/&gt; &lt;h3&gt;PrimeFace Form&lt;/h3&gt; &lt;h:form id="pfsurvey"&gt; Over: &lt;h:outputText value="#{generalController.over}" id="testover"/&gt;&lt;br/&gt; &lt;h:outputText id="question" value="#{generalController.getQuestion()}"/&gt; &lt;p:inputText id="answer" value="#{generalController.answer}" rendered="#{!generalController.over}"/&gt;&lt;br/&gt; &lt;p:commandButton id="submit" value="Next" rendered="#{!generalController.last}" update="pfsurvey" actionListener="#{generalController.next}" /&gt; &lt;p:commandButton id="done" value="Finish" rendered="#{generalController.last}" action="end" ajax="false" /&gt; &lt;/h:form&gt; &lt;/h:body&gt; &lt;/html&gt; </code></pre> <p>The <code>GeneralController</code> bean is:</p> <pre class="lang-java prettyprint-override"><code>import javax.inject.Named; import javax.inject.Inject; import javax.enterprise.context.ApplicationScoped; @Named(value = "generalController") @ApplicationScoped public class GeneralController { String[] questions = {"What is your age?","Where do you come from?","Are you married?"}; String answer; String question; int currentQuestion = 0; boolean over = false; boolean last = false; public String getAnswer() { System.out.println("Get Answer"); return answer; } public void setAnswer(String answer) { System.out.println("Set Answer"); if(currentQuestion &lt; questions.length) { System.out.println("To the question \""+questions[currentQuestion]+"\" your answer is "+answer); currentQuestion++; if(currentQuestion == questions.length -1) last = true; if(currentQuestion == questions.length) over = true; } } public String getQuestion() { System.out.println("Get Question"); if(!over) return questions[currentQuestion]; else return ""; } public void setQuestion(String question) { System.out.println("Set Question"); this.question = question; } public void next() { System.out.println("Next"); } public String reset() { currentQuestion=0; over=false; last=true; return "question"; } public boolean isOver() { return over; } public void setOver(boolean over) { this.over = over; } public boolean isLast() { return last; } public void setLast(boolean last) { this.last = last; } } </code></pre> <p>When the survey is done, it's redirected to the end.xhtml page:</p> <pre class="lang-xml prettyprint-override"><code>&lt;?xml version='1.0' encoding='UTF-8' ?&gt; &lt;!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"&gt; &lt;html xmlns="http://www.w3.org/1999/xhtml" xmlns:p="http://primefaces.org/ui" xmlns:h="http://java.sun.com/jsf/html"&gt; &lt;h:head&gt; &lt;title&gt;Facelet Title&lt;/title&gt; &lt;/h:head&gt; &lt;h:body&gt; Survey is done ! Thank you &lt;h:form&gt; &lt;p:commandButton value="Try Again" ajax="false" action="#{generalController.reset()}"/&gt; &lt;/h:form&gt; &lt;/h:body&gt; &lt;/html&gt; </code></pre> <p>Here is the generated HTML:</p> <p>Question 1:</p> <pre class="lang-xml prettyprint-override"><code>&lt;?xml version='1.0' encoding='UTF-8' ?&gt; &lt;!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"&gt; &lt;html xmlns="http://www.w3.org/1999/xhtml"&gt;&lt;head&gt;&lt;link type="text/css" rel="stylesheet" href="/MenuMobile3/faces/javax.faces.resource/theme.css?ln=primefaces-humanity" /&gt;&lt;link type="text/css" rel="stylesheet" href="/MenuMobile3/faces/javax.faces.resource/primefaces.css?ln=primefaces&amp;amp;v=3.1.1" /&gt;&lt;script type="text/javascript" src="/MenuMobile3/faces/javax.faces.resource/jquery/jquery.js?ln=primefaces&amp;amp;v=3.1.1"&gt;&lt;/script&gt;&lt;script type="text/javascript" src="/MenuMobile3/faces/javax.faces.resource/primefaces.js?ln=primefaces&amp;amp;v=3.1.1"&gt;&lt;/script&gt;&lt;script type="text/javascript" src="/MenuMobile3/faces/javax.faces.resource/jsf.js?ln=javax.faces&amp;amp;stage=Development"&gt;&lt;/script&gt; &lt;title&gt;Question page&lt;/title&gt;&lt;/head&gt;&lt;body&gt; &lt;h1&gt;Question page&lt;/h1&gt; &lt;h3&gt;Regular HTML Form&lt;/h3&gt; &lt;form id="survey" name="survey" method="post" action="/MenuMobile3/faces/question.xhtml" enctype="application/x-www-form-urlencoded"&gt; &lt;input type="hidden" name="survey" value="survey" /&gt; Over: &lt;span id="survey:testover"&gt;false&lt;/span&gt;&lt;br /&gt;&lt;span id="survey:question"&gt;What is your age?&lt;/span&gt;&lt;input id="survey:answer" name="survey:answer" type="text" class="ui-inputfield ui-inputtext ui-widget ui-state-default ui-corner-all" /&gt;&lt;script id="survey:answer_s" type="text/javascript"&gt;PrimeFaces.cw('InputText','widget_survey_answer',{id:'survey:answer'});&lt;/script&gt;&lt;br /&gt;&lt;input id="survey:submit" type="submit" name="survey:submit" value="Next" onclick="mojarra.ab(this,event,'action','survey:answer','survey');return false" /&gt;&lt;input type="hidden" name="javax.faces.ViewState" id="javax.faces.ViewState" value="-8356752339157975334:-3520173479150310510" autocomplete="off" /&gt; &lt;/form&gt; &lt;br /&gt; &lt;h3&gt;PrimeFace Form&lt;/h3&gt; &lt;form id="pfsurvey" name="pfsurvey" method="post" action="/MenuMobile3/faces/question.xhtml" enctype="application/x-www-form-urlencoded"&gt; &lt;input type="hidden" name="pfsurvey" value="pfsurvey" /&gt; Over: &lt;span id="pfsurvey:testover"&gt;false&lt;/span&gt;&lt;br /&gt;&lt;span id="pfsurvey:question"&gt;What is your age?&lt;/span&gt;&lt;input id="pfsurvey:answer" name="pfsurvey:answer" type="text" class="ui-inputfield ui-inputtext ui-widget ui-state-default ui-corner-all" /&gt;&lt;script id="pfsurvey:answer_s" type="text/javascript"&gt;PrimeFaces.cw('InputText','widget_pfsurvey_answer',{id:'pfsurvey:answer'});&lt;/script&gt;&lt;br /&gt;&lt;button id="pfsurvey:submit" name="pfsurvey:submit" class="ui-button ui-widget ui-state-default ui-corner-all ui-button-text-only" onclick="PrimeFaces.ab({formId:'pfsurvey',source:'pfsurvey:submit',process:'@all',update:'pfsurvey'});return false;" type="submit"&gt;&lt;span class="ui-button-text"&gt;Next&lt;/span&gt;&lt;/button&gt;&lt;script id="pfsurvey:submit_s" type="text/javascript"&gt;PrimeFaces.cw('CommandButton','widget_pfsurvey_submit',{id:'pfsurvey:submit'});&lt;/script&gt;&lt;input type="hidden" name="javax.faces.ViewState" id="javax.faces.ViewState" value="-8356752339157975334:-3520173479150310510" autocomplete="off" /&gt; &lt;/form&gt;&lt;/body&gt; &lt;/html&gt; </code></pre> <p>Question 3:</p> <pre class="lang-xml prettyprint-override"><code>&lt;?xml version='1.0' encoding='UTF-8' ?&gt; &lt;!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"&gt; &lt;html xmlns="http://www.w3.org/1999/xhtml"&gt;&lt;head&gt;&lt;link type="text/css" rel="stylesheet" href="/MenuMobile3/faces/javax.faces.resource/theme.css?ln=primefaces-humanity" /&gt;&lt;link type="text/css" rel="stylesheet" href="/MenuMobile3/faces/javax.faces.resource/primefaces.css?ln=primefaces&amp;amp;v=3.1.1" /&gt;&lt;script type="text/javascript" src="/MenuMobile3/faces/javax.faces.resource/jquery/jquery.js?ln=primefaces&amp;amp;v=3.1.1"&gt;&lt;/script&gt;&lt;script type="text/javascript" src="/MenuMobile3/faces/javax.faces.resource/primefaces.js?ln=primefaces&amp;amp;v=3.1.1"&gt;&lt;/script&gt;&lt;script type="text/javascript" src="/MenuMobile3/faces/javax.faces.resource/jsf.js?ln=javax.faces&amp;amp;stage=Development"&gt;&lt;/script&gt; &lt;title&gt;Question page&lt;/title&gt;&lt;/head&gt;&lt;body&gt; &lt;h1&gt;Question page&lt;/h1&gt; &lt;h3&gt;Regular HTML Form&lt;/h3&gt; &lt;form id="survey" name="survey" method="post" action="/MenuMobile3/faces/question.xhtml" enctype="application/x-www-form-urlencoded"&gt; &lt;input type="hidden" name="survey" value="survey" /&gt; Over: &lt;span id="survey:testover"&gt;false&lt;/span&gt;&lt;br /&gt;&lt;span id="survey:question"&gt;What is your age?&lt;/span&gt;&lt;input id="survey:answer" name="survey:answer" type="text" class="ui-inputfield ui-inputtext ui-widget ui-state-default ui-corner-all" /&gt;&lt;script id="survey:answer_s" type="text/javascript"&gt;PrimeFaces.cw('InputText','widget_survey_answer',{id:'survey:answer'});&lt;/script&gt;&lt;br /&gt;&lt;input id="survey:submit" type="submit" name="survey:submit" value="Next" onclick="mojarra.ab(this,event,'action','survey:answer','survey');return false" /&gt;&lt;input type="hidden" name="javax.faces.ViewState" id="javax.faces.ViewState" value="-8356752339157975334:-3520173479150310510" autocomplete="off" /&gt; &lt;/form&gt; &lt;br /&gt; &lt;h3&gt;PrimeFace Form&lt;/h3&gt; &lt;form id="pfsurvey" name="pfsurvey" method="post" action="/MenuMobile3/faces/question.xhtml" enctype="application/x-www-form-urlencoded"&gt; &lt;input type="hidden" name="pfsurvey" value="pfsurvey" /&gt; Over: &lt;span id="pfsurvey:testover"&gt;false&lt;/span&gt;&lt;br /&gt;&lt;span id="pfsurvey:question"&gt;What is your age?&lt;/span&gt;&lt;input id="pfsurvey:answer" name="pfsurvey:answer" type="text" class="ui-inputfield ui-inputtext ui-widget ui-state-default ui-corner-all" /&gt;&lt;script id="pfsurvey:answer_s" type="text/javascript"&gt;PrimeFaces.cw('InputText','widget_pfsurvey_answer',{id:'pfsurvey:answer'});&lt;/script&gt;&lt;br /&gt;&lt;button id="pfsurvey:submit" name="pfsurvey:submit" class="ui-button ui-widget ui-state-default ui-corner-all ui-button-text-only" onclick="PrimeFaces.ab({formId:'pfsurvey',source:'pfsurvey:submit',process:'@all',update:'pfsurvey'});return false;" type="submit"&gt;&lt;span class="ui-button-text"&gt;Next&lt;/span&gt;&lt;/button&gt;&lt;script id="pfsurvey:submit_s" type="text/javascript"&gt;PrimeFaces.cw('CommandButton','widget_pfsurvey_submit',{id:'pfsurvey:submit'});&lt;/script&gt;&lt;input type="hidden" name="javax.faces.ViewState" id="javax.faces.ViewState" value="-8356752339157975334:-3520173479150310510" autocomplete="off" /&gt; &lt;/form&gt;&lt;/body&gt; &lt;/html&gt; </code></pre>
[ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-03-10T19:33:29.787", "Id": "15787", "Score": "1", "body": "Your code looks fine. Nothing to complain about. Just a minor comment on your backing bean code: I would always use brackets for if/else constructs, even if there is only on command in each branch. This improves readability and is less error prone." } ]
[ { "body": "<ol>\n<li><pre><code>@ApplicationScoped\npublic class GeneralController {\n ...\n}\n</code></pre>\n\n<p>I think your bean should be <code>@SessionScoped</code> instead of <code>@ApplicationScoped</code>. Otherwise all of you clients will use the same controller instance.</p></li>\n<li><p>Instead of an array I'd use a <code>List</code>. It's easier to work with.</p>\n\n<pre><code>String[] questions = {\"What is your age?\",\"Where do you come from?\",\"Are you married?\"};\n</code></pre>\n\n<p><a href=\"https://stackoverflow.com/q/1589813/843804\">When to use a List over an Array in Java?</a></p></li>\n<li><p>You could format the code better:</p>\n\n<pre><code>if(!over)\nreturn questions[currentQuestion];\n</code></pre>\n\n<p>According to the <a href=\"http://www.oracle.com/technetwork/java/javase/documentation/codeconventions-142311.html#449\" rel=\"nofollow noreferrer\">Code Conventions for the Java Programming Language</a> <code>if</code> statements always should use braces. Omitting them is error-prone, and hard to read if you don't indent the conditional statement like above.</p></li>\n<li><p>The fields could be <a href=\"https://softwareengineering.stackexchange.com/q/143736/36726\">private</a> instead of the current package private.</p>\n\n<blockquote>\n <p>The rule of thumb is simple: make each class or member as inaccessible as\n possible. In other words, use the lowest possible access level consistent with the\n proper functioning of the software that you are writing.</p>\n</blockquote>\n\n<p>Source: <em>Effective Java 2nd Edition</em>, <em>Item 13: Minimize the accessibility of classes and members</em>, p68.</p></li>\n</ol>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-02-25T11:31:39.380", "Id": "42751", "ParentId": "9916", "Score": "6" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "1", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-03-10T18:32:12.040", "Id": "9916", "Score": "5", "Tags": [ "java", "beginner", "xml", "ajax", "jsf" ], "Title": "Survey program using JSF and Ajax" }
9916
<p>How can this be optimized?</p> <pre><code>char *crunch(char *s) { char *temp,buff[MAX]; int repeat,count,i,j,k; if (*s == '\0') return NULL; temp = (char*)malloc((strlen(s) + 1) * sizeof(char)); if (isdigit(*s)) return NULL; repeat = 0; for (i = 0, j = 0;i &lt; strlen(s);) { temp[j++] = s[i++]; count = 1; while (s[i] == s[i - 1]) { count++; i++; repeat = 1; } if (isdigit(s[i]) &amp;&amp; repeat == 1) return NULL; if (isdigit(s[i]) &amp;&amp; count != 1) return NULL; else if (isalpha(s[i]) &amp;&amp; count != 1) { temp[j++] = count + 48; } else if (isdigit(s[i])) { for (k = 1;k &lt; (s[i] - 48);k++) temp[j++] = s[i - 1]; i++; } } temp[j] = '\0'; return temp; } </code></pre> <p>Examples:</p> <p>Input: "aabbccdef"<br> Output: "a2b2c2def"</p> <p>Input: "a4bd2g4"<br> Output: "aaaabddgggg"</p>
[ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-03-12T13:20:34.423", "Id": "15789", "Score": "0", "body": "You have to be way more specific about your \"string crunching\" algorithm" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-03-12T13:21:27.107", "Id": "15790", "Score": "3", "body": "That sounds like a \"run-length encoding\" implementation." } ]
[ { "body": "<p>Suggestions for improving this code:</p>\n\n<ol>\n<li><p>Comment the hell out of it. Your teacher/professor needs to be able to understand what you're doing and why you're doing it. Imagine you're working on a real-world project and you fall off a cliff--your teammates need to be able to pick up after you. Comments exist for this purpose.</p></li>\n<li><p>Clean up your whitespace. The statements executed in a branch (e.g. <code>if (foo) { bar; }</code>) should be placed on their own lines. This makes it easier to see at-a-glance what is the consequence of what.</p></li>\n</ol>\n\n<p>I have not examined the actual logic of the program.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-03-12T13:25:44.297", "Id": "15791", "Score": "0", "body": "please check it Jonathan and thank you for your suggestions..." } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-03-12T13:23:42.113", "Id": "9921", "ParentId": "9920", "Score": "2" } }, { "body": "<p>As written by Jonathan and</p>\n\n<ul>\n<li>Always put a blank line after every <code>}</code></li>\n<li>Always use { } even for single line <code>if</code>/<code>for</code>/<code>while</code>. There is a class of errors where you add a second line in the if but it isn't \"in\" the if, it is outside. Something like:</li>\n</ul>\n\n\n\n<pre><code>if (1 == 1)\n do something\n</code></pre>\n\n<p>and then you change it in </p>\n\n<pre><code>if (1 == 1)\n do something\n do something else\n</code></pre>\n\n<p>the <code>do something else</code> isn't in the if, even if you spaced it like it was :-)</p>\n\n<p>If you don't want to use the <code>{}</code> a good style that solves it is to put the second part of the instruction in the same line</p>\n\n<pre><code>if (1 == 1) do something\n</code></pre>\n\n<p>I don't like it very much (because it makes the line longer to the right) but it is more difficult you make the \"bad\" error of missing <code>{}</code></p>\n\n<p>The <code>strlen</code> can be pre-calculated once. </p>\n\n<p>The <code>if (isdigit(*s))</code> can be put before the malloc.</p>\n\n<p>If you <code>malloc</code> a block of memory and then <code>return NULL</code> you should free the block of memory, otherwise you cause a memory leak.</p>\n\n<p>Please, don't use the pre-fix/post-fix increment operator in the middle of other instructions, they make the code less readable. </p>\n\n<p>This</p>\n\n<pre><code>temp[j++] = s[i++];\n</code></pre>\n\n<p>is the same as</p>\n\n<pre><code>temp[j] = s[i];\ni++;\nj++;\n</code></pre>\n\n<p>but the second is much more readable, because you don't have to think to the order of the operations.</p>\n\n<p>If you have to decompress the string (from a4bd2g4 to aaaabddgggg) the buffer size is too much small.</p>\n\n<p>Considering the compression and decompression are quite different, I would do it in two passes:</p>\n\n<p>first pass: sum all the digits and count all the characters. If the sum is zero the it's compression, do it in function 1. If sum &lt;> 0 it is decompression. With the sum of the digits and the count of the characters you know the size of the buffer you'll need.</p>\n\n<p>If you want to impress your teacher, you should make it work for aaaaaaaaaa (it is 10x a)... It would compress to a9a and aaaaaaaaaaa (11x a) a9a2.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-03-12T13:49:44.230", "Id": "15793", "Score": "0", "body": "no...if the sum is > 0 then you cannot always say its decompression because a4bbbc2 is an invalid string..." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-03-12T16:05:19.587", "Id": "15805", "Score": "0", "body": "@mmuttam The correctness check can be made in the second function." } ], "meta_data": { "CommentCount": "2", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-03-12T13:36:40.863", "Id": "9922", "ParentId": "9920", "Score": "5" } }, { "body": "<h2>Algorithm</h2>\n\n<ol>\n<li>It feels wrong to put both versions of the code in one single function. It would make more sense to have an <code>encode</code> and <code>decode</code> function.</li>\n<li>Your code doesn't work for <code>a10</code> or <code>aaaaaaaaaaaaaa</code>.</li>\n<li>You are lucky your code doesn't segfault. For example, for \"a9\", temp is only two characters long, and you're writing in nine characters: you're writing outside of the allocated data! You should run throught the string once to see how much memory you're going to need.</li>\n</ol>\n\n<p>Otherwise, it is an intuitive algorithm.</p>\n\n<h2>Code</h2>\n\n<ol>\n<li>Comment your code!</li>\n<li>You don't use <code>buff</code>, remove it.</li>\n<li>The second <code>if</code> should be an <code>else if</code>.</li>\n<li>Use '0' instead of hardcoding 48.</li>\n<li>Convert <code>s[j]</code> into an int and use <code>for (k = 1; k &lt; n; k++)</code> which is easier to read.</li>\n</ol>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-03-12T13:49:11.180", "Id": "9925", "ParentId": "9920", "Score": "2" } }, { "body": "<p>Here are some comments on the code, some of which might be duplicates of what others have noted, so sorry for that.</p>\n\n<p>General points:</p>\n\n<ul>\n<li><p>When writing prose, one often starts with a sketch of the text and then sharpens it up, removing redundancies, contradictions, repetition etc. Coding is similar and your function looks like a first sketch. Many programmers stick with the first sketch, but you should aim for better. There are things in the function that make it obvious that you haven't refined the solution - that's ok: you are learning (aren't we all). You took the trouble to submit it for review which bodes well.</p></li>\n<li><p>I'm always suspicious of functions with nested loops. Sometimes, rarely, they are necessary, but in your case, as in most, they are undesirable.</p></li>\n<li><p>It also catches my attention when the same function is called with the same parameters several times. Again, this can sometimes be worth doing, but calling isdigit(s[i]) three times doesn't qualify.</p></li>\n<li><p>Many times people write dumb comments that explain the obvious. You pass this one with flying colours. But a header with some comments describing the interface and the purpose of the function is necessary.</p></li>\n</ul>\n\n<p>Specific points:</p>\n\n<ul>\n<li><p>A function needs to have a well defined job that is explained by its name. If a function is difficult to name it often indicates that it is not really a coherent function at all. Your function implies that the string is reduced in size, whereas in fact it is either reduced or expanded depending upon its contents. Better stated (thanks to @Jonathan Grynspan), it would be runlength_encode_decode; it would be better as two separate functions. Maybe the homework exercise was to write a single function, in which case it was perhaps badly defined. If it must be combined into one function, I would expect it to have two distinct parts, such as</p>\n\n<pre><code>static char * runlength_encode_decode(const char *s, char *buf, size_t size)\n{\n if (isdigit(*s))\n return NULL;\n\n if (strpbrk(s, \"0123456789\")) /* inefficient is s is long , but who cares? */\n decode(s, buf, size);\n else\n encode(s, buf, size);\n return buf;\n}\n</code></pre></li>\n<li><p><code>s</code> is not modified so make it <code>const</code></p></li>\n<li><p>variables are best defined one-per-line.</p></li>\n<li><p><code>malloc</code> does not need casting (in C) and needs checking for failure. The buffer is also too small. But arguably, <code>malloc</code> doesn't belong inside the function. It would be better to pass an output buffer and its size into the function. This simplifies recovery on failure as crunch() doesn't have to bother with freeing the buffer (which you don't anyway, although in your case it is an error).</p></li>\n<li><p><code>sizeof(char)</code> is 1 by definition in C. It is just noise, so please don't use it.</p></li>\n<li><p><code>strlen</code> should not be in the loop as it will be executed each time round the loop. The length of the string does not change, so do it just once at the start - if it is necessary at all.</p></li>\n<li><p><code>for</code>-loops are best if the control variable is modified in the 3rd part of the for() statement, not in the body of the loop.</p></li>\n<li><p>Your indices are arguably unnecessary. Instead of <code>temp[j++] = s[i++]</code> you can use <code>*temp++ = *s++</code> to perform the assignment and advance the pointers. Some people may object to this but it is a basic C idiom. You will see it often, so get used to it.</p></li>\n<li><p>The <code>while</code>-loop should be extracted to a separate function. It does something very specific - counting the span of the current character - easily defined and easily encapsulated in a function. Ignore anyone who complains about function call overheads (inline such small functions by all means). </p>\n\n<p>Something like this, for example, called before you increment <code>s</code>:</p>\n\n<pre><code>static int span(const char *s)\n{\n char str[2] = {0,0};\n str[0] = *s;\n return strspn(s, str);\n}\n</code></pre></li>\n<li><p>The three conditional statements would be better with brackets around the second condition - i.e. <code>(repeat == 1)</code> - to avoid depending upon knowing the operator precedence.</p></li>\n<li><p>the second <code>isdigit()</code> conditional is already covered by the first - <code>repeat</code> is only even 1 when count > 1</p></li>\n<li><p><code>count + 48</code> should be <code>count + '0'</code> but fails if count > 9</p></li>\n<li><p>The for-loop should be extracted into a separate function. See comments on the while-loop. Note that <code>(s[i] - 48)</code> will be repeated each time around the loop. </p>\n\n<p>Something like this, for example:</p>\n\n<pre><code>static char * dupchar(int ch, char * out, int n)\n{\n for ( ; n &gt; 0; --n)\n *out++ = ch;\n return out;\n}\n</code></pre></li>\n</ul>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-03-24T03:29:39.983", "Id": "10299", "ParentId": "9920", "Score": "1" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "2", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-03-12T13:18:08.980", "Id": "9920", "Score": "2", "Tags": [ "c", "strings", "homework" ], "Title": "String-crunching routine" }
9920
<p>I need to receive an XML post then process all the data, and do whatever I need to do with the data. I could be receiving anywhere from 60 to 100 values. I know what all the elements are going to be, and all except one is mandatory. For billing, it could either be credit card info or checking info, so I need to check the first child's name to see what the billing type is.</p> <p>Here is a cut-down example:</p> <pre class="lang-xml prettyprint-override"><code>&lt;XmlData&gt; &lt;FirstName&gt;FirstName&lt;/FirstName&gt; &lt;LastName&gt;LastName&lt;/LastName&gt; &lt;Address&gt;666 S st.&lt;/Address&gt; &lt;Email&gt;email@email.com&lt;/Email&gt; &lt;City&gt;Beverly Hills&lt;/City&gt; &lt;Zip&gt;90210&lt;/Zip&gt; &lt;PhoneNumber&gt;5555555555&lt;/PhoneNumber&gt; &lt;!-- 14more nodes --&gt; &lt;Billing&gt; &lt;CCType&gt;Visa&lt;/CCType&gt; &lt;CCNumber&gt;55554443332221&lt;/CCNumber&gt; &lt;! -- 8 More Nodes for billing --&gt; &lt;/Billing&gt; &lt;/XmlData&gt; </code></pre> <p>Now, here is how I am handling processing the data. In my <code>Page_Load</code>, I am first calling a method that will verify the XML is well formatted and not null(not posting this code). Next, I call a method that will read all the data and assign it private fields using LINQ to XML.</p> <pre class="lang-cs prettyprint-override"><code>private string firstName = string.Empty; private string lastName = string.Empty; private string address = string.Empty; private string email= string.Empty; private string city= string.Empty; private string zip = string.Empty; private Int64 phoneNumber; private string billingMethod = string.Empty; private string ccType = string.Empty; private Int64 ccNumber; private void ReadXml(){ using (StringReader sr = new StringReader(payload)) { xd = XDocument.Load(sr); } var node = xd.Root; //lets just make sure all the nodes we need are present, then continue //this is where billingMethod is assigned; after validating the Billing //node is present, it will check if I am getting credit card info or check //info, then assign "credit" or "check" to billingMethod ValidateNeededNodesPresent(node); if (errors.Count &gt; 0) { Response(); return; } //verify the nodes are not null, and assign them firstName= VerifyString(node.Element(XmlKey.FirstName).Value, XmlKey.FirstName); lastName= VerifyString(node.Element(XmlKey.LastName).Value, XmlKey.LastName); zip = ValidateStringMax(node.Element(XmlKey.Zip).Value, XmlKey.Zip, 5); email = VerifyString(node.Element(XmlKey.Email).Value, XmlKey.Email); address= VerifyString(node.Element(XmlKey.Address).Value, XmlKey.Address); city= ValidateData(node.Element(XmlKey.City).Value, XmlKey.City); phoneNumber = VerifyInt64(node.Element(XmlKey.PhoneNumber).Value, XmlKey.PhoneNumber); if(billingMethod == "credit") { ccNumber = VerifyInt64(node.Element(XmlKey.Billing).Element(XmlKey.CCNumber).Value, XmlKey.CCdNumber); ccType = VerifyString( node.Element(XmlKey.Billing).Element(XmlKey.CCType).Value, XmlKey.CCType); } } </code></pre> <p>Now, here is my list of verify classes that check to make sure the data is not null and in the correct format (<code>int</code>, <code>int64</code>, <code>DateTime</code>, etc.). If it is not in the correct format, it will add an error to errors. The way is grabs errors is by getting the error string from a dictionary, where the key is the XML node name, and the value is the error message:</p> <pre class="lang-cs prettyprint-override"><code>public Int64 VerifyInt64(string data, string element) { Int64 number = 0L; if (!Int64.TryParse(data, out number) || String.IsNullOrEmpty(data)) { errors.Add(ErrorDictionary.Errors[element]); } return number; } public string VerifyString(string data, string element) { if (String.IsNullOrEmpty(data) || String.IsNullOrEmpty(data)) { errorMessages.Add(ErrorDictionary.Errors[element]); } return data; } public string VerifyStringMax(string data, string element, int lengthMax) { if (data.Length &gt; lengthMax || String.IsNullOrEmpty(data)) { errors.Add(ErrorDictionary.Errors[element]); } return data; } </code></pre> <p>The code works fine, but I cant help but think that I did more than I needed to. I'm strictly speaking about how I'm reading the XML, validating data, and assigning values in this case.</p> <p>Is this code efficient? Is there a better way I can go about reading XML data and assigning values while validating the data?</p>
[]
[ { "body": "<p>If your main goal is to verify the document structure, you may try using an XSD. Once you have a schema doc defined, <a href=\"http://msdn.microsoft.com/en-us/library/bb387037.aspx\" rel=\"nofollow\">you can use some LINQ to XML extensions to perform the validation and get the error messages (if any) that result</a>. Additionally, you can <a href=\"http://www.w3schools.com/schema/schema_simple_attributes.asp\" rel=\"nofollow\">use XSD to define default values for missing elements/attributes</a>.</p>\n\n<p>Once you do that, the code can be simplified:</p>\n\n<pre><code> firstName= (string) node.Element(XmlKey.FirstName);\n lastName= (string) node.Element(XmlKey.LastName);\n zip = (string) node.Element(XmlKey.Zip);\n email = (string) node.Element(XmlKey.Email);\n address= (string) node.Element(XmlKey.Address);\n city= (string) node.Element(XmlKey.City);\n phoneNumber = (long) node.Element(XmlKey.PhoneNumber);\n\n if(billingMethod == \"credit\")\n {\n var billingElement = node.Element(XmlKey.Billing);\n ccNumber = (long) billingElement.Element(XmlKey.CCNumber);\n ccType = (string) billingElement.Element(XmlKey.CCType);\n }\n</code></pre>\n\n<p>Though, to be honest, this feels like you would save a lot of work having a data object for a user that can be serialized/deserialized via a <a href=\"http://msdn.microsoft.com/en-us/library/system.runtime.serialization.datacontractserializer.aspx\" rel=\"nofollow\">DataContractSerializer</a> rather than hand-building and parsing.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-03-12T19:57:28.630", "Id": "15817", "Score": "0", "body": "Unfortunately I am getting the XML from a 3rd party, so having any XML with XSD is out of the question." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-03-12T20:45:29.407", "Id": "15823", "Score": "0", "body": "@Chris Why? You don't need to store the XSD definition in the XML file. See this [StackOverflow question](http://stackoverflow.com/questions/1048764/validate-xml-schema-using-msxml-parser)." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-03-23T17:14:58.120", "Id": "16386", "Score": "0", "body": "You may note that the example provided within the first link does not put any XSD reference in the XML that is validated. While it is nice to have a reference to the XSD within the XML (when using the document in XML editors), it is not required for the LINQ to XML validation to work." } ], "meta_data": { "CommentCount": "3", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-03-12T18:31:56.333", "Id": "9938", "ParentId": "9930", "Score": "2" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-03-12T16:24:07.037", "Id": "9930", "Score": "1", "Tags": [ "c#", "validation", "xml" ], "Title": "Receiving an XML post and parsing" }
9930
<p>I would like to be able to use it with IE8 or earlier, so I'm staying away from newer array methods. I'm not an expert so my code may not be the most efficient choice, but it works.</p> <pre><code>var data = [ ["John", 2], ["Jenny", 3], ["John", 4], ["Beavis", 5]] var newarr = [["John",5]]; for (var x=0; x &lt; data.length; x++) { for (var y=0; y &lt; newarr.length+1; y++) { if (typeof newarr[y] !== 'undefined') { if (newarr[y][0] == data[x][0]) { newarr[y][1] = (newarr[y][1] + data[x][1]); break; } } else { newarr.push([data[x][0]]); newarr[y][1] = data[x][1]; break; } } } alert("newarr is: " + newarr); //if elements are similar, merge them. </code></pre> <p>Would like to find out if this is a decent way of doing it, or maybe there are other easier/less code ways of doing it. Maybe somebody sees an issue with this code that I do not. Thanks.</p>
[ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-03-12T19:13:04.580", "Id": "15814", "Score": "1", "body": "About your \"stay away from newer array methods\", have you considered [ES5-Shim](https://github.com/kriskowal/es5-shim)?" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-03-12T23:44:14.527", "Id": "15836", "Score": "1", "body": "You should not do `data.length` in the for loop for the end condition, declare length as a local variable and use that in the for loop." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-03-13T14:58:14.980", "Id": "15897", "Score": "1", "body": "@epascarello This impairs readability and conciseness. The improvement is probably non significant." } ]
[ { "body": "<p>Some general advice: </p>\n\n<ul>\n<li>You should use a function, even in this demonstration code. It's makes it clearer what the input and output are.</li>\n<li>You should chose better variable names. <code>newarr</code> doesn't make sense, since it's not \"new\" but pre-filled. And <code>x</code> and <code>y</code> should have names that reflect that they are the indexes of <code>data</code> and <code>newarr</code> respectively.</li>\n<li>It seems that the inner structure (<code>[\"John\", 5]</code>) could be better represented as an object (<code>{name: \"John\", value: 5}</code> or even <code>{\"John\": 5}</code>).</li>\n<li>It depends on what you are doing with your result, but it may be sensible not to modify <code>newarr</code>, but create a separate result array. </li>\n</ul>\n\n<p>Actually I just realize you are modifing <code>newarr</code> while iterating over it. That is something you never should do, since it's a potential for bugs. I haven't checked, but I'm quite sure that the code won't work the way you expect it to like that. </p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-03-13T10:17:26.153", "Id": "9957", "ParentId": "9931", "Score": "2" } }, { "body": "<p>You should take a look at the <a href=\"http://documentcloud.github.com/underscore/\" rel=\"nofollow\">Underscore javascript library</a>, which contains a number of methods for comparing and manipulating arrays and objects.</p>\n\n<p>I'm using the _.intersection and _.keys methods to compare your two objects. I've also taken the liberty of restructuring your arrays into objects, which I think makes more sense for what you're trying to do.</p>\n\n<pre><code>// Adds the values of keys that are the same between any two objects \nfunction addObjects(a, b) {\n var sameKeys = _.intersection(_.keys(a), _.keys(b)), // Creates array of similary keys. eg [\"John\", \"Jenny\", \"Amanda\"]\n sumObj = {}\n\n // Loop through sameKeys, and add values from both objects\n for(i=0; i &lt; sameKeys.length; i++) {\n var thisKey = sameKeys[i];\n sumObj[thisKey] = a[thisKey] + b[thisKey]; // eg. sumbObj[\"John\"] = a[\"John\"] + b[\"John\"] = 7 \n }\n\n return sumObj;\n}\n\nvar firstObj = {\n \"John\" : 2,\n \"Jenny\" : 3,\n \"Beavis\" : 5,\n \"Toby\": 6,\n \"Amanda\": 12\n}\n\nvar secondObj = {\n \"John\": 5,\n \"Jenny\": 18,\n \"Amanda\": 2\n}\n\n\nmySumObj = addObjects(firstObj, secondObj);\n/* \nmySumObj = {\n \"Amanda\": 14,\n \"Jenny\": 21,\n \"John\": 7\n}\n*/\n</code></pre>\n\n<p>I hope this helps you. It may help if you could explain a bit more what your end goal here is.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-03-13T14:33:24.013", "Id": "9976", "ParentId": "9931", "Score": "4" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "3", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-03-12T16:55:34.800", "Id": "9931", "Score": "2", "Tags": [ "javascript" ], "Title": "JavaScript - Comparing 2 arrays - Would like to check if I'm reinventing the wheel or am I good to go?" }
9931
<p>We are generating our data access code following this pattern: </p> <pre><code>public static IEnumerable&lt;SomeDataOutputDTO&gt; GetSomeData(SomeDataInputDTO dto, IDbConnection dbConnection) { var queryString = @"Some SQL query"; using (var command = (OracleCommand)dbConnection.CreateCommand()) { command.CommandText = queryString; command.BindByName = true; command.Parameters.Add("SomeParam", OracleDbType.Int16, dto.SomeParam, ParameterDirection.Input); command.Parameters.Add("SomeOtherParam", OracleDbType.Int16, dto.SomeOtherParam, ParameterDirection.Input); var success = false; try { using (var reader = command.ExecuteReader()) { success = true; while (reader.Read()) { object data; var newDto = new SomeDataOutputDTO(); data = reader["first_column"]; newDto.FirstColumn = (short)Convert.ChangeType(data, typeof(short)); data = reader["second_column"]; if (data != DBNull.Value) { newDto.SecondColumn = (short)Convert.ChangeType(data, typeof(short)); } yield return newDto; } } } finally { if (success) { QueryLogger.Debug(queryString, command.Parameters, "TheseQueries.GetSomeData"); } else { QueryLogger.Error(queryString, command.Parameters, "DocumentTypeQueries.GetDocumentTypesByApplyType"); } } } </code></pre> <p>I want to know if there are any pitfalls regarding this code. As you can see the control flow is a bit complex since it returns an Enumerable and to do that it contains a </p> <pre><code>yield return </code></pre> <p>statement. </p> <p>Note also that there are two using() blocks and one try block in the middle. The purpose of the try-finally block is to ensure proper logging of the query, in Error level if there was an error, or Debug level if the query ran OK. The purpose of the using blocks is to ensure proper disposal of the command and reader objects. </p> <p>The QueryLogger helper class uses log4net, not that it should matter much. </p> <p>Please also remember that this is code generated by a tool, so whether it's readable or easy to maintain is not a concern. My concerns are with proper resource disposal, proper logging, etc. </p> <p>Also, returning an IEnumerable is very important because it allows to use LINQ when consuming the results. Of particular interest when using LINQ are: </p> <ul> <li>Take / Skip</li> <li>ToLookup / ToDictionary</li> <li>ToList</li> <li>FirstOrDefault</li> </ul>
[ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-03-12T18:10:37.577", "Id": "15813", "Score": "0", "body": "It seems your code is badly indented, `try` doesn't match with `finally`." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-06-30T13:02:17.877", "Id": "380836", "Score": "0", "body": "Please do not change the code inside the question after getting a review. This possibly invalidates the answers provided." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-06-30T17:11:00.523", "Id": "380859", "Score": "0", "body": "@Mast the code didn't change, I accepted an edit with some reindents that's all" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-07-01T04:48:23.857", "Id": "380918", "Score": "0", "body": "Take a look at the [revision history](https://codereview.stackexchange.com/posts/9933/revisions) and click on 'side-by-side markdown' to see what exactly did change. It was more than indentation." } ]
[ { "body": "<p>Initially, I shared your concern over resource disposal. My assumption was that there was the possibility the command could be left hanging around in cases where you did not enumerate over the entire collection (as with something like FirstOrDefault).</p>\n\n<p>However, a few quick tests with a test project reveals that the using statement performs its clean-up as soon as you are done with the enumerator. A LINQ statement or a foreach loop may only partially traverse the results, but they both still clean up the enumerator when exiting scope.</p>\n\n<p>Keep in mind, though, that there is still potential confusion that might arise from the deferred execution of GetSomeData. The command doesn't execute until you start enumerating the result. If anything were to modify the data before between the time you call GetSomeData and when you enumerate the result, you could get different results than you expect.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-03-12T19:33:38.907", "Id": "15815", "Score": "0", "body": "+1 - Both the `foreach` and the LINQ statements clean up by calling `Dispose()` on the enumerator, which disposes any open using statements and executes finally blocks. The only case worth mentioning where neither would be executed is when you call `GetSomeData().GetEnumerator()` yourself and don't bother to call `Dispose()`. That's relatively uncommon, though." } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-03-12T17:52:34.977", "Id": "9935", "ParentId": "9933", "Score": "2" } }, { "body": "<p>Careful with <code>yield</code> and <code>Dispose</code>.</p>\n\n<p>It is true that <code>LINQ</code> and <code>foreach</code> call the <code>Dispose</code> method; but if you use the <code>Enumerator</code> manually (by using <code>MoveNext()</code> and <code>Current</code> etc.) for some reason you are also responsible to dispose the enumerator yourself. And a lot less seasoned developers simply forget to check or assume it's not needed at all. This is one of those major pitfalls that are not obvious without knowing the implementation details of your method.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2016-07-21T09:22:35.717", "Id": "135474", "ParentId": "9933", "Score": "1" } } ]
{ "AcceptedAnswerId": "9935", "CommentCount": "4", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-03-12T16:55:04.497", "Id": "9933", "Score": "1", "Tags": [ "c#" ], "Title": "Please critique my Enumerable DataReader with yield and log data access pattern" }
9933