body
stringlengths
25
86.7k
comments
list
answers
list
meta_data
dict
question_id
stringlengths
1
6
<p>I just spent the whole night writing this little script for my search engine. Now i want to improve it.</p> <p>Any ideas?</p> <pre><code>&lt;?php echo "KEYWORDS : ". $searchstring = "the and"; $sentence = "Skype Home is unavailable at the moment. Check back later to see your news and alerts. It's easy to start a conversation on Skype: Choose a contact and start talking Call a phone or mobile from the dial pad, or send an SMS."; echo "&lt;br&gt;&lt;br&gt;&lt;b&gt;ORIGINAL STRING&lt;/b&gt;&lt;br&gt;&lt;br&gt;$sentence"; $kt=split(' ',$searchstring); //Breaking the string to array of words $num=1; while(list($key,$val)=each($kt)){ // do not load sentence from session on first run! if($num&lt;=1){ } else { $sentence = $_SESSION['NewSentence']; } if($val&lt;&gt;" " and strlen($val) &gt; 0){ // make keyword bold and send entire sentence to session $_SESSION['NewSentence'] = eregi_replace ("$val", "&lt;b&gt;$val&lt;/b&gt;", $sentence); // output sentence with added keyword echo "&lt;br&gt;&lt;br&gt;$num bolding: &lt;b style='color:green;'&gt;$val&lt;/b&gt; &lt;br&gt;&lt;br&gt; ".$_SESSION['NewSentence']; $num++; } } // make all bold keywords to red` echo '&lt;br&gt;&lt;br&gt;&lt;b&gt;FINAL STRING&lt;/b&gt;&lt;br&gt;&lt;br&gt;'; echo $_SESSION['NewSentence'] = eregi_replace ("&lt;b&gt;", "&lt;b style='color:red'&gt;", $_SESSION['NewSentence']); //destroy session unset($_SESSION['NewSentence']); session_unregister($_SESSION['NewSentence']);?&gt; </code></pre>
[]
[ { "body": "<h1>Unused if statements</h1>\n\n<p>You have a <code>if($num&lt;=1)</code> statment that is empty, while your using <code>else</code>. Reverse the statement like this.</p>\n\n<pre><code>if ($num &gt; 1) {\n $sentence = $_SESSION['NewSentence'];\n}\n</code></pre>\n\n<h1>Ambiguous use of $_SESSION</h1>\n\n<p>You should not use <code>$_SESSION</code> as a storage unless you are going to use it in another session (read: new page load/refresh). At the end of your script you're destroying the session, if that's your intention use variables as placeholders and leave <code>$_SESSION</code> alone.</p>\n\n<h1>Hard to read code</h1>\n\n<p>You should always aim to make the code as readable as possible. Take for example look at <a href=\"https://github.com/php-fig/fig-standards/blob/master/accepted/PSR-1-basic-coding-standard.md\" rel=\"nofollow\">PSR-1</a> and <a href=\"https://github.com/php-fig/fig-standards/blob/master/accepted/PSR-2-coding-style-guide.md\" rel=\"nofollow\">PSR-2</a> to learn a coding <em>standard</em>.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-11-09T00:22:09.007", "Id": "18374", "ParentId": "18240", "Score": "2" } }, { "body": "<h1>Use of deprecated functions</h1>\n\n<p>Both <code>split()</code> and <code>eregi_replace()</code> are deprecated since PHP 5.3. Don't use them.</p>\n\n<p>Use <a href=\"http://php.net/manual/en/function.preg-replace.php\" rel=\"nofollow\"><code>preg_replace()</code></a> instead of <code>eregi_replace()</code> and <a href=\"http://php.net/manual/en/function.explode.php\" rel=\"nofollow\"><code>explode()</code></a> instead of <code>split()</code> Other alternatives are <a href=\"http://php.net/manual/en/function.str-replace.php\" rel=\"nofollow\"><code>str_replace()</code></a> and <a href=\"http://php.net/manual/en/function.preg-split.php\" rel=\"nofollow\"><code>preg_split()</code></a>.</p>\n\n<h1>Unexpected results</h1>\n\n<p>When the search string is lowercase, all replaced words will be lowercase too. The case of the original word is not preserved.</p>\n\n<h1>Unused variables</h1>\n\n<p>The <code>$key</code> variable is assigned but never used. In fact, the entire <code>while</code> loop is odd. Use a <code>foreach</code> loop instead, like so:</p>\n\n<pre><code>foreach($kt as $val) {\n ...\n</code></pre>\n\n<h2>Missing function</h2>\n\n<p>The code should be in a function. The function would require two parameters, the string and an array of words to highlight, and return the result string. The function should not echo anything (but I presume the echo statements are debugging things).</p>\n\n<h2>Old HTML</h2>\n\n<p>Although valid, the use of <code>&lt;b&gt;</code> tags is outdated. It describes formatting in a document layout, without specifying the need for the format. You should use html for layout and css for styling. Then you can replace the <code>&lt;b&gt;</code> with a <code>&lt;span class=\"highlight&gt;</code> (or any other sensible class name).</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-11-09T06:40:08.743", "Id": "18384", "ParentId": "18240", "Score": "4" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-11-05T08:48:35.210", "Id": "18240", "Score": "3", "Tags": [ "php" ], "Title": "php highlight search keywords [working solution]!" }
18240
<p>I am new at OOP and I wonder if the code below is OOP or it can be better and also what can be better?</p> <pre><code>class cForm{ private $_TagAction; private $_TagMethod; private $_TagName; private $_TagExtraAttr; //var form field private $_FieldType; private $_FieldName; //var button private $_ButtonValue; private $_ButtonName; public function __construct( $_TagAction , $_TagMethod , $_TagName , $_TagExtraAttr ){ $this-&gt;_TagAction = $_TagAction; $this-&gt;_TagMethod = $_TagMethod; $this-&gt;_TagName = $_TagName; $this-&gt;_TagExtraAttr = $_TagExtraAttr; } public function getTagOpen(){ return '&lt;form action="' . $this-&gt;_TagAction . '" method="' . $this-&gt;_TagMethod . '" name="' . $this-&gt;_TagName .'" ' . $this-&gt;_TagExtraAttr . '&gt;' . PHP_EOL; } public function setFormField( $FieldType , $FieldName ){ $this-&gt;_FieldType = $FieldType; $this-&gt;_FieldName = $FieldName; } public function getFormField(){ return '&lt;input type="' . $this-&gt;_FieldType . '" name="' . $this-&gt;_FieldName . '" &gt;'. PHP_EOL; } public function setButton( $ButtonValue , $ButtonName ){ $this-&gt;_ButtonValue = $ButtonValue; $this-&gt;_ButtonName = $ButtonName; } public function getButton(){ return '&lt;input type="submit" value="' . $this-&gt;_ButtonValue . '" name="'. $this-&gt;_ButtonName .'"&gt;'; } public function getTagEnd(){ return '&lt;/form&gt;' . PHP_EOL; } } $objForm = new cForm( '/' , 'post' , 'test' , 'onsubmit="test"' ); echo $objForm-&gt;getTagOpen(); echo $objForm-&gt;setFormField('text','2'); echo $objForm-&gt;getFormField(); echo $objForm-&gt;setButton('test value','test name'); echo $objForm-&gt;getButton(); echo $objForm-&gt;getTagEnd(); </code></pre>
[]
[ { "body": "<p>If you have more than one button or input field per form, or are ever using the same instance for more than one form, then no, this code is not OO at all. Even if you only have one, it's quite a stretch, and the way you're using it in your example is not very OO. If you'd set everything first and <em>then</em> echoed everything out, i could see the point. But pretty much all you're doing is splitting the functionality of generating an HTML element into half-procedures, and you're not even taking advantage of the few benefits of doing so.</p>\n\n<p>I was trying to come up with a way to objectify this, but each path amounts to a total rewrite. So instead, let's discuss principles, and how this class might be better written to be more OO.</p>\n\n<p>First off, an object is basically <em>data that does stuff</em>. As in, <em>active</em> data. Your class's approach makes data extremely passive, and amounts to the aforementioned \"half-procedures\" thing. It's all \"store params, generate element, store params, generate element\" etc. All you're doing is hiding procedures in objects.</p>\n\n<p>Secondly, your class seems to be violating the heck out of SRP, in that you have it doing no less than three <em>totally separate</em> things (generating form tags, generating buttons, and generating input fields) that are only logically linked by all having something to do with forms. They don't use the same fields, or any of the same methods. They don't even have to be associated with the same form! You basically have three separate classes masquerading as one.</p>\n\n<p>A class should have one clear, well-defined purpose. Like, in this case, <em>to generate a form</em>. I'd personally lose (or make private) the getters for the individual elements, and have one method that generates a form complete with buttons and inputs and opening and closing tags.</p>\n\n<p>Alternatively, you could break the class up into three...but that leaves the caller having to arrange form elements itself. You're not really gaining anything from using objects if the caller has to micromanage all the interactions. OOP is all about the objects doing most of those interactions on their own, and the caller just firing off requests to do <em>sets</em> of things. The more you can get objects to do independently, the more leverage you have, and the more you can get done with one method call.</p>\n\n<p>Oh, and namingwise:</p>\n\n<ul>\n<li>It's generally expected that when you <code>setSomething</code> and then <code>getSomething</code>, you get back the same thing you set, or at least something similar.</li>\n<li>Hungarian notation is dead. Let it rest in peace, by losing the <code>c</code> in <code>cForm</code>.</li>\n</ul>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-11-05T15:41:02.633", "Id": "18254", "ParentId": "18241", "Score": "2" } }, { "body": "<p>A very rough view I have about improving this is having a method in the class to create a form, not the class being a form, leading to a separate instance for each form; Just this is just a brief extension of what cHao mentioned at the beginning.</p>\n\n<pre><code>class cForm\n{\n public function __construct()\n {\n //let it set some global html values related to the charset or something.\n }\n\n public function createForm()\n {\n //The old construct\n }\n\n public function generateFormElement($formAttributes/*, optional parameters*/)\n {\n if(is_array($formAttributes))\n {\n //break down the array and generate form elements, add checks to suit each type.\n }else if(isset(/*optional variables, i.e. form type, etc.*/ $optional))\n {\n //create the form from provided information\n }\n }\n}\n</code></pre>\n\n<p><strong>Usability</strong></p>\n\n<ul>\n<li>Next on, you're not adding anything special to creation of forms using this class, - personally, I'd enjoy writing pure html than using functions that might make my work harder and not worthy.</li>\n</ul>\n\n<p>For example, have you taken a look at the form generator of codeigniter or even zend? They provide security according to the field type or specific parameters provided to the function.</p>\n\n<ul>\n<li>Have you noticed that all those functions could be swallowed down to one or 2 functions?\nIn the end, you're creating input tags, all you need is to improvise and add in some clever ways to set different types of forms in different situations needed e.g. generateFormElement function.</li>\n</ul>\n\n<p>And you have the simplest possible flexible module that might suit custom use. </p>\n\n<p><strong>Flexibility</strong></p>\n\n<p>Also, I see a complete lack on the utilization of arrays. Don't you think that using an array to create multiple form elements is much more flexible that calling a function whenever I need to create a new element?</p>\n\n<p><strong>Exceptions</strong></p>\n\n<p>People now-a-days seem to underestimate the power of exceptions, you are not handling input to the function what so ever, and not producing any exceptions. A beautiful class is that which allows use of custom error messages(pure opinion).</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-11-05T16:27:36.500", "Id": "18256", "ParentId": "18241", "Score": "0" } }, { "body": "<p>If you are building an Object-Oriented Form then you need to start with building the HTML elements. Once you have that, you can easily build from out of them.</p>\n\n<pre><code>class Form extends HtmlElement {\nfunction init(){\n parent::init();\n $this-&gt;setElement('form');\n}\nfunction addInput($type,$name,$value,$tag='Content'){\n $f=$this-&gt;add('HtmlElement',$name,$tag);\n $f-&gt;setElement('input');\n $f-&gt;setAttr('type',$type);\n $f-&gt;setAttr('value',$value);\n $f-&gt;set('');\n return $f;\n}\n}\n</code></pre>\n\n<p>This example illustrates two very significant principles of OOP: inheritance (you inherit form from HtmlElement, thus it retains all the properties such as setAttr, setElement, and also setting contents) and the second principle is encapsulation - your Form consists of many other objects.</p>\n\n<p>You can also base HtmlElement on DOM objects, but in my case, here is the <a href=\"https://github.com/atk4/atk4/blob/master/lib/View.php\" rel=\"nofollow\">implementation of HtmlElement</a>:</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-11-06T11:53:00.540", "Id": "18282", "ParentId": "18241", "Score": "1" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-11-05T09:56:03.657", "Id": "18241", "Score": "4", "Tags": [ "php", "object-oriented", "form" ], "Title": "OOP PHP form ok?" }
18241
<p>The following script closes a virtual machine (which is run in a screen session), waits for the session to close, creates a backup of the VM, and restarts the VM. The shutdown and bootup scripts speak for themselves, but I can post them if necessary. Is there any way to clean up the <code>sockets_found</code> function? It seems like there should be an easier way to detect whether or not screen has any open sessions.</p> <pre><code>#!/bin/bash now=`date '+%Y%m%d'` # No Sockets found # There is a screen on function sockets_found { screen -ls | grep "There is a screen on" if [ $? -eq 1 ]; then return 1 else return 0 fi } function wait_for_sockets_to_close { while sockets_found; do echo "Waiting for screen to close..." sleep 1 done; } echo "Shutdown VM..." /bin/bash ~/shutdown.sh wait_for_sockets_to_close # ensure that the backup directory exists mkdir -p ~/backup echo "Copying VM to backup directory..." cp -Rf ~/VirtualBox\ VMs/ ~/backup/VirtualBox\ VMs${now}/ echo "Booting VM..." /bin/bash ~/bootup.sh </code></pre>
[]
[ { "body": "<p>You also can find if the socket file exists on <code>/var/run/screen/S-yourname/pid.screenname</code>.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-11-15T10:05:15.393", "Id": "18655", "ParentId": "18246", "Score": "2" } }, { "body": "<p>There is no need to grep here:</p>\n\n<pre><code>screen -ls | grep \"There is a screen on\"\nif [ $? -eq 1 ]; then\n</code></pre>\n\n<p><code>Screen -ls</code> will return with exit code 1 in the case no sockets are found in <code>/var/run</code>.</p>\n\n<p>I would run the date command just before the copy is run, in case the sockets close during a date roll and you get the wrong date on your backup.</p>\n\n<pre><code>echo \"Copying VM to backup directory...\"\nnow=$(date '+%Y%m%d')\ncp -Rf ~/VirtualBox\\ VMs/ ~/backup/VirtualBox\\ VMs${now}/\n</code></pre>\n\n<p>As above use <code>$(cmd)</code> notation instead of backtick notation. They achieve the same thing, but <code>$()</code> is visually clearer and can be nested.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-11-21T15:06:52.763", "Id": "18889", "ParentId": "18246", "Score": "1" } }, { "body": "<p>This can be improved and simplified:</p>\n\n<blockquote>\n<pre><code>function sockets_found {\n screen -ls | grep \"There is a screen on\"\n if [ $? -eq 1 ]; then\n return 1\n else\n return 0\n fi\n}\n</code></pre>\n</blockquote>\n\n<p>Like this:</p>\n\n<pre><code>function sockets_found {\n screen -ls | grep -q \"There is a screen on\"\n}\n</code></pre>\n\n<p>That is:</p>\n\n<ul>\n<li>You can remove the <code>if</code> statement, as the exit code of <code>grep</code> naturally becomes the exit code of the function</li>\n<li>If the exit code of <code>grep</code> is greater than 1, the original function exits with 0. That's inappropriate. Such exit codes indicate errors in <code>grep</code>, and do not imply that screen sessions exist</li>\n<li>I added the <code>-q</code> flag to suppress the output of <code>grep</code> in case of success</li>\n</ul>\n\n<p>Other minor things:</p>\n\n<ul>\n<li>No need for the <code>;</code> in <code>done;</code></li>\n<li>It would be better to double-quote <code>${now}</code> in the backup target directory to prevent accidental globbing or word splitting, in case you might make a mistake in the syntax of the <code>date</code> command</li>\n<li>It would be good to add some blank lines in the last chunk of commands for better readability</li>\n</ul>\n\n<p>Like this:</p>\n\n<pre><code>echo \"Shutdown VM...\"\n/bin/bash ~/shutdown.sh\n\nwait_for_sockets_to_close\n\n# ensure that the backup directory exists\nmkdir -p ~/backup\n\necho \"Copying VM to backup directory...\"\nnow=$(date '+%Y%m%d')\ncp -Rf ~/VirtualBox\\ VMs/ ~/backup/VirtualBox\\ VMs\"${now}\"/\n\necho \"Booting VM...\"\n/bin/bash ~/bootup.sh\n</code></pre>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2016-05-14T06:27:58.027", "Id": "128332", "ParentId": "18246", "Score": "1" } } ]
{ "AcceptedAnswerId": "128332", "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-11-05T13:23:29.683", "Id": "18246", "Score": "4", "Tags": [ "bash" ], "Title": "Bash Backup Script" }
18246
<p>I just wanted to confirm if this example I created would qualify as a good example of a multithreaded producer consumer. I would like any review changes on improving this example. I found that static fields are essential for synchronization of the threads. The wait-timeout mechanism along with the available flag functions as good as the wait/notifyAll mechanism. Synchronizing small blocks of code with private final static lock objects gives finer grained concurrency and prevents deadlocking.</p> <pre><code>package concurrency; import java.util.ArrayList; import java.util.List; /* * A Producer Consumer example scenario. There are MAX_THREAD number of producers and consumers. * each thread produces and consumes a single element. * Field transferCollection functions as the intermediatory collection between the producer and consumer. * Boolean field available acts as the signaling mechanism between the producer and consumer. * switched to true at the time when maximum number of threads have produced elements. * */ public class ProduceConsume { static int counter = 0; static List&lt;Integer&gt; transferCollection = new ArrayList&lt;Integer&gt;(); static volatile boolean available = false; static int producer_sum, CONSUMER_SUM, MAX_THREADS = 1000; private static final Object addLock = new Object(); private static final Object getLock = new Object(); public static void main(String[] args) throws Exception { List&lt;Runnable&gt; producers = new ArrayList&lt;Runnable&gt;(); Runnable producer = null; for (int i = 0; i &lt; MAX_THREADS; i++) { producer = new Runnable() { ProduceConsume pc = new ProduceConsume(); @Override public void run() { pc.produce(); } }; producers.add(producer); } for (Runnable x : producers) new Thread(x).start(); List&lt;Runnable&gt; consumers = new ArrayList&lt;Runnable&gt;(); Runnable consumer = null; for (int i = 0; i &lt; MAX_THREADS; i++) { consumer = new Runnable() { ProduceConsume pc = new ProduceConsume(); @Override public void run() { pc.consume(); } }; consumers.add(consumer); } for (Runnable x : consumers) new Thread(x).start(); } /* * Consumer threads invoke this method when MAX_THREADS of the producer are finished producing and adding to the list the same * number of items. * &lt;b&gt;getLock&lt;/b&gt; * A private final static lock object which threads wait on until the producer signals that elements are available on the list. * &lt;b&gt;addLock&lt;/b&gt; * A private final static lock object which threads wait on to sum up elements in the transferCollection. */ private void consume() { synchronized (getLock) { while (!available) { try { getLock.wait(200); } catch (InterruptedException e) { Thread.currentThread().interrupt(); } } } if (counter &gt; 0) { int size0 = transferCollection.size() - 1; synchronized (addLock) { int idx = --counter; CONSUMER_SUM += transferCollection.get(size0 - idx); } } if (counter == 0) { System.out.println("sum of consumer elements : " + CONSUMER_SUM); available=false; } } /* * Producer threads invoke this method till number of threads has reached MAX_THREADS which have produced same * number of items. * &lt;b&gt;addLock&lt;/b&gt; * A private final static lock object that allows thread to sequentially add elements to the collection and * produce a checksum at the end. */ private void produce() { synchronized (addLock) { transferCollection.add(++counter); producer_sum += counter; } if (counter == MAX_THREADS) { System.out.println("sum of producer elements : " + producer_sum); available = true; } } } </code></pre>
[ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2015-01-19T15:20:31.870", "Id": "141235", "Score": "0", "body": "I would suggest using classes in the concurrent packages and also an Executor for your workers." } ]
[ { "body": "<p>Why don't you use a <a href=\"http://docs.oracle.com/javase/6/docs/api/java/util/concurrent/BlockingQueue.html\" rel=\"nofollow\">BlockingQueue</a> instead of the transfer collection? The implemenations in util.concurrent use internal synchronization, which is most likely more performant than external synchronization objects. Additionally your consumers can consume almost as fast as the producers produce, instead of waiting until all producer finished.</p>\n\n<p>As the queue handles synchronization internally you could also remove the static variables and pass it to the producers and consumers on construction.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-11-12T05:36:12.650", "Id": "29467", "Score": "0", "body": "I didn't want to use any of the classes in the java.util.concurrent package as it they are examples of complete synchronizers. Mixing up synchronization methods in the Object class with java.util.concurrent package would make the class less cohesive." } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-11-09T22:10:07.977", "Id": "18425", "ParentId": "18250", "Score": "1" } }, { "body": "<p>There are several visibility issues.</p>\n\n<ol>\n<li>Write operations on <code>counter</code> are protected by <code>addLock</code>. However, at least 3 read operations on this static field aren't protected by the same lock. Since the field is not volatile, the visibility of updates are not guaranteed at all. </li>\n<li><code>transferCollection.size()</code> is not protected by <code>addLock</code>, so the size changes may not be visible for other threads.</li>\n</ol>\n\n<p>Same issue exists for <code>CONSUMER_SUM</code> and <code>producer_sum</code> fields. </p>\n\n<p>It may lead to:</p>\n\n<ul>\n<li><em>livelock</em> or <em>resource starvation</em> due to stale data;</li>\n<li>logical errors due to <em>instructions re-ordering</em>;</li>\n</ul>\n\n<p>Alternatively, consider using classes from <code>java.util.concurrent</code> package.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-11-15T06:41:41.313", "Id": "29679", "Score": "0", "body": "I thought that volatile should be used mainly with flag variables. If there were some visibility issues I wasn't able to notice it even after running it a number of times. How is it possible to recreate errors caused by non-volatile reads ?" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-11-20T01:51:02.440", "Id": "30020", "Score": "0", "body": "@clinton `volatile` is just a memory consistency mechanism in Java, it can be used not only for flags. To re-produce such errors you should run a load test in highly-concurrent environment for millions of iterations. It greatly depends on hardware, OS, etc. But such visibility issues are common, do not underestimate them." } ], "meta_data": { "CommentCount": "2", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-11-14T06:59:33.043", "Id": "18584", "ParentId": "18250", "Score": "1" } } ]
{ "AcceptedAnswerId": "18584", "CommentCount": "1", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-11-05T15:07:06.810", "Id": "18250", "Score": "1", "Tags": [ "java", "multithreading", "locking", "producer-consumer" ], "Title": "Multithreading concepts with Producer Consumer" }
18250
<p>I have an XML layout used by 2 activities. Within this layout, there's a view that is <code>visible</code> for <code>Activity1</code> and <code>gone</code> for <code>Activity2</code>. <code>Activity1</code> is used more times compared to <code>Activity2</code>. I would like to know which of the following methods is a better practice, if there's a better one.</p> <p><strong>Method 1</strong>: The view is <code>gone</code> and it's turned <code>visible</code> with every instance of the <code>Activity1</code>. </p> <p>XML:</p> <pre><code>&lt;View android:id="@+id/myView" android:visibility="gone" /&gt; </code></pre> <p>Java:</p> <pre><code>class Activity1 extends Activity { ((View) findViewById(R.id.myView)).setVisibility(0); } class Activity2 extends Activity { } </code></pre> <p><strong>Method 2</strong>: The view is <code>visible</code> and it's turned <code>gone</code> only when <code>Activity2</code> is being used. </p> <p>XML:</p> <pre><code>&lt;View android:id="@+id/myView" android:visibility="visible" /&gt; </code></pre> <p>Java:</p> <pre><code>class Activity1 extends Activity { } class Activity2 extends Activity { ((View) findViewById(R.id.myView)).setVisibility(8); } </code></pre> <p>So, is it better to change the visibility programmatically multiple times or fewer times?</p>
[]
[ { "body": "<p>According to <a href=\"http://grepcode.com/file/repository.grepcode.com/java/ext/com.google.android/android/4.1.1_r1/android/view/View.java\" rel=\"nofollow\">View source code</a> setting visibility through xml (line 3450) is cheaper than through <code>setVisibility</code> method (line 5511).</p>\n\n<p>So it is better to change visibility programmatically fewer times.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-11-06T05:19:19.077", "Id": "18277", "ParentId": "18255", "Score": "4" } }, { "body": "<p>You should never use \"magic numbers\" in your code, otherwise code is unreadable.\n<code>setVisibility(0)</code> looks like you are hiding the view, while the truth is opposite.\nAlways use constants (<code>View.GONE</code> and <code>View.VISIBLE</code> in this case).</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-11-14T13:36:02.780", "Id": "29621", "Score": "0", "body": "Constants are already implemented, I just prefer not to use them. The question was regarding a better methodology, not readability of code." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-11-14T17:20:17.100", "Id": "29643", "Score": "1", "body": "this is a codereview site ;). and i can just add that preference to not to use constants is very poor." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-11-14T18:21:28.027", "Id": "29650", "Score": "0", "body": "That should be a comment, not an answer since it doesn't answer the question." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-11-14T22:31:30.810", "Id": "29670", "Score": "0", "body": "@slybloty - agree, you are right." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-11-14T22:37:26.207", "Id": "29671", "Score": "1", "body": "@TrevorPilley I understand that you've edited my answer to make it look better. But probably you should not change code snippets in areas you are not too familiar about. On Android notation for constants is all-upper-case. And there is no need for some \"ViewVisibility\" since needed constants defined within SDK View class, as was shown in my answer initially" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-11-15T01:16:18.663", "Id": "29673", "Score": "0", "body": "I was wondering why those constants were not Android specific." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-11-15T12:01:47.293", "Id": "29691", "Score": "0", "body": "@Alex noted, sorry!" } ], "meta_data": { "CommentCount": "7", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-11-14T09:17:38.590", "Id": "18590", "ParentId": "18255", "Score": "1" } } ]
{ "AcceptedAnswerId": "18277", "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-11-05T16:10:11.093", "Id": "18255", "Score": "2", "Tags": [ "java", "design-patterns", "android" ], "Title": "Change View visibility programmatically or through XML?" }
18255
<p>A while back I was asked to write some sample code for a job that I was applying for. They wanted a class that had a function that would accept three lengths and return the appropriate type of triangle (Scalene, Isosceles or Equilateral) based on that. They also wanted unit tests.</p> <p>After sending this I never heard back, so I'm wondering if anyone would have any suggestions for a better way to implement this.</p> <pre><code>using NUnit.Framework; namespace Triangle { /**** * This test is divided into two halves. * 1. Implement the GetTriangleType method so that it returns the appropriate * enum value for different inputs. * 2. Write a complete series of passing unit tests for the GetTriangleType method * under various input conditions. In this example we're using NUnit, but * you can use whatever testing framework you prefer. * * When finished, send back your solution (your version of TriangleTester.cs * will suffice) including any explanatory comments you feel are needed. */ public enum TriangleType { Scalene = 1, // no two sides are the same length Isosceles = 2, // two sides are the same length and one differs Equilateral = 3, // all sides are the same length Error = 4 // inputs can't produce a triangle } public class TriangleTester { /// &lt;summary&gt; /// Given the side lengths a, b, and c, determine and return /// what type of triangle the lengths describe, or whether /// the input is invalid /// &lt;/summary&gt; /// &lt;param name="a"&gt;length of side a&lt;/param&gt; /// &lt;param name="b"&gt;length of side b&lt;/param&gt; /// &lt;param name="c"&gt;length of side c&lt;/param&gt; /// &lt;returns&gt;The triangle type based on the number of matching sides passed in.&lt;/returns&gt; public static TriangleType GetTriangleType(int a, int b, int c) { //Placing items in an array for processing int[] values = new int[3] {a, b, c}; // keeping this as the first check in case someone passes invalid parameters that could also be a triangle type. //Example: -2,-2,-2 could return Equilateral instead of Error without this check. //We also have a catch all at the end that returns Error if no other condition was met. if (a &lt;= 0 || b &lt;= 0 || c &lt;= 0) { return TriangleType.Error; } else if (values.Distinct().Count() == 1) //There is only one distinct value in the set, therefore all sides are of equal length { return TriangleType.Equilateral; } else if (values.Distinct().Count() == 2) //There are only two distinct values in the set, therefore two sides are equal and one is not { return TriangleType.Isosceles; } else if (values.Distinct().Count() == 3) // There are three distinct values in the set, therefore no sides are equal { return TriangleType.Scalene; } else { return TriangleType.Error; } } } [TestFixture] public class TriangleTesterTests { [Test] public void Test_GetTriangleType() { Assert.AreEqual(TriangleType.Equilateral, TriangleTester.GetTriangleType(4, 4, 4), "GetTriangleType(4, 4, 4) did not return Equilateral"); Assert.AreEqual(TriangleType.Isosceles, TriangleTester.GetTriangleType(4, 4, 3), "GetTriangleType(4, 4, 3) did not return Isosceles"); Assert.AreEqual(TriangleType.Scalene, TriangleTester.GetTriangleType(4, 3, 2), "GetTriangleType(4, 3, 2) did not return Scalene"); Assert.AreEqual(TriangleType.Error, TriangleTester.GetTriangleType(-4, 4, 4), "GetTriangleType(-4, 4, 4) did not return Error"); Assert.AreEqual(TriangleType.Error, TriangleTester.GetTriangleType(4, -4, 4), "GetTriangleType(4, -4, 4) did not return Error"); Assert.AreEqual(TriangleType.Error, TriangleTester.GetTriangleType(4, 4, -4), "GetTriangleType(4, 4, -4) did not return Error"); } } } </code></pre>
[ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-11-05T20:38:43.183", "Id": "29124", "Score": "1", "body": "Did they want a 'type' proper, as in some kind of triangle factory, or just the kind for identification, as demonstrated by the enum?" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2016-12-21T16:31:06.007", "Id": "283244", "Score": "0", "body": "You probably have to check for this too http://www.wikihow.com/Determine-if-Three-Side-Lengths-Are-a-Triangle" } ]
[ { "body": "<p>I don't see anything wrong with your standards.</p>\n\n<p>I do see some design issues though.</p>\n\n<p>The biggest one is your unit test. I count 6 distinct unit tests, not 1. Each one of those asserts should be in its own test with a method name describing the test. Assuming you are using NUnit. I would also use Assert.That, but I think that is just personal preference:</p>\n\n<pre><code>[Test]\npublic void ThreeEqalValuesShouldReturnEquilateral()\n{\n Assert.That(TriangleTester.GetTriangleType(4, 4, 4), Is.EqualTo(TriangleType.Equilateral);\n}\n</code></pre>\n\n<p>Again, if using Nunit, another option would be to use the TestCase attribute:</p>\n\n<pre><code>[Test]\n[TestCase(4, 4, 4, TriangleType.Equilateral)]\n[TestCase(4, 4, 3, TriangleType.Isosceles)]\n// ...\npublic void CheckDifferentTriangleTypes(int a, int b, int c, TriangleType expected )\n{\n Assert.That(TriangleTester.GetTriangleType(a, b, c), Is.EqualTo(expected);\n}\n</code></pre>\n\n<p>That being the biggest issue, but I think you could of done something with that monster if/else statement in your main program. I also think you over commented it. What I mean is that your comments are explaining the logic that most people would be able to read.</p>\n\n<p>An easy way to fix this is to create functions for each check. Then you don't need to comment. Also, because each if / else has a return in it, I you can lose the elses. I would also move the assignment of the array until after the first check.</p>\n\n<pre><code>if (a &lt;= 0 || b &lt;= 0 || c &lt;= 0) \n{\n return TriangleType.Error;\n}\n\nint[] values = new int[3] {a, b, c};\n\nif (AllThreeSidesAreEqual(values)) \n{\n return TriangleType.Equilateral;\n}\n\nif (TwoSidesAreEqual(values))\n{\n return TriangleType.Isosceles;\n}\n\nif (NoSidesAreEqual(values))\n{\n return TriangleType.Scalene;\n}\n\nreturn TriangleType.Error;\n</code></pre>\n\n<p>where</p>\n\n<pre><code>private static bool AllThreeSidesAreEqual(int[] values)\n{\n return values.Distinct().Count() == 1;\n}\n\n// Build other methods\n</code></pre>\n\n<p>Try fixing these and look at your code again. Hopefully you will see a difference in the two ways of doing it.</p>\n\n<p>Good luck.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-11-05T18:17:06.423", "Id": "29115", "Score": "3", "body": "In addition, they might be looking for the class to implement an interface and not have a static method so that the method can be mocked out of any calling methods." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-11-05T18:18:24.157", "Id": "29116", "Score": "1", "body": "That crossed my mind too." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-11-05T18:39:17.590", "Id": "29119", "Score": "1", "body": "Good info on the unit tests, thanks. I have very little experience using them so I'm not surprised they are a little screwy." } ], "meta_data": { "CommentCount": "3", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-11-05T18:08:20.010", "Id": "18258", "ParentId": "18257", "Score": "7" } }, { "body": "<p>I don't code C#, so just some generic notes:</p>\n\n<ol>\n<li><p>You can omit the <code>else</code> keyword if you return immediately:</p>\n\n<pre><code>if (a &lt;= 0 || b &lt;= 0 || c &lt;= 0) \n{\n return TriangleType.Error;\n}\nif (values.Distinct().Count() == 1) //There is only one distinct value in the set, therefore all sides are of equal length\n{\n return TriangleType.Equilateral;\n}\n...\n</code></pre></li>\n<li><p>Some comments are just says what's in the code. I'd remove them, they're just noise.</p></li>\n<li><p>The code doesn't check that the the sum of the lengths of any two sides of the triangle have to be greater than the length of the third side. (<code>a + b &gt; c</code>)</p></li>\n<li><p>About the specification: in case of an error you might want to throw an exception with a detailed error message instead of the <code>Error</code> enum which tells nothing about the cause of the error to the clients.</p></li>\n<li><p>Just a link for <em>@Jeff's</em> point: Too many assert in one test is a bad smell. If the first <code>AreEqual</code> throws an exception you won't know anything about the results of the other assert calls which could be important because they could help debugging and <a href=\"http://xunitpatterns.com/Goals%20of%20Test%20Automation.html#Defect%20Localization\">defect localization</a>.</p></li>\n</ol>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-11-05T18:38:12.923", "Id": "29118", "Score": "2", "body": "Good point on the `a+b>c` error. I didn't even think of that until just now." } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-11-05T18:12:26.627", "Id": "18259", "ParentId": "18257", "Score": "12" } }, { "body": "<p>Some style suggestions:</p>\n\n<ul>\n<li>Move the argument bounds checking to the top of the method. No sense allocating the array (even if it's small) if the values aren't valid in the first place. This is also a different check than the one you are doing to test the triangle so it doesn't really belong in that if-else chain.</li>\n</ul>\n\n<p>A different look (comments snipped, most are self explanatory):</p>\n\n<pre><code> public static TriangleType GetTriangleType(int a, int b, int c)\n {\n // There should also be a side length check\n if (a &lt;= 0 || b &lt;= 0 || c &lt;= 0) \n {\n return TriangleType.Error;\n }\n\n if (a == b &amp;&amp; a == c) // These could also be their own methods\n {\n return TriangleType.Equilateral;\n }\n else if (a == b || a == c || b == c)\n {\n return TriangleType.Isosceles;\n }\n else\n {\n return TriangleType.Scalene;\n }\n }\n</code></pre>\n\n<p>Edit: Maybe a static utility method isn't the best in this case either (rather a <code>Triangle</code> class). Your best bet is if you still have a contact for whoever you submitted this code to, perhaps you could send a follow-up asking for feedback.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-11-05T18:18:00.067", "Id": "18261", "ParentId": "18257", "Score": "3" } }, { "body": "<p>Maybe I'm missing the obvious but... shouldn't you first check if the values actually form a valid triangle?</p>\n\n<p>For instance, entering lengths 10, 10, 100000 wouldn't make it a valid isosceles triangle.</p>\n\n<p>... just saying.</p>\n\n<p>For valid triangle lengths you can check this <a href=\"https://stackoverflow.com/questions/10946230/check-input-to-create-a-valid-triangle\">stack overflow question</a>.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-11-06T18:03:33.280", "Id": "29148", "Score": "1", "body": "Yes, @palacsint pointed that out as well." } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-11-06T14:31:16.500", "Id": "18284", "ParentId": "18257", "Score": "3" } }, { "body": "<p>OK, I don't do C#, (I come from VB) I'll have the wrong syntax in some instances, but I think you'll understand what I'm driving at.</p>\n\n<p>My idea would be to have an enum who's numerical value is the number of similar sides</p>\n\n<pre><code>Enum TriangleType as integer\n Error = -1 //cannot make a triangle\n Scalene = 0 //no sides equal\n Isosceles = 2 //2 sides equal\n Equilateral = 3 //3 sides equal\nEnd Enum\n</code></pre>\n\n<p>Then you have the calling functions</p>\n\n<pre><code>public sub GetInputs as integer()\n//whatever code you need to get inputs here\n\nint InputArray[] = {a,b,c} //create an array with the values\n\n //Calculate results and write to the screen\n int ThisTriangleType = GetTriangleType(InputArray)\n Console.Write (ThisTriangleType.Tostring)\n Console.Write(\" has \")\n Console.Write(ThisTriangleType)\n Console.Writeline(\" equal sides\")\n\nend sub\n\n\npublic function GetTriangleType(int IntegerArray*) as TriangleType\n IntegerArray.sort(numerical ascending)\n if IntegerArray(0) &lt;=0 then\n //smallest (thus all values) must be greater than zero\n Return TriangleType.Error \n end if\n\n if IntegerArray(0) == IntegerArray(1) and IntegerArray(0)== IntegerArray(2)\n //We have an Equilateral Triangle\n Return TriangleType.Equilateral\n end if\n\n if IntegerArray(0) == IntegerArray(1) then\n //the two short sides are equal, \n //Long side must be less than their sum\n if IntegerArray(0) + IntegerArray(1) &gt; IntegerArray(2)\n Return TriangleType.Error\n End if\n //We have a valid Isosceles triangle with &lt;60* angle\n Return TriangleType.Isosceles\n End if\n\n if IntegerArray(1) == IntegerArray(2) then\n //the two long sides are equal\n //automatically valid Isoscelese with a &gt;60* angle\n Return TriangleType.Isosceles\n End if \n\n if IntegerArray(0) + IntegerArray(1) &gt; IntegerArray(2) then\n //We've tested for all conditions with 2 or more equal lengths\n //We have a valid Scalene since the longest is less \n //than the sum of the 2 shortest\n Return TriangleType.Scalene\n end if\n //We have an invalid triangle\n Return TriangleType.Error\nend function\n</code></pre>\n\n<p>I'm sorry for the mixing of VB and C..</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2016-01-16T01:54:54.253", "Id": "217403", "Score": "0", "body": "As a side note, while this has some good information, you should either (re)write equivalent code in the language you know/pseudocode, or stick to a pure text description, if you don't know the language." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2016-01-16T12:31:07.953", "Id": "217451", "Score": "0", "body": "@QPaysTaxes I think it's fine. Any C# developer should be able to read VB.Net as \"pseudo code\", even if they're not familiar with VB." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2016-01-16T22:00:26.937", "Id": "217553", "Score": "0", "body": "@RubberDuck Please note that I said \"write it in a language you know\" as an option." } ], "meta_data": { "CommentCount": "3", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2016-01-16T01:26:41.593", "Id": "116943", "ParentId": "18257", "Score": "1" } } ]
{ "AcceptedAnswerId": "18259", "CommentCount": "2", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-11-05T17:20:39.690", "Id": "18257", "Score": "9", "Tags": [ "c#", ".net", "unit-testing", "nunit" ], "Title": "Function for determining triangle type" }
18257
<p>I have an application where I am receiving big byte array very fast around per 50 miliseconds.</p> <p>The byte array contains some information like file name etc. The data (byte array ) may come from several sources.</p> <p>Each time I receive the data, I have to find the file name and save the data to that file name.</p> <p>I need some guide lines to how should I design it so that it works efficient.</p> <p>Following is my code...</p> <pre><code>public class DataSaver { private Dictionary&lt;string, FileStream&gt; _dictFileStream; public void SaveData(byte[] byteArray) { string fileName = GetFileNameFromArray(byteArray); FileStream fs = GetFileStream(fileName); fs.Write(byteArray, 0, byteArray.Length); } private FileStream GetFileStream(string fileName) { FileStream fs; bool hasStream = _dictFileStream.TryGetValue(fileName, out fs); if (!hasStream) { fs = new FileStream(fileName, FileMode.Append); _dictFileStream.Add(fileName, fs); } return fs; } public void CloseSaver() { foreach (var key in _dictFileStream.Keys) { _dictFileStream[key].Close(); } } } </code></pre> <p>How can I improve this code ? I need to create a thread maybe to do the saving.</p>
[ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-11-05T22:35:36.400", "Id": "29126", "Score": "0", "body": "Consider using [this][1] approach, I believe you have a similar situation.\r\n\r\n\r\n [1]: http://stackoverflow.com/questions/6203836/most-efficient-way-to-process-a-queue-with-threads" } ]
[ { "body": "<p>Careful about how many files you keep open, OS handles are not free. See <a href=\"http://msdn.microsoft.com/en-us/library/yz8tx0w3.aspx\" rel=\"nofollow\">http://msdn.microsoft.com/en-us/library/yz8tx0w3.aspx</a></p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-11-05T22:37:03.880", "Id": "18267", "ParentId": "18266", "Score": "3" } }, { "body": "<p>You need to ask yourself 4 questions to start with:</p>\n\n<ol>\n<li>How \"big\" is \"big byte array\"?</li>\n<li>How fast is \"very fast\" ? Can we take 20 Hz as a design assumption?</li>\n<li>Should data be appended in-order?</li>\n<li>What is the expected overall size for a given file?</li>\n</ol>\n\n<p>Just for the taste of it, appending 4MB to a file, on my 10 YO machine, takes less than 10 ms. A modern SSD and CPU will outdo this by an order of magnitude.</p>\n\n<p>Anyway, knowing nothing, I would start with the most simple imaginable scheme, which is completely synchronous, and let it fail:</p>\n\n<pre><code>public static class FileSaver\n{\n public static bool TrySaveData(byte[] data)\n {\n int dataOffset = 0;\n var file = GetFileName(data, out dataOffset);\n return TryAppend(file, data, dataOffset);\n }\n\n private static string GetFileName(byte[] data, out int offset)\n {\n string res = ... // get the file name\n offset = ... // depends on your format \n return res;\n }\n\n private static bool TryAppend(string file, byte[] data, int offset = 0)\n {\n try\n {\n using (var stream = new FileStream(file, FileMode.Append))\n {\n stream.Write(data, offset, data.Length - offset);\n }\n return true;\n }\n catch (Exception ex) { /* log some error */ }\n return false;\n }\n}\n</code></pre>\n\n<p>Why is this good? Because by the time it fails, you'll be smart enough to answer 1-4, and then we would design something else based on real understanding of the problem.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-11-06T00:41:38.633", "Id": "18271", "ParentId": "18266", "Score": "6" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "1", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-11-05T22:19:30.287", "Id": "18266", "Score": "4", "Tags": [ "c#" ], "Title": "Design guideline for saving big byte stream in c#" }
18266
<p>I have an implementation of a BrickBreaker-like game where instead of pieces being just removed from the ceiling, each impact results in a new ball being released, gradually building up to a pretty chaotic game.</p> <p>The SDL related code that actually draws the game is not included here.</p> <p>This is my second "big" project using Haskell, so I'd appreciate some critique, specifically concerning the <code>approach</code> and <code>collisionBlock</code> functions. First in <code>approach</code> I zip <code>Data.Map.lookup</code> over a list of keys, and then use msum to get the first successful lookup. Then in <code>collisionBlock</code> I use <code>Data.Map.updateLookupWithKey</code> again on the key I already know is successful and had already performed a lookup with. I'd like to be able to eliminate this extra lookup or otherwise improve the <code>approach</code> function.</p> <pre><code>{-# LANGUAGE BangPatterns #-} module BrickBreaker where import Control.Monad import Data.List import qualified Data.Map as M import System.Random width = 640 :: Int height = 420 :: Int blockW = width blockH = height `quot` 3 data Particle = Particle { partX, partY, partDX, partDY :: !Int } data Paddle = Paddle { paddleX, paddleW, paddleH :: !Int } data GameState = GS ![Particle] !Block data CollisionResult = Miss | Hit Particle Block type Block = M.Map Pos Particle type Pos = (Int, Int) getPos, getSpeed :: Particle -&gt; Pos getPos pt = (partX pt, partY pt) getSpeed pt = (partDX pt, partDY pt) genBlock :: Block genBlock = mkMap [Particle w h 0 0 | w &lt;- [1..blockW], h &lt;- [1..blockH]] where mkMap = M.fromList . map (\pt -&gt; (getPos pt, pt)) approach :: Particle -&gt; Block -&gt; Maybe Particle approach pt bs = msum $ zipWith ((flip M.lookup bs .) . addSpeed) (enum dx) (enum dy) where (x, y) = getPos pt; (dx, dy) = getSpeed pt addSpeed dx dy = (x + dx, y + dy) enum 0 = repeat 0 enum n = let i = if n &lt; 0 then (-1) else 1 in enumFromThenTo i (i+i) n collisionBlock :: Particle -&gt; Block -&gt; CollisionResult collisionBlock pt bs | dy &gt; 0 &amp;&amp; y &gt; blockH = Miss | dy &lt; 0 &amp;&amp; y &gt; blockH - dy = Miss | otherwise = case approach pt bs of Just pt -&gt; let ~(Just pt', bs') = searchRemove pt in Hit pt' bs' Nothing -&gt; Miss where y = partY pt; dy = partDY pt searchRemove = flip (M.updateLookupWithKey (\_ _ -&gt; Nothing)) bs . getPos collisionPaddle :: Paddle -&gt; Particle -&gt; Bool collisionPaddle pd pt = y &gt;= height - paddleH pd &amp;&amp; x `between` (padX, padX + paddleW pd) &amp;&amp; dy &gt; 0 where n `between` (a, b) = n &gt;= a &amp;&amp; n &lt;= b (x, y) = getPos pt; dy = partDY pt padX = paddleX pd checkCollisions :: Paddle -&gt; GameState -&gt; GameState checkCollisions pd (GS ps bs) = foldl go (GS [] bs) ps where go (GS ps bs) pt | collisionPaddle pd pt = GS (bar:ps) bs | otherwise = case collisionBlock pt bs of Hit pt bs' -&gt; GS (blk:(randomParticle pt:ps)) bs' Miss -&gt; GS (pt:ps) bs where (x, y) = getPos pt; (dx, dy) = getSpeed pt bar = Particle x (min y height) dx (-dy) blk = Particle x y dx (abs dy) randomParticle :: Particle -&gt; Particle randomParticle pt = Particle x y (ceiling $ dx * 10) (ceiling $ dy * 9 + 1) where (x, y) = getPos pt (dx, g) = randomR ((-1.0), 1.0) (mkStdGen $ x + y) :: (Double, StdGen) (dy, _) = randomR (0.1, 1.0) g :: (Double, StdGen) updateParticle :: Particle -&gt; Particle updateParticle pt = Particle (x + dx') (y + dy') dx' dy' where (x, y) = getPos pt; (dx, dy) = getSpeed pt dx' = if (x &gt; width &amp;&amp; dx &gt; 0) || (x &lt; 0 &amp;&amp; dx &lt; 0) then (-dx) else dx dy' = if y &lt; 0 &amp;&amp; dy &lt; 0 then (-dy) else dy updateGame :: Paddle -&gt; GameState -&gt; GameState updateGame pd gs = GS (map updateParticle $ filter inBounds ps) bs where GS ps bs = checkCollisions pd gs inBounds = (&lt;= height) . partY </code></pre> <p>Here is the main loop in the SDL related code that calls the drawing functions and updates the <code>GameState</code>:</p> <pre><code>updateWorld :: Surface -&gt; Paddle -&gt; GameState -&gt; IO () updateWorld screen pd gs = do ticks &lt;- getTicks quit &lt;- whileEvents drawGame screen pd gs (x, _, _) &lt;- getMouseState ticks' &lt;- getTicks let pd' = Paddle x (paddleW pd) (paddleH pd) delta = ticks' - ticks when (delta &lt; (fromIntegral secsPerFrame)) $ delay $ fromIntegral secsPerFrame - delta unless (quit || gameOver gs) (updateWorld screen pd' $ updateGame pd' gs) where whileEvents = do event &lt;- pollEvent case event of KeyDown (Keysym key _ _) -&gt; case key of SDLK_q -&gt; return True _ -&gt; return False _ -&gt; return False </code></pre>
[ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-11-08T11:48:04.410", "Id": "29225", "Score": "1", "body": "Removing SDL dependency would help to review the code as it's hard to install" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-11-08T15:49:20.590", "Id": "29240", "Score": "0", "body": "@nponeccop: I didnt find SDL too difficult to install, but I'll remove the dependency if it wil help." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-11-10T09:44:09.820", "Id": "29398", "Score": "0", "body": "`randomParticle` generates particles moving in any direction, but `approach` only checks diagonal paths. Is it a mistake or an approximation?" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-11-10T23:21:43.817", "Id": "29422", "Score": "0", "body": "@nponeccop: good point, thats something I overlooked. I was having trouble coming up with a way to allow the particles to \"approach\" the block. Without an `approach` function, the particles can \"tunnel\" into the block, and if the new particle generated from `randomParticle` doesnt have enough y velocity to get out of the block it sets off a chain reaction and the entire block is gone in seconds." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-11-11T16:20:02.313", "Id": "29438", "Score": "0", "body": "Collision detection should be rather well-known part of game development, so maybe you should look at the literature. Did you try assuming that particles travel in continuous space and time and finding collisions \"between\" pixels and frames by solving parametric equations (time as parameter) of particle movement?" } ]
[ { "body": "<p>One comment on your modelling...</p>\n\n<p>Consider making the paddle position part of your <code>GameState</code>. Regardless of how you are going to control the paddle, conceptually it is part of the state. In particular, it is required in order to draw the game screen. Your game loop will look something like:</p>\n\n<pre><code>gameLoop :: GameState -&gt; IO ()\ngameLoop s = if stillPlaying s\n then do drawScreen s\n e &lt;- getEvent\n gameLoop $ nextState s e\n else return ()\n\ndrawScreen :: GameState -&gt; IO ()\n...\n\ngetEvent :: IO Event\n...\n</code></pre>\n\n<p><code>stillPlaying</code> has the signature <code>GameState -&gt; Bool</code> and returns false when the game is over.</p>\n\n<p><code>nextState</code> has the signature <code>GameState -&gt; Event -&gt; GameState</code> and creates the next state by applying the effects of an event.</p>\n\n<p>One of the events could be \"move the paddle left\" or \"move the paddle right\" which would affect the position of the paddle.</p>\n\n<p>Also, don't forget to put a random number generator into your <code>GameState</code> - I'm sure you will want to have some randomness in your game eventually.</p>\n\n<p>Update: It's a good idea to think in alternative use cases when defining the roles and responsibilities of your functions.</p>\n\n<p>For instance, one possible definition of <code>drawScreen</code> is to simply <code>putStrLn $ show s</code> - assuming that you've derived a <code>Show</code> instance for <code>GameState</code>. And <code>getEvent</code> could simply read a number from stdin and create the <code>Event</code> value. Then you can test your game code without using SDL.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-11-08T21:29:41.013", "Id": "29262", "Score": "0", "body": "The SDL code that actually draws the game is in a seperate module. It has simlar functions to the ones you've mentioned. My rationale for keeping the paddle out of the `GameState` is that the paddle is controlled by the user (ie. it has to be updated in the IO monad), whereas the current `GameState` can be used with complete purity. Specifically, the paddle is moved by updating the padX field with the X co-ord of SDL.getMouseState" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-11-08T21:47:16.020", "Id": "29263", "Score": "0", "body": "You can run `SDL.getMouseState` as part of the `getEvent` function. `getEvent` is an `IO Event` so it can call `SDL.getMouseState`." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-11-08T22:35:12.333", "Id": "29270", "Score": "0", "body": "okay, but i already have the entire drawing/user input part of the game worked out in a separate module. I'll add the main update loop to the question." } ], "meta_data": { "CommentCount": "3", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-11-08T20:22:30.297", "Id": "18362", "ParentId": "18268", "Score": "2" } }, { "body": "<p>You can use <code>let i = signum n</code> in <code>enum</code> instead of <code>if</code>.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-11-10T09:43:56.327", "Id": "18445", "ParentId": "18268", "Score": "1" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "5", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-11-05T23:43:45.260", "Id": "18268", "Score": "3", "Tags": [ "game", "haskell", "collision" ], "Title": "BrickBreaker Spinoff in Haskell" }
18268
<p>Background: I need to use mutation observers to watch for nodes being added/removed under a specific element.</p> <p>The code below is an attempt to implement something re-usable that uses <a href="https://developer.mozilla.org/en-US/docs/DOM/MutationObserver" rel="nofollow"><code>MutationObserver</code></a>s where available and falls back to <a href="https://developer.mozilla.org/en-US/docs/DOM/Mutation_events" rel="nofollow">mutation events</a> where not available, providing a simple unified interface to both. The aim is to have the behaviour as predictable as possible regardless if the mechanism that is powering it behind.</p> <p>You will notice it only implements a very part of the functionality that is available through these methods, but that is intentional, as it only implements the parts I need to use. I may look to extend it in the future.</p> <pre><code>/*jslint plusplus: true, white: true, browser: true */ /* * DOMChildListMutationListenerFactory definition */ function DOMChildListMutationListenerFactory() {'use strict';} DOMChildListMutationListenerFactory.prototype.MOFactory = { isSupported: function() { // Determines whether the environment supports MutationObservers and caches a // reference to the constructor if it does 'use strict'; if (this.MOConstructor === undefined) { this.MOConstructor = null; if (window.MutationObserver !== undefined) { // Mozilla/standard this.MOConstructor = window.MutationObserver; } else if (window.WebKitMutationObserver !== undefined) { // Webkit this.MOConstructor = window.WebKitMutationObserver; } } return this.MOConstructor !== null; }, getObserver: function(callback) { // Gets a MutationObserver instance 'use strict'; return new this.MOConstructor(callback); } }; DOMChildListMutationListenerFactory.prototype.getListener = function(element) { // Determines which wrapper constructor to use, caches the result and gets an instance 'use strict'; if (this.WrapperInUse === undefined) { DOMChildListMutationListenerFactory.prototype.WrapperInUse = null; if (this.MOFactory.isSupported()) { DOMChildListMutationListenerFactory.prototype.WrapperInUse = this.MutationObserverWrapper; } else if (window.addEventListener) { DOMChildListMutationListenerFactory.prototype.WrapperInUse = this.MutationEventWrapper; } } if (this.WrapperInUse === null) { throw new Error('Your browser does not support Child List mutation listeners'); } return new this.WrapperInUse(this, element); }; /* * MutationObserverWrapper definition */ DOMChildListMutationListenerFactory.prototype.MutationObserverWrapper = function(parent, element) { // Constructor for MutationObserver wrapper 'use strict'; this.parent = parent; this.element = element; this.callbacks = { nodeadded: [], noderemoved: [] }; this.mutationObserver = parent.MOFactory.getObserver(this.observerCallback.bind(this)); }; // Whether the observer is currently active (boolean flag) DOMChildListMutationListenerFactory.prototype.MutationObserverWrapper.prototype.observing = false; DOMChildListMutationListenerFactory.prototype.MutationObserverWrapper.prototype.observerCallback = function(mutations) { // Iterate over all nodes in mutation and fire event callbacks 'use strict'; var i, j, k, l, m, n; for (i = 0, l = mutations.length; i &lt; l; i++) { for (j = 0, m = mutations[i].removedNodes.length; j &lt; m; j++) { for (k = 0, n = this.callbacks.noderemoved.length; k &lt; n; k++) { this.callbacks.noderemoved[k](mutations[i].removedNodes[j]); } } for (j = 0, m = mutations[i].addedNodes.length; j &lt; m; j++) { for (k = 0, n = this.callbacks.nodeadded.length; k &lt; n; k++) { this.callbacks.nodeadded[k](mutations[i].addedNodes[j]); } } } }; DOMChildListMutationListenerFactory.prototype.MutationObserverWrapper.prototype.on = function(eventName, callback) { // Register an event callback and start the observer if required 'use strict'; eventName = eventName.toLowerCase(); if (this.callbacks[eventName] !== undefined &amp;&amp; typeof callback === 'function' &amp;&amp; this.callbacks[eventName].indexOf(callback) &lt; 0) { this.callbacks[eventName].push(callback); if (!this.observing) { this.mutationObserver.observe(this.element, { childList: true, subtree: true }); this.observing = true; } } }; DOMChildListMutationListenerFactory.prototype.MutationObserverWrapper.prototype.off = function(eventName, callback) { // De-register an event callback and stop the observer if no callbacks left 'use strict'; var i; eventName = eventName.toLowerCase(); if (this.callbacks[eventName] !== undefined) { i = this.callbacks[eventName].indexOf(callback); if (i &gt; -1) { this.callbacks[eventName].splice(i, 1); } } if (this.observing &amp;&amp; !this.callbacks.nodeadded.length &amp;&amp; !this.callbacks.noderemoved.length) { this.mutationObserver.disconnect(); this.observing = false; } }; /* * MutationEventWrapper definition */ DOMChildListMutationListenerFactory.prototype.MutationEventWrapper = function(parent, element) { // Constructor for Mutation Events wrapper 'use strict'; this.parent = parent; this.element = element; this.callbacks = { nodeadded: [], noderemoved: [] }; }; // Whether the observer is currently active (boolean flag) DOMChildListMutationListenerFactory.prototype.MutationObserverWrapper.prototype.insertObserving = false; DOMChildListMutationListenerFactory.prototype.MutationObserverWrapper.prototype.removeObserving = false; DOMChildListMutationListenerFactory.prototype.MutationEventWrapper.prototype.nodeInsertedListener = function(event) { // Fire insert callbacks 'use strict'; var i, l, node = event.target || event.srcElement; for (i = 0, l = this.callbacks.nodeadded.length; i &lt; l; i++) { this.callbacks.nodeadded[i](node); } }; DOMChildListMutationListenerFactory.prototype.MutationEventWrapper.prototype.nodeRemovedListener = function(event) { // Fire remove callbacks 'use strict'; var i, l, node = event.target || event.srcElement; for (i = 0, l = this.callbacks.noderemoved.length; i &lt; l; i++) { this.callbacks.noderemoved[i](node); } }; DOMChildListMutationListenerFactory.prototype.MutationEventWrapper.prototype.on = function(eventName, callback) { // Register an event callback and add the event listeners if required 'use strict'; eventName = eventName.toLowerCase(); if (this.callbacks[eventName] !== undefined &amp;&amp; typeof callback === 'function' &amp;&amp; this.callbacks[eventName].indexOf(callback) &lt; 0) { this.callbacks[eventName].push(callback); if (!this.insertObserving &amp;&amp; this.callbacks.nodeadded.length) { this.nodeInsertedListener = this.nodeInsertedListener.bind(this); this.element.addEventListener('DOMNodeInserted', this.nodeInsertedListener); this.insertObserving = true; } if (!this.removeObserving &amp;&amp; this.callbacks.noderemoved.length) { this.nodeRemovedListener = this.nodeRemovedListener.bind(this); this.element.addEventListener('DOMNodeRemoved', this.nodeRemovedListener); this.removeObserving = true; } } }; DOMChildListMutationListenerFactory.prototype.MutationEventWrapper.prototype.off = function(eventName, callback) { // De-register an event callback and remove the event listeners if no callbacks left 'use strict'; var i; eventName = eventName.toLowerCase(); if (this.callbacks[eventName] !== undefined) { i = this.callbacks[eventName].indexOf(callback); if (i &gt; -1) { this.callbacks[eventName].splice(i, 1); } if (this.insertObserving &amp;&amp; !this.callbacks.nodeadded.length) { this.element.removeEventListener('DOMNodeInserted', this.nodeInsertedListener); this.insertObserving = false; } if (this.removeObserving &amp;&amp; !this.callbacks.noderemoved.length) { this.element.removeEventListener('DOMNodeRemoved', this.nodeRemovedListener); this.removeObserving = false; } } }; /* * Example Usage */ var factory = new DOMChildListMutationListenerFactory(); var listener = factory.getListener(document.getElementById('some-element')); listener.on('NodeAdded', function(addedNode) { // Do stuff here }); </code></pre>
[ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-11-06T01:49:51.723", "Id": "29132", "Score": "0", "body": "Any reason you're not declaring `'use strict'` globally?" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-11-06T05:21:38.550", "Id": "29138", "Score": "2", "body": "Those functions are quite a mouth-full" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-11-06T08:02:56.777", "Id": "29141", "Score": "1", "body": "JS !== Java. Factories?! Come on..." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-11-06T09:17:41.857", "Id": "29142", "Score": "0", "body": "@JosephSilber Because JSLint complains about it, that's the sole reason." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-11-06T09:23:09.937", "Id": "29143", "Score": "0", "body": "@FlorianMargaine I would be quite happy to use an alternative approach, but I have yet to understand why this is such a problem. The above code works, does not continually redeclare methods because everything is done on the prototype, and because it's a factory I can avoid tight coupling. I am open to other approaches (that's why I posted the question) but can you explain the better approach and *why* it is better?" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-11-06T09:26:41.257", "Id": "29144", "Score": "0", "body": "@Zirak Indeed they are but a) they are accurate descriptions of what they do and b) one of the places this code will be used is in the environment of a Firefox extension, where all extensions (ridiculously, as far as I can work out from the docs) share a namespace. As a result I try to name my global objects in a way that minimises collision risk." } ]
[ { "body": "<p>2 observations:</p>\n\n<ol>\n<li><p>You can place 'use strict' in an IIFE, which keeps lint happy and it's DRYer</p>\n\n<pre><code>function DOMChildListMutationListenerFactory() {'use strict';}\n\n(function () \n{\n 'use strict';\n /* Do your thing with DOMChildListMutationListenerFactory.prototype,\n no need to repeat 'use strict */\n}();\n</code></pre></li>\n<li><p>You can assign all functions to a prototype with Object Literal Notation like you do for <code>MOFactory</code>. So you do not need to repeat over a dozen times \n<code>DOMChildListMutationListenerFactory.prototype</code>. </p></li>\n</ol>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-12-12T18:36:51.940", "Id": "37241", "ParentId": "18269", "Score": "2" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "6", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-11-06T00:15:15.237", "Id": "18269", "Score": "4", "Tags": [ "javascript", "dom" ], "Title": "Simple DOM mutation abstraction" }
18269
<p>Recently, I've been thinking about better ways to make my WP themes more maintainable. What I've tried on one of my last projects is to separate out the presentation and logic as much as I can. First, I created a function with the loop in it and has all of the logic. It returns all of the data into an array. In the template page, I call the function, loop through the array, and output the HTML.</p> <p>At the most basic level, this is what it looks like. In functions.php (or a plugin):</p> <pre><code>function get_data(){ if (have_posts()) : while (have_posts()) : the_post(); $results['title'] = get_the_title(); $results['field'] = get_field('field'); endwhile; endif; return $results; } </code></pre> <p>In the template file:</p> <pre><code>query_posts( 'posts_per_page=5' ); $results = get_data(); foreach ($results as $result) : &lt;section&gt; &lt;h1&gt;echo $result['title'];&lt;/h1&gt; echo $result['field']; &lt;/section&gt; endforeach; </code></pre> <p>Is this a good practice? From what I can see, it's a good solution but I haven't seen any other developers use it. Is there something better that other people are doing?</p>
[]
[ { "body": "<p>Actually, there is something better, and that is <strong>using templates</strong>. Yes, it might be \"radical\" especially when you see no other developer near you use it. And yes, even my college instructors and friends don't know what templates are and still stuff logic with the presentation so I know how it feels as well.</p>\n\n<p>I suggest you take a look at <a href=\"https://github.com/bobthecow/mustache.php\" rel=\"nofollow\">Mustache</a> for starters. Basically, your templates will be logicless. The template will only contain a bit of custom markup. What your logic will only need to do is load the data, load the template, use the render function and it returns rendered markup, complete with the data.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-11-06T04:59:01.810", "Id": "18276", "ParentId": "18275", "Score": "2" } }, { "body": "<p>Your <code>get_data()</code> function is broken. You are overwriting <code>$results['title']</code> and <code>$results['field']</code> on each iteration, instead of appending it to $results array. Moreover, if no posts existed to loop over, you'd get an \"undefined variable $results\" notice. Let's fix both issues:</p>\n\n<pre><code>function get_data(){\n $results = array(); // &lt;- Initialize array to prevent \"undefined variable\" notices\n if (have_posts()) : \n while (have_posts()) : the_post();\n $results[] = array( // &lt;- Append a new result set to the results\n 'title' =&gt; get_the_title(),\n 'field' =&gt; get_field('field'),\n );\n endwhile;\n endif;\n return $results;\n}\n</code></pre>\n\n<p>About the code in your template file, it'd be better not to use <code>query_posts()</code> at all. Use the <code>pre_get_posts</code> hook to alter the main query if needed. Please, <a href=\"https://wordpress.stackexchange.com/questions/50761/when-to-use-wp-query-query-posts-and-pre-get-posts/50762\">see this question over at WordPress Answers</a>.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-11-07T13:20:21.273", "Id": "18314", "ParentId": "18275", "Score": "1" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-11-06T04:50:43.390", "Id": "18275", "Score": "2", "Tags": [ "php" ], "Title": "Separating logic and presentation in wordpress" }
18275
<p>I posted a question last week <a href="https://codereview.stackexchange.com/questions/18158/improve-on-an-after-create-callback-with-database-queries-ruby-on-rails">about refactoring an after_create callback</a>. The code in this question is for the create action. I'm using Stripe to handle credit card payments and am roughly following the <a href="http://railscasts.com/episodes/288-billing-with-stripe" rel="nofollow noreferrer">railscast on Stripe integration</a>.</p> <p>Here's my create action on the Payment model:</p> <pre><code>def create @unpaid_subs = Subscription.where(:user_id =&gt; current_user.id).unpaid.includes(:course) @payment = Payment.new(params[:payment]) @payment.user_id = current_user.id @payment.email = current_user.email @payment.kind = @payment.determine_kind @payment.amount = calculate_cost(@unpaid_subs) if @payment.save_with_payment redirect_to dashboard_url, :notice =&gt; "Thank you for Paying!" else render :action =&gt; 'new' end end </code></pre> <p>I am going to change the model associations so that payment <code>belongs_to :user</code>, so setting the user_id and email will go away. Here's the <code>save_with_payment</code> method:</p> <pre><code>def save_with_payment if valid? charge = Stripe::Charge.create(amount: amount, description: "Charge for #{email}", card: stripe_card_token, currency: "usd") save! end rescue Stripe::InvalidRequestError =&gt; e logger.error "Stripe error while creating charge: #{e.message}" errors.add :base, "There was a problem with your credit card." false end </code></pre> <p><code>determine_kind</code> is a simple if conditional for setting the kind attribute. <code>calculate_cost</code> is in a module right now and included where needed.</p> <pre><code>def calculate_cost(unpaid) # Used to return amount total in cents for payment @amount_in_pesos = BigDecimal.new(unpaid.size) * COURSE_COST @amount_in_cents = (@amount_in_pesos.div(EXCHANGE_RATE, 10).round(2) * 100).to_i @amount = @amount_in_cents @amount end </code></pre> <p>So, I'm mainly wanting general suggestions for improvement of this code. I was a little confused as to where calculate_cost should go (maybe as a method on the Payment model, even though it doesn't use an instance of Payment). Is there any better way to handle the call to the Stripe API?</p>
[]
[ { "body": "<p>Most of the following can be summed up as the ol' Rails rule-of-thumb: <em>Skinny controller, fat model</em></p>\n\n<hr>\n\n<p><strong>1. Move logic to the model, and make it automatic</strong></p>\n\n<p>If you're doing this:</p>\n\n<pre><code>@payment.kind = @payment.determine_kind\n</code></pre>\n\n<p>it means that the logic should move to the model itself. If the model's doing the logic already and the result is saved to the very same model, why involve the controller at all?</p>\n\n<p>Instead, you should do this:</p>\n\n<pre><code>class Payment &lt; ActiveRecord::Base\n before_create :set_kind # determine and set the :kind attribute\n # ...\n\n private\n\n def set_kind\n self.kind = ... code ...\n end\nend\n</code></pre>\n\n<p>However, there may be an even cleaner solution. As far as I can tell, <code>determine_kind</code> probably relies solely on information already in the payment record.</p>\n\n<p>If that's the case, there may not be a reason to have a <code>kind</code> attribute/column at all. Just add a <code>kind</code> method to the <code>Payment</code> model:</p>\n\n<pre><code>class Payment &lt; ActiveRecord::Base\n # ...\n def kind\n # same code as `determine_kind`\n end\n # ...\nend\n</code></pre>\n\n<p>Now you can say <code>some_payment.kind</code> and get the kind without storing it in the database at all.</p>\n\n<p><strong>Note:</strong> this <em>won't</em> work if <code>kind</code> must be \"kind as determined <em>at the time of creation</em>\" <em>or</em> if you're doing database queries that involve the <code>kind</code> column. If either of those is the case, you can still use the <code>before_create</code> approach above.</p>\n\n<hr>\n\n<p><strong>2. Add <code>calculate_cost</code> to the collection</strong></p>\n\n<p>Here's what I'd do:</p>\n\n<p>First, I'd move <code>COURSE_COST</code> to a <code>COST</code> constant on the <code>Course</code> model (accessible as <code>Course::COST</code>). That seems the most logical place to keep it. It'd probably be smart to also move <code>EXCHANGE_RATE</code> to <code>Payment::EXCHANGE_RATE</code> while you're at it.<br>\nOh, and \"exchange rate\" is a little ambiguous: It's the rate from what to what? Pesos to USD? Or the other way around? Would be good to make the name more descriptive.</p>\n\n<p>Then, assuming \"user has_many subscriptions\", you can first of all do this:</p>\n\n<pre><code>@unpaid_subs = current_user.subscriptions.unpaid.includes(:course)\n</code></pre>\n\n<p>but it also means that you can define modules that should be added to the collection. In your case, you make a module like so:</p>\n\n<pre><code># in app/modules/subscription_collection.rb\nmodule SubscriptionCollection\n def cost\n pesos = count * Course::COST\n usd = pesos / Payment::EXCHANGE_RATE\n (usd * 100).round\n end\nend\n</code></pre>\n\n<p>(I skipped the <code>BigDecimal</code> stuff because I didn't think it necessary, but as covered in the comments, it might be. I'll leave the code as is, though. <code>BigDecimal</code> or not, the procedure's the same.)</p>\n\n<p>And then include that module in the relation declaration</p>\n\n<pre><code>class User &lt; ActiveRecord::Base\n has_many :subscriptions, :extend =&gt; SubscriptionCollection\n # ...\nend\n</code></pre>\n\n<p>Now, whenever you get a collection of subscriptions via a user model you can simply call <code>cost</code> on the collection itself, and get the total cost.</p>\n\n<hr>\n\n<p>Now you should be able to say:</p>\n\n<pre><code>def create\n @unpaid_subs = current_user.subscriptions.unpaid.includes(:course)\n @payment = current_user.payments.new(params[:payment])\n\n @payment.amount = @unpaid_subs.cost\n\n if @payment.save_with_payment\n redirect_to dashboard_url, :notice =&gt; \"Thank you for Paying!\"\n else\n render :action =&gt; 'new'\n end\nend\n</code></pre>\n\n<p><em>Last little thing: This is just me, but the name <code>save_with_payment</code> is a little iffy, since the model's already called <code>payment</code>. So, \"save payment with payment\" seems semantically messy. I'd suggest something like <code>charge_and_save</code> instead. You might also want to raise an exception if someone tries to call the method on an already-charged payment. You don't want to accidentally charge people multiple times!</em></p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-11-06T18:55:55.273", "Id": "29149", "Score": "0", "body": "Wow, thanks a bunch for the detailed answer. Payment.kind indicates the payment method (we have 2 available so far). It will be set using a `hidden_field` in the future (just haven't done it yet). One question though: I thought BigDecimal was needed for accuracy of calculating decimals. Do the standard arithmetic functions not use a float unless you specifically convert to a float?" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-11-07T01:17:22.180", "Id": "29154", "Score": "0", "body": "@GorrillaMcD Makes sense with regard to `kind`. As for float versus BigDecimal, you're probably right. I forgot for a moment that we were dealing with money - sorry. However, it might be a lot easier to simply _always_ use cents and thus integers. No BDs or floats to contend with. You're storing `amount` as an int anyway, so it might be useful to make the course-cost an int as well. [Here's a discussion on BD vs float](http://www.ruby-forum.com/topic/155183) that also mentions the Money gem, which might be worth looking into." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-11-07T01:26:04.003", "Id": "29156", "Score": "0", "body": "Yeah, I should look at it and use cents where I can, especially since Stripe only accepts `amount` in cents and db is set for that as well. The problem arises with the conversion between pesos and dollars, since that almost always produces a decimal number. I need to look at the money gem, but I wanted to do it myself this time so I could learn and understand for myself what's going on." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-11-07T01:38:31.170", "Id": "29159", "Score": "0", "body": "@GorrillaMcD Well, if all the amounts and costs are always in cents, there's little room for rounding errors - you don't need precision to the nth decimal, since cents don't have decimals anyway. And I think it's great you're trying it yourself! But be sure to write some very robust tests; don't blunder through like I just did :)" } ], "meta_data": { "CommentCount": "4", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-11-06T13:14:38.920", "Id": "18283", "ParentId": "18278", "Score": "1" } } ]
{ "AcceptedAnswerId": "18283", "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-11-06T05:36:20.010", "Id": "18278", "Score": "2", "Tags": [ "ruby", "ruby-on-rails" ], "Title": "Create Action in Rails 3.2" }
18278
<p>I am making a review system and I need to be able to only select the DISTINCT url from the database, but then pull the relevant page title and rating time. I have managed to get it working by using:</p> <pre><code>&lt;?php //opens conection include 'conn.php'; echo $_COOKIE["search"]; $sql = "SELECT * FROM feedback WHERE url LIKE '%$_COOKIE[search]%' GROUP BY url ORDER BY ratingtime DESC"; //runs the query $query = mysql_query($sql); $linecount = 1; //populates the table with the information echo '&lt;table id="myTable" class="tablesorter"&gt;'; echo'&lt;thead&gt; &lt;tr class ="null"&gt; &lt;th&gt;URL&lt;/th&gt; &lt;th&gt;Page Title&lt;/th&gt; &lt;th&gt;Date Last Modified&lt;/th&gt; &lt;th&gt;Average Rating&lt;/th&gt; &lt;/tr&gt; &lt;/thead&gt;'; echo '&lt;tbody&gt;'; echo '&lt;tr&gt;'; while($row = mysql_fetch_array($query)) { echo '&lt;td class="overFlow"&gt;&lt;a href="extra_info.php?url='.$row['url'].'"&gt;' .$row['url']. '&lt;/a&gt;&lt;/td&gt;'; echo '&lt;td&gt;&lt;a href="extra_info.php?url='.$row['url'].'"&gt;' . $row['pagetitle'] . '&lt;/a&gt;&lt;/td&gt;'; echo '&lt;td&gt;' . $row['ratingtime'] . '&lt;/td&gt;'; $check = mysql_query("SELECT `rating` FROM feedback WHERE url = '$row[url]'"); $totalvotes = mysql_num_rows($check); $result = mysql_query("SELECT SUM(rating) AS 'rating_total' FROM feedback WHERE url = '$row[url]'") or die(mysql_error()); $row = mysql_fetch_assoc($result); $add = $row['rating_total']; $average = $add / $totalvotes; echo '&lt;td&gt;' .round($average, 2). '&lt;/td&gt;'; echo '&lt;/tr&gt;'; $linecount++; } echo '&lt;/tbody&gt;'; echo "&lt;/table&gt;"; ?&gt; </code></pre> <p>I just wondered if there was a much better way to go about doing this? I am a complete noob when it come to php so if you provide any advice could you please provide evidence/documentation so that I can read up on it and learn.</p>
[]
[ { "body": "<p>I would do it like this</p>\n\n<pre><code>&lt;?php\n#opens conection\ninclude 'conn.php';\n\necho $_COOKIE[\"search\"];\n\n\n$search = mysql_real_escape_string($_COOKIE[search]);\n$sql = \"SELECT * FROM feedback WHERE url LIKE '%{$search}%' GROUP BY url ORDER BY ratingtime DESC\";\n#runs the query\n$query = mysql_query($sql);\n$linecount = 1;\n\n#populates the table with the information\necho '&lt;table id=\"myTable\" class=\"tablesorter\"&gt;';\necho '&lt;thead&gt;\n &lt;tr class =\"null\"&gt;\n &lt;th&gt;URL&lt;/th&gt;\n &lt;th&gt;Page Title&lt;/th&gt;\n &lt;th&gt;Date Last Modified&lt;/th&gt;\n &lt;th&gt;Average Rating&lt;/th&gt;\n &lt;/tr&gt;\n &lt;/thead&gt;\n &lt;tbody&gt;';\n\nwhile($row = mysql_fetch_array($query)){\n\n $sqlurl = mysql_real_escape_string($row['url']);\n\n $feedback_query = mysql_query(\"SELECT SUM(`rating ) / COUNT(`rating`) AS avg_rating FROM feedback WHERE url = '{$sqlurl}'\");\n $feedback = mysql_fetch_assoc($feedback_query);\n\n $encodedurl = urlencode($row['url']);\n\n echo \"&lt;tr&gt;\n &lt;td class'overFlow'&gt;&lt;a href='extra_info.php?url={$encodedurl}'&gt;{$row['url']}&lt;/a&gt;&lt;/td&gt;\n &lt;td&gt;&lt;a href='extra_info.php?url={$encodedurl}'&gt;{$row['pagetitle']}&lt;/a&gt;&lt;/td&gt;\n &lt;td&gt;{$row['ratingtime']}&lt;/td&gt;\n &lt;td&gt;\".round($feedback['avg_rating'], 2).\"&lt;/td&gt;\n &lt;/tr&gt;\";\n $linecount++;\n}\n\necho '&lt;/tbody&gt;\n &lt;/table&gt;';\n?&gt;\n</code></pre>\n\n<p>If improved your query to get the Avg. Rating and added <code>mysql_real_escape_string</code> to prevent the mysql injection vulnerability. </p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-11-06T16:57:34.917", "Id": "29147", "Score": "1", "body": "Other than the above mentioned code, what other positives are there to they way you have produced your code? MySQL injection isn't really an issue currently but thankyou for pointing that out to me" } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-11-06T16:32:45.317", "Id": "18287", "ParentId": "18285", "Score": "1" } } ]
{ "AcceptedAnswerId": "18287", "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-11-06T16:11:11.227", "Id": "18285", "Score": "2", "Tags": [ "php", "mysql" ], "Title": "Need unique url but require non unique information from other columns" }
18285
<p>I'm pretty new to asp and c# and I have a couple of concerns with the security of the code I have written (shown below). Basically all it does is allow you to enter a quantity before you add the item to your cart using a razor form.</p> <p>Every example I see uses validation on input fields, like: </p> <pre><code>[Required] [DataType(DataType.EmailAddress)] </code></pre> <p>Is that sort of validation (or any other) necessary in this case, or is my form secure enough because the controller requires the input of the product id and the quantity, both of which are limited to integers? Also, is there anything else that I should be concerned about with this form, like Javascript injection? </p> <p>Thanks for your help!</p> <p>The view has a razor input form:</p> <pre><code>@using ( Html.BeginForm( "AddToCart", "Cart" ) ) { @Html.HiddenFor(_ =&gt; item .ProductID) @Html.TextBoxFor(_=&gt; item.Quantity) &lt;input type="submit" value="+ Add to cart" /&gt; } </code></pre> <p>The form is posted to the AddToCart action of the CartController:</p> <pre><code>[HttpPost] public ActionResult AddToCart(int id, int quantity) { // Retriebe the product from the database var addedProduct = storeDB.Products .Single(product =&gt; product.ProductId == id); // Add it to the shopping cart var cart = ShoppingCart.GetCart(this.HttpContext); cart.AddToCart(addedProduct, quantity); //Go back to the main store page for more shopping return RedirectToAction("Index"); } </code></pre> <p>And here is the AddToCart method:</p> <pre><code>public void AddToCart(Product product, int quantity) { //Get the matching cart and album instances var cartItem = storeDB.Carts.SingleOrDefault( c =&gt; c.CartId == ShoppingCartId &amp;&amp; c.ProductId == product.ProductId); if (cartItem == null) { // Create a new cart item if no cart exists cartItem = new Cart { ProductId = product.ProductId, CartId = ShoppingCartId, Count = quantity, DateCreated = DateTime.Now }; storeDB.Carts.Add(cartItem); } else { // If the item does exist in the car, // than add one to the quantity var newCount = cartItem.Count + quantity; cartItem.Count = newCount; } // Save changes storeDB.SaveChanges(); } </code></pre> <p>Thanks again for your help!</p>
[ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-11-06T22:59:59.907", "Id": "29151", "Score": "1", "body": "What exactly do you mean by 'secure'?" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-11-08T18:38:53.117", "Id": "29250", "Score": "0", "body": "I'm not that familiar with ShoppingCarts but don't they normally have some sort of timeout? In that case if the ShoppingCart timedout by the time this request happens what would happen to the line ShoppingCart.GetCart() ??" } ]
[ { "body": "<p>Security is an important aspect of any application, so you must evaluate what you want to do for security.If this is a public portal then you need to make sure all query string value are safe and no problem with the input value , MVC also does care these things automatically but t to make sure you can double check this params.</p>\n\n<p>like in this case you can make sure quantity cannot be zero or product ID cannot be zero.</p>\n\n<p>It depends upon your requirement and your security model.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-11-08T08:33:00.947", "Id": "29216", "Score": "0", "body": "Checking that the quantity or product Id is not zero is validation, not security." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-11-08T09:31:51.113", "Id": "29219", "Score": "2", "body": "validation is also a form of security... input type should be secured by means of validation." } ], "meta_data": { "CommentCount": "2", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-11-08T07:28:55.490", "Id": "18340", "ParentId": "18286", "Score": "1" } }, { "body": "<p>You can secure against CSRF (pronounced C-surf) by using ValidateAntiForgeryTokenAttribute and AntiForgeryToken method.</p>\n\n<p>How CSRF (Cross Site Request Forgery) works: </p>\n\n<blockquote>\n <p>We have 2 actors, an evil person E and a good person G. E makes an\n evil html image tag on some forum, that links to your website and puts\n a product in your user's cart.</p>\n \n <p>If G has a cookie for your site and the cookie is not expired, when G\n goes to E's forum, the browser tries to load the html img and it will\n send a <em>Request</em> to your site. Even though G didn't intend to do that...</p>\n</blockquote>\n\n<p>Implementation:</p>\n\n<p>View:</p>\n\n<pre><code>@using (Html.BeginForm(\"AddToCart\", \"Cart\"))\n{\n @HtmlHelper.AntiForgeryToken()\n // Code --&gt;\n}\n</code></pre>\n\n<p>Controller:</p>\n\n<pre><code>[HttpPost][ValidateAntiForgeryToken]\npublic ActionResult AddToCart(int id, int quantity)\n{\n // Code --&gt;\n}\n</code></pre>\n\n<p>How it prevents CSRF:</p>\n\n<ol>\n<li>In the view a hidden input field with a unique string is created.</li>\n<li>A cookie is sendt to the user with the same string. (I believe it is a httpOnly cookie).</li>\n<li>The controller checks if the form contains the same string as is in the cookie.</li>\n</ol>\n\n<p>Because person E, cannot form a valid form post the cross site request will fail. But note that if you have XSS (Cross site scripting) vulnerability this security check can be circumvented.</p>\n\n<p>And another thing... If your 2nd method <code>public void AddToCart(Product product, int quantity)</code> is not an action consider using the [NonAction] attribute, because all public methods in a controller are considered by default Action methods. Meaning it is invokable as an Action method.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-11-12T05:15:33.800", "Id": "29466", "Score": "0", "body": "I would go as far at the controller level to say, if it's not an action it should in general be private." } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-11-12T03:06:00.027", "Id": "18478", "ParentId": "18286", "Score": "2" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "2", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-11-06T16:28:32.503", "Id": "18286", "Score": "6", "Tags": [ "c#", "html", "security", "asp.net-mvc-3" ], "Title": "Is this user input field secure?" }
18286
<p>I'd like to display a vector (implemented in my custom <code>Vector</code> class) and have the output width of the elements be configurable. I've done this by creating a simple wrapper for the element being displayed which stores the desired width in a static field. I'm not sure if this is the best approach.</p> <pre><code>/** A struct for formatting doubles with a fixed width. */ struct FixedWidthDouble { FixedWidthDouble(double x) : x_(x) {} double x_; static int width_; }; /** Apply a fixed width manipulator to a double for display. */ std::ostream&amp; operator&lt;&lt;(std::ostream&amp; out, const FixedWidthDouble &amp;fixedWidthDouble) { return out &lt;&lt; std::setw(fixedWidthDouble.width_) &lt;&lt; fixedWidthDouble.x_; } </code></pre> <p>Here's an example of it being applied:</p> <pre><code>/** Convert a Vector into a stream suitable for display. */ std::ostream&amp; Vector::Print(std::ostream&amp; out, int width) const { out &lt;&lt; "[" &lt;&lt; std::setprecision(1) &lt;&lt; std::fixed; FixedWidthDouble::width_ = width; std::copy(begin(), end(), std::ostream_iterator&lt;FixedWidthDouble&gt;(out, " ")); return out &lt;&lt; " ]"; } </code></pre> <p>Is there a cleaner way to do this?</p> <p><strong>Proposed Solution</strong></p> <p>Based on feedback from Begemoth this is the solution I decided to go with. Does this look reasonable?</p> <pre><code>template&lt;int width&gt; struct FixedWidthDouble { FixedWidthDouble(double x) : x_(x) {} double x_; }; /** Apply a fixed width manipulator to a double for display. */ template &lt;int width&gt; std::ostream&amp; operator&lt;&lt;(std::ostream&amp; out, const FixedWidthDouble&lt;width&gt; &amp;fixedWidthDouble) { return out &lt;&lt; std::setw(width) &lt;&lt; fixedWidthDouble.x_; } /** Convert a Vector into a stream suitable for display. */ template &lt;int width&gt; std::ostream&amp; Vector::Print(std::ostream&amp; out) const { out &lt;&lt; "[" &lt;&lt; std::setprecision(1) &lt;&lt; std::fixed; std::copy(begin(), end(), std::ostream_iterator&lt;FixedWidthDouble&lt;width&gt; &gt;(out, " ")); return out &lt;&lt; " ]"; } </code></pre>
[]
[ { "body": "<p>There are one problem with your approach you make local information global as consequence your <code>FixedWidthDouble</code> class is not thread-safe. There is a simple way to solve the problem by turning <code>width_</code> into a integral template argument of the class template <code>template&lt;int width&gt; FixedWidthDouble</code>.</p>\n\n<p>In C++11 I'd use range-based for:</p>\n\n<pre><code>std::ostream&amp; Vector::Print(std::ostream&amp; out, int width) const\n{\n out &lt;&lt; \"[\" &lt;&lt; std::setprecision(1) &lt;&lt; std::fixed;\n for (auto&amp; x : *this)\n out &lt;&lt; std::setw(width) &lt;&lt; x;\n return out &lt;&lt; \" ]\";\n}\n</code></pre>\n\n<p>In the old C++98 it is cleaner to use old <code>for</code> with iterators. Also you can create a new iterator type that will set the width:</p>\n\n<pre><code>template&lt;typename T, typename CharT = char, typename Traits = std::char_traits&lt;CharT&gt; &gt;\nclass width_ostream_iterator\n : public std::iterator&lt;std::output_iterator_tag, void, void, void, void&gt;\n{\npublic:\n typedef CharT char_type;\n typedef Traits traits_type;\n typedef std::basic_ostream&lt;CharT, Traits&gt; ostream_type;\n\nprivate:\n ostream_type* stream;\n const CharT* separator;\n int width;\n\npublic:\n explicit width_ostream_iterator(ostream_type&amp; stm, int width, const CharT* separator = 0)\n : stream(&amp;stm), separator(separator), width(width)\n { }\n\n width_ostream_iterator&amp; operator=(const T&amp; value)\n {\n *stream &lt;&lt; std::setw(width) &lt;&lt; value;\n if (separator) *stream &lt;&lt; separator;\n return *this;\n }\n\n width_ostream_iterator&amp; operator*() { return *this; }\n width_ostream_iterator&amp; operator++() { return *this; }\n width_ostream_iterator&amp; operator++(int) { return *this; }\n};\n</code></pre>\n\n<p><strong>Update:</strong> Your proposed solution is valid if the width can only be changed at compile time, if you want to change the width at the runtime (e.g. from configuration file or command line arguments) you have to use plain <code>for</code> loop or the <code>width_ostream_iterator</code> I've provided. One thing I do not like about the <code>width_ostream_iterator</code> — it is definitely a library entity intended to be used in multiple places but it allows you only to change the width of the field and nothing else. It is too specific for the library (it does not allow an arbitrary manipulator to a stream before outputting a value) it is too complicated for a single use.</p>\n\n<p>And one more note: the <code>Print</code> function uses only public interface of the vector (I assume that <code>begin</code> and <code>end</code> functions are public), so it does not required to be a member function. Prefer to make such functions free not member. Why not use member function for all class operations? You can extend the interface of a class without modifying it, e.g. you can have a <code>Vector</code> class and stream I/O operations defined in separate headers, you can later add another I/O operations (e.g. for <code>QDataStream</code>) in a third header and you will not have to recompile the parts of the program that depend only on the first and second headers. Your <code>Print</code> function can potentially work with any class which looks and behaves like a standard sequence, just like any algorithm from the standard library. The class (just a function) must do one thing well, the <code>Vector</code> class stores a number of values of some type and provides constant-time random-access to the elements, it doesn't sort elements (that what <code>std::sort</code> algorithm is for), it does not search for elements (that what <code>std::find</code> and <code>std::find_if</code> algorithms are for), it does nit provide elementwise arithmetic operations (oops, there is no <code>std::zip</code> to combine several sequences into one), etc.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-11-07T09:50:01.340", "Id": "29170", "Score": "0", "body": "Thank you. I was think of using template<int width> as you suggested however I wasn't sure how to write operator<< for a generic FixedWidthDouble. Could you please show how this is done?" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-11-07T13:01:46.847", "Id": "29185", "Score": "0", "body": "Thank you again. Could you expand a little on why you prefer not to make such methods a member? I come from a Java background where everything belongs to a class so I always get a strange feeling when I define a global function. Could you give some advice on when global functions are the 'right' thing to do in C++? Perhaps global functions are somewhat like static member functions in Java?" } ], "meta_data": { "CommentCount": "2", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-11-07T05:53:58.053", "Id": "18298", "ParentId": "18291", "Score": "6" } } ]
{ "AcceptedAnswerId": "18298", "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-11-06T21:49:37.703", "Id": "18291", "Score": "7", "Tags": [ "c++", "iterator", "stl" ], "Title": "Setting output width with ostream_iterator" }
18291
<p>I am asking this for coding style. I have a program class that calls a function(of a data access class) that reads from a table (using entity framework by the way), and I'm preparing to write the <code>DataAccess.ReadMethod()</code>. </p> <p>Is it better to pass the function a 2d string array <code>string[rows][fields]</code>, reading each field and each row, and put it in the <code>DataAccess.ReadMethod</code>'s out parameter <code>string[rows][fields]</code> to return to the main program and have the main program display it? or just repeatedly call the <code>DataAccess.ReadMethod(string[fields])</code> and in the main program print each record out individually to the console? </p> <p>I imagine that my <code>ReadMethod()</code> will look something like this:</p> <pre><code>public class DataAccess { public Exception ReadMan(TestDatabaseEntities dbEntities, IQueryable myQuery, out string sManDetails) { Exception ex = null; sManDetails = ""; try { foreach (Man m in myQuery) { sManDetails += m.ManID.ToString() + " " + m.Name + "\n"; } } catch (Exception myException) { ex = myException; } return ex; } } </code></pre> <p>the calling code in program class looks like this:</p> <pre><code>class program { static private void DoRead() { var dbEntities = new TestDatabaseEntities(); UserInterface MyUI = new UserInterface(); DataAccess MyDA = new DataAccess(); Exception ex = null; string sMyMen = ""; var query = from person in dbEntities.Men where true select person; MyUI.DisplayDivider(); ex = MyDA.ReadMan(dbEntities, query, out sMyMen); if (ex != null) sMyMen = ex.ToString(); MyUI.DisplayMessage(sMyMen); MyUI.DisplayDivider(); } } </code></pre>
[ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-11-06T23:52:17.467", "Id": "29152", "Score": "1", "body": "Why are you even considering using an array of strings? Don't you have an entity for what you need?" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-11-07T01:27:51.963", "Id": "29157", "Score": "0", "body": "@svick `DataAccess.ReadMethod()` needs to return a variable which stores the contents that it read from the entity, i figured on storing the data in a string array, so that it can be passed back to the program class, and the program class can call my `UserInterface.DisplayMethod(string somestring)` method. I want to keep logic seperate from database access and UI." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-11-07T01:37:38.580", "Id": "29158", "Score": "0", "body": "@ArmorCode It might be best if you wrote the ReadMethod() with the way you imagine it to be done and then post the code for review? Otherwise I'm not sure if this is the best forum for your question....." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-11-07T04:08:14.777", "Id": "29163", "Score": "0", "body": "@dreza I updated the question to show some code. I thought about it some more and posted the code, now that I wrote it." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-11-07T05:37:21.977", "Id": "58459", "Score": "0", "body": "Could you start by sharing your thoughts about returning an Exception?\nPlease consult this link: [Is it a good idea to return an Exception from a method ?](http://stackoverflow.com/questions/973292/is-it-bad-practice-to-return-exceptions-from-your-methods)" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-11-07T14:53:58.253", "Id": "58460", "Score": "0", "body": "I thought that if I examined the exception returned, checked to see if it was null, that I could safely assume the function ran ok, and if it returned an exception, I would print out the exception instead of the data the function was supposed to retrieve." } ]
[ { "body": "<p>I have discovered, with thanks to you each, that it is better to call the display method within the DataAccess.ReadMethod() than to pass strings, Here's what I think i should do:</p>\n\n<pre><code>public class DataAccess\n{\n public bool CreateMan(TestDatabaseEntities dbEntities, Man M)\n {\n return TryDataBase(dbEntities, \"Man created successfully\",\n () =&gt;\n {\n dbEntities.Men.Add(new Man { ManID = M.ManID, Name = M.Name });\n });\n }\n\n public bool UpdateMan(TestDatabaseEntities dbEntities, IQueryable&lt;Man&gt; query, Man man)\n {\n return TryDataBase(dbEntities, \"Man updated Successfully\",\n () =&gt;\n {\n foreach (Man M in query)\n {\n M.Name = man.Name;\n }\n });\n }\n\n public bool DeleteMan(TestDatabaseEntities dbEntities, IQueryable myQuery)\n {\n return TryDataBase(dbEntities, \"Man deleted Successfully\",\n () =&gt;\n {\n foreach (Man M in myQuery)\n {\n dbEntities.Men.Remove(M);\n }\n });\n }\n\n public bool ReadMan(TestDatabaseEntities dbEntities, IQueryable myQuery)\n {\n UserInterface MyUI = new UserInterface();\n bool bSuccessful;\n\n bSuccessful = TryDataBase(dbEntities, \"Records read successfully\",\n () =&gt;\n { \n MyUI.DisplayDivider();\n foreach (Man m in myQuery)\n {\n MyUI.DisplayMessage(new string[] { m.ManID.ToString(), m.Name });\n }\n MyUI.DisplayDivider();\n });\n\n\n return bSuccessful;\n }\n\n public bool TryDataBase(TestDatabaseEntities MyDBEntities, string SuccessMessage, Action MyDBAction)\n {\n UserInterface MyUI = new UserInterface();\n try\n {\n MyDBAction();\n MyUI.DisplayMessage(SuccessMessage);\n return true;\n }\n catch (Exception e)\n {\n MyUI.DisplayMessage(e.ToString());\n return false;\n }\n }\n}\n</code></pre>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-11-07T22:45:51.273", "Id": "18330", "ParentId": "18292", "Score": "1" } } ]
{ "AcceptedAnswerId": "18330", "CommentCount": "6", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-11-06T23:35:22.090", "Id": "18292", "Score": "0", "Tags": [ "c#", "entity-framework" ], "Title": "using 2D array to read datatable ok? or repeatedly call function that reads record by record?" }
18292
<p>I've simplified this for posting, since there are going to be more than 4 options sets for this function to cycle through:</p> <pre><code>function redundantSee() { var optionSet1 = $('.wrapper:eq(0)'), optionSet2 = $('.wrapper:eq(1)'); optionSet1.find('.options').each(function(){ var self = $(this), input = self.find('input'), title = self.find('.title').text(), value = input.val(), source = self.find('img').attr('src'), id = input.attr('id'), listItem = $('&lt;li/&gt;', {'value': value, 'id': id }), imageElement = $('&lt;img/&gt;', {'src': source, 'title': title}); $('div.corresponding1').append(nameListItem); listItem.append(imageElement); }); optionSet2.find('.options').each(function(){ var self = $(this), input = self.find('input'), title = self.find('.title').text(), value = input.val(), source = self.find('img').attr('src'), id = input.attr('id'), listItem = $('&lt;li/&gt;', {'value': value, 'id': id }), imageElement = $('&lt;img/&gt;', {'src': source, 'title': title}); $('div.corresponding2').append(listItem); listItem.append(imageElement); }); } </code></pre> <p>I'm having a problem figuring out how to turn all of the repetitive code into something much more manageable. But since each option set has its own <code>each</code> loop, the <code>$(this)</code> variable (and all corresponding variables) are specific to the loop that is run on the (<code>'.options'</code>) element.</p> <p>If I do one each loop and use a counter, like this:</p> <pre><code>$('wrapper').each(function(i){ // ... }); </code></pre> <p>I still run into the problem of needing to re-declare all my new variables specific to that <code>optionSet</code>'s turn in the loop.</p> <p>Can someone help me figure out how I can condense this so that I'm not constantly repeating the same code every time I add a new option set to the function?</p>
[]
[ { "body": "<p>Create a function with the common code:</p>\n\n<pre><code>function redundantSee() {\n\n var optionSet1 = $('.wrapper:eq(0)'),\n optionSet2 = $('.wrapper:eq(1)');\n\n\n function addImage(correspond, item) {\n var self = $(this),\n input = self.find('input'),\n title = self.find('.title').text(),\n value = input.val(),\n source = self.find('img').attr('src'),\n id = input.attr('id'),\n listItem = $('&lt;li/&gt;', {'value': value, 'id': id }),\n imageElement = $('&lt;img/&gt;', {'src': source, 'title': title});\n\n $(correspond).append(item);\n item.append(imageElement);\n }\n\n optionSet1.find('.options').each(function() {addImage('div.corresponding1', nameListItem);})\n optionSet1.find('.options').each(function() {addImage('div.corresponding2', listItem);})\n}\n</code></pre>\n\n<hr>\n\n<p>Here's a further reduced version that is also a little more efficient:</p>\n\n<pre><code>function redundantSee() {\n function processSet(set, correspond, item) {\n set.find('.options').each(function() {addImage(correspond, item);})\n } \n\n function addImage(correspond, item) {\n var self = $(this),\n input = self.find('input'),\n title = self.find('.title').text(),\n value = input.val(),\n source = self.find('img').attr('src'),\n id = input.attr('id'),\n listItem = $('&lt;li/&gt;', {'value': value, 'id': id }),\n imageElement = $('&lt;img/&gt;', {'src': source, 'title': title});\n\n $(correspond).append(item);\n item.append(imageElement);\n }\n\n var wrappers = $('.wrapper');\n processSet(wrappers.eq(0), 'div.corresponding1', nameListItem);\n processSet(wrappers.eq(1), 'div.corresponding2', listItem);\n}\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-11-07T05:05:29.200", "Id": "29164", "Score": "0", "body": "These are two completely new ways for me to try out.... so definitely helpful. I always want to abstract the anonymous callback function of the each loop into its own function... wouldn't I be able to do that here by substituting .each(function(){addImage(correspond,item);} with .each(addImage(correspond,item);} ?" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-11-07T05:13:13.073", "Id": "29165", "Score": "0", "body": "@user1798630 - no. `.each()` takes a function reference and that function is called by `.each()` with two predetermined arguments. Your version executes `addImage()` immediately and passes the return result from that (which is nothing) to `.each()` as the function reference. It will not work. You have to pass a function reference - you can't call it right away and you can't determine what the arguments are." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-11-07T05:18:01.543", "Id": "29167", "Score": "0", "body": "I see... that makes sense now. That actually clears up some other issues that I've had with callbacks too. I appreciate the help!" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-11-08T04:28:13.167", "Id": "29210", "Score": "0", "body": "Because extending jQuery was suggested on my initial post, and it looked like the simplest option, I chose that. It required only one function definition with a few parameters. I appreciate you looking at my code and offering solutions though... it helps me think about it in a different way." } ], "meta_data": { "CommentCount": "4", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-11-07T03:22:07.467", "Id": "18294", "ParentId": "18293", "Score": "1" } }, { "body": "<p>Pretty much explained in the comments</p>\n\n<pre><code>//extract reusable code\nfunction operateOptions(el, correspondsTo) {\n\n\n var self = $(el),\n input = self.find('input'),\n id = input.attr('id'),\n value = input.val(),\n title = self.find('.title').text(),\n source = self.find('img').attr('src'),\n listItem = $('&lt;li/&gt;', {\n 'value': value,\n 'id': id\n }),\n imageElement = $('&lt;img/&gt;', {\n 'src': source,\n 'title': title\n });\n\n //chain methods\n listItem.append(imageElement).appendTo(correspondsTo);\n}\n\n//create function that accepts multiple options\nfunction redundantSee(list) {\n\n //loop through each option\n $.each(list, function (optionSet, correspondsTo) {\n\n //operate on each option in the optionSet\n $(optionSet).find('.options').each(function (i, el) {\n\n //send over the option element and it's corresponding selector\n operateOptions(el, correspondsTo);\n });\n });\n}\n\nredundantSee({'.wrapper:eq(0)': 'div.corresponding1', '.wrapper:eq(1)': 'div.corresponding2'});​\n</code></pre>\n\n<hr>\n\n<p>Here's a pretty-printed, cleaned version:</p>\n\n<pre><code>function operateOptions(el, correspondsTo) {\n var self = $(el),\n input = self.find('input'),\n id = input.attr('id'),\n value = input.val(),\n title = self.find('.title').text(),\n source = self.find('img').attr('src'),\n listItem = $('&lt;li/&gt;', {\n 'value': value,\n 'id': id\n }),\n imageElement = $('&lt;img/&gt;', {\n 'src': source,\n 'title': title\n });\n listItem.append(imageElement).appendTo(correspondsTo);\n}\n\nfunction redundantSee(list) {\n $.each(list, function (optionSet, correspondsTo) {\n $(optionSet).find('.options').each(function (i, el) {\n operateOptions(el, correspondsTo);\n });\n });\n}\nredundantSee({'.wrapper:eq(0)': 'div.corresponding1', '.wrapper:eq(1)': 'div.corresponding2'});​\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-11-07T05:13:15.030", "Id": "29166", "Score": "0", "body": "This is interesting. I'm gonna try this out cause it is such a different way of thinking than I am used to. So $.each's first parameter 'list' is operated on by the callback for each element. It looks like what I understand $.map would do.. but I have not used $.map yet, so not sure of the differences. Anyway, very cool and I'm gonna give this a whirl. So many different ways to go on this one!" } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-11-07T03:33:24.757", "Id": "18295", "ParentId": "18293", "Score": "1" } }, { "body": "<p>It doesn't make much sense to put <code>&lt;li&gt;</code> elements inside a <code>&lt;div&gt;</code>. <a href=\"http://dev.w3.org/html5/html-author/#the-li-element\" rel=\"nofollow\">By the HTML5 specification</a>, <code>&lt;li&gt;</code> elements belong inside <code>&lt;ol&gt;</code>, <code>&lt;ul&gt;</code>, or <code>&lt;menu&gt;</code> only. If you don't want it to look like a bulleted list, use CSS to suppress the list styling. But don't use a <code>&lt;div&gt;</code> to contain a list — it violates the spec and is semantically inferior is well.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2015-04-02T13:25:02.833", "Id": "154400", "Score": "0", "body": "Thanks for correcting me on the HTML5 spec. However, this is a JavaScript / jQuery question. Most likely I was inserting HTML into an already prepared DOM that was generated with someone else's PHP code, and it probably wasn't using HTML5. Either way, thanks for keeping me up to spec." } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2015-04-01T06:22:39.920", "Id": "85561", "ParentId": "18293", "Score": "0" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-11-07T03:14:13.040", "Id": "18293", "Score": "3", "Tags": [ "javascript", "jquery", "dom" ], "Title": "Populating two lists, each from their respective with user input field" }
18293
<p>I am doing a database design I want to create a database with information of employees, their jobs, salaries and projects.</p> <p>I want to keep information of the cost of a project (real value of project and the days a employee invested).</p> <p>For <code>Employee</code> and <code>Project</code>, each <code>Employee</code> has one role on the <code>Project</code> through the PK constraint, and allows for the addition of a new role type ("Tertiary" perhaps) in the future. To get the total amount of the cost of a project and have it for future Work quote, I would just sum the working days of each job for each employee in an aggregate query.</p> <p>To sum all working days knowing the employees involved in a particular project to know the cost generated for their work I did:</p> <pre><code>select projectid, sum(total_salary) as total_salaries from project_pay group by projectid </code></pre> <p><a href="http://sqlfiddle.com/#!2/bc02d/1" rel="nofollow">Here is the sqlfiddle</a></p> <p>There must be a way to improve this a lot:</p> <pre><code>CREATE TABLE Employee( EmployeeID INTEGER NOT NULL PRIMARY KEY, Name VARCHAR(30) NOT NULL, Sex CHAR(1) NOT NULL, Address VARCHAR(80) NOT NULL, Security VARCHAR(15) NOT NULL ); CREATE TABLE Departments ( DeptID INTEGER NOT NULL PRIMARY KEY, DeptName VARCHAR(30) NOT NULL ); CREATE TABLE `Dept-Employee`( EmployeeID INTEGER NOT NULL, DeptID INTEGER NOT NULL, CONSTRAINT fk_DeptID FOREIGN KEY (DeptID) REFERENCES Departments(DeptID), CONSTRAINT fk_EmployeeID FOREIGN KEY (EmployeeID) REFERENCES Employee(EmployeeID) ); CREATE TABLE `Dept-Manager`( EmployeeID INTEGER NOT NULL, DeptID INTEGER NOT NULL, CONSTRAINT fk_DeptIDs FOREIGN KEY (DeptID) REFERENCES Departments(DeptID), CONSTRAINT fk_EmployeeIDs FOREIGN KEY (EmployeeID) REFERENCES Employee(EmployeeID) ); CREATE TABLE Jobs ( JobID INTEGER NOT NULL PRIMARY KEY, JobName VARCHAR(30) NOT NULL, JobSalary DOUBLE(15,3) NOT NULL default '0.000', JobSalaryperDay DOUBLE(15,3) NOT NULL default '0.000', DeptID INTEGER NOT NULL ); CREATE TABLE `Jobs-Employee`( EmployeeID INTEGER NOT NULL, JobID INTEGER NOT NULL, CONSTRAINT fk_JobIDs FOREIGN KEY (JobID) REFERENCES Jobs(JobID), CONSTRAINT fk_EmployeeIDss FOREIGN KEY (EmployeeID) REFERENCES Employee(EmployeeID) ); CREATE TABLE Project( ProjectID INTEGER NOT NULL PRIMARY KEY, ProjectDesc VARCHAR(200) NOT NULL, StartDate DATE NOT NULL, EndDate DATE NOT NULL, DaysOfWork INTEGER NOT NULL, NoEmployees INTEGER NOT NULL, EstimatedCost DOUBLE(15,3) NOT NULL default '0.000', RealCost DOUBLE(15,3) NOT NULL default '0.000' ); CREATE TABLE `Project-Employee`( ProjectID INTEGER NOT NULL, EmployeeID INTEGER NOT NULL, Note VARCHAR(200), DaysWork INTEGER NOT NULL, CONSTRAINT fk_ProjectIDsss FOREIGN KEY (ProjectID) REFERENCES Project(ProjectID), CONSTRAINT fk_EmployeeIDsss FOREIGN KEY (EmployeeID) REFERENCES Employee(EmployeeID) ); INSERT INTO `Departments` VALUES (1, 'Outsourcing'); INSERT INTO `Departments` VALUES (2, 'Technician'); INSERT INTO `Departments` VALUES (3, 'Administrative'); INSERT INTO `Jobs` VALUES (1, 'welder' ,500.550,16.7 ,2); INSERT INTO `Jobs` VALUES (2, 'turner' ,500.100,16.67,2); INSERT INTO `Jobs` VALUES (3, 'assistant' ,650.100,21.67,2); INSERT INTO `Jobs` VALUES (4, 'supervisor',800.909,26.70,3); INSERT INTO `Jobs` VALUES (5, 'manager' ,920.345,30.68,3); INSERT INTO `Jobs` VALUES (6, 'counter' ,520.324,17.35,1); INSERT INTO `Employee` VALUES (10, 'Joe', 'M', 'Anywhere', '927318344'); INSERT INTO `Employee` VALUES (20, 'Moe', 'M', 'Anywhere', '827318322'); INSERT INTO `Employee` VALUES (30, 'Jack', 'M', 'Anywhere', '927418343'); INSERT INTO `Employee` VALUES (40, 'Marge','F', 'Evererre', '127347645'); INSERT INTO `Employee` VALUES (50, 'Greg' ,'M', 'Portland', '134547633'); INSERT INTO `Dept-Employee` VALUES (10,1); INSERT INTO `Dept-Employee` VALUES (20,2); INSERT INTO `Dept-Employee` VALUES (30,3); INSERT INTO `Dept-Employee` VALUES (40,1); INSERT INTO `Dept-Employee` VALUES (50,3); INSERT INTO `Jobs-Employee` VALUES (10,3); INSERT INTO `Jobs-Employee` VALUES (20,3); INSERT INTO `Jobs-Employee` VALUES (30,4); INSERT INTO `Jobs-Employee` VALUES (40,6); INSERT INTO `Jobs-Employee` VALUES (50,5); INSERT INTO `Project` VALUES (1, 'The very first', '2008-7-04' , '2008-7-24' , 20, 5, 3000.50, 2500.00); INSERT INTO `Project` VALUES (2, 'Second one pro', '2008-8-01' , '2008-8-30' , 30, 5, 6000.40, 6100.40); INSERT INTO `Project-Employee` VALUES (1, 10, 'Worked all days' , 20); INSERT INTO `Project-Employee` VALUES (1, 20, 'Worked just in defs', 11); INSERT INTO `Project-Employee` VALUES (1, 30, 'Worked just in defs', 17); INSERT INTO `Project-Employee` VALUES (1, 40, 'Contability ' , 8); INSERT INTO `Project-Employee` VALUES (1, 50, 'Managed the project', 8); CREATE VIEW `Emp-Job` as SELECT e.*,j.jobID FROM Employee e,`Jobs-Employee` j WHERE e.EmployeeID = j.EmployeeID; CREATE VIEW `employee_pay` as select e.*, j.jobname, j.jobsalary, j.jobsalaryperday from `Emp-Job` e inner join `Jobs` j on e.JobID = j.JobID; create view project_pay as select pe.projectid, pe.employeeid, pe.dayswork, e.jobsalaryperday, (e.jobsalaryperday * dayswork) as total_salary from `Project-Employee` pe inner join `employee_pay` e on e.employeeid = pe.employeeid </code></pre> <p><a href="http://sqlfiddle.com/#!2/0f741" rel="nofollow">Updated code</a></p>
[ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-11-07T08:37:48.240", "Id": "29168", "Score": "0", "body": "One change I would prefer is to have a primary key named as \"id\" for every table. So here Employee table will have the primary key - id, not the \"EmployeeID\". Doing so Dept-Employee table will also include a primary key along with the foreign key EmployeeID" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-11-07T08:50:10.680", "Id": "29169", "Score": "0", "body": "The reason I did that naming was to have a little control of which Primary key I was refering to... but sounds ok" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-07-21T17:38:58.437", "Id": "103066", "Score": "0", "body": "As for your design, you are making the assumption that nobody will change roles on a project." } ]
[ { "body": "<ul>\n<li><p>Make the ids of the m-n-mapping tables their PK, you probably don't want to have duplicates there.</p></li>\n<li><p>Address and Name are to short for real world data.</p></li>\n<li><p>Avoid duplication of the table name in columns (e.g. jobname) in table jobs</p></li>\n<li><p>I'd apply that to ids as well, but your approach is ok, as long as it is used consistent.</p></li>\n<li><p>Drop the plural s for tables and constraints, they don't add any value</p></li>\n<li><p>Check all names for typos</p></li>\n<li><p>StartDate + EndDate + DaysOfWork seem to be redundant</p></li>\n<li><p>The structure assumes that all employees work on a project for the complete project. This is completely unrealistic. I'd normally expect a time interval in the employee-job table.</p></li>\n<li><p>Why is there a department in a job?</p></li>\n</ul>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-11-07T17:58:31.660", "Id": "29194", "Score": "0", "body": "I have checked your answer, but I would like to correct the point number 8 \"Time interval\" could you please explain a little more in how to add that in mysql, I updated the database-design" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-11-07T18:06:48.513", "Id": "29195", "Score": "0", "body": "The updated code is in http://sqlfiddle.com/#!2/4744e" } ], "meta_data": { "CommentCount": "2", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-11-07T11:34:42.723", "Id": "18309", "ParentId": "18299", "Score": "3" } }, { "body": "<p>A little addition to Jens Schauder's answer:</p>\n\n<p>You shouldn't abbreviate a field name, especially if the field name is a key to a table whose name isn't abbreviated.</p>\n\n<p><code>DeptId</code> primary key and foreign keys should be renamed to <code>DepartmentId</code>.</p>\n\n<p>This assures consistency and helps avoid problems if using some ORMs.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-11-07T19:33:42.233", "Id": "29198", "Score": "0", "body": "I updated the code, but do you know how to accomplish @Jens Schauder's point 8? http://sqlfiddle.com/#!2/0f741" } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-11-07T19:20:21.943", "Id": "18325", "ParentId": "18299", "Score": "4" } }, { "body": "<p>remove the Dept-Employee table and add a column named Department_ID as a foreign key in Employee table for one-to-one relationship. </p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2016-11-28T09:22:36.020", "Id": "278945", "Score": "1", "body": "Maybe you could elaborate how this would make the database structure better? As it stands now, this is barely an answer." } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2016-11-28T09:11:23.000", "Id": "148313", "ParentId": "18299", "Score": "0" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "3", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-11-07T07:52:01.237", "Id": "18299", "Score": "4", "Tags": [ "sql", "mysql" ], "Title": "Database design with information of employees, their jobs, salaries and projects" }
18299
<pre><code> (function( $ ){ var monthNames = [ "Январь", "Февраль", "Март", "Апрель", "Май", "Июнь", "Июль", "Август", "Сентябрь", "Октябрь", "Ноябрь", "Декабрь" ]; var dayNames = ["Пн","Вт","Ср","Чт","Пт","Сб","Вс"]; var now = new Date(); var methods = { init : function( options ) { var settings = $.extend( { 'year' : now.getFullYear(), 'month' : now.getMonth(), 'link' : '%y/%m/%d', 'url' : '', 'dates' : [] }, options); return this.each(function(){ if (!$(this).data('year')){ $(this).data('year',settings.year); } if (!$(this).data('month')){ $(this).data('month',settings.month); } if (!$(this).data('link')){ $(this).data('link',settings.link); } $(this).data('dates',settings.dates); $(this).data('url',settings.url); methods.render($(this)); }); }, destroy : function( ) { return this.each(function(){ $(this).html(''); }) }, render : function( elem ) { year = elem.data('year'); month = elem.data('month'); link = elem.data('link'); dates = elem.data('dates'); date = new Date(year,month,1); elem.html('&lt;table class="calendar"&gt;&lt;/table&gt;'); var calendar=elem.find('.calendar'); calendar.append('&lt;tr class="calendar-header"&gt;&lt;th colspan="7"&gt;&lt;a href="#" class="icon-chevron-left calendar-prev-month"&gt;&lt;/a&gt;'+monthNames[month]+' '+year+'&lt;a href="#" class="icon-chevron-right calendar-next-month"&gt;&lt;/a&gt;&lt;/th&gt;&lt;/tr&gt;'); calendar.append('&lt;tr class="calendar-week"&gt;&lt;th&gt;'+dayNames.join('&lt;/th&gt;&lt;th&gt;')+'&lt;/th&gt;&lt;/tr&gt;'); var str = '&lt;tr&gt;'; var week = date.getDay(); if (week == 0) { week=7} for (day=1;day&lt;week;day++){ str=str+"&lt;td&gt;&lt;/td&gt;"; } date.setMonth(month+1); date.setDate(0); for (day=1;day&lt;=date.getDate();day++){ var link_href = link.replace("%y",year).replace("%m",month+1).replace("%d",day); var day_text = ''; if ($.inArray(day, dates)&gt;=0){ day_text = '&lt;a href="'+link_href+'" class="calendar-day-link"&gt;'+day+'&lt;/a&gt;'; } else { day_text = day; } str=str+'&lt;td&gt;'+day_text+'&lt;/td&gt;'; if (week++ % 7 == 0){ str=str+"&lt;/tr&gt;&lt;/tr&gt;"; } } str = str + '&lt;/tr&gt;'; calendar.append(str); calendar.find('.calendar-next-month').click(methods.next_month); calendar.find('.calendar-prev-month').click(methods.prev_month); }, next_month : function( e ) { e.preventDefault(); elem = $(this).parents('.calendar').parent(); year = elem.data('year'); month = elem.data('month')+1; url = elem.data('url'); if (month&gt;11){ year++; month=0; } elem.data('year',year).data('month',month); $.getJSON(url+'?year='+year+'&amp;month='+(month+1),function(data) { elem.data('dates',data); methods.render(elem); }); }, prev_month : function( e ) { e.preventDefault(); elem = $(this).parents('.calendar').parent(); year = elem.data('year'); month = elem.data('month')-1; url = elem.data('url'); if (month==-1){ year--; month=11; } elem.data('year',year).data('month',month); $.getJSON(url+'?year='+year+'&amp;month='+(month+1),function(data) { elem.data('dates',data); methods.render(elem); }); }, }; $.fn.calendar = function( method ) { // Create some defaults, extending them with any options that were provided if ( methods[method] ) { return methods[method].apply( this, Array.prototype.slice.call( arguments, 1 )); } else if ( typeof method === 'object' || ! method ) { return methods.init.apply( this, arguments ); } else { $.error( 'Method ' + method + ' does not exist on jQuery.tooltip' ); } }; })( jQuery ); </code></pre>
[]
[ { "body": "<p>From a once over:</p>\n\n<ul>\n<li>THANK YOU for having all your code and variables in English, very nice</li>\n<li><p>In init I would suggest you extract <code>data</code>, fill it in if needed and put it back, so going from this</p>\n\n<pre><code> return this.each(function(){\n if (!$(this).data('year')){\n $(this).data('year',settings.year);\n }\n if (!$(this).data('month')){\n $(this).data('month',settings.month);\n }\n if (!$(this).data('link')){\n $(this).data('link',settings.link);\n }\n $(this).data('dates',settings.dates);\n $(this).data('url',settings.url);\n methods.render($(this));\n });\n</code></pre>\n\n<p>to this:</p>\n\n<pre><code> return this.each(function(){\n var data = $(this).data() || {};\n data.year = data.year || settings.year;\n data.month = data.month || settings.month;\n data.link = data.link || settings.link;\n data.dates = settings.dates;\n data.url = settings.url;\n $(this).data(data);\n methods.render($(this));\n });\n</code></pre>\n\n<p>It looks DRY'er and the reduced amount of calls to <code>$(this).data()</code> should make it more efficient as well.</p></li>\n<li>You could do the same with <code>year</code> and <code>month</code> in <code>next_month</code> and <code>prev_month</code>.</li>\n<li>lowerCamelCasing is how JavaScript ought to be done: <code>next_month</code> -> <code>nextMonth</code>, <br><code>prev_month</code> -> <code>previousMonth</code> etc.</li>\n<li>You should really look into a templating routine/library for building your HTML, extracting your HTML templates into <code>var</code>s and making it more readable by splitting over multiple lines. You could even use templating to construct the JSON URL's.</li>\n<li>From JsHint ( jshint.com )\n<ul>\n<li><code>year</code> , <code>month</code>, <code>link</code>, <code>dates</code> etc. are declared in your code without <code>var</code>, polluting the global namespace</li>\n<li>If you want to compare with <code>0</code>, you should use <code>===</code> not <code>==</code></li>\n</ul></li>\n</ul>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-02-07T17:01:55.573", "Id": "41166", "ParentId": "18300", "Score": "3" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-11-07T09:01:21.393", "Id": "18300", "Score": "3", "Tags": [ "javascript", "jquery", "datetime" ], "Title": "jQuery calendar plugin" }
18300
<p>I have a method(C#) which takes an XmlNodeList and a String and saves the xml data into a database. That code isn't the problem (at least for the moment), but because I have multiple XmlNodeLists, each needing a different String (the heading), I end up with code like</p> <pre><code>saveToDB(students, "Students"); saveToDB(teachers, "Teachers"); saveToDB(workers, "Workers"); </code></pre> <p>...etc, there's about 8 of those in total. It all works okay, but I wonder if there's a better way to call the function, rather than doing it 8 times? I guess I could wrap all of the data into an object, but I'd still have to set it up, and pull the data out before and afterwards, so that's surely just moving the problem elsewhere? Or is there simply no real way around this, and the issue lies with how I've approached this method in the first place?</p> <p>I look forward to your responses.</p>
[ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-11-07T11:00:25.470", "Id": "29171", "Score": "0", "body": "Where does the `saveToDB` method live? Is it static? How are the `XmlNodeList` created and modified?" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-11-07T11:07:36.090", "Id": "29174", "Score": "0", "body": "@Tag The `saveToDB` method is in the same class file. The `XmlNodeList` are created using the `.SelectNodes` method from a `XmlElement` object." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-11-07T12:16:47.207", "Id": "29183", "Score": "1", "body": "Oops, I asked 'How' when I meant to ask 'Where'. I was trying to understand the relationship between the node lists and the class where `saveToDB` lives. There might be a better way to organize the class to make saving the node lists easier." } ]
[ { "body": "<p>I think you could create a new <code>saveToDB</code> method that requires a <code>Dictionary&lt;string, XmlNodeList&gt;</code> inside this new method you could cycle through the Keys (string) and for each one call the current <code>saveToDB(string, XmlNodeList)</code>.</p>\n\n<p>Yes, it only move your problem: you've to prefill the dictionary, but I really think there's no other options... at one point you HAVE to enumerate your datas.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-11-07T14:35:39.493", "Id": "29187", "Score": "0", "body": "I would agree with you, @tanathos, I think this is the best option. It'll reduce it down to a single looped call to `saveToDB`, and I doubt that it would effect performance noticeably. Thanks!" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-11-08T22:55:08.430", "Id": "29276", "Score": "3", "body": "Just remember that a `Dictionary` doesn't preserve order; that might be okay, or you might need to use a `List<KeyValuePair>` instead." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-11-08T23:23:01.933", "Id": "29281", "Score": "0", "body": "It's a good point" } ], "meta_data": { "CommentCount": "3", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-11-07T11:07:08.760", "Id": "18305", "ParentId": "18301", "Score": "7" } }, { "body": "<p>There are few ways you can save our work .. this is one way you can do this easily..</p>\n\n<p>you can have a List or Tuple of above string and XMLnodelist which you can iterate through and save the db result.</p>\n\n<pre><code>//pseudo code will be \nfor(obj in collectionOfStringandXMlnodeList)\n SaveToDb(obj);\n</code></pre>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-11-07T11:08:24.547", "Id": "18307", "ParentId": "18301", "Score": "1" } } ]
{ "AcceptedAnswerId": "18305", "CommentCount": "3", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-11-07T09:15:27.143", "Id": "18301", "Score": "7", "Tags": [ "c#", ".net" ], "Title": "Is there a better way to call the same method with different parameters?" }
18301
<p>There are a number of different ways to do this. What do people prefer and why?</p> <pre><code>public boolean checkNameStartsWith(List&lt;Foo&gt; foos) { for (Foo foo : foos) { if (!(foo.getName().startsWith("bar"))) { return Boolean.FALSE; } } return Boolean.TRUE; } </code></pre>
[]
[ { "body": "<p>I'd change <code>Boolean.FALSE</code> to <code>false</code> and <code>Boolean.TRUE</code> to <code>true</code>. Using the constants objects from <code>Boolean</code> is rather unnecessary since the method returns with primitive <code>boolean</code>.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-11-07T11:04:50.237", "Id": "29173", "Score": "0", "body": "I had got into the habit of always referencing the static constants as consumes less memory. Other people don't then ?" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-11-07T11:19:24.720", "Id": "29175", "Score": "6", "body": "a reference to an object consuming less memory then a primitive? Do you have tests verifying that? Even if it is true, did you actually encounter a case where it did matter?" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-11-07T11:27:55.667", "Id": "29176", "Score": "0", "body": "@NimChimpsky: Using `Boolean.FALSE` and `TRUE` is better than creating new objects with `new Boolean(false)` but here the return type is `boolean` primitive, not an object reference." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-11-07T11:39:55.213", "Id": "29179", "Score": "0", "body": "@JensSchauder a reference to lots and lots of primitives across my whole application, consumes less memory than one Object reference, was my thinking." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-11-07T11:49:07.887", "Id": "29180", "Score": "7", "body": "there are no references to primitives. Just references or primitives. In case of a local boolean the difference surely is neglectable. If you have huge volumes of those (like huge Arrays) one should do some tests. For everything else, use the one easiest on the eye." } ], "meta_data": { "CommentCount": "5", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-11-07T10:53:14.663", "Id": "18304", "ParentId": "18302", "Score": "14" } }, { "body": "<p>Though <code>for</code> loop is enough, you can rewrite using <a href=\"http://docs.guava-libraries.googlecode.com/git-history/v13.0.1/javadoc/src-html/com/google/common/collect/Iterables.html#line.628\">Guava</a> if you like lambdas:</p>\n\n<pre><code>public boolean checkNameStartsWith(List&lt;Foo&gt; foos){\n return Iterables.all(foos, new Predicate&lt;Foo&gt;() {\n public boolean apply(Foo foo) {\n return foo.getName().startsWith(\"bar\");\n }\n });\n}\n</code></pre>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-11-07T11:36:56.400", "Id": "18310", "ParentId": "18302", "Score": "8" } }, { "body": "<p>In addition to the other answers, I suggest adding a second parameter to the <code>checkNameStartsWith</code> method named <code>prefix</code>, e.g.</p>\n\n<pre><code>public boolean checkNameStartsWith(List&lt;Foo&gt; foos, final String prefix) {\n for (Foo foo : foos) {\n if (!foo.getName().startsWith(prefix)) {\n return false;\n }\n }\n return true;\n}\n</code></pre>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-11-07T12:34:35.723", "Id": "18312", "ParentId": "18302", "Score": "5" } }, { "body": "<p>I know it <a href=\"https://stackoverflow.com/questions/3887769/java-loop-efficiency-if-continue-or-if\">probably doesn't matter from a performance standpoint</a> (due to branch prediction and compiler optimization), but I still prefer this form:</p>\n\n<pre><code>public boolean checkNameStartsWith(List&lt;Foo&gt; foos) {\n for (Foo foo : foos) {\n if (foo.getName().startsWith(\"bar\")) continue;\n\n // Mismatch found\n return false; \n }\n return true;\n}\n</code></pre>\n\n<p>I think it's because it makes it easier to see that you're absolutely done with the iteration once you've determined there's no match. Otherwise, you might have something like this:</p>\n\n<pre><code>public boolean myMethod(List&lt;Foo&gt; foos, final String prefix) {\n for (Foo foo : foos) {\n if (!foo.getName().startsWith(prefix)) {\n // do something complex (many lines of code)\n }\n // here you could possibly do something else, regardless of condition true/false\n }\n return true;\n}\n</code></pre>\n\n<p>You don't know unless you search for the end of the loop whether something is still done if the condition is false.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-11-07T17:38:19.937", "Id": "18323", "ParentId": "18302", "Score": "3" } }, { "body": "<p><code>Boolean.FALSE</code> and <code>Boolean.TRUE</code> should be definitely replaced with <code>true</code> and <code>false</code> because of auto-boxing. You don't need an additional <code>Integer.intValue()</code> call for each invocation.</p>\n\n<p>I'm pretty sure Oracle HotSpot will optimize this automatically, but the code readability still suffers. </p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-11-14T01:32:54.883", "Id": "18573", "ParentId": "18302", "Score": "1" } }, { "body": "<p>Have only one exit point from the method. Also, despite being old school, I would iterate using a while loop with a stop condition instead of the for-each.</p>\n\n<pre><code>public boolean checkNamesStartWith(List&lt;Foo&gt; foos, String prefix) {\n boolean ret = true;\n int index = 0;\n while (index &lt; foos.size() &amp;&amp; ret) {\n ret &amp;= foos.get(index).getName().startsWith(prefix);\n }\n return ret;\n}\n</code></pre>\n\n<p>Here the while loop will only iterate as long as it doesn't find a foo that starts with the prefix - or will iterate through the whole list. I would also rename the method from <code>checkNameStart</code> to <code>checkNamesStart</code> as it iterates through a whole collection, so usually more than one names will be checked.</p>\n\n<p>Or, to preserve readibility, you can use an if condition with a break from the for-each loop:</p>\n\n<pre><code>public boolean checkNamesStartWith(List&lt;Foo&gt; foos, String prefix) {\n boolean ret = true;\n for (Foo foo : foos) {\n if (!foo.getName().startsWith(prefix)) {\n ret = false;\n break;\n }\n }\n return ret;\n}\n</code></pre>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-06-28T15:20:26.673", "Id": "27902", "ParentId": "18302", "Score": "0" } }, { "body": "<p>I would actually suggest you making a number of improvements:</p>\n\n<p>1) Use an Iterator to walk over the list. Although this solution does not provide any performance benefits over the for loop, it actually makes your code more generalized and easier adaptable, should you sometime decide to use some other collection instead of a List.</p>\n\n<p>2) Replace <code>Boolean.TRUE</code> and <code>BOOLEAN.FALSE</code> stuff by <code>true</code> and <code>false</code> respectively for reasons, explained by <strong>stoweesh</strong>.</p>\n\n<p>3) Get rid of multiple returns. When you find an element in the list whose name does not start with bar, just set a boolean variable and break out of the loop. Return only in the end. This also improves readability and maintainability of your code.</p>\n\n<p>My version of the iteration looks like this:</p>\n\n<pre><code> public boolean checkNameStartsWith(List&lt;Foo&gt; foos) {\n\n Iterator&lt;Foo&gt; it = foos.iterator();\n boolean isAllStartWithBar = true;\n\n while (it.hasNext()) {\n if (!it.next().getName().startsWith(\"bar\")) {\n isAllStartWithBar = false;\n break;\n } \n }\n\n return isAllStartWithBar; \n }\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-06-28T20:04:52.503", "Id": "43533", "Score": "0", "body": "`it actually makes your code more generalized and easier adaptable` really? foreach loop supports arrays, but your approach cannot be adopted to arrays. Also, I'd recommend use an iterator instead of foreach only if you need to remove elements." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-06-29T11:06:32.377", "Id": "43569", "Score": "0", "body": "@tcb well, he did not say anything about arrays anyway, code features a List. And iterators are usable with arrays, just transform array into List by calling Arrays.asList. By more generalized I mean easier to adopt, if you decide to change the data structure, say use a LinkedList, ArrayList, some custom collection, etc. instead of List making your code polimorphic. Iterator enables you not only safely remove elements from the collection, but also supports paralelly traversing multiple collections, if you need. For these reasons I generally prefer to use an iterator rather than a foor loop." } ], "meta_data": { "CommentCount": "2", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-06-28T18:23:02.760", "Id": "27912", "ParentId": "18302", "Score": "0" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-11-07T10:22:06.420", "Id": "18302", "Score": "7", "Tags": [ "java" ], "Title": "Looping over a list, checking a boolean and return value" }
18302
<p>If I have this basic structure</p> <pre><code>var Foo = function(str) { console.log('Object string: ' + this.str); console.log('Param string : ' + str); } var Bar = function() { this.str = 'object string'; } var obj = new Bar(); Foo.call(obj, 'param string'); </code></pre> <p>It's fairly obvious what .call() is doing in context. I recently came across some articles that went into depth on abstracting the .call() function. The premise is along these lines (this code is verging on pseudo code as I have stripped it down for ease of reading) : </p> <pre><code>var Extension = { // Fire a callback in global scope fireCallback : function(event, args) { this.callbacks[event].apply(window, args); }, // Attach a callback addCallback : function(event, fn) { this.callbacks[event].push(fn); }, // Now the bit that I really can't wrap my head around enable : function() { var self = this; if ( ! self.callbacks ) { self.callbacks = {}; } self.fireCallback = function(event, args) { Extension.fireCallback.call(self, event, args); }; self.addCallback = function(event, fn) { Extension.addCallback.call(self, event, fn); }; } } </code></pre> <p>There is some form of JS voodoo going on here that I can't programatically work out, can anyone help me shed light on how JS is interpreting this and why when I call:</p> <pre><code>Extension.enable.call(this); </code></pre> <p>within a class scope, the Extension object seems to extend the calling objects prototypes allowing me to bind a callback within the class scope. And then attach a handler after I have instantiated the class.</p> <pre><code>function Bar() { Extension.enable.call(this); // Do stuff this.fnCallback = function() { this.fireEvent('complete'); } } var bar = new Bar(); bar.addCallback('complete', function(args) { console.log('complete'); }); bar.fnCallback(); // logs 'complete' to console </code></pre> <p>The logic is really confusing me, I understand how call() and apply() work in the simple example above but I have no idea how or why the prototypes of the object are extended when I call <code>Extension.enable.call(this);</code>.</p> <p>Could anyone help me shed some light on this?</p>
[]
[ { "body": "<p>I may be misunderstanding your question, but I'll have a go at answering. If I'm completely off, let me know.</p>\n\n<p>Technically, no prototypes are being extended, only the instance is being extended. In your last example, the <code>Bar</code> constructor (aka \"class\") does not have any of the callback functions in its prototype. However, since <code>Bar</code> invokes <code>enable</code> when being instantiated, any instance of <code>Bar</code> will always be extended at runtime.</p>\n\n<p>If you have code like</p>\n\n<pre><code>var Extension = {\n enable: function () {\n // Here, \"this\" === Extension, unless overridden by call/apply\n this.sayHi = function () {\n // Here, \"this\" === (whatever \"this\" is above)\n console.log(this.text);\n };\n }\n};\n\nfunction Foo() {\n // Here, when instantiating, \"this\" will be a new instance of Foo.\n Extension.enable.call(this);\n this.text = \"Hello, world\";\n}\n\nvar instance = new Foo;\ninstance.sayHi(); // logs \"Hello, world\"\n</code></pre>\n\n<p>it's equivalent to </p>\n\n<pre><code>function Foo() {\n // Here, \"this\" === instance of Foo\n this.sayHi = function () {\n // Here, \"this\" === (whatever \"this\" is above)\n console.log(this.text);\n };\n\n this.text = \"Hello, world\";\n}\n\nvar instance = new Foo;\ninstance.sayHi(); // logs \"Hello, world\"\n</code></pre>\n\n<p>Said another way:<br>\nYou have function <em>F</em> (<code>enable</code> in this case) in which <code>this</code> would normally refer to the object of which <em>F</em> is a property (<code>Extension</code> in this case).<br>\nThen you have constructor, <em>C</em>. When you instantiate <em>C</em>, the constructor's <code>this</code> refers to a new instance of <em>C</em>. Within that constructor - by using <code>call()</code>- <em>F</em> is invoked as though <em>F</em> is a property of that same <em>C</em>-instance.<br>\nSo when <em>F</em> is invoked, its <code>this</code> refers to the instance of <em>C</em>. Thus, whatever <em>F</em> does to <code>this</code>, will be done to the <em>C</em> instance.</p>\n\n<p>In your case, <code>enable</code> adds a few methods to <code>this</code>, so in effect it's adding those methods to the instance of <code>Bar</code>. In other words, if you start at the call to <code>enable</code> in the <code>Bar</code> construtor, just read through all the code in and every time you see <code>this</code> think of it as <code>bar</code>.</p>\n\n<p>But note again, that all this is taking place on instances; not prototypes. It's just that since you can only get an instance by invoking the constructor, and the constructor immediately extends the instance, the extra methods seem as though they're prototypal.</p>\n\n<p>I hope that made even the slightest sense - it really is pretty hard to explain.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-11-08T00:13:28.580", "Id": "29207", "Score": "0", "body": "You explanation seems to misconstrue scope. There is no scope issue here, only a misundertanding of objects and properties." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-11-08T07:16:54.727", "Id": "29215", "Score": "0", "body": "@RobG Yeah, you're right - I'll revise my answer." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-12-13T18:16:11.577", "Id": "31334", "Score": "0", "body": "Apologies for the very late follow up to your answer! This did go someway to helping em understand what was going on, it is much clearer how this all fits together now thanks to this and RobG's answer." } ], "meta_data": { "CommentCount": "3", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-11-07T12:10:56.877", "Id": "18311", "ParentId": "18306", "Score": "1" } }, { "body": "<p>Flambino has it mostly right, my explanation may help or hinder. Anyhow, here goes.</p>\n\n<pre><code>&gt; var Foo = function(str)\n</code></pre>\n\n<p>I don't know why you are using a function expression, a declaration seems more suitable:</p>\n\n<pre><code>function Foo(str) {\n</code></pre>\n\n<p>.</p>\n\n<blockquote>\n <p>var obj = new Bar();</p>\n \n <p>Foo.call(obj, 'param string');</p>\n \n <p>It's fairly obvious what .call() is doing in context</p>\n</blockquote>\n\n<p>Perhaps, but unless you say what <strong>you</strong> think is going on, we can't know if your understanding is correct. And while the mechanics are fairly straight forward, it is more important to know what you are trying to do.</p>\n\n<p>Such explanations are important to confirm that you and others are thinking the same thing.</p>\n\n<blockquote>\n <p>... can anyone help me shed light on how JS is interpreting this and why when I call:</p>\n \n <p>Extension.enable.call(this);</p>\n \n <p>within a class scope,</p>\n</blockquote>\n\n<p>I would say \"from within the constructor\", as javascript doesn't have classes and only function's have scope (and constructors called with <code>new</code> can only create plain objects).</p>\n\n<blockquote>\n <p>Extension object seems to extend the calling objects prototypes</p>\n</blockquote>\n\n<p>Not the prototype but the object itself, see below.</p>\n\n<blockquote>\n <p>... allowing me to bind a callback within the class scope. And then\n attach a handler after I have instantiated the class.</p>\n \n <p>function Bar() {\n Extension.enable.call(this);</p>\n</blockquote>\n\n<p>The <code>enable</code> function is called as a plain function with its <code>this</code> set to the new instance of Bar. So <code>enable</code> is adding properties (\"extending\") the instance itself, not its <code>[[Prototype]]</code> (which is <code>Bar.prorotype</code>).</p>\n\n<pre><code>&gt; this.fnCallback = function() {\n&gt; this.fireEvent('complete');\n&gt; }\n&gt; }\n</code></pre>\n\n<p>That also extends the instance (i.e. there is now <code>bar.fnCallback</code> property). And I think <code>fireEvent</code> should be <code>fireCallback</code>.</p>\n\n<pre><code>&gt; var bar = new Bar();\n&gt;\n&gt; bar.addCallback('complete', function(args) {\n&gt; console.log('complete');\n&gt; });\n</code></pre>\n\n<p>That is calling the <code>addCallback</code> method of <code>bar</code>, so <code>this</code> within the function is <code>bar</code>. It rather circuitously adds a member to <code>bar.callbacks</code> with a name of <code>complete</code> and value of the provided function, effectively:</p>\n\n<pre><code>bar.callbacks['complete'] = function(args){...}; \n\n&gt;\n&gt; bar.fnCallback(); // logs 'complete' to console\n</code></pre>\n\n<p>So that calls <code>fnCallback</code> with <code>bar</code> as <code>this</code>. That function calls <code>bar.fireEvent</code>, passing it the parameter <code>'complete'</code> and setting its <code>this</code> to <code>bar</code>.</p>\n\n<p>I've assumed <code>fireEvent</code> should be <code>fireCallback</code> (since <code>fireEvent</code> isn't defined).</p>\n\n<p>Anyhow, it calls </p>\n\n<pre><code>Extension.fireCallback.call(self, event, args);\n</code></pre>\n\n<p>where <code>self</code> is <code>bar</code>, which ultimately calls (replacing <code>this</code> with <code>bar</code>):</p>\n\n<pre><code>bar.callbacks['complete'].apply(window, args);\n</code></pre>\n\n<p>So the prototype isn't invovled at all (unless I'm wrong about <code>fireEvent</code>). Setting <code>this</code> to <code>window</code> within the callback doesn't do anything in this case since it isn't used. </p>\n\n<p>Within the function, <code>console</code> will be resolved on the scope chain, probably being found on the global object (<code>window.console</code> in a browser), then it's <code>log</code> property will be called, writing <code>'complete'</code> to the console.</p>\n\n<p>Does that help?</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-12-13T18:17:39.410", "Id": "31335", "Score": "0", "body": "Thanks for the answer rob, to clear it up, I do understand how call and apply work, the question was more aimed at how the object could be bound to another objects context with a call to it's own method from within that context. Very informative answer mind you and did help me considerably. Thanks" } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-11-08T00:11:35.073", "Id": "18333", "ParentId": "18306", "Score": "1" } } ]
{ "AcceptedAnswerId": "18333", "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-11-07T11:07:35.990", "Id": "18306", "Score": "-1", "Tags": [ "javascript" ], "Title": "Extending an object with .call() and .apply()" }
18306
<p>I am new to WCF and need to work with another programmer's code. I am unsure of the way the WCF service client is used here:</p> <pre><code>private void barButtonDocuments_ItemClick(object sender, ItemClickEventArgs e) { try { MyServiceClient myServiceClient = new MyServiceClient(); try { documents = myServiceClient.GetDocuments(); // More code that isn't useful including here ... } finally { try { myServiceClient.Close(); } catch { } } } catch (FaultException&lt;ServiceErrorDetails&gt; error) { MessageBox.Show(error.Detail.Message, "Erreur", MessageBoxButtons.OK, MessageBoxIcon.Error); } } </code></pre> <p>Is it good practice to close the proxy in a <code>finally</code> block, and doing so in an additional <code>try</code>/<code>catch</code> block? I personally don't like the empty <code>catch</code> block because it's like hiding potentially useful exceptions when trying to close the service client.</p> <p>Are there any better way of handling a WCF service client?</p>
[ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-02-14T21:41:03.960", "Id": "71717", "Score": "0", "body": "You may be interested in this WCF approach I asked about here: http://codereview.stackexchange.com/q/41692/1714" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-09-25T08:23:45.023", "Id": "116689", "Score": "0", "body": "Any final _solution_ with **full source code** sample application ? _IMHO, better samples for minimize learning curve are real \n\napplications with full source code and good patterns_" } ]
[ { "body": "<p>Use <code>Close</code> always for a clean path of code execution. Use <code>Abort</code> in case of a faulted channel, or if your code threw an error. As you might know, if you call <code>Close</code> on a faulted channel, it will throw another error, <code>Close</code> is a graceful shutdown of channel, whereas <code>Abort</code> is an instant shut down of the channel. Here's an example of such code:</p>\n\n<pre><code>MyServiceClient myServiceClient = new MyServiceClient();\n\ntry\n{\n documents = myServiceClient.GetDocuments();\n // More code that isn't useful including here ...\n myServiceClient.Close();\n}\ncatch(Exception ex)\n{\n myServiceClient.Abort();\n}\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-11-07T16:57:27.700", "Id": "29193", "Score": "1", "body": "Thanks for your answer. I didn't know about Abort(), very useful in case something's wrong with the service code. Now, I can be sure that the channel is shut down." } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-11-07T15:46:18.843", "Id": "18320", "ParentId": "18319", "Score": "4" } }, { "body": "<p>Although paritosh's answer is very helpful, there is additional useful information to take into account when using a service client, as found in <a href=\"http://msdn.microsoft.com/en-us/library/ms733912.aspx\">this MSDN article</a> :</p>\n\n<blockquote>\n <p>It is recommended that a calling application open the channel, use it,\n and close the channel inside <strong>one</strong> try block.</p>\n</blockquote>\n\n<p>Let's look at the original try/catch block that was used for the solely purpose of closing the channel :</p>\n\n<pre><code> try\n {\n myServiceClient.Close();\n }\n catch\n {\n }\n</code></pre>\n\n<p>This is useless, as stated in the article :</p>\n\n<blockquote>\n <p>Datagram channels never fault <strong>even if exceptions occur when they are\n closed</strong>.</p>\n</blockquote>\n\n<p>About handling exceptions, MSDN suggests that no <em>unexpected exceptions</em> (like OutOfMemoryException, ArgumentNullException or InvalidOperationException) should be caught when using a service client, as stated in <a href=\"http://msdn.microsoft.com/en-us/library/aa354510.aspx\">this MSDN article</a> :</p>\n\n<blockquote>\n <p>Exceptions that are thrown from communication methods on a Windows\n Communication Foundation (WCF) client are either expected or\n unexpected. Unexpected exceptions include catastrophic failures like\n OutOfMemoryException and programming errors like ArgumentNullException\n or InvalidOperationException. Typically there is no useful way to\n handle unexpected errors, so typically you should not catch them when\n calling a WCF client communication method.</p>\n</blockquote>\n\n<p>Recommended exceptions to catch while using a service client are <strong>TimeoutException</strong> and any other exception that derives from <strong>CommunicationException</strong>.</p>\n\n<p>As the article states :</p>\n\n<blockquote>\n <p>One way to handle such errors is to <strong>abort the client</strong> and <strong>report\n the communication failure.</strong></p>\n</blockquote>\n\n<p>In addition, as this particular project handles it's own <strong>FaultException</strong> (of type ServiceErrorDetails), the recommended method to catch exceptions while using this service client would be to first catch any <strong>TimeoutException</strong>, then any <strong>FaultException</strong> and finally any <strong>CommunicationException</strong>.</p>\n\n<p>The rewritten code would then look like this :</p>\n\n<pre><code>MyServiceClient myServiceClient = new MyServiceClient();\n\ntry\n{\n documents = myServiceClient.GetDocuments();\n // More code that isn't useful including here ...\n myServiceClient.Close();\n}\ncatch (TimeoutException exception)\n{\n MessageBox.Show(exception.Message, \"Timeout error\", MessageBoxButtons.OK, MessageBoxIcon.Error);\n myServiceClient.Abort();\n}\ncatch (FaultException&lt;ServiceErrorDetails&gt; error)\n{\n MessageBox.Show(error.Detail.Message, \"Service error\", MessageBoxButtons.OK, MessageBoxIcon.Error);\n myServiceClient.Abort();\n}\ncatch (CommunicationException exception)\n{\n MessageBox.Show(exception.Message, \"Communication error\", MessageBoxButtons.OK, MessageBoxIcon.Error);\n myServiceClient.Abort();\n}\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2018-03-22T14:44:58.250", "Id": "364890", "Score": "0", "body": "Which ***`exceptions`*** with _statusCode_ for ***do Retry*** ?" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2018-03-22T14:45:39.730", "Id": "364891", "Score": "0", "body": "`ServiceErrorDetails` is custom class ?" } ], "meta_data": { "CommentCount": "2", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-11-07T18:32:40.787", "Id": "18324", "ParentId": "18319", "Score": "14" } } ]
{ "AcceptedAnswerId": "18324", "CommentCount": "2", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-11-07T14:45:34.193", "Id": "18319", "Score": "14", "Tags": [ "c#", "beginner", "error-handling", "wcf" ], "Title": "Using a WCF service client and handling its exceptions" }
18319
<p>I have a select statement which is infact a subquery within a larger select statement built up programmatically. The problem is if I elect to include this subquery it acts as a bottle neck and the whole query becomes painfully slow.</p> <p>An example of the data is as follows:</p> <pre><code>Payment .Receipt_no|.Person |.Payment_date|.Type|.Reversed| 2|John |01/02/2001 |PA | | 1|John |01/02/2001 |GX | | 3|David |15/04/2003 |PA | | 6|Mike |26/07/2002 |PA |R | 5|John |01/01/2001 |PA | | 4|Mike |13/05/2000 |GX | | 8|Mike |27/11/2004 |PA | | 7|David |05/12/2003 |PA |R | 9|David |15/04/2003 |PA | | </code></pre> <p>The subquery is as follows :</p> <pre><code>select Payment.Person, Payment.amount from Payment inner join (Select min([min_Receipt].Person) 'Person', min([min_Receipt].Receipt_no) 'Receipt_no' from Payment [min_Receipt] inner join (select min(Person) 'Person', min(Payment_date) 'Payment_date' from Payment where Payment.reversed != 'R' and Payment.Type != 'GX' group by Payment.Person) [min_date] on [min_date].Person= [min_Receipt].Person and [min_date].Payment_date = [min_Receipt].Payment_date where [min_Receipt].reversed != 'R' and [min_Receipt].Type != 'GX' group by [min_Receipt].Person) [1stPayment] on [1stPayment].Receipt_no = Payment.Receipt_no </code></pre> <p>This retrieves the first payment of each person by .Payment_date (ascending), .Receipt_no (ascending) where .type is not 'GX' and .Reversed is not 'R'. As Follows:</p> <pre><code>Payment .Receipt_No|.Person|.Payment_date 5|John |01/01/2001 3|David |15/04/2003 8|Mike |27/11/2004 </code></pre> <p><strike>I am unable to move the subquery out to a temporary table as temporary tables are simply not supported within the programming language used by my application.</strike></p> <p><strong>Edit :</strong> Incorrect statement. Temporary tables are supported and therefore this is a valid option.</p> <h2><a href="https://stackoverflow.com/questions/13272553/optimise-sql-sub-query-containing-inner-joins-and-aggregate-functions">Following a post on StackOverflow</a> -</h2> <p>The Query was rewritten as the following.</p> <p>Query 1.</p> <pre><code>select min(Payment.Person) 'Person', min(Payment.receipt_no) 'receipt_no' from Payment a where a.type&lt;&gt;'GX' and (a.reversed not in ('R') or a.reversed is null) and a.payment_date = (select min(payment_date) from Payment i where i.Person=a.Person and i.type &lt;&gt; 'GX' and (i.reversed not in ('R') or i.reversed is null)) group by a.Person </code></pre> <p>I added this as a subquery within my much larger query, however it still ran very slowly. So I tried rewriting the query whilst trying to avoid the use of aggregate functions and came up with the following.</p> <p>Query 2.</p> <pre><code>SELECT receipt_no, person, payment_date, amount FROM payment a WHERE receipt_no IN (SELECT top 1 i.receipt_no FROM payment i WHERE (i.reversed NOT IN ('R') OR i.reversed IS NULL) AND i.type&lt;&gt;'GX' AND i.person = a.person ORDER BY i.payment_date DESC, i.receipt_no ASC) </code></pre> <p>Which I wouldn't necessarily think of as being more efficient. In fact if I run the two queries side by side on my larger data set Query 1. completes in a matter of milliseconds where as Query 2. takes several seconds.</p> <p>However if I then add them as subqueries within a much larger query, the larger query completes in hours using Query 1. and completes in 40 seconds using Query 2.</p> <p>I can only attribute this to the use of aggregate functions in one and not the other.</p>
[ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-11-08T14:14:39.873", "Id": "29231", "Score": "1", "body": "**What is the database type and version?** Also, have you looked into [`RANK()`](http://msdn.microsoft.com/en-us/library/ms176102.aspx) or equivalent?" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-11-08T15:22:09.093", "Id": "29236", "Score": "0", "body": "The Database I'm working with is Visual dataflex 14.0 with a Sql server 2008 R2 back end. However any Sql commands I use would have to be backwardly compatible to atleast Sql server 2005. Preferably sql server 2000 if possible." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-11-08T15:58:10.703", "Id": "29242", "Score": "0", "body": "I've never used RANK() before but I can definitely see myself using it again. Very useful thank you. I've added my rewritten Query using Rank() above." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-11-12T08:27:51.597", "Id": "29473", "Score": "1", "body": "FYI, `RANK()` is not available in SQL Server 2k. :(" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-11-12T12:01:45.070", "Id": "143382", "Score": "1", "body": "Setting the [Date_Correlation_Optimization](http://sqlserverpedia.com/wiki/Db_Config_-_Date_Correlation_Optimization_Option) option to true within database>properties>options may also improved the overall speed without the need to rewrite the sub query." } ]
[ { "body": "<p>I see that in your question you said:</p>\n\n<blockquote>\n <p><em>\"I am unable to move the subquery out to a temporary table as temporary tables are simply not supported within the programming language used by my application.\"</em></p>\n</blockquote>\n\n<p>But, have you considered calling a stored procedure instead? Is this even an option, considering the limitations with the programming language?</p>\n\n<p>If this is a viable option, you could simply have the results of your subquery inserted into a temp table transparently &amp; encapsulate all the logic in the stored procedure.</p>\n\n<hr>\n\n<p><strong>Edit</strong></p>\n\n<p>I got to thinking about this some more, and perhaps the columns that you're using in your <code>JOIN</code> condition are of different collations. While this will usually result in a specific error message, there may be some implicit collation coversion occurring instead (see: <a href=\"http://msdn.microsoft.com/en-us/library/ms179886.aspx\" rel=\"nofollow\">MSDN: Collation Precedence (Transact-SQL)</a>) between the sub-query &amp; the data being joined.</p>\n\n<p>Here are a few links about collation that might be useful to you:</p>\n\n<ul>\n<li><p><a href=\"http://www.olcot.co.uk/sql-blogs/revised-difference-between-collation-sql_latin1_general_cp1_ci_as-and-latin1_general_ci_as\" rel=\"nofollow\">Difference between collation <code>SQL_Latin1_General_CP1_CI_AS</code> and <code>Latin1_General_CI_AS</code></a></p></li>\n<li><p><a href=\"http://weblogs.sqlteam.com/dang/archive/2009/07/26/Collation-Hell-Part-1.aspx\" rel=\"nofollow\">Collation Hell (Part 1)</a></p></li>\n<li><p><a href=\"http://blog.sqlauthority.com/2008/12/16/sql-server-find-collation-of-database-and-table-column-using-t-sql/\" rel=\"nofollow\">SQL SERVER – Find Collation of Database and Table Column Using T-SQL</a></p></li>\n<li><p><a href=\"http://blog.sqlauthority.com/2008/12/20/sql-server-change-collation-of-database-column-t-sql-script/\" rel=\"nofollow\">SQL SERVER – Change Collation of Database Column – T-SQL Script</a></p></li>\n</ul>\n\n<p>Also, you may be able to trick your programming language into using a temp table with syntax like this:</p>\n\n<pre class=\"lang-sql prettyprint-override\"><code>SELECT *\n FROM tempdb..#MyTempTable\n</code></pre>\n\n<p>Just keep in mind that sometimes the temp database has a different collation then the data you're working with too, in which case you'll need to explicitly convert the data to/from each collation.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-11-09T02:17:33.673", "Id": "29299", "Score": "1", "body": "Completely agree with Alexander ...also tryin to add few index to speed a bit more" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-11-12T08:30:51.887", "Id": "29474", "Score": "0", "body": "2 people `completely agree`, but this answer has neither up-votes nor edits to improve whatever could be better explained? I'm baffled." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-11-12T11:51:57.153", "Id": "29483", "Score": "0", "body": "The statement I made with regards to my programming language not supporting temporary tables is incorrect and I have marked it as such. I'm not sure where I drew this conclusion from? Therefore using a temporary table is a valid option. From what I can tell there are no differences in collation between columns included in the joins. Though the information you posted on collation within Sql made for interesting reading most of which I was unaware of." } ], "meta_data": { "CommentCount": "3", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-11-08T18:05:29.697", "Id": "18356", "ParentId": "18321", "Score": "2" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "5", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-11-07T16:01:20.177", "Id": "18321", "Score": "3", "Tags": [ "optimization", "sql" ], "Title": "Optimize a Sql subquery containing multiple inner joins and aggregate functions" }
18321
<p>Okay, so I wrote this function yesterday for one of our websites here at the office, the site is responsive, but one of the banners wasn't behaving at a certain screen size (was getting chopped off when screen size was less than 1067px). Basically, this script checks for window size of 1067px (higher than 1068px, banner is fine) to 980px (lower than 981, banner is hidden)</p> <pre><code>function updateReadyGoBG(){ var vpWidth, difference, position = 0; vpWidth = jQuery(this).width(); if(vpWidth &gt; 980 &amp;&amp; vpWidth &lt; 1067){ position = jQuery(".ready_go_bg").css("left").replace("px", "") difference = (position - (600 - (vpWidth - position) ) ) + 100; jQuery(".ready_go_bg").css("left", difference + "px") } } </code></pre> <p>Any ideas on how to improve this to improve performance or reduce calls? Any review, refactoring or just general thoughts would be highly appreciated. What did I do wrong? What would you change? </p> <p>Thanks all! </p> <p><strong>EDIT</strong>: <em>adding rudimentary html snipped this acts on</em></p> <pre><code>&lt;style&gt; .banner-container{ width:1000px; height:150px; } .banner{ width: 100% } .ready_go_bg{ position:absolute; left:600px; top:100px; } &lt;/style&gt; &lt;div class="banner-container"&gt; &lt;div class="banner"&gt; &lt;span class="ready_go_bg"&gt;Ready. Go.&lt;/span&gt; &lt;/div&gt; &lt;/div&gt; </code></pre>
[]
[ { "body": "<p>Ok, assuming:</p>\n\n<ul>\n<li>You didn't use media queries for cross-browser reasons</li>\n<li>This function is already bound to a resize event, since you didn't include what triggers the function call</li>\n<li>Assuming that <code>this</code> is the <code>window</code> object, judging from the way you call it <code>vp</code> as in viewport and getting its width.</li>\n</ul>\n\n<p>Then:</p>\n\n<pre><code>function updateReadyGoBG(){ \n\n //you can actually merge declaration and assignment\n var vpWidth = jQuery(this).width(),\n //cache the ready_go_bg jQuery object to avoid requerying\n readyGoBg = jQuery('.ready_go_bg'),\n position = 0,\n difference;\n\n if(vpWidth &gt; 980 &amp;&amp; vpWidth &lt; 1067){\n\n //you could use position instead of getting the CSS left\n //to avoid getting a string, and chopping off the \"px\" part\n position = readyGoBg.position().left;\n\n difference = (position - (600 - (vpWidth - position) ) ) + 100;\n\n //sadly, position is just a \"getter\".\n //you could use .offset(value) but calculating relative\n //to your offset parent would be too much work\n //we use .css(prop,value) to set the left value\n //if unit wasn't specified, jQuery assumes it's in pixels\n readyGoBg.css('left', difference);\n }\n}\n</code></pre>\n\n<hr>\n\n<pre><code>function updateReadyGoBG() {\n var vpWidth = jQuery(this).width(),\n readyGoBg = jQuery('.ready_go_bg'),\n position = 0,\n difference;\n if (vpWidth &gt; 980 &amp;&amp; vpWidth &lt; 1067) {\n position = readyGoBg.position().left;\n difference = (position - (600 - (vpWidth - position))) + 100;\n readyGoBg.css('left', difference);\n }\n}\n</code></pre>\n\n<hr>\n\n<p>General Advice:</p>\n\n<ul>\n<li>Never forget <code>;</code> at every line. You may run into issues during minification if you forget them</li>\n<li>Though personal preference, but it's cleaner to use <code>'</code> instead of <code>\"</code>.</li>\n<li>Unless totally necessary, I'd avoid absolute positioning. Let the layout dictate positions.</li>\n</ul>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-11-08T13:35:57.563", "Id": "29229", "Score": "1", "body": "1. Use `window` instead of `this`, because it's confusing where this points to without the context where the function is bound. 2. `readyGoBg.css('left'` add 'px' to the end. Otherwise it's not clear what you're setting (percentages, unicorns?)" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-11-08T18:22:30.580", "Id": "29249", "Score": "0", "body": "Most of your assumptions are correct. Media queries are being used, but the banner was breaking on active resize of the browser window. This function is indeed already bound to a `jQuery(window).resize()` event - thus the `this` instead of `window` to save a call. Thank you for this! More than I expected." } ], "meta_data": { "CommentCount": "2", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-11-07T23:29:55.277", "Id": "18331", "ParentId": "18328", "Score": "3" } } ]
{ "AcceptedAnswerId": "18331", "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-11-07T22:29:10.250", "Id": "18328", "Score": "2", "Tags": [ "javascript", "jquery" ], "Title": "Refactor/Review JS function which moves a banner on window resize" }
18328
<p>I came across an exercise (in the book "The Art and Science of Java" by Eric Roberts) that requires using only GArc and GLine classes to create a lettering library which draws your initials on the canvas. This should be made independent of the GLabel class.</p> <blockquote> <p>Write a <strong><code>GraphicsProgram</code></strong> to draw your initials on the graphics window using only the <strong><code>GArc</code></strong> and <strong><code>GLine</code></strong> classes rather than <strong><code>GLabel</code></strong>. For example, if I wrote this program, I would want the output to be </p> <p>[an image showing simple letters E S R on a canvas]</p> <p>Think about the best decomposition to use in writing the program. Imagine that you’ve been asked to design a more general letter-drawing library. How would you want the methods in that library to behave in order to make using them as simple as possible for your clients?</p> </blockquote> <p>I'd like to know the correct approach to use in solving this problem. I'm not sure what I have so far is good enough (I'm thinking it's too long). The questions requires that I use a good Top-Down approach.</p> <p>Here's my code so far:</p> <pre><code>//Passes letters to GLetter objects and draws them on the canvas package artScienceJavaExercises.chapter8; package artScienceJavaExercises.chapter8; import acm.program.*; //import acm.graphics.*; public class DrawInitials extends GraphicsProgram{ public void init(){ resize(400,400); } public void run(){ //String let = readLine("Letter?: "); letter = new GLetter("l"); add(letter, (getWidth()-letter.getWidth()*2)/2, (getHeight()-letter.getHeight())/2); add(new GLetter("o"), (letter.getX()+letter.getWidth()), letter.getY()); } private GLetter letter; } </code></pre> <hr> <pre><code>//GLetter Class package artScienceJavaExercises.chapter8; import acm.graphics.*; import java.awt.*; public class GLetter extends GCompound{ private static final int ONE_THIRD = 30; private static final int ROW_2_HEIGHT = 40; private GArc[] arc = new GArc[4]; private GLine[] line = new GLine[24]; public GLetter(String s){ line[0] = new GLine(0,0, ONE_THIRD, 0); line[1] = new GLine(ONE_THIRD,0, ONE_THIRD*2, 0); line[2] = new GLine(ONE_THIRD*2,0, ONE_THIRD*3, 0); line[3] = new GLine(0,0, 0,ONE_THIRD); line[4] = new GLine(ONE_THIRD,0, ONE_THIRD, ONE_THIRD); line[5] = new GLine(ONE_THIRD*2,0, ONE_THIRD*2, ONE_THIRD); line[6] = new GLine(ONE_THIRD*3,0, ONE_THIRD*3, ONE_THIRD); line[7] = new GLine(0,ONE_THIRD, ONE_THIRD*2, ONE_THIRD); line[8] = new GLine(ONE_THIRD,ONE_THIRD, ONE_THIRD*2, ONE_THIRD); line[9] = new GLine(ONE_THIRD*2,ONE_THIRD, ONE_THIRD*3, ONE_THIRD); line[10] = new GLine(0,ONE_THIRD, 0, ONE_THIRD+ROW_2_HEIGHT); line[11] = new GLine(ONE_THIRD, ONE_THIRD, ONE_THIRD, ONE_THIRD+ROW_2_HEIGHT); line[12] = new GLine(ONE_THIRD*2,ONE_THIRD, ONE_THIRD*2, ONE_THIRD+ROW_2_HEIGHT); line[13] = new GLine(ONE_THIRD*3,ONE_THIRD, ONE_THIRD*3, ONE_THIRD+ROW_2_HEIGHT); line[14] = new GLine(0, ONE_THIRD+ROW_2_HEIGHT, ONE_THIRD, ONE_THIRD+ROW_2_HEIGHT); line[15] = new GLine(ONE_THIRD, ONE_THIRD+ROW_2_HEIGHT, ONE_THIRD*2, ONE_THIRD+ROW_2_HEIGHT); line[16] = new GLine(ONE_THIRD*2, ONE_THIRD+ROW_2_HEIGHT, ONE_THIRD*3, ONE_THIRD+ROW_2_HEIGHT); line[17] = new GLine(0, ONE_THIRD+ROW_2_HEIGHT, 0, ONE_THIRD*2+ROW_2_HEIGHT); line[18] = new GLine(ONE_THIRD, ONE_THIRD+ROW_2_HEIGHT, ONE_THIRD, ONE_THIRD*2+ROW_2_HEIGHT); line[19] = new GLine(ONE_THIRD*2, ONE_THIRD+ROW_2_HEIGHT, ONE_THIRD*2, ONE_THIRD*2+ROW_2_HEIGHT); line[20] = new GLine(ONE_THIRD*3, ONE_THIRD+ROW_2_HEIGHT, ONE_THIRD*3, ONE_THIRD*2+ROW_2_HEIGHT); line[21] = new GLine(0,ONE_THIRD*2+ROW_2_HEIGHT, ONE_THIRD, ONE_THIRD*2+ROW_2_HEIGHT); line[22] = new GLine(ONE_THIRD, ONE_THIRD*2+ROW_2_HEIGHT, ONE_THIRD*2, ONE_THIRD*2+ROW_2_HEIGHT); line[23] = new GLine(ONE_THIRD*2,ONE_THIRD*2+ROW_2_HEIGHT, ONE_THIRD*3, ONE_THIRD*2+ROW_2_HEIGHT); for(int i = 0; i&lt;line.length; i++){ add(line[i]); line[i].setColor(Color.BLACK); line[i].setVisible(false); } arc[0] = new GArc(getWidth(), getHeight(), 106.699, 49.341); arc[1] = new GArc(getWidth(), getHeight(), 23.96, 49.341); arc[2] = new GArc(getWidth(), getHeight(), -23.96, -49.341); arc[3] = new GArc(0,0,getWidth(), getHeight(), -106.699, -49.341); for(int i = 0; i&lt;arc.length; i++){ add(arc[i],0,0); arc[i].setColor(Color.BLACK); arc[i].setVisible(false); } paintLetter(s); } private void paintLetter(String s){ if (s.equalsIgnoreCase("l")){ turnOn(line[3]); turnOn(line[10]); turnOn(line[17]); turnOn(line[21]); turnOn(line[22]); turnOn(line[23]); } else if(s.equalsIgnoreCase("o")){ for(int i = 0; i&lt;4; ++i){ turnOn(arc[i]); } turnOn(line[1]); turnOn(line[10]); turnOn(line[13]); turnOn(line[22]); } } private void turnOn(GObject g){ g.setVisible(true); } } </code></pre> <hr> <p>I created a class (GLetter.java) with arrays for GArc and GLine objects. They are positioned in certain ways thereby turning certain Glines and/or GArcs on or off (changing visiblity) would create a pattern for a letter. This Gletter uses the if/else statements to determine which pattern to create - this makes me feel my code is too long.</p> <p>There is another class (DrawInitials.java) that simulates a GraphicsProgram and allows the user to pass certain letters as arguments to the GLetter object. I've used 'L' and 'O' as examples.</p> <p>However, I posted this because I'm not sure I'm using the right approach. That's why I need your help.</p> <p>I feel MY CODE IS TOO LONG!</p> <p>The code above is not the complete project...it only draws letters 'L' and 'O' for now.</p>
[]
[ { "body": "<ol>\n<li><p>You might want to remove the unused lines. The code does not use <code>line[2]</code>, <code>line[4]</code>, <code>line[5]</code>, <code>line[18]</code> etc.</p></li>\n<li><p>You should check the input value of the <code>GLetter</code> class. Currently it does not show, for example, letter <code>a</code>, it would be nice to tell the users that's not their fault that the class ignores this letter. I'd throw an <code>IllegalArgumentException</code> in this case. (<em>Effective Java, Second Edition, Item 38: Check parameters for validity</em>)</p></li>\n<li><p>You might want to change the input type of the <code>GLetter</code> class to <code>char</code>. Does it make sense to call it with more than one character?</p></li>\n<li><p>I'd create a map with the letters and the required segments for each letter:</p>\n\n<pre><code>final Multimap&lt;Character, GObject&gt; segmentsMap = HashMultimap.create();\nsegmentsMap.putAll('l', Lists.newArrayList(line[3], line[10], line[17], \n line[21], line[22], line[23]));\nsegmentsMap.putAll('o', Lists.newArrayList(line[1], line[10], line[13], \n line[22], arc[0], arc[1], arc[2], arc[3]));\n</code></pre>\n\n<p>Then all you need is a for loop to make visible the required segments:</p>\n\n<pre><code>if (!segmentsMap.containsKey(c)) {\n throw new IllegalArgumentException(\"Invalid letter: \" + c);\n}\n\nfinal Collection&lt;GObject&gt; segments = segmentsMap.get(c);\nfor (final GObject segment: segments) {\n turnOn(segment);\n}\n</code></pre>\n\n<p>(I've used <a href=\"http://guava-libraries.googlecode.com/svn/tags/release03/javadoc/com/google/common/collect/Multimap.html\" rel=\"nofollow\">Guava's Multimap</a> here but you can do this with multidimensional arrays too.)</p></li>\n</ol>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-11-10T05:57:04.407", "Id": "29393", "Score": "0", "body": "Thanks for the response. Like I said, the code is still incomplete. By the time I fully implement the entire GLetter class, those unused GLine objects would become useful because the class would create an entire \"letter library\".\n\nAlso, it is completely independent of GLabel class.\nThis question comes before we are being taught about arrays, which is one of the things that make me feel my code is being wrongly implemented.\n\nSo, I don't think the use of segments is appropriate in solving this problem." } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-11-09T19:44:08.920", "Id": "18414", "ParentId": "18332", "Score": "1" } }, { "body": "<p>A code like this is never TOO LONG, if each letters have différent parameters and different algoritmes. <br><strong><em>Easy to maintain</em></strong> without disturbing other letters for maintenaing a letter, not difficult to repeat on each letter if necessary(just to pay attention, and a second reader/controler).</p>\n\n<p>So if you have time to parametrize all, few classes are necessary, choosing good design pattern may be difficult.<br></p>\n\n<p>Letter parameters will be in <code>letterPrmFile.properties/globalPrm.properties</code>. <br>Changing <code>.properties</code> is easy, but changing a method, a condition, a single bit in the code need to prepare many <code>jUnit</code> testcases, and many tests in many different types of windows.</p>\n\n<p>It is up to you under your constraints.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-01-10T16:24:20.040", "Id": "20386", "ParentId": "18332", "Score": "0" } }, { "body": "<p>Your answer is too long because you are trying to do more than you were asked to.</p>\n\n<pre><code>public class DrawInitials extends GraphicsProgram{\n public void run(){\n drawLetterL();\n drawLetterO();\n }\n\n public void drawLetterL(){\n add(new GLine( ... )); // Vertical Stroke\n add(new GLine( ... )); // Horizontal Stroke\n }\n\n public void drawLetterO(){\n add(new GArc( ... )); // A circle\n }\n}\n</code></pre>\n\n<p>How would you generalize this. There may be many answer to this question but an answer similar to the one below is expected I guess:</p>\n\n<pre><code>public abstract class LetterDrawer {\n // this is to show that you cannot hard-code \n // coordinates in a generalized graphics routine\n\n abstract void draw(GObject o, double xOffset, double yOffset);\n}\n\n// this is the class *your clients* will actually use\npublic class LetterDrawingService {\n Map&lt;Character, LetterDrawer&gt; letterDrawers;\n\n LetterDrawingService () {\n // initialize your drawer map\n }\n\n public draw(GObject o, char c, double xOffset, double yOffset) {\n // Validate as in the @Palacsint's answer\n letterDrawers.get(c).draw(o, c, xOffset, yOffset);\n }\n}\n</code></pre>\n\n<p>I doubt book teaches factory classes before arrays, so I will not give an example for that case. Basic Idea is you have a class for each letter which extends some abtract <code>GLetter</code> and pass Offset Position to the constructor. (Side note: you should have a position class, if the graphics library doesn't have them).</p>\n\n<p>I do not know <code>acm.grahics</code> package so do not get hung up on the details.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-01-11T13:50:18.640", "Id": "20423", "ParentId": "18332", "Score": "2" } } ]
{ "AcceptedAnswerId": "20423", "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-11-07T23:37:49.470", "Id": "18332", "Score": "2", "Tags": [ "java", "api" ], "Title": "ACM API based Java exercise" }
18332
<p>Here is my QuadTree class and node.</p> <p>The problem is really with Querying.</p> <p>In my game, I have a city which can have n * n streets (randomly generated). And each street has buildings.</p> <p>What I do is put all buildings and roads in a quadtree and render the result. The problem is as the city gets bigger, I lose lots of FPS. But QuadTree is supposed to be O(log n) so increasing the city size from 15 * 15 to 30 * 30 should not have that much impact on FPS.</p> <p>In fact, doing bounding box check on each street individually against camera rect is much faster than quadtree right now.</p> <p>Is there anything here that might benefit from optimization?</p> <p>I'm mostly interested in optimizing OrientedQuery function. Inserting is pretty fast.</p> <p>Thanks</p> <pre><code> public class QuadTree&lt;T extends Entity&gt; { /// &lt;summary&gt; /// The root QuadTreeNode /// &lt;/summary&gt; QuadTreeNode&lt;T&gt; m_root; /// &lt;summary&gt; /// The bounds of this QuadTree /// &lt;/summary&gt; OBB2D m_rectangle; List&lt;T&gt; results = new LinkedList&lt;T&gt;(); public QuadTree(OBB2D rectangle) { m_rectangle = rectangle; m_root = new QuadTreeNode&lt;T&gt;(m_rectangle); } /// &lt;summary&gt; /// Get the count of items in the QuadTree /// &lt;/summary&gt; public int size() { return m_root.size(); } /// &lt;summary&gt; /// Insert the feature into the QuadTree /// &lt;/summary&gt; /// &lt;param name="item"&gt;&lt;/param&gt; public void Insert(T item) { m_root.Insert(item); } /// &lt;summary&gt; /// Query the QuadTree, returning the items that are in the given area /// &lt;/summary&gt; /// &lt;param name="area"&gt;&lt;/param&gt; /// &lt;returns&gt;&lt;/returns&gt; private List&lt;T&gt; OrientedQuery(OBB2D area, List&lt;T&gt; results) { return m_root.OrientedQuery(area,results); } public List&lt;T&gt; OrientedQuery(OBB2D queryArea) { results.clear(); return OrientedQuery(queryArea, results); } } Node public class QuadTreeNode&lt;T extends Entity&gt; { /// &lt;summary&gt; /// Construct a quadtree node with the given bounds /// &lt;/summary&gt; /// &lt;param name="area"&gt;&lt;/param&gt; public QuadTreeNode(OBB2D bounds) { m_bounds = bounds; } /// &lt;summary&gt; /// The area of this node /// &lt;/summary&gt; OBB2D m_bounds; /// &lt;summary&gt; /// The contents of this node. /// Note that the contents have no limit: this is not the standard way to impement a QuadTree /// &lt;/summary&gt; List&lt;T&gt; m_contents = new LinkedList&lt;T&gt;(); /// &lt;summary&gt; /// The child nodes of the QuadTree /// &lt;/summary&gt; List&lt;QuadTreeNode&lt;T&gt;&gt; m_nodes = new LinkedList&lt;QuadTreeNode&lt;T&gt;&gt;(); /// &lt;summary&gt; /// Is the node empty /// &lt;/summary&gt; public boolean isEmpty() { return m_bounds.getBoundingRect().isEmpty() || m_nodes.size() == 0; } /// &lt;summary&gt; /// Area of the quadtree node /// &lt;/summary&gt; public OBB2D getBounds() { return m_bounds; } /// &lt;summary&gt; /// Total number of nodes in the this node and all SubNodes /// &lt;/summary&gt; public int size() { int count = 0; for(QuadTreeNode&lt;T&gt; node : m_nodes) count += node.size(); count += this.Contents().size(); return count; } /// &lt;summary&gt; /// Return the contents of this node and all subnodes in the true below this one. /// &lt;/summary&gt; public List&lt;T&gt; SubTreeContents(List&lt;T&gt; results) { for (QuadTreeNode&lt;T&gt; node : m_nodes) node.SubTreeContents(results); results.addAll(this.Contents()); return results; } public List&lt;T&gt; Contents() { return m_contents; } /// &lt;summary&gt; /// Query the QuadTree for items that are in the given area /// &lt;/summary&gt; /// &lt;param name="queryArea"&gt;&lt;/pasram&gt; /// &lt;returns&gt;&lt;/returns&gt; public List&lt;T&gt; OrientedQuery(OBB2D queryArea, List&lt;T&gt; results) { // this quad contains items that are not entirely contained by // it's four sub-quads. Iterate through the items in this quad // to see if they intersect. for (T item : this.Contents()) { if (queryArea.overlaps(item.getRect())) results.add(item); } for (QuadTreeNode&lt;T&gt; node : m_nodes) { if (node.isEmpty()) continue; // Case 1: search area completely contained by sub-quad // if a node completely contains the query area, go down that branch // and skip the remaining nodes (break this loop) if (node.getBounds().getBoundingRect().contains(queryArea.getBoundingRect())) { node.OrientedQuery(queryArea,results); break; } // Case 2: Sub-quad completely contained by search area // if the query area completely contains a sub-quad, // just add all the contents of that quad and it's children // to the result set. You need to continue the loop to test // the other quads if (queryArea.overlaps(node.getBounds())) { node.SubTreeContents(results); continue; } // Case 3: search area intersects with sub-quad // traverse into this quad, continue the loop to search other // quads if (node.getBounds().overlaps(queryArea)); { node.OrientedQuery(queryArea,results); } } return results; } /// &lt;summary&gt; /// Insert an item to this node /// &lt;/summary&gt; /// &lt;param name="item"&gt;&lt;/param&gt; public void Insert(T item) { // if the item is not contained in this quad, there's a problem if (!m_bounds.getBoundingRect().contains(item.getRect().getBoundingRect())) { return; } // if the subnodes are null create them. may not be sucessfull: see below // we may be at the smallest allowed size in which case the subnodes will not be created if (m_nodes.size() == 0) CreateSubNodes(); // for each subnode: // if the node contains the item, add the item to that node and return // this recurses into the node that is just large enough to fit this item for (QuadTreeNode&lt;T&gt; node : m_nodes) { if (node.getBounds().getBoundingRect().contains(item.getRect().getBoundingRect())) { node.Insert(item); return; } } // if we make it to here, either // 1) none of the subnodes completely contained the item. or // 2) we're at the smallest subnode size allowed // add the item to this node's contents. this.Contents().add(item); } /// &lt;summary&gt; /// Internal method to create the subnodes (partitions space) /// &lt;/summary&gt; private void CreateSubNodes() { // the smallest subnode has an area if ((m_bounds.getBoundingRect().height() * m_bounds.getBoundingRect().width()) &lt;= 10) return; float halfWidth = (m_bounds.getBoundingRect().width() / 2.0f); float halfHeight = (m_bounds.getBoundingRect().height() / 2.0f); float quarterWidth = (halfWidth / 2.0f); float quarterHeight = (halfHeight / 2.0f); m_nodes.add(new QuadTreeNode&lt;T&gt;( new OBB2D(m_bounds.getBoundingRect().left + quarterWidth, m_bounds.getBoundingRect().top + quarterHeight, halfWidth,halfHeight))); m_nodes.add(new QuadTreeNode&lt;T&gt;( new OBB2D(m_bounds.getBoundingRect().left, m_bounds.getBoundingRect().top + halfHeight + quarterHeight, halfWidth,halfHeight))); m_nodes.add(new QuadTreeNode&lt;T&gt;( new OBB2D(m_bounds.getBoundingRect().left + halfWidth + quarterWidth, m_bounds.getBoundingRect().top + quarterHeight, halfWidth,halfHeight))); m_nodes.add(new QuadTreeNode&lt;T&gt;( new OBB2D(m_bounds.getBoundingRect().left + halfWidth + quarterWidth, m_bounds.getBoundingRect().top + halfHeight + quarterHeight, halfWidth, halfHeight))); } } </code></pre>
[ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-11-26T15:52:30.797", "Id": "59081", "Score": "0", "body": "Did you profile that code? What happens when the city size grows by 10x? 100x? (Without doing anything else than quadtree queries.)" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-11-29T14:30:32.667", "Id": "59576", "Score": "0", "body": "What arguments does the `OBB2D` constructor take?" } ]
[ { "body": "<p>Unless you really need fast performance for head-insert, or <code>iterator.add()</code>/<code>remove()</code>, then LinkedList is almost always the wrong choice for a program.</p>\n\n<p>Certainly, LinkedList has a bigger footprint on memory (it takes up many times more bytes of memory than the equivalent data in an <code>ArrayList()</code>).</p>\n\n<p>So, my suggestion to you is to convert your LinkedLists to ArrayLists. ArrayList will take less space.</p>\n\n<p>If you feel you really need to use a LinkedList, then you can do that, but, <strong>please</strong> use <code>list.isEmpty()</code> instead of <code>list.size() == 0</code>. This is <a href=\"https://stackoverflow.com/questions/11152536/check-if-a-collection-is-empty-in-java-which-is-the-best-method/11152624#11152624\">generally a good thing</a> to do.</p>\n\n<hr>\n\n<p>Previously I suggested that the performance problems may be because of O(n) performance of LinkedList.size(). In the past I have fallen victim to a problem with <code>size() == 0</code> instead of using <code>isEmpty()</code> and now, when I see it, I 'react'. In this case, it was premature, so I have edited out that part of my answer.</p>\n\n<p>After that failed knee-jerk response, and after looking more carefully at your code, I have one suggestion, one potential bug, and a couple of questions...</p>\n\n<p><strong>The suggestion:</strong></p>\n\n<p>In your QuadTree class you keep an instance array:</p>\n\n<pre><code> List&lt;T&gt; results = new LinkedList&lt;T&gt;();\n</code></pre>\n\n<p>Which you 'reuse' in the method:</p>\n\n<pre><code> public List&lt;T&gt; OrientedQuery(OBB2D queryArea)\n {\n results.clear();\n return OrientedQuery(queryArea, results);\n }\n</code></pre>\n\n<p>This is a problem because it is possible that you may be holding on to memory for much longer than you need. There is no advantage to doing what you do. The code could simply be:</p>\n\n<pre><code> public List&lt;T&gt; OrientedQuery(OBB2D queryArea)\n {\n return OrientedQuery(queryArea, new LinkedList&lt;T&gt;());\n }\n</code></pre>\n\n<p><strong>The potential bug:</strong></p>\n\n<p>You have three 'Case' sections in the OrientedQuery. One for if the node fully-contains the search area, the second for if the query-area fully-contains the node, and the third is if there's an overlap, not a full-contains condition.</p>\n\n<p>The Second Case has a bug:</p>\n\n<pre><code> // Case 2: Sub-quad completely contained by search area \n // if the query area completely contains a sub-quad,\n // just add all the contents of that quad and it's children \n // to the result set. You need to continue the loop to test \n // the other quads\n if (queryArea.overlaps(node.getBounds()))\n {\n node.SubTreeContents(results);\n continue;\n } \n</code></pre>\n\n<p>The <code>if</code> condition should surely be <code>if (queryArea.contains(...)) ...</code> rather than <code>if (queryArea.overlaps(node.getBounds())) ...</code></p>\n\n<p>As it stands, it is possible that you are returning many nodes that should not otherwise be returned. This is potentially the source of your performance problem.</p>\n\n<p><strong>Questions:</strong></p>\n\n<p>I have scoured the code have presented here, and cannot otherwise find where your code performance may regress. This leads me to believe that the performance issue is in one of the methods you call that is not presented in this question.</p>\n\n<p>Places where I thing it would be useful to inspect are:</p>\n\n<ul>\n<li><code>OBB2D.getBoundingRect()</code> - presume this is a constant-time operation.</li>\n<li><code>queryArea.overlaps(...)</code> and <code>queryArea.contains(...)</code>. What do these methods look like?</li>\n</ul>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-11-29T14:26:31.257", "Id": "59575", "Score": "2", "body": "`LinkedList.size()` is O(1). Look at the [openjdk source](http://grepcode.com/file/repository.grepcode.com/java/root/jdk/openjdk/6-b14/java/util/LinkedList.java#LinkedList.size%28%29)." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-11-29T15:42:43.983", "Id": "59585", "Score": "0", "body": "Well, arn't I just floozing today.... huh. Did that change 'recently' ? (off to do some research)." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-11-29T17:20:31.837", "Id": "59595", "Score": "1", "body": "@PeterTaylor `LinkedList.size()` is O(1) _in the reference implementation_, but O(1) performance is not guaranteed unless it is documented. The reference implementation could even change in the future — [as it did for `String.substring()`](http://stackoverflow.com/q/16123446/1157100). Therefore, you should always prefer `.isEmpty()` to `.size() == 0`." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-11-29T18:15:55.247", "Id": "59605", "Score": "1", "body": "@200_success, O(1) performance isn't documented for `isEmpty()` either, and in fact if you take the API doc literally then `LinkedList` is documented to inherit its implementation of `isEmpty()` from `AbstractCollection`, which is documented to implement `isEmpty()` by calling `size()`. I personally prefer `isEmpty()` to `size() == 0`, but that's a matter of style rather than performance guarantees." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-11-29T23:15:21.080", "Id": "59622", "Score": "1", "body": "@PeterTaylor Revised my answer. Thanks for the O(1) point. I **do** appreciate knowing when I am wrong **almost** as much as knowing when I am right .... ;p" } ], "meta_data": { "CommentCount": "5", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-11-29T02:15:46.510", "Id": "36324", "ParentId": "18334", "Score": "2" } }, { "body": "<p>I smell a rat in <code>CreateSubNodes</code>.</p>\n\n<pre><code> float quarterWidth = (halfWidth / 2.0f);\n float quarterHeight = (halfHeight / 2.0f);\n</code></pre>\n\n<p>Why do you need quarters? The only thing that I can think of is that the <code>OBB2D</code> constructor takes <code>(centre_x, centre_y, width, height)</code> rather than the more conventional <code>(left, top, width, height)</code>.</p>\n\n<pre><code> m_nodes.add(new QuadTreeNode&lt;T&gt;(\n new OBB2D(m_bounds.getBoundingRect().left + quarterWidth, \n m_bounds.getBoundingRect().top + quarterHeight, halfWidth,halfHeight)));\n</code></pre>\n\n<p>is consistent with that hypothesis.</p>\n\n<pre><code> m_nodes.add(new QuadTreeNode&lt;T&gt;(\n new OBB2D(m_bounds.getBoundingRect().left,\n m_bounds.getBoundingRect().top + halfHeight + quarterHeight, \n halfWidth,halfHeight)));\n</code></pre>\n\n<p>is not. The x-coord is offset by a quarter and the y-coord by a half.</p>\n\n<p>If the arguments to the constructor are centre and size then one of the four quads is misplaced, so on average something like 1/8 of the items which should go further down the quad are being stored in the current node. If the arguments to the constructor are corner and size then three of the four quads are misplaced, and on average something like 7/16 of the items is not being pushed further down.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-11-29T23:34:14.333", "Id": "36383", "ParentId": "18334", "Score": "2" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "2", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-11-08T00:23:59.280", "Id": "18334", "Score": "3", "Tags": [ "java", "optimization", "performance", "complexity" ], "Title": "Not getting Log(n) performance from quadtree" }
18334
<p>I'm new to Python, just attempted the task <a href="https://www.cs.duke.edu/courses/cps100/fall03/assign/extra/treesum.html" rel="nofollow">here</a>.</p> <p>The part I found hardest was parsing the expression into the tree structure. I was originally trying to build a regular tree structure (i.e. a Node object with left and right nodes), but without any logic for the insertion (i.e. newNode &lt; node then insert left, newNode > node then insert right) I couldn't find a way.</p> <p>In the end I've used Python's lists to kind of replicate the expression structure, and walk the paths as they're created. Each time I find a leaf, I calculate the cumulative sum, pop the last added node, and carry on.</p> <p>The one part of the code I really don't like is the way I'm finding leafs:</p> <pre><code>if tree and expression[i-1:i+3] == ['(',')','(',')']: </code></pre> <p>and I don't like that I've done:</p> <pre><code>pair[1].replace('(', ' ( ').replace(')', ' ) ').split() </code></pre> <p>twice.</p> <p>Any guidance on any part of this - style or just general approach and logic would be great.</p> <pre><code>def pairs(value): """ Yields pairs (target, expression) """ nest_level = 0 expr = "" target = 0 value = value.replace('(', ' ( ').replace(')', ' ) ').split() for x in value: if x.isdigit() and not expr: target = x else: expr += x if x is '(': nest_level += 1 elif x is ')': nest_level -= 1 if nest_level is 0: yield target, expr expr = '' target = 0 def main(): with open('input') as f: expr_input = f.read() level = 0 current_target = 0 for pair in pairs(expr_input): current_target = pair[0] # stack representing the 'current path' tree = list() # store the cumulative total of each path for this expression cumulative_totals = list() running_total = 0 expression = pair[1].replace('(', ' ( ').replace(')', ' ) ').split() for i, s in enumerate(expression): if s is '(': level += 1 elif s == ')': level -= 1 # "is leaf?" ugh. if tree and expression[i-1:i+3] == ['(',')','(',')']: cumulative_totals.append(running_total) # remove the node and carry on down the next path node = tree.pop() running_total = running_total - int(node) if level is 0: if int(current_target) in cumulative_totals: print "yes" else: print "no" else: running_total += int(s) tree.append(s) if __name__ == '__main__': main() </code></pre>
[]
[ { "body": "<ol>\n<li><p><strong>Avoid indentation</strong>.</p>\n\n<pre><code> print \"no\"\n</code></pre>\n\n<p>When you need this amount of spaces in front of your code, I'd say <em>no</em> too.</p>\n\n<p>This is clearly a sign that what you're writing could be extracted into a function call, our main could be a chain of function calls instead of a big clump of code.</p>\n\n<pre><code>with open('input') as f:\n parseFile(f)\n\ndef parseFile(...):\n ...\n for pair in pairs(expr_input): parsePair(pair)\n ...\n\ndef parsePair(...):\n ...\n for i, s in enumerate(expression): addExpressionToSummation(i, s)\n ...\n</code></pre>\n\n<p>Of course, this won't work out of the box; that's what object-oriented programming will help with.</p>\n\n<p>Also, if you need to map one-to-one, use list comprehensions or functions like <code>map</code>.</p></li>\n<li><p><strong>Regular expressions might sometimes be valuable</strong>.</p>\n\n<pre><code>value = value.replace('(', ' ( ').replace(')', ' ) ').split()\n</code></pre>\n\n<p>can be</p>\n\n<pre><code>value = re.sub(r'(\\(|\\))', r' \\1 ', value).split();\n</code></pre>\n\n<p>which can be improved to not add multiple spaces by restricting the match or by doing another replace where you replace <code>r' +'</code> by <code>r' '</code>. Of course this example might not be worth it, but if you've got to do heavier duty then you'll quickly want to resort to a regular expression instead of much longer trial-and-error code.</p></li>\n<li><p><strong>Conditions can be functions, too.</strong></p>\n\n<pre><code># \"is leaf?\" ugh.\nif tree and expression[i-1:i+3] == ['(',')','(',')']:\n</code></pre>\n\n<p>Imagine that'd be</p>\n\n<pre><code>if isLeaf(tree, expression):\n</code></pre>\n\n<p>Oh look, our documentation line is gone. ;)</p></li>\n</ol>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-11-08T10:38:11.670", "Id": "18343", "ParentId": "18342", "Score": "4" } }, { "body": "<p>This is not per-ce what you asked, but code can be split into two distinct steps:</p>\n\n<ol>\n<li>Parse the given string to some data structure.</li>\n<li>Execute algorithm on that structure.</li>\n</ol>\n\n<p>Step [1] can be done in 3 lines, as the string is almost a python syntax as is:</p>\n\n<pre><code>s = '(5 (4 (11 (7 () ()) (2 () ()) ) ()) (8 (13 () ()) (4 () (1 () ()) ) ) )'\ns = s.replace('(',',[')\ns = s.replace(')',']')\ns = s[1:]\n</code></pre>\n\n<p>Now <code>s</code> is a valid python list:</p>\n\n<pre><code>'[5 ,[4 ,[11 ,[7 ,[] ,[]] ,[2 ,[] ,[]] ] ,[]] ,[8 ,[13 ,[] ,[]] ,[4 ,[] ,[1 ,[] ,[]] ] ] ]'\n</code></pre>\n\n<p>Let's put it into a variable:</p>\n\n<pre><code>ltree = eval(s)\n</code></pre>\n\n<p>Now <code>ltree</code> is a good tree representation - it is in fact a DFS walk on the tree.</p>\n\n<p><code>ltree[0]</code> is the root value, <code>ltree[1]</code> is the left subtree, and <code>ltree[2]</code> is the right subtree - and so on.</p>\n\n<p>And the code to test the walk becomes simple:</p>\n\n<pre><code>def is_sum(tree, num):\n if (len(tree) == 0): # 'in' a leaf\n return False\n if (len(tree[1]) == 0 &amp; len(tree[2]) == 0): # leaf\n return num == tree[0]\n return (is_sum(tree[1], num-tree[0]) | is_sum(tree[2], num-tree[0]))\n</code></pre>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-11-08T18:23:52.963", "Id": "18358", "ParentId": "18342", "Score": "0" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-11-08T09:48:31.203", "Id": "18342", "Score": "5", "Tags": [ "python", "beginner" ], "Title": "Parsing s-expression structure into tree and summing the paths" }
18342
<p>I'm writing a validation class, and I need one version which takes one type parameter, and one which takes two, and who knows one day I might want one which takes three. I have a lot of repeated code as the two versions are effectively identical except for the different number of type parameters. I'm looking for suggestions about how (if possible) to refactor this to reduce the amount of repeated code:</p> <pre><code>public class Validator&lt;T&gt; : Validator { // Because this is a static property, the rules are only evaluated once per type // no matter how many instances are created. private static IEnumerable&lt;IValidate&lt;T&gt;&gt; rules; public IEnumerable&lt;IValidate&lt;T&gt;&gt; Validate(T item) { if (rules == null || rules.Any() == false) { CreateRules(); } return rules.Where(rule =&gt; rule.IsValid(item) == false); } private static IValidate&lt;T&gt; CreateRule(Type type) { return (IValidate&lt;T&gt;)Activator.CreateInstance(type); } protected virtual void CreateRules() { IEnumerable&lt;Type&gt; ruleTypes = GetTypes&lt;T&gt;(t =&gt; typeof(IValidate&lt;T&gt;).IsAssignableFrom(t)); rules = ruleTypes.Select(CreateRule); } } public class Validator&lt;T, K&gt; : Validator { // Because this is a static property, the rules are only evaluated once per type // no matter how many instances are created. private static IEnumerable&lt;IValidate&lt;T, K&gt;&gt; rules; public IEnumerable&lt;IValidate&lt;T, K&gt;&gt; Validate(T item, K itemToCompare) { if (rules == null || rules.Any() == false) { CreateRules(); } return rules.Where(rule =&gt; rule.IsValid(item, itemToCompare) == false); } private static IValidate&lt;T, K&gt; CreateRule(Type type) { return (IValidate&lt;T, K&gt;)Activator.CreateInstance(type); } protected virtual void CreateRules() { IEnumerable&lt;Type&gt; ruleTypes = GetTypes&lt;T&gt;(t =&gt; typeof(IValidate&lt;T, K&gt;).IsAssignableFrom(t)); rules = ruleTypes.Select(CreateRule); } } public abstract class Validator { protected static IEnumerable&lt;Type&gt; GetTypes&lt;T&gt;(Func&lt;Type, bool&gt; predicate) { return Assembly.GetAssembly(typeof(T)).GetTypes().Where(predicate); } } </code></pre> <p>Edit: </p> <p>As the validator will be used many times to validate the same type of item, it's important that it only creates the rules once using Reflection, and that this unit test passes:</p> <pre><code>public class Validator_Tests { [Test] public void Validator_Only_Creates_Rules_Once_Per_Type() { // Running this test in isolation will pass, but running it as part of a test suite can fail. var validator = new TestClass1_Validator(); validator.Validate(new TestClass1()); Assert.AreEqual(1, validator.rulesCreated); validator = new TestClass1_Validator(); validator.Validate(new TestClass1()); Assert.AreEqual(0, validator.rulesCreated); var validator2 = new TestClass1_Validator(); validator2.Validate(new TestClass1()); Assert.AreEqual(0, validator2.rulesCreated); var validator3 = new TestClass2_Validator(); validator3.Validate(new TestClass2()); Assert.AreEqual(1, validator3.rulesCreated); validator3 = new TestClass2_Validator(); validator3.Validate(new TestClass2()); Assert.AreEqual(0, validator3.rulesCreated); } private class TestClass1 { } private class TestClass2 { } private class TestClass1_Validator : Validator&lt;TestClass1&gt; { public int rulesCreated; protected override void CreateRules() { base.CreateRules(); rulesCreated++; } } private class TestClass2_Validator : Validator&lt;TestClass2&gt; { public int rulesCreated; protected override void CreateRules() { base.CreateRules(); rulesCreated++; } } private class A_Rule_Must_Exist_Using_TestClass1 : IValidate&lt;TestClass1&gt; { public bool IsValid(TestClass1 item) { return true; } public string ErrorMessage { get; set; } } private class A_Rule_Must_Exist_Using_TestClass2 : IValidate&lt;TestClass2&gt; { public bool IsValid(TestClass2 item) { return true; } public string ErrorMessage { get; set; } } } </code></pre>
[]
[ { "body": "<p>The biggest difference between the two classes is whether they use <code>IValidate&lt;T&gt;</code> or <code>IValidate&lt;T, K&gt;</code>. So, you want to create a base class that can use either of those types in a type-safe manner. You can do that by making the base class also generic, so your derived class will be for example <code>class Validator&lt;T, K&gt; : ValidatorBase&lt;IValidate&lt;T, K&gt;&gt;</code>.</p>\n\n<p>Then you can refactor the classes to move most methods to the base class and keep only the one that actually differs: <code>Validate()</code>. Also, you will need some way to get the “main” type in the base class, for use in <code>CreateRules()</code>. You could use reflection to do that (assuming all <code>IValidate</code> types follow the same convention), but I think a better way is to use an abstract method or property.</p>\n\n<p>The rewritten code could the look something like:</p>\n\n<pre><code>public class Validator&lt;TTarget&gt; : ValidatorBase&lt;IValidate&lt;TTarget&gt;&gt;\n{\n public IEnumerable&lt;IValidate&lt;TTarget&gt;&gt; Validate(TTarget item)\n {\n CreateRulesIfNecessary();\n\n return Rules.Where(rule =&gt; !rule.IsValid(item));\n }\n\n protected override Type TargetType\n {\n get { return typeof(TTarget); }\n }\n}\n\npublic class Validator&lt;TTarget, TCompared&gt; : ValidatorBase&lt;IValidate&lt;TTarget, TCompared&gt;&gt;\n{\n public IEnumerable&lt;IValidate&lt;TTarget, TCompared&gt;&gt; Validate(TTarget item, TCompared itemToCompare)\n {\n CreateRulesIfNecessary();\n\n return Rules.Where(rule =&gt; !rule.IsValid(item, itemToCompare));\n }\n\n protected override Type TargetType\n {\n get { return typeof(TTarget); }\n }\n}\n\npublic abstract class ValidatorBase&lt;TValidate&gt;\n{\n // Because this is a static property, the rules are only evaluated once per type\n // no matter how many instances are created.\n protected static IEnumerable&lt;TValidate&gt; Rules { get; set; }\n\n protected abstract Type TargetType { get; }\n\n protected virtual void CreateRulesIfNecessary()\n {\n if (Rules == null || !Rules.Any())\n {\n var ruleTypes = Assembly.GetAssembly(TargetType).GetTypes()\n .Where(t =&gt; typeof(TValidate).IsAssignableFrom(t));\n Rules = ruleTypes.Select(CreateRule).ToArray();\n }\n }\n\n private static TValidate CreateRule(Type type)\n {\n return (TValidate)Activator.CreateInstance(type);\n }\n}\n</code></pre>\n\n<p>Other notes:</p>\n\n<ul>\n<li>In your code, <code>rules</code> wasn't a property, so your comment was inaccurate and possibly confusing.</li>\n<li>Instead of <code>== false</code>, you can simply use <code>!</code>.</li>\n<li>Most of the time, if you have a generic method that doesn't use its type argument in its signature (like your <code>GetTypes&lt;T&gt;()</code>), you can replace it with a normal parameter of type <code>Type</code>, making the method usable in more cases.</li>\n<li>If <code>CreateRules()</code> will always be used the same way (enclosed with the check), you can include that in the method too, possibly renaming it reflect the change.</li>\n<li>The names of type parameters should follow the same rules as other names: it should be clear what they mean, so don't use single letter names unless it's clear what you mean.</li>\n<li>If you use the result of LINQ query directly, the whole query will be evaluated every time you use its result. You can use <code>ToArray()</code> (or <code>ToList()</code>) to evaluate it just once.</li>\n</ul>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-11-12T14:15:30.077", "Id": "29496", "Score": "0", "body": "Unfortunately, this version does not create the rules once per type, it creates them every time so I can't use it. Thanks anyway." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-11-12T18:41:48.433", "Id": "29514", "Score": "0", "body": "It does create them only once per type, look at the check in `ValidatorBase.CreateRulesIfNecessary()`." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-11-15T20:25:17.667", "Id": "29731", "Score": "0", "body": "Your unit tests don't seem to be using my code. And I modify them to use my code, they do pass for me." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-11-16T10:18:12.823", "Id": "29788", "Score": "0", "body": "I did indeed have my tests wrong. Apologies and thanks again." } ], "meta_data": { "CommentCount": "4", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-11-09T09:57:25.353", "Id": "18389", "ParentId": "18344", "Score": "1" } } ]
{ "AcceptedAnswerId": "18389", "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-11-08T12:19:22.687", "Id": "18344", "Score": "4", "Tags": [ "c#" ], "Title": "Identical classes with different number of type parameters" }
18344
<p>I have two sieves that I wrote in python and would like help optimizing them if at all possible. The divisorSieve calculates the divisors of all numbers up to <code>n</code>. Each index of the list contains a list of its divisors. The numDivisorSieve just counts the number of divisors each index has but doesn't store the divisors themselves. These sieves work in a similar way as you would do a Sieve of Eratosthenes to calculate all prime numbers up to <code>n</code>.</p> <p><em>Note: <code>divs[i * j].append(i)</code> changed from <code>divs[i * j] += [i]</code> with speed increase thanks to a member over at stackoverflow. I updated the table below with the new times for divisorSieve. It was suggested to use this board instead so I look forward to your input.</em></p> <pre><code>def divisorSieve(n): divs = [[1] for x in xrange(0, n + 1)] divs[0] = [0] for i in xrange(2, n + 1): for j in xrange(1, n / i + 1): divs[i * j].append(i) #changed from += [i] with speed increase. return divs def numDivisorSieve(n): divs = [1] * (n + 1) divs[0] = 0 for i in xrange(2, n + 1): for j in xrange(1, n / i + 1): divs[i * j] += 1 return divs #Timer test for function if __name__=='__main__': from timeit import Timer n = ... t1 = Timer(lambda: divisorSieve(n)) print n, t1.timeit(number=1) </code></pre> <p>Results:</p> <pre><code> -----n-----|--time(divSieve)--|--time(numDivSieve)-- 100,000 | 0.333831560615 | 0.187762331281 200,000 | 0.71700566026 | 0.362314797537 300,000 | 1.1643773714 | 0.55124339118 400,000 | 1.63861821235 | 0.748340797412 500,000 | 2.06917832929 | 0.959312993718 600,000 | 2.52753840891 | 1.17777010636 700,000 | 3.01465945139 | 1.38268800149 800,000 | 3.49267338434 | 1.62560614543 900,000 | 3.98145114138 | 1.83002270324 1,000,000 | 4.4809342539 | 2.10247496423 2,000,000 | 9.80035361075 | 4.59150618897 3,000,000 | 15.465184114 | 7.24799900479 4,000,000 | 21.2197508864 | 10.1484527586 5,000,000 | 27.1910144928 | 12.7670585308 6,000,000 | 33.6597508864 | 15.4226118057 7,000,000 | 39.7509513591 | 18.2902677738 8,000,000 | 46.5065447534 | 21.1247001928 9,000,000 | 53.2574136966 | 23.8988925173 10,000,000 | 60.0628718044 | 26.8588813211 11,000,000 | 66.0121182435 | 29.4509693973 12,000,000 | MemoryError | 32.3228102258 20,000,000 | MemoryError | 56.2527237669 30,000,000 | MemoryError | 86.8917332214 40,000,000 | MemoryError | 118.457179822 50,000,000 | MemoryError | 149.526622815 60,000,000 | MemoryError | 181.627320396 70,000,000 | MemoryError | 214.17467749 80,000,000 | MemoryError | 246.23677614 90,000,000 | MemoryError | 279.53308422 100,000,000 | MemoryError | 314.813166014 </code></pre> <p>Results are pretty good and I'm happy I was able to get it this far, but I'm looking to get it even faster. If at all possible, I'd like to get <em><strong>100,000,000</strong></em> at a reasonable speed with the divisorSieve. Although this also brings into the issue that anything over <em><strong>12,000,000+</strong></em> throws a <code>MemoryError</code> at <code>divs = [[1] for x in xrange(0, n + 1)]</code>) in divisorSieve. numDivisorSieve does allow the full <em><strong>100,000,000</strong></em> to run. If you could also help get past the memory error, that would be great.</p> <p>I've tried replacing numDivisorSieve's <code>divs = [1] * (n + 1)</code> with both <code>divs = array.array('i', [1] * (n + 1))</code> and <code>divs = numpy.ones((n + 1), dtype='int')</code> but both resulted in a loss of speed (slight difference for array, much larger difference for numpy). I expect that since numDivisorSieve had a loss in efficiency, then so would divisorSieve. Of course there's always the chance I'm using one or both of these incorrectly since I'm not used to either of them.</p> <p>I would appreciate any help you can give me. I hope I have provided enough details. Thank you.</p>
[ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-11-09T02:04:30.323", "Id": "29298", "Score": "0", "body": "What are you doing with the result?" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-11-09T02:31:49.577", "Id": "29301", "Score": "0", "body": "If storing only prime factors counts as 'optimization', we can do ~3-4 times faster." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-11-09T10:48:20.477", "Id": "29335", "Score": "0", "body": "Have you tested the application using Python 64bit?" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-11-09T22:29:14.767", "Id": "29377", "Score": "0", "body": "Thanks for the suggestion about Python 64bit. It's looking like it solves the memory issues. Will update once I've run all the tests" } ]
[ { "body": "<p>You can use <code>xrange</code>'s third param to do the stepping for you to shave off a little bit of time (not huge).</p>\n\n<p>Changing:</p>\n\n<pre><code>for j in xrange(1, n / i + 1):\n divs[i * j].append(i)\n</code></pre>\n\n<p>To:</p>\n\n<pre><code>for j in xrange(i, n + 1, i):\n divs[j].append(i)\n</code></pre>\n\n<p>For <code>n=100000</code>, I go from <code>0.522774934769</code> to <code>0.47496509552</code>. This difference is bigger when made to <code>numDivisorSieve</code>, but as I understand, you're looking for speedups in <code>divisorSieve</code></p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-11-09T21:52:07.010", "Id": "29374", "Score": "0", "body": "This was a great optimization! for `n = 10,000,000` divisorSieve's time is down to _**9.56704298066**_ and for `n = 100,000,000` numDivisorSieve's time is down to _**67.1441108416**_ which are both great optimizations." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-11-09T22:07:14.110", "Id": "29376", "Score": "0", "body": "Wow... that's better than I expected! Glad I could help." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-11-11T04:14:31.580", "Id": "29425", "Score": "0", "body": "Well...apparently the reason it did so well is I had the range messed up. So while it's still an improvement, it's not quite as good as I thought. Doesn't make me appreciate your help any less, just makes me feel a little stupid. Guess that's what I get for not testing the output well enough. Will update the original post when I get a chance to recompute all the results" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-11-11T04:28:39.427", "Id": "29426", "Score": "0", "body": "@JeremyK That's fine. At least I know I'm not crazy now. :)" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-12-13T07:03:58.300", "Id": "31317", "Score": "0", "body": "@JeremyK I was commenting on your OP about the erratic range before reading this. You should update the post - atleast change the code and say that the results are incorrect for now." } ], "meta_data": { "CommentCount": "5", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-11-09T17:57:52.603", "Id": "18411", "ParentId": "18346", "Score": "2" } }, { "body": "<p><strong>EDIT</strong>: <code>map(lambda s: s.append(i) , [divs[ind] for ind in xrange(i, n + 1, i)])</code>\nSeems to be <del>~0.2% faster</del> <strong>~2 times slower</strong> than Adam Wagner's (for <code>n=1000000</code>)</p>\n\n<p>The infamous 'test the unit test' problem.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-11-09T21:52:52.147", "Id": "29375", "Score": "0", "body": "Maybe I'm doing something incorrectly, but when I put this in there I get `TypeError: list indices must be integers, not xrange`" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-12-13T07:55:26.067", "Id": "31320", "Score": "0", "body": "**~2 times slower** Must be due to function call overhead for calling the lambda function." } ], "meta_data": { "CommentCount": "2", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-11-09T19:57:05.510", "Id": "18416", "ParentId": "18346", "Score": "0" } }, { "body": "<p>The following offers a very very small improvement to <code>divisorSieve</code> and a good improvement to <code>numdivisorSieve</code>. But the factors will not be sorted inside each list. For example the factors list of of 16 will be [4, 2, 8, 1, 16].</p>\n\n<pre><code>def divisorSieve(n):\n divs = [[] for j in xrange(n + 1)]\n nsqrt = int(sqrt(n))\n for i in xrange(1, nsqrt + 1):\n divs[i*i].append(i)\n for j in xrange(i, i*i, i):\n divs[j].append(j/i) #If j/i is replaced by i, a good improvement is seen. Of course, that would be wrong.\n divs[j].append(i)\n for i in xrange(i+1, n+1):\n for j in xrange(i, n+1, i):\n divs[j].append(j/i)\n divs[j].append(i)\n return divs\n\ndef numdivisorSieve(n):\n divs = [1] * (n + 1)\n divs[0] = 0\n nsqrt = int(sqrt(n))\n for i in xrange(2, nsqrt + 1):\n divs[i*i] += 1\n for j in xrange(i, i*i, i):\n divs[j] += 2\n for i in xrange(i+1, n+1):\n for j in xrange(i, n+1, i):\n divs[j] += 2\n return divs\n</code></pre>\n\n<p>Unfortunately, modifying this definition to create two lists divsmall ([4,2,1]) and divlarge ([8,16]) and in the end doing <code>divsmall[j].reverse(); divsmall[j].extend(divlarge[j]); return divsmall</code> makes it slightly slower than the original.</p>\n\n<p>Also, I think it makes more sense for <code>divs[0]</code> to be <code>[]</code> instead of <code>[0]</code></p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-12-13T12:01:19.540", "Id": "19578", "ParentId": "18346", "Score": "0" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "4", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-11-08T13:16:23.207", "Id": "18346", "Score": "4", "Tags": [ "python", "optimization" ], "Title": "Optimizing Divisor Sieve" }
18346
<p>This is a script I use to count how many items are selected in a form. It currently loops through the entire form to count how many check boxes are selected, each time a checkbox is clicked. The form has thousands of checkboxes, and it's painfully obvious how slow the script is with this many elements (About 18,240 items in my sample query).</p> <p>Any ideas on how I can speed this up? The speed is fine when there's less than 1,000 results, but there's rarely that few when it's running in production.</p> <pre><code>function countSelected() { var daform = document.forms.resultsForm; var daspan = document.getElementById("acctSelected"); var counter = 0; var i = 0; if (daform.multi.length == undefined) { if (daform.multi.checked) { counter = "1"; } else { counter = "0"; } } else { for (i = 0; i &lt; daform.multi.length; i++) { if (daform.multi[i].checked) { counter++; } } } daspan.innerHTML = counter; } </code></pre> <p>Fun facts:</p> <ul> <li>This script is fastest in Firefox 16.0.2 (about 2 secs)</li> <li>Second fastest by a slim margin in Internet Explorer 9 (about 2.25 secs)</li> <li>And absurdly slow in Chrome version 23.--- (I got tired of waiting)</li> </ul>
[ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-11-09T00:44:12.483", "Id": "29293", "Score": "0", "body": "Adding a listener to every checkbox is pretty inefficient (though much better than your original). See my answer for how to use a single listener on the form instead (same concept, different implementation)." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-11-09T08:14:49.970", "Id": "29330", "Score": "1", "body": "@jdstankosky [I would use the `onchange` event instead](http://jsfiddle.net/yLCC8/) since there might be other ways for the user to check the checkbox other than clicking (i.e. keyboard)." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2016-02-17T18:29:57.110", "Id": "224141", "Score": "0", "body": "I have rolled back Rev 8 ⟶ 7. Please see *[What to do when someone answers](http://codereview.stackexchange.com/help/someone-answers)*." } ]
[ { "body": "<p>Maybe the slowlyness is because you do not use the default functions. I never heard of the function \"multi\".</p>\n\n<pre><code>function countSelected()\n{\n var form = document.forms.resultsForm;\n var counter = 0;\n\n for (var i = 0; i &lt; form.elements.length; i++)\n {\n var formField = form.elements[i];\n if (formField.type == \"checkbox\" &amp;&amp; formField.checked) {\n counter++;\n }\n }\n document.getElementById(\"acctSelected\").innerHTML = counter;\n}\n</code></pre>\n\n<p>You can loop through all the elements in the form and (optionally) check if the type is a checkbox.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-11-08T16:23:49.440", "Id": "29244", "Score": "2", "body": "`multi` is the name on the checkboxes." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-11-08T18:56:41.510", "Id": "29252", "Score": "0", "body": "Ah.\nWith that you are basically performing a Named lookup for/with every record. This is not the fastest method to access elements in the page." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-11-08T19:18:18.673", "Id": "29254", "Score": "0", "body": "What would be faster?" } ], "meta_data": { "CommentCount": "3", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-11-08T16:05:48.963", "Id": "18353", "ParentId": "18349", "Score": "2" } }, { "body": "<p>I suspect you're going to struggle to optimise that, as DOM manipulation is always slow. <a href=\"https://stackoverflow.com/a/11925491/457104\">See this guy's answer</a>.</p>\n\n<p>You could try do something like he suggests, keeping your data and the DOM separate from each other.</p>\n\n<blockquote>\n <p>Currently it loops through the entire form to count how many check boxes are selected, <strong>each time a checkbox is clicked</strong></p>\n</blockquote>\n\n<p>Why not increment or decrement a counter when a checkbox's state is changed? That'll be a lot quicker.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-11-08T16:47:56.937", "Id": "29245", "Score": "0", "body": "I thought of that, but I wasn't sure if a javascript variable will persist through multiple function calls?" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-11-08T16:52:54.693", "Id": "29246", "Score": "0", "body": "Declare the variable in the global scope (outside of any functions) with `var whatever;`, and then it will persist for the lifetime of the page." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-11-08T17:29:46.037", "Id": "29247", "Score": "0", "body": "That helped me out tremendously, thank you. I've updated my question to include a working answer based on the `++` and `--`." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-11-08T18:53:02.297", "Id": "29251", "Score": "0", "body": "DOM access is not slow. DOM manipulation is. (really read that guy's answer)\nAnd you are doing it once." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-11-08T23:09:13.550", "Id": "29279", "Score": "0", "body": "@SPee isn't it still relatively slow, as we can see by how long it takes to read the state of so many checkboxes?" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-11-08T23:47:06.663", "Id": "29285", "Score": "0", "body": "@crdx: I imagine the biggest cause of the slowdown would be going through a whole tree of crap looking for checkbox elements with a specific name. Whether the process itself is painfully slow or not, messing with hundreds of DOM elements will make just about anything look slow. :)" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-11-09T00:24:01.030", "Id": "29289", "Score": "0", "body": "Alright. I changed it to _manipulation_ to make it clearer." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-11-09T00:48:57.290", "Id": "29294", "Score": "0", "body": "Note that if the page is refreshed in some browsers, checked checkboxes remain checked but the counter will be reset to zero." } ], "meta_data": { "CommentCount": "8", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-11-08T16:45:30.907", "Id": "18355", "ParentId": "18349", "Score": "5" } }, { "body": "<p>It sounds like you have your answer, but I wanted to contribute another point of view, maybe just for later reference or the good of the people :-)</p>\n\n<p>Something that would most definitely speed things up would be to hold references to the objects instead of fetching them from the DOM every time. A simple example would be:</p>\n\n<p>Instead of:</p>\n\n<pre><code>function doSomethingTenMillionTimes(){\n var awesomeButton = document.getElementById(\"awesomeButtonId\");\n //...do something with it\n}\n</code></pre>\n\n<p>Do this:</p>\n\n<pre><code>var awesomeButton = null;\n\nfunction doSomethingTenMillionTimes(){\n getAwesomeButton()...\n //...do something with it\n}\n\nfunction getAwesomeButton(){\n if(awesomeButton === null){\n awesomeButton = document.getElementById(\"awesomeButtonId\");\n }\n return awesomeButton;\n}\n</code></pre>\n\n<p>If you have to do this for a large number of objects, once you have them retrieved, say in an array, just save that array to a variable and by storing a reference to it instead of having the DOM deliver it up each time, it becomes instantly available.</p>\n\n<p>I had to do something like this recently, and solved it by storing an array of the objects I needed, assigning each of the objects a unique identifier (object.rolodexIndex = x), and when one of those objects got clicked on, I could pull it or any of it's accompanying objects out of the array rapidly and do what I needed with them.</p>\n\n<p>Some other food for thought regarding large JavaScript operations:</p>\n\n<p>When you are doing massive operations in JavaScript, it ties up the entire page. The solution is to insert breaks in between operations to allow for breathing room. This gives the illusion of multitasking and doesn't lock other things up. There's an excellent breakdown of how to do this here:</p>\n\n<p><a href=\"http://www.sitepoint.com/multi-threading-javascript/\">http://www.sitepoint.com/multi-threading-javascript/</a></p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-11-08T21:56:54.740", "Id": "18367", "ParentId": "18349", "Score": "5" } }, { "body": "<p>In your code:</p>\n\n<pre><code>&gt; if (daform.multi.length == undefined) {\n</code></pre>\n\n<p>if <em>multi</em> is the name of all the checkboxes, then <code>dataform.multi</code> will return either:</p>\n\n<ol>\n<li>one element if there's only one form control named multi</li>\n<li>an HTML collection of all the form controls named multi if there's more than one</li>\n<li><code>undefined</code> if there are no elements with a name of multi (and no form properties of that name).</li>\n</ol>\n\n<p>So the only case that the above test will \"work\" is in #2. In #3 it will throw an error. </p>\n\n<p>Much better to do:</p>\n\n<pre><code>var multis = daform.multi; // might be a collection, DOM element or undefined\n\nif (typeof multis != 'undefined') { // might be a collection or DOM element\n\n if (multis.tagName) {\n // dealing with an element\n\n } else {\n // dealing with a collection\n }\n\n} else {\n // there are no form controls named multi\n}\n</code></pre>\n\n<p>Anyhow, consider instead putting a single click listener on the form. If it gets a click from a checkbox named 'multi', and it's checked, add one to a \"checked\" varable. If it's not checked, subract one. e.g.</p>\n\n<pre><code>&lt;form name=\"daform\" onclick=\"countCheckedMultis(event);\"&gt;\n &lt;input type=\"checkbox\" name=\"multi\" value=\"...\"&gt; \n &lt;input type=\"checkbox\" name=\"multi\" value=\"...\"&gt; \n &lt;input type=\"checkbox\" name=\"multi\" value=\"...\"&gt; \n&lt;/form&gt;\n</code></pre>\n\n<p>and the function:</p>\n\n<pre><code>var countCheckedMultis = (function() {\n\n // Keep running total in a closure (\"private\" member)\n var numberChecked = 0;\n\n return function (evt) {\n var el = evt.target || evt.src;\n\n // Deal with case where target isn't an element node \n if (el.nodeType != 1) el = el.parentNode;\n\n // Increment or decrement counter if came from multi element\n // depending on if it's checked or not\n if (el.name == 'multi') numberChecked += el.checked? 1 : -1;\n\n // Debug\n alert(numberChecked);\n }\n}());\n</code></pre>\n\n<p>The flaw in the above is that if the page is refreshed, some browser will keep all the checked checkboxes checked, but reset the counter. So you need to initialise the counter on the first click.</p>\n\n<p>Note that the collection returned by <code>daform.multi</code> is converted to an array before processing. This hugely increases performance, looping over 10,000 checkboxes takes less than a second in Firefox 15, Chrome 22 and IE 9 on a modest PC.</p>\n\n<pre><code>// Convert obj to array (simple function for this case)\nfunction toArray(obj) {\n var result = [];\n for (var i=0, iLen=obj.length; i&lt;iLen; i++) {\n result[i] = obj[i]\n }\n return result;\n}\n\nvar countCheckedMultis = (function() {\n var initialised;\n var numberChecked = 0;\n\n return function (evt) {\n var el = evt.target || evt.src;\n\n if (el.nodeType != 1) el = el.parentNode;\n\n // If this is the first run, need to count checked checkboxes\n // as page may have been reloaded, resetting the counter but not\n // the checked checkboxes in some browsers \n if (!initialised &amp;&amp; el.form) {\n var multis = el.form.multi;\n\n // Converting a collection to an array before processing\n // hugely increases speed\n if (multis &amp;&amp; !multis.tagName) {\n multis = toArray(multis);\n\n for (var i=0, iLen=multis.length; i&lt;iLen; i++) {\n if (multis[i].checked) ++numberChecked;\n }\n }\n initialised = true;\n } else {\n if (el.name == 'multi') numberChecked += el.checked? 1 : -1;\n }\n\n console.log(numberChecked);\n }\n}());\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-11-18T10:36:32.787", "Id": "29896", "Score": "0", "body": "Take note of `var multis = el.form.multi;` and setting length to a variable in `for (var i=0, iLen=multis.length; i<iLen; i++)`. This might not look like much and newer browsers might already optimize it away, but in general case these expressions would be evaluated on every loop iteration. Preassigning them to variables like RobG did should save some time on older browsers at least." } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-11-09T00:39:48.967", "Id": "18375", "ParentId": "18349", "Score": "0" } } ]
{ "AcceptedAnswerId": "18355", "CommentCount": "3", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-11-08T15:14:50.017", "Id": "18349", "Score": "5", "Tags": [ "javascript", "performance", "form", "dom" ], "Title": "Counting thousands of selected checkboxes" }
18349
<p>I've been reading <em>The Pragmatic Programmer</em> for a few days and I've come across a reference to the strategy pattern. Looked it up in <em>Design Patterns</em> and figured I could refactor a piece of code I'm currently working on to comply with the strategy pattern.</p> <p>I need to process text using many string algorithms much like Lucene analyze and tokenize text. This is for an importation routine. <strong>Strategy:</strong></p> <pre><code>public class ChainOfProcessor: IStringProcessor { public List&lt;IStringProcessor&gt; Processors; public ChainOfProcessor() { Processors = new List&lt;IStringProcessor&gt;(); } public ChainOfProcessor Add&lt;TProcessor&gt;() where TProcessor: IStringProcessor, new() { return Add(new TProcessor()); } public ChainOfProcessor Add(IStringProcessor processor) { Processors.Add(processor); return this; } public string Process(string input) { return Processors.Aggregate(input, (current, processor) =&gt; processor.Process(current)); } } public interface IStringProcessor { string Process(string input); } public class HtmlStripper: IStringProcessor { public virtual string Process(string input) { var htmlDoc = new HtmlDocument(); htmlDoc.LoadHtml(input); return htmlDoc.DocumentNode.InnerText; } } public class HtmlDecoder: IStringProcessor { public string Process(string input) { return HttpUtility.HtmlDecode(input); } } </code></pre> <p>In <em>Design Patterns</em>, the authors use a <code>Composition</code> class and <code>Compositor</code> classes as examples. The client is allowed to chose a single <code>Compositor</code> through <code>Composition</code> to do whatever the <code>Compositor</code> is supposed to do. There is a subtle difference in how the client uses the <code>Composition</code> in my example. Instead of allowing a single <code>IStringProcessor</code> to be used through some <code>Composition</code> class, I allow many, to be executed one after the other through the concrete class <code>ChainOfProcessor</code>. <strong>Usage:</strong></p> <pre><code>var text = new ChainOfProcessor() .Add&lt;HtmlStripper&gt;() .Add&lt;HtmlDecoder&gt;() .Process(html); </code></pre>
[]
[ { "body": "<p>It seems like a you should implement Chain of responsibility as you are passing the same string to different kind of processor with a particular sequence</p>\n\n<p><a href=\"http://www.dofactory.com/Patterns/PatternChain.aspx#_self1\">http://www.dofactory.com/Patterns/PatternChain.aspx#_self1</a></p>\n\n<p>This is a gud pattern in your scenario. </p>\n\n<p>One more thing your StringProcessorChain might not be needed in this case....</p>\n\n<p>Let me know if you need a more highlight on same </p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-11-08T19:34:06.507", "Id": "29257", "Score": "0", "body": "It bothers me to write chaining code in every single processor. Also, usability is reduced on the client for large chains of processors; In the end it requires more code on the client and the framework." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-11-08T22:38:33.883", "Id": "29273", "Score": "2", "body": "You could make an abstract `StringProcessorBase` class that has the chaining code, and make your processors extend that..." } ], "meta_data": { "CommentCount": "2", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-11-08T18:28:41.493", "Id": "18359", "ParentId": "18352", "Score": "10" } }, { "body": "<p>Minor stylistic things (not exposing a public <code>List</code>), etc. But otherwise, you're looking good:</p>\n\n<pre><code>public interface IStringProcessor\n{\n string Process(string input);\n}\n\npublic sealed class ChainOfProcessor : IStringProcessor\n{\n private readonly IList&lt;IStringProcessor&gt; processors = new List&lt;IStringProcessor&gt;();\n\n public IList&lt;IStringProcessor&gt; Processors\n {\n get\n {\n return this.processors;\n }\n }\n\n public ChainOfProcessor Add&lt;TProcessor&gt;() where TProcessor : IStringProcessor, new()\n {\n return Add(new TProcessor());\n }\n\n public ChainOfProcessor Add(IStringProcessor processor)\n {\n this.processors.Add(processor);\n return this;\n }\n\n public string Process(string input)\n {\n return this.processors.Aggregate(input, (current, processor) =&gt; processor.Process(current));\n }\n}\n\npublic class HtmlStripper : IStringProcessor\n{\n public virtual string Process(string input)\n {\n var htmlDoc = new HtmlDocument();\n\n htmlDoc.LoadHtml(input);\n return htmlDoc.DocumentNode.InnerText;\n }\n}\n\npublic sealed class HtmlDecoder : IStringProcessor\n{\n public string Process(string input)\n {\n return HttpUtility.HtmlDecode(input);\n }\n}\n</code></pre>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-11-09T16:02:24.357", "Id": "18405", "ParentId": "18352", "Score": "4" } }, { "body": "<p>I would call this an implementation of the Composite pattern. </p>\n\n<p>The strategy pattern is about choosing one from a selection of techniques to accomplish a goal. A common example is different formatting (xml or json) or different storage (db or file system). The encapsulation is around which choice is made.</p>\n\n<p>In the composite pattern, an implementation of an interface delegates to N other implementation according to some algorithm (like \"call all of them in order\"). The encapsulation is cardinality of child objects being called. This is a very good example of exactly that.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-11-16T03:23:59.463", "Id": "18692", "ParentId": "18352", "Score": "2" } } ]
{ "AcceptedAnswerId": "18359", "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-11-08T15:32:41.133", "Id": "18352", "Score": "12", "Tags": [ "c#", "design-patterns" ], "Title": "Is this a good example of the strategy pattern?" }
18352
<p>Just saw this at work in a code review and was wondering if this style of coding - for loop, doing &amp;&amp; like that, seems fine to you or is there a better way of doing the same?</p> <pre><code>for (int j = 1; j &lt;= ETtop; j++) { // Check everything. int k = ET[j].PriIdx; for (int z = 1; z &lt;= ET[k].ArgTop; z++ ) { // Check to make sure every Argument in the equation is valid. // If it's a calc this is only true if it's been evaluated. ready = ready &amp;&amp; ET[k].Arg[z].Valid; } } </code></pre>
[ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-11-08T22:20:47.577", "Id": "29267", "Score": "1", "body": "Yep seems ok to me. Perhaps minor changes might be changing j, z and k to an actual meaning if relevant." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-11-09T09:57:37.080", "Id": "29333", "Score": "1", "body": "Only thing you could do is change to `ready &= ET[k].Arg[z].Valid`, but that might lower readability for some. I'd improve the variable names though, but that's another topic. :)" } ]
[ { "body": "<p>Currently, once you get <code>ready</code> to be false, all other checks after that will fail (as <code>false &amp;&amp; condition2</code> will always be false). </p>\n\n<p>Why not just break out of the inner for loop when <code>ET[k].Arg[z].Valid</code> is false? If <code>ready</code> is needed, you may keep the assignment line, but break when it's false.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-11-08T21:50:55.777", "Id": "29264", "Score": "0", "body": "somewhere above the code that I posted there are some areas that ready can be set to True...so in this case does your answer still correct?" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-11-08T21:53:39.727", "Id": "29265", "Score": "0", "body": "Nope. If `ready` can be changed back to true, then the && condition is probably necessary. The optimization may be that you could break out earlier depending on when you check things . . ." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-11-08T23:52:37.670", "Id": "29287", "Score": "0", "body": "@ernie : As this is code review, it would be appreciated if you posted your rewritten version of the code." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-11-09T00:29:30.123", "Id": "29291", "Score": "0", "body": "@yekAdami I should clarify, if `ready` can be changed in the inner for-loop, then the code is likely fine." } ], "meta_data": { "CommentCount": "4", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-11-08T21:32:32.413", "Id": "18364", "ParentId": "18363", "Score": "5" } }, { "body": "<p>If possible, I would rewrite your code to use collections instead of indexers and <code>top</code> properties. That way, you could use <code>foreach</code> instead of <code>for</code>, or, even better, LINQ:</p>\n\n<pre><code>ready = ET.All(e =&gt; e.Arg.All(arg =&gt; arg.Valid))\n</code></pre>\n\n<p>or:</p>\n\n<pre><code>ready = (from e in ER\n from arg in e.Arg\n select arg.Valid)\n .All();\n</code></pre>\n\n<p>This most likely won't make your code faster (although it does use short-circuit evaluation), but it will make it more readable, IMHO.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-11-09T18:54:20.207", "Id": "29360", "Score": "0", "body": "Combining this answer with ernie's, perhaps it could instead be ready = !ET.Any(e => e.Arg.Any(arg => !arg.Valid))." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-11-10T00:27:37.080", "Id": "29380", "Score": "0", "body": "@DanLyons I think that only makes things more complicated for no benefit." } ], "meta_data": { "CommentCount": "2", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-11-09T10:06:10.223", "Id": "18391", "ParentId": "18363", "Score": "1" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "2", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-11-08T21:13:33.130", "Id": "18363", "Score": "3", "Tags": [ "c#", "algorithm" ], "Title": "Is this a right and effcient way of checking AND in a for loop" }
18363
<p>I want to insert about 10000 new rows into an existing table which already contains 10000 rows. I need to get the <code>insertid</code> for the query and to use that <code>id</code> in another function inside the loop.</p> <pre><code>foreach($values as $val){ $sql = "INSERT INTO wp_posts (`post_author`, `post_date`, `post_content`, `post_title`, `post_excerpt`, `post_status`,`post_modified`,`post_type`) VALUES('".$val[author]."',NOW(),'".$val[content]."','".$val[title]."','".$val[excerpt]."','published',NOW(),'post')"; $result = mysql_query($sql); $insertid = mysql_insert_id(); add_post_meta($insertid, $val[metakey], $val[metaval], true ); } </code></pre> <p>I am fetching the values for the <code>$values</code> array from a CSV file. As of now, I can insert only 20 new rows per 3 minutes. Is there any way to speed up this insertion?</p>
[]
[ { "body": "<p>Before I continue, the following must be said:</p>\n\n<h1>Stop using <code>mysql_query</code>.</h1>\n\n<p>Seriously. There have been very good replacements for going-on a decade now. And considering this code does not appear to escape anything at all, you'd do well to learn to use parameterized queries so that it doesn't have to.</p>\n\n<hr>\n\n<p>With all that said, though, the SQL might not even be necessary. Is there a good reason you're not using <a href=\"http://codex.wordpress.org/Function_Reference/wp_insert_post\" rel=\"nofollow\"><code>wp_insert_post</code></a> to, well, insert a post? Looks like it lets you set everything you want to set, and then some. It also returns the post ID, so you don't even have to touch the database directly to get it.</p>\n\n<p>It sounds like the problem is not SQL or WordPress, really. This code should not be as slow as you're describing. If you have a DB server that's not your web server (which is generally the case in shared hosting and such), there will naturally be a bit of slowdown. Generally not <em>that</em> much delay, though, unless the DB is hosted in a totally different place (ie: not from your web hosting company). That, and the possibility that the server (DB or web server, either one) is simply overloaded, are more likely possibilities.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-11-08T22:18:37.750", "Id": "29266", "Score": "0", "body": "I have tried with wp_insert_post but same result as I said then I have replaced wp_insert_post with mysql_query()" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-11-08T22:22:05.470", "Id": "29268", "Score": "0", "body": "@ArunVKumar: `mysql_query` is about ten steps backwards. Regardless, though, it's not really the SQL or WP that's causing things to be slow. Hold on..." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-11-08T22:44:01.323", "Id": "29274", "Score": "0", "body": "this is the actual code http://pastebin.com/NTRzMRBu" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-11-08T22:50:46.583", "Id": "29275", "Score": "0", "body": "@Arun: You do realize this is \"Code Review\", right? Posting your real code in the question is pretty much *the whole point*. Truth is, though, this sounds more like a problem for SO. If the code is *abnormally* slow, that's more a bug than an optimization thing." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-11-08T22:59:32.273", "Id": "29277", "Score": "0", "body": "Sorry cHao.. It was possible 900 insertion into wp_posts table as the data in the wp_posts increased its dropped into 30-40 insertions to wp_posts table" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-11-08T23:01:14.623", "Id": "29278", "Score": "0", "body": "First I thought it may be due to the so much function calls in the wp_insert_post function. So I replaced my code with the one I posted above in this post." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-11-08T23:37:00.420", "Id": "29282", "Score": "0", "body": "It's almost certainly not the `wp_insert_post` calls. WP does a bit more DB stuff than strictly necessary, but not enough to cause the degree of slowdown that you're seeing. How was the table created? You let WP do its five minute install thing, or create the tables yourself?" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-11-08T23:39:32.030", "Id": "29283", "Score": "0", "body": "wp did table creation" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-11-08T23:41:17.100", "Id": "29284", "Score": "0", "body": "And your web server and mysql server...are they the same machine? On the same network? Or are they in two different places? (Simplified a bit: what does the hostname param look like?)" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-11-09T00:04:09.297", "Id": "29288", "Score": "0", "body": "i am trying this on local server. So web server and mysql server are on same machine!!" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-11-09T02:22:47.963", "Id": "29300", "Score": "0", "body": "So yeah. Unless your machine is overloaded, things should not be as slow as they are. I'd expect at least a few dozen posts a second even on a slow machine. Sounds like there's a problem with something else here besides the code." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-11-09T02:49:17.627", "Id": "29302", "Score": "0", "body": "Could you able to test tht?? I will provide you the necessary files.." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-11-09T02:57:33.013", "Id": "29304", "Score": "0", "body": "I don't use WP, so i don't have an install handy to set up a test in. Lemme see if i can scrounge up a site to put one in, though." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-11-09T03:06:30.837", "Id": "29306", "Score": "0", "body": "the problem comes only when there is 2000+ entries in wp_posts table.." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-11-09T03:10:38.563", "Id": "29307", "Score": "0", "body": "I just created the site...i don't have 2000 posts. :)" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-11-09T03:28:34.333", "Id": "29308", "Score": "0", "body": "may i send you the files to create the 2000 posts?" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-11-09T03:54:24.380", "Id": "29310", "Score": "0", "body": "I have increased the max_execution_time for php script. Still the problem exists.." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-11-09T05:16:58.597", "Id": "29317", "Score": "0", "body": "unzip the file and place in wordpress root folder and access the script import-csv.php through browser." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-11-10T04:17:08.980", "Id": "29390", "Score": "0", "body": "I just ran the script four times from the command line...even starting with 2600 posts in the database (from thr first three runs), the script still runs the fourth time at about the same speed as the first time. Whatever performance problems you're having are not due to the code." } ], "meta_data": { "CommentCount": "19", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-11-08T22:16:25.117", "Id": "18368", "ParentId": "18365", "Score": "1" } } ]
{ "AcceptedAnswerId": "18368", "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-11-08T21:44:59.803", "Id": "18365", "Score": "2", "Tags": [ "php", "performance", "mysql" ], "Title": "Inserting new rows into an existing table" }
18365
<p>I am using C# and the .NET entity framework, and I'm also learning how to better use OOP concepts in my program. My code is all displayed below. I would like to ensure my logic is properly organized before I try to implement the next step in my program.</p> <p>My goal is twofold:</p> <ol> <li>Ensure my code is SOLID, OOP, reusable, etc.</li> <li>Enable my code to select via a menu, like the one that currently exists in program, which table it uses CRUD functions on. </li> </ol> <p>Because have 2 entities in my entity model, and the code currently uses only the Man entity. But I'm hoping I don't need additional copies of the CRUD functions for alternative entities. I'm hoping that someone in StackExchange knows how to implement CRUD methods that will take any entity I give it.</p> <p>I think that my code is organized in an MVC fashion, where <code>Program</code> is the controller, <code>UserInterface</code> is the view, and <code>DataAccess</code> is the Model.</p> <h2>Program class</h2> <pre><code>class Program { private enum MenuStage { MENU_EXIT, MENU_CRUD //MENU_TableSelect } static private MenuStage _MyMenuStage; static void Main(string[] args) { DoUICycle(); Console.ReadLine(); } // ================================ // MENU DISPLAY AND PROCESSING // ================================ private static void DoUICycle() { string [] sCRUDMenu = new string[] {"Exit", "Create", "Read", "Update", "Delete" }; string [] sTableMenu = new string[] {"Quit", "Men", "Locations"}; string[] sMyMenuChoices; UserInterface MyUI = new UserInterface(); int iChoice = -1; _MyMenuStage = MenuStage.MENU_CRUD; while (_MyMenuStage != MenuStage.MENU_EXIT) { if (_MyMenuStage == MenuStage.MENU_CRUD) { sMyMenuChoices = sCRUDMenu; } else //if (MyStage == MenuStage.MENU_Tables) { sMyMenuChoices = sTableMenu; } while (iChoice != 0) { iChoice = MyUI.GetMenuInput(sMyMenuChoices); MenuSwitch(iChoice); } if (iChoice == 0) { _MyMenuStage = MenuStage.MENU_EXIT; } } } static private void MenuSwitch(int selection) { if (_MyMenuStage == MenuStage.MENU_CRUD) { switch (selection) { case 1: DoCreate(); break; case 2: DoRead(); break; case 3: DoUpdate(); break; case 4: DoDelete(); break; default: break; } } /* else if (_MyStage == MenuStage.MENU_TableSelect) { // should i really use enum? or IAmAnEntity interface variable switch (selection) { // not sure what to do here, somehow select a table to be used in CRUD functions? // do i need to call more CRUD functions for each new table I add? } }*/ } // ============================ // CRUD FUNCTIONS // ============================ static private void DoCreate() { int myID; bool bIsValidID; var dbEntities = new TestDatabaseEntities(); string sNewName; UserInterface MyUI = new UserInterface(); DataAccess MyDA = new DataAccess(); do { bIsValidID = MyUI.GetValidTypeInput&lt;int&gt;("Enter ID: ", "Error: ID must be an integer", int.TryParse, out myID); } while (!bIsValidID); sNewName = MyUI.GetInput&lt;string&gt;("Enter Name:", x =&gt; x.Trim()); MyDA.CreateMan(dbEntities, new Man() {ManID = myID, Name = sNewName }); SaveChanges(dbEntities); } static private void DoRead() { var dbEntities = new TestDatabaseEntities(); UserInterface MyUI = new UserInterface(); DataAccess MyDA = new DataAccess(); var query = from person in dbEntities.Men where true select person; MyDA.ReadMan(dbEntities, query); } static private void DoUpdate() { int myID; var dbEntities = new TestDatabaseEntities(); string sNewName = ""; UserInterface MyUI = new UserInterface(); DataAccess MyDA = new DataAccess(); myID = MyUI.GetInput&lt;int&gt;("Enter ID to update: ", int.Parse); sNewName = MyUI.GetInput&lt;string&gt;("Enter new name: ", x =&gt; x.Trim()); var query = from person in dbEntities.Men where person.ManID == myID select person; MyDA.UpdateMan(dbEntities, query, new Man() { ManID = myID, Name = sNewName }); SaveChanges(dbEntities); } static private void DoDelete() { int myID; bool bValidInput; var dbEntities = new TestDatabaseEntities(); UserInterface MyUI = new UserInterface(); DataAccess MyDA = new DataAccess(); do { bValidInput = MyUI.GetValidTypeInput&lt;int&gt;("Enter ID to delete: ", "ID Invalid, please re-enter", int.TryParse, out myID); } while (!bValidInput); var Query = from person in dbEntities.Men where person.ManID == myID select person; MyDA.DeleteMan(dbEntities, Query); SaveChanges(dbEntities); } // ============================ // SAVECHANGES FUNCTION // ============================ private static void SaveChanges(TestDatabaseEntities dbEntities) { DataAccess MyDA = new DataAccess(); MyDA.TryDataBase(dbEntities, "Changes saved successfully", () =&gt; dbEntities.SaveChanges()); } } </code></pre> <h2>UserInterface Class</h2> <pre><code>public class UserInterface { /// &lt;summary&gt; /// Delegate that matches the signature of TryParse, method defined for all primitives. /// &lt;/summary&gt; /// &lt;typeparam name="T"&gt;Output type of This Delegate&lt;/typeparam&gt; /// &lt;param name="input"&gt;input for this Delegate to translate to type T&lt;/param&gt; /// &lt;param name="output"&gt;The translated variable to return via out parameter&lt;/param&gt; /// &lt;returns&gt;Whether the Parse was successful or not, and output as output&lt;/returns&gt; public delegate bool TryParse&lt;T&gt;(string input, out T output); /// &lt;summary&gt; /// Prompts user for input with given message, and converts input to type T /// &lt;/summary&gt; /// &lt;typeparam name="T"&gt;Value type to convert to, and return&lt;/typeparam&gt; /// &lt;param name="message"&gt;Message to be printed to console&lt;/param&gt; /// &lt;param name="transform"&gt;The type conversion function to use on user's input&lt;/param&gt; /// &lt;returns&gt;Type T&lt;/returns&gt; public T GetInput&lt;T&gt;(string message, Converter&lt;string, T&gt; transform) { DisplayPrompt(message); return transform(Console.ReadLine()); } /// &lt;summary&gt; /// Asks the user for valid input /// &lt;/summary&gt; /// &lt;typeparam name="T"&gt;The type of result to return as out parameter&lt;/typeparam&gt; /// &lt;param name="message"&gt;The message to prompt the user with&lt;/param&gt; /// &lt;param name="errorMessage"&gt;The message to Display to user with if input is invalid&lt;/param&gt; /// &lt;param name="TypeValidator"&gt;The TryParse function to use to test the input.&lt;/param&gt; /// &lt;returns&gt;True if input is valid as per function given to TypeValidator, Result as type T&lt;/returns&gt; public bool GetValidTypeInput&lt;T&gt;(string message, string errorMessage, TryParse&lt;T&gt; TypeValidator, out T result, int upper = -1, int lower = -1) { bool bIsValid = false; bool bTestValidRange = (upper != -1 &amp;&amp; lower != -1); DisplayPrompt(message); bIsValid = TypeValidator(Console.ReadLine(), out result); if (!bIsValid) DisplayDBMessage(errorMessage); if (bTestValidRange &amp;&amp; bIsValid) { bIsValid = isValidRange(int.Parse(result.ToString()), lower, upper); if (!bIsValid) DisplayDBMessage("Input out of valid range"); } return bIsValid; } public bool isValidRange(int item, int Lower, int Upper) { return (Lower &lt;= item &amp;&amp; item &lt;= Upper); } // ============================ // DISPLAY FUNCTIONS // ============================ public void DisplayDBMessage(string Msg) { Console.WriteLine(Msg); } public void DisplayPrompt(string Msg) { Console.Write(Msg); } public void DisplayRecord(string [] Msg) { if (Msg == null) return; foreach (string s in Msg) { Console.Write(s + " "); } Console.Write("\n"); } public void DisplayMenuItems(string[] items) { byte ChoiceIndex = 0; DisplayDivider('~'); Console.WriteLine("Select an action from menu"); foreach (string s in items) { Console.WriteLine(ChoiceIndex++ + ") " + s); } } public void DisplayDivider(char cCharacter = '|') { String sDivider = new String(cCharacter, 30); DisplayDBMessage(sDivider); } // ============================ // MENU PROMPTING FOR USER INPUT // ============================ public int GetMenuInput(string[] sChoices) { int selection; bool bValid = false; UserInterface MyUI = new UserInterface(); DisplayMenuItems(sChoices); do { bValid = (MyUI.GetValidTypeInput&lt;int&gt;("Enter&gt; ", "Error: Numbers only&gt; ", int.TryParse, out selection, lower: 0, upper: sChoices.Length - 1)); } while (!bValid); return selection; } } </code></pre> <h2>DataAccess Class</h2> <pre><code>public class DataAccess { // ============================ // CRUD FUNCTIONS for MAN TABLE // ============================ public bool CreateMan(TestDatabaseEntities dbEntities, Man M) { return TryDataBase(dbEntities, "Man created successfully", () =&gt; { dbEntities.Men.Add(new Man { ManID = M.ManID, Name = M.Name }); }); } public bool UpdateMan(TestDatabaseEntities dbEntities, IQueryable&lt;Man&gt; query, Man man) { return TryDataBase(dbEntities, "Man updated successfully", () =&gt; { foreach (Man M in query) { M.Name = man.Name; } }); } public bool DeleteMan(TestDatabaseEntities dbEntities, IQueryable myQuery) { return TryDataBase(dbEntities, "Man deleted successfully", () =&gt; { foreach (Man M in myQuery) { dbEntities.Men.Remove(M); } }); } public bool ReadMan(TestDatabaseEntities dbEntities, IQueryable myQuery) { UserInterface MyUI = new UserInterface(); bool bSuccessful; bSuccessful = TryDataBase(dbEntities, "Records read successfully", () =&gt; { MyUI.DisplayDivider(); foreach (Man m in myQuery) { MyUI.DisplayRecord(new string[] { m.ManID.ToString(), m.Name }); } MyUI.DisplayDivider(); }); return bSuccessful; } // ============================ // TRY FUNCTION // ============================ public bool TryDataBase(TestDatabaseEntities MyDBEntities, string SuccessMessage, Action MyDBAction) { UserInterface MyUI = new UserInterface(); try { MyDBAction(); MyUI.DisplayDBMessage(SuccessMessage); return true; } catch (Exception e) { MyUI.DisplayDBMessage(e.ToString()); return false; } } } </code></pre> <h2>Man Class (auto-generated)</h2> <pre><code>public partial class Man { public Man() { this.Locations = new HashSet&lt;Location&gt;(); } public int ManID { get; set; } public string Name { get; set; } public virtual ICollection&lt;Location&gt; Locations { get; set; } } </code></pre> <h2>Location Class (auto-generated)</h2> <pre><code>public partial class Location { public Location() { this.Men = new HashSet&lt;Man&gt;(); } public int PlaceID { get; set; } public string Place { get; set; } public virtual ICollection&lt;Man&gt; Men { get; set; } } </code></pre>
[]
[ { "body": "<p>A few comments on your code as follows :</p>\n\n<ol>\n<li><p>Your UI code should not contain a <code>SaveChanges</code> methods as per SRP, it should be in EF itself.</p></li>\n<li><p>Your UserInterface is actually just a utility method. Encapsulate your validation\nand prompt logic different places. Although Utility method is not considered as good but it is okay to use in this case although their responsibility should be defined properly. </p></li>\n<li><p>Your whole architecture is like <code>UI =&gt; BL =&gt;EF</code> so EF layer should not interact with UI Code. As <code>TryDataBase</code> methods is showing the errors in prompt. This is not good idea as this concerns to UI not EF or BL. Throw known exception in case of error do not handle it but <strong>log it</strong> inside BLL or EF.</p></li>\n</ol>\n\n<p>I would advise you to write test cases even before writing any line of code. By writing unit test properly you can ensure that you followed the SOLID pattern or design pattern. So do this re-factoring part using Unit Test. By EOD eventually you will start following all applicable design pattern.</p>\n\n<p>Create a layer between EF and BLL to improve the code reuse (put them in separate projects, this will help you keep the code in the correct place).</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-11-09T18:28:55.637", "Id": "29359", "Score": "1", "body": "What kind of stuff would go in this layer between the EF and BLL. Could you provide an example maybe?" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-11-09T20:46:39.350", "Id": "29370", "Score": "0", "body": "@dreza, I am also confused by that portion of paritosh's explanation." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-11-10T06:31:40.300", "Id": "29394", "Score": "0", "body": "I think I skipped the part of Data access layer which is defined above.I am really sorry.." } ], "meta_data": { "CommentCount": "3", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-11-09T10:43:05.787", "Id": "18393", "ParentId": "18366", "Score": "2" } }, { "body": "<p>Your design is very complicated. As stated you should not instantiate a userinterface class in your data calls. Also there are some fundamental problems beyond your design such as magic numbers choice =-1, routes with poor names Menuswitch, etc. I recommend you buy Code Complete by Steve McConnell and read it twice then once each year. As far as your data access goes.. I'd look around for a code template that creates repository classes and a unit of work class to wrap all entity framework calls. You can fid one that will create it all for you based on your model. Good luck.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-11-11T14:11:58.123", "Id": "29432", "Score": "0", "body": "two or three routines that simply take a string and then call console.writeline.. this is duplicate code and too much abstraction.. its better in this instance to simply call console.writeline instead of wrapping it in multiple methods" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-11-11T16:26:42.280", "Id": "29439", "Score": "0", "body": "renaming `MenuSwitch()` to `MakeDecisionFromMenuSelection()` or `DecideFromSelection()` or `DecideFromMenuChoice()` be better?" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-11-11T23:11:06.170", "Id": "29457", "Score": "0", "body": "I agree it's complicated, I\"m trying to simplify it, but without repeating any code and keeping single responsibility." } ], "meta_data": { "CommentCount": "3", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-11-11T14:04:40.830", "Id": "18460", "ParentId": "18366", "Score": "0" } } ]
{ "AcceptedAnswerId": "18393", "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-11-08T21:48:33.153", "Id": "18366", "Score": "1", "Tags": [ "c#", "entity-framework", "crud" ], "Title": "Preparing code for more versatile CRUD functions" }
18366
<p>This is what I have, But I think I can write it in a sohrter and more efficient way too, what do you suggest?</p> <pre><code> string actionString= string.Empty; if (auditAction == DSRHelper.SaveStatusEnum.Save) { actionString = Properties.Resources.SAVE_ACTION_MESSAGE; } if (auditAction == DSRHelper.SaveStatusEnum.Complete &amp;&amp; model.Dirty) { actionString = "Save'NComplete"; } else if(auditAction == DSRHelper.SaveStatusEnum.Complete) { actionString = "OnlyComplete."; } </code></pre> <p><strong>EDIT: Ok I changed it a little bit, better now?</strong></p> <pre><code> string actionString= string.Empty; if (auditAction == DSRHelper.SaveStatusEnum.Save) { actionString = Properties.Resources.SAVE_ACTION_MESSAGE; } else if (auditAction == DSRHelper.SaveStatusEnum.Complete ) { if (model.Dirty) { actionString = "Save'NComplete"; } else { actionString = "OnlyComplete"; } } </code></pre>
[ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-11-08T22:37:03.730", "Id": "29272", "Score": "1", "body": "I really don't like the nested 'if' in the 'else if'. I would go with the method solution below." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-11-08T23:09:50.437", "Id": "29280", "Score": "0", "body": "I'm not very fond of switches... how about a stack ternary operators? XD" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-11-09T01:54:11.440", "Id": "29297", "Score": "1", "body": "As @Omega suggested perhaps if not the switch then you could also look at the ternary I used for dirty part i.e. actionString = model.IsDirty ? \"Save'NComplete\" : \"OnlyComplete\" to further shorten it if you wanted" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-11-09T06:56:16.950", "Id": "29327", "Score": "0", "body": "I am not that fond of enums, they always mess the code with if's, switches. Can't you specialize your class and move this logic in each specialized class?" } ]
[ { "body": "<p>Maybe a switch? Although whether it's shorter or more efficient or even easier to read up for debate.</p>\n\n<pre><code>string actionString = GetStatusMessage(auditAction);\n\n// ...\nfunction GetStatusMessage(DSRHelper.SaveStatusEnum status) \n{\n switch(status)\n {\n case DSRHelper.SaveStatusEnum.Save:\n return Properties.Resources.SAVE_ACTION_MESSAGE;\n case DSRHelper.SaveStatusEnum.Complete:\n return model.Dirty ? \"Save'NComplete\" : \"OnlyComplete.\";\n default:\n return string.Empty;\n }\n}\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-11-08T22:36:00.097", "Id": "29271", "Score": "1", "body": "I was 80% typing this exact same answer. One thing though, you might have to pass in the model object to the GetStatusMessage method." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-11-09T01:52:16.077", "Id": "29296", "Score": "0", "body": "@JeffVanzella yeah I thought about that after I wrote it and then figured I'd wait until the OP stated that it wasn't a class level variable. Just another way to skin this cat :)" } ], "meta_data": { "CommentCount": "2", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-11-08T22:32:30.993", "Id": "18370", "ParentId": "18369", "Score": "7" } } ]
{ "AcceptedAnswerId": "18370", "CommentCount": "4", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-11-08T22:25:46.213", "Id": "18369", "Score": "3", "Tags": [ "c#" ], "Title": "Is there better way of writing these IF checks?" }
18369
<p>My <a href="https://www.github.com/silvinci/node-sanitize-arguments" rel="nofollow">argument sanitization</a> lib has a byproduct which does some typechecking and constructor investigation. I'm unsure if I'm using the fastest / most efficient approach here.</p> <p>What are your opinions? Total rubbish or does it have a right to exist? ;)</p> <pre><code>// Return the type of an object aka safe typeof function typeOf(o) { return Object.prototype.toString.call(o).match(/(\w+)\]/)[1]; } // Return the name of a function aka class name function nameOf(o) { return typeOf(o) == "Function" ? Function.prototype.toString.call(o).match(/function\s?(\w*)\(/)[1] : false; } // Return the expected arguments of a function function argumentsOf(o) { if(typeOf(o) == "Function") { var args = Function.prototype.toString.call(o).match(/\((.+)\)\s*{/); if(!!args &amp;&amp; !!args[1]) return args[1].replace(/\s+/g, "").split(","); else return []; } else return false; } </code></pre>
[ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-11-09T00:41:24.820", "Id": "29292", "Score": "2", "body": "You could return the string `\"anonymous\"` instead of `false` for a function name. Also it will throw an error for `[1]` because `.match()` can return `null`" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-11-09T06:17:14.030", "Id": "29323", "Score": "0", "body": "I prefer `false`. Are there any substantial benefits?" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-11-09T06:19:22.670", "Id": "29324", "Score": "0", "body": "Function should always match the pattern and `[1]` should therefore always match. But just to be safe, I'll check that. Thanks." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-11-09T11:42:49.473", "Id": "29344", "Score": "0", "body": "`false` is not a string, though returning an empty string is viable as well. Getting a boolean from a function named `nameOf` is kinda iffy :P" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-11-09T21:04:03.423", "Id": "29371", "Score": "0", "body": "I think we got something twisted here: `false`is returned when no function was given and `nameOf` doesn't know what to do. `\"\"` is returned when there is no function name. I think it's safer than `\"anonymous\"`, because some weird users might name their function `anonymous` and then things would blow up." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-11-09T21:05:44.263", "Id": "29372", "Score": "0", "body": "I thought about throwing a `TypeError` (which is generally safer) instead of returning `false`, but then simple loose-type control statements would have to involve `try { ... } catch { ... }`." } ]
[ { "body": "<p>Fun question,</p>\n\n<p>I believe the only reliable way of getting the name and parameters of a function is to indeed parse the <code>toString</code>. However, you can figure out whether the parameter is a function without a regex. I would propose from <a href=\"https://codereview.stackexchange.com/q/5278/14625\">here</a> : </p>\n\n<pre><code>function isType(object, type){\n return object != null &amp;&amp; type ? object.constructor.name === type.name : object === type;\n}\n\n// Return the name of a function aka class name\nfunction nameOf(o) {\n return isType( o , Function )\n ? Function.prototype.toString.call(o).match(/function\\s?(\\w*)\\(/)[1]\n : false;\n}\n</code></pre>\n\n<p>There are still a few things that bother me here, why is the parameter name <code>o</code>, which is the Spartan convention for <code>Object</code> whereas we expect a <code>f</code>unction ? Also, why name the function <code>nameOf</code>, which creates an expectation of being to name anything whereas it really only can give the name for a function, maybe it ought to be called <code>nameOfFunction</code> or <code>functionName()</code>. Finally, as per the comments, making a function with <code>name</code> return <code>false</code> is making the name lie, just return ''. Something like this then:</p>\n\n<pre><code>// Return the name of a function aka class name\nfunction functionName(f) {\n return isType( f , Function )\n ? Function.prototype.toString.call(f).match(/function\\s?(\\w*)\\(/)[1]\n : '';\n}\n</code></pre>\n\n<p>Finally, for <code>argumentsOf</code>, I sincerely dislike dropping the newline in <code>if</code> statements, removing curly braces is fine, but no newlines makes it too hard to read.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-02-04T16:32:30.390", "Id": "40856", "ParentId": "18372", "Score": "3" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "6", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-11-08T23:53:08.657", "Id": "18372", "Score": "4", "Tags": [ "javascript", "node.js" ], "Title": "Type / Constructor testing utilities" }
18372
<p>I'm working on a school project right now. It's an ordered(ascending) doubly linked list. I just wrote the Insert operation on it but I feel like the way I wrote it isn't that great.</p> <pre><code>void OrdListClass::Insert(ItemType item) { if(Find(item)) { //throw DuplicateKeyException; }//End Duplicate Key Check else { //Due to Find, currPos points to the node that we're inserting AFTER node* newNode = new node; newNode-&gt;data = item; if(currPos == nullptr) { //We're inserting at the head. newNode-&gt;prev = nullptr; newNode-&gt;next = head; head-&gt;prev = newNode; head = newNode; } else if(currPos-&gt;next == nullptr) { //We're inserting at the tail newNode-&gt;next = nullptr; newNode-&gt;prev = tail; tail-&gt;next = newNode; tail = newNode; } else { //We're inserting in the middle of the list. newNode-&gt;prev = currPos; newNode-&gt;next = currPos-&gt;next; currPos-&gt;next-&gt;prev = newNode; currPos-&gt;next = newNode; } currPos = newNode; }//End Not Duplicate Else }//End Insert </code></pre> <p>EDIT: Of note.. ItemType is just a typedef for an int.</p> <pre><code>bool OrdListClass::Find(/*IN*/ItemType searchKey) { //Skip operations if empty. if(IsEmpty()) return false; currPos = head; while(!EndOfList()) { if(currPos-&gt;data == searchKey) { return true; } else if (currPos-&gt;data &gt; searchKey) { currPos = currPos-&gt;prev; return false; } //else continue; } } </code></pre>
[ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-11-09T08:33:23.530", "Id": "29331", "Score": "0", "body": "Could you explain a bit more about the `Find` function? Is it used elsewhere in the class? Is it public?" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-11-09T14:54:43.217", "Id": "29352", "Score": "0", "body": "It is public. It'll return true if the item is found in the list, and it makes currPos point to the node that the item is in. If the item is NOT found in the list, it returns false, and currPos points to the node in front of where it should be inserted. Example in case it's not clear: List of:{[7][9]} Find(8) would return false and currPos would be pointing at the [7] node, so if find was called via Insert(8); it will make the list {[7][8][9]}. I put the source for Find in the OP." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-12-10T06:30:02.610", "Id": "31145", "Score": "0", "body": "I agree with @tenterhook's answer in that it's weird to have `Find` implictly update some `currPos` member and have `Insert` depend on this behavior. It'd be much better to have the lookup function return a node more explicitly, through a return value or out parameter." } ]
[ { "body": "<p>I think your <code>Insert</code> function is about as tight as you can make it without getting into strictly-organizational functions to tuck the list details (<code>head</code>, <code>tail</code>) and node details (<code>next</code>, <code>prev</code>) out of sight. Not a big deal for this one function and probably not for the class overall.</p>\n\n<p>If I could make one suggestion, though, it would be that you reconsider having the <code>Find</code> function serve as both a match-finding function (returning <code>true</code> or <code>false</code> accordingly) and a state-modifying function that updates member <code>currPos</code>. </p>\n\n<p>If I saw the definition of <code>Find</code> in the header, I would wonder why it was not a <code>const</code> function since the name and return value give me no reason to think it's modifying the object itself -- surely it just returns <code>true</code> if a match is found and nothing else. Also, since the list is ordered, it would seem that <code>currPos</code> must always be updated before any meaningful modification is performed: it determines where the current insert/delete occurs (not an arbitrary insert/delete like against <code>head</code> or <code>tail</code>) so <code>currPos</code> has no value to insertion/deletion before or after the call and thus no value as a member. So <code>currPos</code> as a member seems like unnecessary temporary storage at best and error-prone storage at worst.</p>\n\n<p>Assuming my assessment of <code>Find</code> and <code>currPos</code> are fair, consider removing member <code>currPos</code> and adding a function to manage the list search without storing the node or the match flag in the object, like so:</p>\n\n<pre><code>node* OrdListClass::FindNode(/*IN*/ItemType searchKey, bool&amp; matchFound) const\n{\n matchFound = false;\n\n //Skip operations if empty.\n if(IsEmpty()) return nullptr;\n\n node* currPos = head;\n\n while(currPos != nullptr)\n {\n if(currPos-&gt;data == searchKey)\n {\n matchFound = true;\n return currPos;\n }\n else if (currPos-&gt;data &gt; searchKey)\n {\n currPos = currPos-&gt;prev;\n return currPos;\n }\n }\n}\n</code></pre>\n\n<p><code>Find</code> then becomes:</p>\n\n<pre><code>bool OrdListClass::Find(/*IN*/ItemType searchKey) const\n{\n bool matchFound = false;\n //FindNode is only called to determine if there is an exact match.\n FindNode(searchKey, matchFound);\n return matchFound;\n}\n</code></pre>\n\n<p>And <code>Insert</code> becomes:</p>\n\n<pre><code>void OrdListClass::Insert(ItemType item)\n{\n bool matchFound = false;\n node* currPos = FindNode(item, matchFound);\n\n if (matchFound)\n {\n //Nothing to insert.\n return;\n }\n\n //currPos points to the node that we're inserting AFTER\n node* newNode = new node;\n newNode-&gt;data = item;\n\n if(currPos == nullptr)\n {\n //We're inserting at the head.\n newNode-&gt;prev = nullptr;\n newNode-&gt;next = head;\n head-&gt;prev = newNode;\n head = newNode;\n }\n else if(currPos-&gt;next == nullptr)\n {\n //We're inserting at the tail\n newNode-&gt;next = nullptr;\n newNode-&gt;prev = tail;\n tail-&gt;next = newNode;\n tail = newNode;\n }\n else\n {\n //We're inserting in the middle of the list.\n newNode-&gt;prev = currPos;\n newNode-&gt;next = currPos-&gt;next;\n currPos-&gt;next-&gt;prev = newNode;\n currPos-&gt;next = newNode;\n }\n}//End Insert\n</code></pre>\n\n<p>There are alternative ways to implement <code>FindNode</code> rather than passing a <code>bool</code> reference for the matching flag (e.g., returning something like a <code>NodeSearchResult</code> object that contains the flag and the node together), but the gist is that <code>FindNode</code> is a function that manages the insertion/deletion point without resorting to using a member for temporary storage.</p>\n\n<p>Whether or not you choose to go with something like this, I hope it gives you something to think about. Otherwise, like I said, <code>Insert</code> itself seems fine.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-11-10T00:47:39.540", "Id": "18431", "ParentId": "18373", "Score": "1" } }, { "body": "<p>2 questions:</p>\n\n<ol>\n<li>What is the expected logic for inserting the first node to an empty\nlist?</li>\n<li>Is <code>nullptr</code> just a typedef to <code>NULL</code>, or you used the 'dummy node'\napproach? If it is <code>NULL</code>, you cannot move your <code>currPos</code> there -\nyou should be 'in the list', and check next/prev for null-ness.</li>\n</ol>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-11-10T05:43:36.250", "Id": "29392", "Score": "0", "body": "`nullptr` is a C++11 feature: http://en.wikipedia.org/wiki/C%2B%2B11#Null_pointer_constant (though he could have aliased it to NULL I suppose... >.<)" } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-11-10T05:34:48.903", "Id": "18442", "ParentId": "18373", "Score": "0" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "3", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-11-09T00:04:57.193", "Id": "18373", "Score": "1", "Tags": [ "c++", "linked-list" ], "Title": "Ordered Doubly Linked List Insertion" }
18373
<p>Based off simple controller implementations like those seen in micro-frameworks like Slim, Silex, F3, Laravel, Tonic, Flight, Klein, etc.</p> <p>/EDIT tried to link the above sources, but as a new user I only get 2 links...</p> <p>Any potential issues? Improvements? </p> <pre><code>class Router { private static $routes = array(); private function __construct() {} private function __clone() {} public static function route($pattern, $callback) { $pattern = '/' . str_replace('/', '\/', $pattern) . '/'; self::$routes[$pattern] = $callback; } public static function execute() { $url = $_SERVER['REQUEST_URI']; $base = str_replace('\\', '/', dirname($_SERVER['SCRIPT_NAME'])); if(strpos($url, $base) === 0) { $url = substr($url, strlen($base)); } foreach (self::$routes as $pattern =&gt; $callback) { if(preg_match($pattern, $url)){ preg_match_all($pattern, $url, $matches); array_shift($matches); $params = array(); foreach($matches as $match){ if(array_key_exists(0, $match)){ $params[] = $match[0]; } } return call_user_func_array($callback, $params); } } } } </code></pre> <p>Takes a regexp and a callback, checks the URI for the first match... e.g.,</p> <pre><code>Router::route('blog/(\w+)/(\d+)', function($category, $id){ print $category . ':' . $id; }); Router::execute(); // if url was http://example.com/blog/php/312 you'd get back "php:312"... </code></pre> <p>TYIA.</p>
[]
[ { "body": "<p>I'm not seeing why you <code>preg_match_all</code>, considering you (can!) really only deal with the first match. Why not something like </p>\n\n<pre><code>if (preg_match($pattern, $url, $params)) {\n array_shift($params);\n return call_user_func_array($callback, array_values($params));\n}\n</code></pre>\n\n<p>The <code>str_replace</code> to build a regex feels rickety to me; if the pattern were, say, <code>'\\/'</code>, it'd get regexified wrong and give you a PHP warning. (PCRE is pretty consistent about saying that <em>any</em> punctuation, metacharacter or not, can be escaped without ill effects. Blindly prefixing every <code>/</code> with a <code>\\</code> breaks that.) I'm not sure how you'd fix that, but one way to sidestep the problem might be to require that <code>$pattern</code> already include the delimiters rather than the router trying to tack them on itself. Besides that, it'd also serve as a clear \"this is a PCRE-flavored regex\" indicator, so the rules are known and people are less likely to accidentally use stuff like <code>.</code> without escaping it.</p>\n\n<p>I'm thinking that <code>private function __clone() {}</code> isn't strictly necessary, and in fact hints that an instance may somehow exist. (If there's no instance possible, there's nothing to clone, and thus no need to prevent cloning.) </p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-11-09T02:54:40.513", "Id": "29303", "Score": "0", "body": "very good point, i'll implement your suggestion. Anything else you see? Any potential problem areas?" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-11-09T04:40:43.380", "Id": "29312", "Score": "0", "body": "@momo: Just updated with other things i considered." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-11-09T16:10:10.717", "Id": "29355", "Score": "0", "body": "great feedback. i'd upvote but need more rep. thanks again." } ], "meta_data": { "CommentCount": "3", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-11-09T02:44:42.737", "Id": "18377", "ParentId": "18376", "Score": "3" } } ]
{ "AcceptedAnswerId": "18377", "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-11-09T02:21:47.880", "Id": "18376", "Score": "3", "Tags": [ "php" ], "Title": "Simple PHP Router" }
18376
<p>For homework, I had to write an RPN Evaluator and write the results to a text file. I've done all that, but it feels weird, like the writing to my results text file. It also doesn't feel efficient. There are some constraints, like no <code>&lt;vector&gt;</code> or <code>&lt;string&gt;</code> libraries and no other external classes besides my stack.</p> <p>Any tips on how I can improve this?</p> <p>Here are my Pastebin files:</p> <ul> <li><a href="http://pastebin.com/Rt7gqVZW" rel="nofollow">Main.cpp</a></li> <li><a href="http://pastebin.com/gyfMaBfT" rel="nofollow">Stack.h</a></li> <li><a href="http://pastebin.com/hTekkydk" rel="nofollow">RPN expressions</a></li> <li><a href="http://pastebin.com/JSVVzDUa" rel="nofollow">Results output file</a></li> </ul> <p><strong>Main.cpp</strong></p> <pre><code>#include &lt;iostream&gt; #include &lt;iomanip&gt; #include &lt;fstream&gt; #include &lt;ctype.h&gt; using namespace std; #include "stack.h" //************************************************************************** bool writeOperate(Stack&lt;int&gt;&amp;, ofstream&amp;, char); void writePush(Stack&lt;int&gt;&amp;, ofstream&amp;, char[]); void getResult(Stack&lt;int&gt;&amp;, ofstream&amp;, bool); //************************************************************************** int main() { char token[3]; bool valid = true; Stack&lt;int&gt; stack(10); ifstream expressions; ofstream results; expressions.open("expressions.txt"); results.open("results.txt"); while(expressions &gt;&gt; token) { if(token[0] == ';') getResult(stack, results, valid); else if(isdigit(token[0])) writePush(stack, results, token); else if(ispunct(token[0])) valid = writeOperate(stack, results, token[0]); } return 0; } //************************************************************************** void writePush(Stack&lt;int&gt;&amp; stack, ofstream&amp; file, char* numStr) { int num = atoi(numStr); cout &lt;&lt; numStr &lt;&lt; " "; stack.push(num); file &lt;&lt; "(Token: " &lt;&lt; numStr &lt;&lt; left &lt;&lt; setfill(' ') &lt;&lt; setw(15) &lt;&lt; ")" ; file &lt;&lt; "Push " &lt;&lt; numStr &lt;&lt; endl; } //************************************************************************** bool writeOperate(Stack&lt;int&gt;&amp; stack, ofstream&amp; file, char op) { int num1, num2; int total = 0; bool success = false; cout &lt;&lt; op &lt;&lt; " "; stack.pop(num2); if(stack.pop(num1)) { switch (op) { case '+': total = num1 + num2; break; case '-': total = num1 - num2; break; case '*': total = num1 * num2; break; case '/': total = num1 / num2; break; case '%': total = num1 % num2; break; } stack.push(total); success = true; } file &lt;&lt; "(Token: " &lt;&lt; op &lt;&lt; left &lt;&lt; setfill(' ') &lt;&lt; setw(15) &lt;&lt; ")"; file &lt;&lt; "Pop " &lt;&lt; left &lt;&lt; setfill(' ') &lt;&lt; setw(15) &lt;&lt; num1; file &lt;&lt; "Pop " &lt;&lt; left &lt;&lt; setfill(' ') &lt;&lt; setw(15) &lt;&lt; num2; file &lt;&lt; "Push " &lt;&lt; total &lt;&lt; endl; return success; } //************************************************************************** void getResult(Stack&lt;int&gt;&amp; stack, ofstream&amp; file, bool success) { int total; int size = stack.getSize(); if(size == 1 &amp;&amp; success) { stack.pop(total); cout &lt;&lt; "= " &lt;&lt; total &lt;&lt; endl; file &lt;&lt; "\t\t\t\t"; file &lt;&lt; left &lt;&lt; setfill(' ') &lt;&lt; setw(15) &lt;&lt; "Valid: "; file &lt;&lt; "result = " &lt;&lt; total; size--; } else { cout &lt;&lt; "= Invalid" &lt;&lt; endl; file &lt;&lt; "\t\t\t\t"; file &lt;&lt; "RPN Expressions is Invalid"; } file &lt;&lt; "\n\n\n"; for(int i = 0; i &lt; size; i++) { stack.pop(total); } } </code></pre> <p><strong>Stack.h</strong></p> <pre><code>#ifndef STACK_H #define STACK_H //************************************************************************** template&lt;typename TYPE&gt; class Stack { private: TYPE* stack; int top, capacity; public: Stack(int c = 100); ~Stack(); bool push(const TYPE&amp;); bool pop(TYPE&amp;); bool peek (TYPE&amp;) const; bool isEmpty() const; bool isFull() const; int getSize() const; }; //************************************************************************** template&lt;typename TYPE&gt; Stack&lt;TYPE&gt;::Stack(int c) { capacity = c; stack = new(nothrow) TYPE[capacity]; top = -1; }; //************************************************************************** template&lt;typename TYPE&gt; Stack&lt;TYPE&gt;::~Stack() { delete[] stack; capacity = 0; top = -1; }; //************************************************************************** template&lt;typename TYPE&gt; bool Stack&lt;TYPE&gt;::push(const TYPE&amp; dataIn) { bool success = false; if(top + 1 &lt; capacity) { top++; stack[top] = dataIn; success = true; } return success; }; //************************************************************************** template&lt;typename TYPE&gt; bool Stack&lt;TYPE&gt;::pop(TYPE&amp; dataOut) { bool success = false; if(top &gt; -1) { dataOut = stack[top]; top--; success = true; } return success; }; //************************************************************************** template&lt;typename TYPE&gt; bool Stack&lt;TYPE&gt;::peek(TYPE&amp; dataOut) const { bool success = false; if(top &gt; -1) { dataOut = stack[top]; success = true; } return success; }; //************************************************************************** template&lt;typename TYPE&gt; int Stack&lt;TYPE&gt;::getSize() const { return (top + 1); }; //************************************************************************** template&lt;typename TYPE&gt; bool Stack&lt;TYPE&gt;::isEmpty() const { return (top == -1); }; //************************************************************************** template&lt;typename TYPE&gt; bool Stack&lt;TYPE&gt;::isFull() const { return (top + 1 == capacity); }; #endif </code></pre> <p><strong>Expressions.txt</strong></p> <blockquote> <pre class="lang-none prettyprint-override"><code>2 4 * 5 + ; 13 5 % 5 + ; 15 1 + 2 / 1 - ; 15 + 1 + 2 / 1 - ; 3 4 + 15 10 - * ; 3 4 + 6 15 10 - * ; 4 5 - 7 * 2 3 + + ; 2 13 + 14 6 - - 5 * 4 + ; 35 6 4 2 2 / + * - ; 3 4 + 1 2 - * 4 2 / 3 - + ; 3 14 1 2 4 2 3 + % * + - + ; 9 2 1 + / 11 * ; </code></pre> </blockquote> <p><strong>Results.txt</strong></p> <blockquote> <pre class="lang-none prettyprint-override"><code>(Token: 2) Push 2 (Token: 4) Push 4 (Token: *) Pop 2 Pop 4 Push 8 (Token: 5) Push 5 (Token: +) Pop 8 Pop 5 Push 13 Valid: result = 13 (Token: 13) Push 13 (Token: 5) Push 5 (Token: %) Pop 13 Pop 5 Push 3 (Token: 5) Push 5 (Token: +) Pop 3 Pop 5 Push 8 Valid: result = 8 (Token: 15) Push 15 (Token: 1) Push 1 (Token: +) Pop 15 Pop 1 Push 16 (Token: 2) Push 2 (Token: /) Pop 16 Pop 2 Push 8 (Token: 1) Push 1 (Token: -) Pop 8 Pop 1 Push 7 Valid: result = 7 (Token: 15) Push 15 (Token: +) Pop -858993460 Pop 15 Push 0 (Token: 1) Push 1 (Token: +) Pop -858993460 Pop 1 Push 0 (Token: 2) Push 2 (Token: /) Pop -858993460 Pop 2 Push 0 (Token: 1) Push 1 (Token: -) Pop -858993460 Pop 1 Push 0 RPN Expressions is Invalid (Token: 3) Push 3 (Token: 4) Push 4 (Token: +) Pop 3 Pop 4 Push 7 (Token: 15) Push 15 (Token: 10) Push 10 (Token: -) Pop 15 Pop 10 Push 5 (Token: *) Pop 7 Pop 5 Push 35 Valid: result = 35 (Token: 3) Push 3 (Token: 4) Push 4 (Token: +) Pop 3 Pop 4 Push 7 (Token: 6) Push 6 (Token: 15) Push 15 (Token: 10) Push 10 (Token: -) Pop 15 Pop 10 Push 5 (Token: *) Pop 6 Pop 5 Push 30 RPN Expressions is Invalid (Token: 4) Push 4 (Token: 5) Push 5 (Token: -) Pop 4 Pop 5 Push -1 (Token: 7) Push 7 (Token: *) Pop -1 Pop 7 Push -7 (Token: 2) Push 2 (Token: 3) Push 3 (Token: +) Pop 2 Pop 3 Push 5 (Token: +) Pop -7 Pop 5 Push -2 Valid: result = -2 (Token: 2) Push 2 (Token: 13) Push 13 (Token: +) Pop 2 Pop 13 Push 15 (Token: 14) Push 14 (Token: 6) Push 6 (Token: -) Pop 14 Pop 6 Push 8 (Token: -) Pop 15 Pop 8 Push 7 (Token: 5) Push 5 (Token: *) Pop 7 Pop 5 Push 35 (Token: 4) Push 4 (Token: +) Pop 35 Pop 4 Push 39 Valid: result = 39 (Token: 35) Push 35 (Token: 6) Push 6 (Token: 4) Push 4 (Token: 2) Push 2 (Token: 2) Push 2 (Token: /) Pop 2 Pop 2 Push 1 (Token: +) Pop 4 Pop 1 Push 5 (Token: *) Pop 6 Pop 5 Push 30 (Token: -) Pop 35 Pop 30 Push 5 Valid: result = 5 (Token: 3) Push 3 (Token: 4) Push 4 (Token: +) Pop 3 Pop 4 Push 7 (Token: 1) Push 1 (Token: 2) Push 2 (Token: -) Pop 1 Pop 2 Push -1 (Token: *) Pop 7 Pop -1 Push -7 (Token: 4) Push 4 (Token: 2) Push 2 (Token: /) Pop 4 Pop 2 Push 2 (Token: 3) Push 3 (Token: -) Pop 2 Pop 3 Push -1 (Token: +) Pop -7 Pop -1 Push -8 Valid: result = -8 (Token: 3) Push 3 (Token: 14) Push 14 (Token: 1) Push 1 (Token: 2) Push 2 (Token: 4) Push 4 (Token: 2) Push 2 (Token: 3) Push 3 (Token: +) Pop 2 Pop 3 Push 5 (Token: %) Pop 4 Pop 5 Push 4 (Token: *) Pop 2 Pop 4 Push 8 (Token: +) Pop 1 Pop 8 Push 9 (Token: -) Pop 14 Pop 9 Push 5 (Token: +) Pop 3 Pop 5 Push 8 Valid: result = 8 (Token: 9) Push 9 (Token: 2) Push 2 (Token: 1) Push 1 (Token: +) Pop 2 Pop 1 Push 3 (Token: /) Pop 9 Pop 3 Push 3 (Token: 11) Push 11 (Token: *) Pop 3 Pop 11 Push 33 Valid: result = 33 </code></pre> </blockquote>
[]
[ { "body": "<p>Once you've underflowed the stack, an expression is invalid. Every operation from that point til the next <code>;</code> could be considered broken. Even if the expression later \"recovers\" and contains enough extra operands to look valid at the end, at some point along the way an invalid operation was performed and you can't trust the result.</p>\n\n<p>I might suggest that you clear the stack as soon as you notice an error, and stop even doing operations (just eat tokens) til you see another <code>;</code>.</p>\n\n<p>Aside from that,</p>\n\n<ul>\n<li>In <code>Stack&lt;TYPE&gt;::Stack()</code>, you should probably let <code>new</code> throw. The object is in an unusable state if <code>new (nothrow)</code> returns null, and the first attempt to use it will trigger UB. What's worse is that you have no way of telling the caller that.</li>\n</ul>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-11-09T05:28:05.887", "Id": "29318", "Score": "0", "body": "What do you mean by \"Underflowed\"? The problem with then clearing the stack is I'd have to find a way to skip the rest of the line in the file and move on sine I'm reading it character by character." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-11-09T05:33:36.010", "Id": "29320", "Score": "0", "body": "\"Underflowed\" in this case means \"needed to pop an operand from an empty stack\"." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-06-12T00:52:45.097", "Id": "94103", "Score": "0", "body": "As for how to skip the rest of the line, you could have the operation throw an exception. Catch it in `main`, and have the exception handler eat tokens til it encounters a semicolon." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-06-28T02:11:57.687", "Id": "97341", "Score": "0", "body": "It's worse than that. You're referencing an undefined variable, which means that the compiler is free to emit code that cause anything to happen, literally anything whatsoever. This is known as the \"demons fly out your nose\" bug." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-06-28T02:20:32.250", "Id": "97342", "Score": "0", "body": "s/undefined/uninitialized/" } ], "meta_data": { "CommentCount": "5", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-11-09T05:19:33.007", "Id": "18382", "ParentId": "18378", "Score": "3" } }, { "body": "<h2>Review of plain code:</h2>\n\n<h3>Stack:</h3>\n\n<p>You have made the choice to use top to represent the current top (a valid choice). Personally I would have used top to represent the insertion point of the <strong>next</strong> item. This way it will never become negative and most of the utility functions at the end become much nicer to read. Note if the top can never be negative you can use <code>unsigned</code> variants of int, such as <code>std::size_t</code>, to represent your data.</p>\n\n<pre><code> int top,\n capacity;\n</code></pre>\n\n<p>Stop being lazy, and make each member's type explicit.<br>\nIn every workplace I have come across, they ban this. There are a couple of corner cases where it can go wrong, so they just plain disallow it.</p>\n\n<p>You should not be using no throw variants of new (in 99.999% of the time). If you really do need it (you don't) then you need to take the appropriate action to validate that new worked correctly.</p>\n\n<pre><code> stack = new(nothrow) TYPE[capacity];\n</code></pre>\n\n<p>The destructor is for tidying up resources.</p>\n\n<pre><code> capacity = 0;\n top = -1;\n</code></pre>\n\n<p>There is no point in doing meaningless work (like the above) when the members are not going to exist as soon as the destructor empties.</p>\n\n<p>Also you basically implemented your own (simplified) vector internally to your Stack class. It would have been a lot simpler if you had used <code>std::vector&lt;TYPE&gt;</code> rather than <code>TYPE*</code>. The problem is that when your class contains a RAW owned pointer, you need to do extra work to make sure that the compiler generated methods don't mess up.</p>\n\n<p>The following methods are generated for you by the compiler:</p>\n\n<ul>\n<li>Default Constructor (not in this case since you have a constructor)</li>\n<li>Copy Constructor</li>\n<li>Assignment Operator</li>\n<li>Destructor</li>\n</ul>\n\n<p>The basic rule is that if you need to define any of the last three (doing real work), then you need to define all three of them (it's known as the rule of three (rule of five in C++11)). In this case you need to define the copy constructor and assignment operator (or disable them).</p>\n\n<p>Since you don't seem to be using them you should disable them:</p>\n\n<pre><code> class Stack\n {\n private:\n Stack(Stack const&amp; copy); // Deliberately not defined.\n Stack&amp; operator=(Stack const&amp; copy); // Deliberately not defined.\n };\n</code></pre>\n\n<h3>headers</h3>\n\n<p>In C++, all the C header files are available in two versions. <code>&lt;X&gt;.h</code> and <code>c&lt;X&gt;</code>. The first version is the C version and puts all the identifiers in the global namespace. The second version is the C++ version and puts all the identifiers in the <code>std::</code> namespace (it is implementation defined if the identifiers are placed in both by the headers).</p>\n\n<p>Thus it is generally good practice to always use the C++ versions of these headers when writing C++ code.</p>\n\n<pre><code>#include &lt;ctype.h&gt;\n// Replace with\n#include &lt;cctype&gt;\n</code></pre>\n\n<p>This is only OK for small demo programs. Get out of the habit of using it (it is a very bad habit and is hard to break later).</p>\n\n<pre><code>using namespace std;\n</code></pre>\n\n<p>Using it pollutes the current namespace (in this case global) and can cause clashes with other code that will be a pain in any real program.</p>\n\n<h3>main()</h3>\n\n<p>Why not declare an open in one go:</p>\n\n<pre><code>ifstream expressions;\nofstream results;\n\n\nexpressions.open(\"expressions.txt\");\nresults.open(\"results.txt\");\n</code></pre>\n\n<p>Much easier to write and read as:</p>\n\n<pre><code>std::ifstream expressions(\"expressions.txt\");\nstd::ofstream results(\"results.txt\");\n</code></pre>\n\n<p>You had better hope that token is no longer than 2 characters long</p>\n\n<pre><code>while(expressions &gt;&gt; token)\n</code></pre>\n\n<p>Remember you declared this: <code>char token[3];</code>. The third place is going to be a <code>\\0'</code>. It is always better to use <code>std::string</code> for this type of thing; if it is not large enough, it will dynamically expand to prevent a crash.</p>\n\n<p>The following conditions are fine as long as you know that your input has already been sanitized.</p>\n\n<pre><code> if(token[0] == ';')\n getResult(stack, results, valid);\n else if(isdigit(token[0]))\n writePush(stack, results, token);\n else if(ispunct(token[0]))\n valid = writeOperate(stack, results, token[0]);\n</code></pre>\n\n<p>Any funky input is going to cause your program to go haywire. I would assume that your input is not sanitized and take the appropriate steps to validate that the input is exactly what you expect.</p>\n\n<pre><code>std::string token;\nwhile(expressions &gt;&gt; token)\n{\n // Note the use of \"\"; this does an exact string comparison to make sure\n // that we are not swallowing any other characters.\n if(token == \";\")\n getResult(stack, results, valid);\n\n // Make sure that puctuation tokens are exactly 1 character long.\n else if (ispunct(token[0]) &amp;&amp; token.size() == 1)\n valid = writeOperate(stack, results, token[0]);\n\n // Otherwise assume is a number\n // Let the function writePush() validate it varactiy and throw an exception\n // if there is something wrong.\n else\n writePush(stack, results, token);\n}\n\nreturn 0;\n</code></pre>\n\n<p>}</p>\n\n<h3>writePush(Stack&amp; stack, ofstream&amp; file, char* numStr)</h3>\n\n<p>The function <code>atoi()</code> does not check what the trailing characters are. So if your input contained \"25+\", you will silently ignore the '+', which may change the meaning of your expression. Or \"1Loki\" will be parsed with a result even though it has no meaning.</p>\n\n<pre><code>int num = atoi(numStr);\n</code></pre>\n\n<p>I would use the stringstream operator:</p>\n\n<pre><code>std::stringstream numstream(numStr);\nint num;\nchar errorCheck;\nif ((numstream &gt;&gt; num) &amp;&amp; !(numstream &gt;&gt; errorCheck))\n{\n // We reached here then we have a valid number.\n\n // It means that `numstream &gt;&gt; num` succeeded and we read a valid number\n // and `numstream &gt;&gt; errorCheck` (note the !) failed, and thus there was\n // no more input to read.\n}\n</code></pre>\n\n<h3>bool writeOperate(Stack&amp; stack, ofstream&amp; file, char op)</h3>\n\n<p>Since all your operators currently require two numbers, you should make sure that when popping them you get both:</p>\n\n<pre><code>stack.pop(num2);\n\nif(stack.pop(num1))\n</code></pre>\n\n<p>Should be:</p>\n\n<pre><code>if(stack.pop(num2) &amp;&amp; stack.pop(num1))\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-06-28T02:10:54.463", "Id": "97340", "Score": "0", "body": "You suggest using `string` multiple times but the problem doesn't allow it. What kind of a sadist makes an assignment where the programmer can't use `string`? There's a chance it'll mess up the programmer for years to come." } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-11-09T15:49:49.820", "Id": "18404", "ParentId": "18378", "Score": "4" } } ]
{ "AcceptedAnswerId": "18404", "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-11-09T02:58:56.100", "Id": "18378", "Score": "2", "Tags": [ "c++", "homework", "stack", "math-expression-eval" ], "Title": "RPN Evaluator that writes the results to a text file" }
18378
<p>I have 2 methods that do almost the same things except a few lines of code. The sample is like below.</p> <pre><code>public void Method1() { DoX(); if (value) { var input = GetA(); DoA1(); DoA2(input); } DoY(); } public void Method2() { DoX(); if (value) { var input = GetB(); DoB(input); } DoY(); } </code></pre> <p>I have two questions for this code.<br> 1. Is it a good idea to remove code duplication is this case?<br> 2. How to remove the duplication without make it harder to read the code</p>
[ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-11-09T04:21:11.463", "Id": "29311", "Score": "2", "body": "ermmm, Perhaps you could post the actual code and see if someone could offer comment. Or perhaps this is better suited for SE??" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-11-09T07:15:21.210", "Id": "29328", "Score": "0", "body": "I was suggested to ask this question on codereview.se (this site.) I cannot post the actual code here due to a policy. :(" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-11-09T07:52:12.037", "Id": "29329", "Score": "0", "body": "No problem. I thought SE might have been more appropiate, but I always get confused myself half the time. Hopefully you get enough answers to be helpful enough for you" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-11-09T14:12:37.747", "Id": "29351", "Score": "1", "body": "I try to apply the [Rule of 3] (http://en.wikipedia.org/wiki/Rule_of_three_%28computer_programming%29) when coding. `It's okay to copy once, if you copy twice it is time to refactor.`" } ]
[ { "body": "<p>Yes your code needs few re-factoring.Always remember encapsulate logic in one place if it varies.</p>\n\n<p>try this way and include a new param bool and when you need to include it pass true else false </p>\n\n<pre><code>public void Method1(bool IncludeDoA1)\n {\n DoX();\n\n if (value)\n {\n var input = GetA();\n if (IncludeDoA1) DoA1();\n DoA2(input);\n }\n\n DoY();\n }\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-11-09T05:32:41.743", "Id": "29319", "Score": "0", "body": "What if I have 5 duplicate methods?" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-11-09T06:15:09.590", "Id": "29321", "Score": "2", "body": "oohhh, don't know if I'm a fan of the boolean flag. Check this out for more info of discussion around it http://martinfowler.com/bliki/FlagArgument.html" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-11-09T06:16:02.320", "Id": "29322", "Score": "0", "body": "@Anonymous do you have 5 duplicate methods?" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-11-09T06:22:02.900", "Id": "29325", "Score": "0", "body": "@Anonymous why you want to write the 5 duplicate method , take my advise write few unit test cases for you code first and try to refactor it" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-11-09T06:42:13.810", "Id": "29326", "Score": "0", "body": "@dreza There are 2 methods in the real code. I threw my comment because I don't think passing boolean flag is a good idea. Thanks for theh link to Fowler's website!" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-11-09T21:35:36.597", "Id": "29373", "Score": "0", "body": "@Anonymous: If you have 5 duplicate methods, replace the bool parameter with an Action :)" } ], "meta_data": { "CommentCount": "6", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-11-09T04:31:26.830", "Id": "18380", "ParentId": "18379", "Score": "0" } }, { "body": "<p>One thing you could do is to create a common function that contains the DoX(), if(value), and DoY() logic, and takes a delegate as a parameter. That way you have the common logic encapsulated in one place but can still specify the piece specific to each method. For example:</p>\n\n<pre><code> //making value a property so it's defined somewhere :)\n public bool Value { get; set; }\n\n //defining all of the methods called above\n public string GetA() { return \"\"; }\n public string GetB() { return \"\"; }\n public void DoA1() { }\n public void DoA2(string input) { }\n public void DoB(string input) { }\n public void DoX() { }\n public void DoY() { }\n\n //this delegate will hold the part of the original Method1/Method2 that is inside the if statement\n public delegate void DoDelegate();\n\n //this is the part inside the if statement of the original Method1\n public void Method1Specific() {\n var input = GetA();\n DoA1();\n DoA2(input);\n }\n\n //this is the part inside the if statement of the original Method2\n public void Method2Specific() {\n var input = GetB();\n DoB(input);\n }\n\n //this is the common part of both methods\n //it takes a parameter indicating what to run for the specific part inside the if statement\n public void Method(DoDelegate Do) {\n DoX();\n\n if (Value) {\n Do();\n }\n\n DoY();\n }\n\n //this would replace the existing Method1\n public void Method1() {\n Value = true;\n Method(Method1Specific);\n }\n\n //this would replace the existing Method2\n public void Method2() {\n Value = false;\n Method(Method2Specific);\n }\n</code></pre>\n\n<p>I commented this code to show what is actually happening here.</p>\n\n<p>In this code, you will still call Method1 and Method2, just like before, but each of those methods just calls the Method method passing in the method appropriate for each. To extend this for more methods, just create (for example) a Method3Specific method that would do the logic specific to the new method, and then create a Method3 that passes in Method3Specific as the delegate. As you can see, once this structure is set up, it is easy to extend it to any number of methods.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-11-09T04:48:26.213", "Id": "18381", "ParentId": "18379", "Score": "1" } }, { "body": "<p>Based on your code as that is what we are reviewing a couple of suggestions.</p>\n\n<ol>\n<li>Pass in a delegate that handles the changeable part</li>\n<li>Use <a href=\"http://en.wikipedia.org/wiki/Template_method_pattern\">Template</a> method pattern to implement the changing parts</li>\n<li>Use composition and DI to inject the different elements</li>\n</ol>\n\n<p>Example: Using delegates</p>\n\n<pre><code>private void DoMethod12(Action doMyAction)\n{\n DoX();\n doMyAction();\n DoY();\n}\n\npublic void Method1()\n{\n DoMethod12(_ =&gt;\n {\n var input = GetA();\n DoA1();\n DoA2(input);\n });\n}\n\npublic void Method2()\n{\n DoMethod12(_ =&gt;\n {\n var input = GetB();\n DoB(input);\n });\n}\n</code></pre>\n\n<p>Example 2: Template pattern</p>\n\n<pre><code>public abstract class MyDo\n{\n protected abstract DoMyAction1();\n protected abstract DoMyAction2();\n\n public void Method1()\n {\n DoMethod12(doMyAction);\n }\n\n public void Method2()\n {\n DoMethod12(doMyAction2);\n }\n\n private void DoMethod12(Action doMyAction)\n {\n DoX();\n doMyAction();\n DoY();\n }\n private void DoX()\n {\n }\n private void DoY()\n {\n }\n}\n\npublic class MyDoer : MyDo\n{\n protected override DoMyAction1()\n {\n var input = GetA();\n DoA1();\n DoA2(input);\n }\n\n protected override DoMyAction2()\n {\n var input = GetB();\n DoB(input);\n }\n}\n</code></pre>\n\n<p>Example 3: DI and composition</p>\n\n<pre><code>public interface IMyDoer\n{\n void MyMethod1();\n void MyMethod2();\n}\n\npublic class MyDoer\n{\n private MyDoer _doer;\n\n public MyDoer(IMyDoer doer)\n {\n _doer = doer;\n }\n\n public void Method1()\n {\n DoMethod12(_doer.MyMethod1);\n }\n\n public void Method2()\n {\n DoMethod12(_doer.MyMethod2);\n }\n\n private void DoMethod12(Action doMyAction)\n {\n DoX();\n doMyAction();\n DoY();\n }\n\n private void DoX()\n {\n }\n private void DoY()\n {\n }\n}\n</code></pre>\n\n<p>These written in notepad so no guareentee on exact syntax although hopefully they can give some ideas.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-11-09T13:51:24.470", "Id": "29348", "Score": "0", "body": "I really like that answer. It provides three different interesting ways to solve it using different design patterns." } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-11-09T06:33:31.160", "Id": "18383", "ParentId": "18379", "Score": "8" } }, { "body": "<p>For this specific code example, I see that there is some open-close pattern in the functions. If this is more relevant to your actual problem and is prominent in code then maybe you could look into AOP framework to help you define pointcut.</p>\n\n<p>You could also try Func&lt;>, Action&lt;>, delegate to be passed as parameters and define the recipe using some dictionary, like a state machine if that is the case in the example.</p>\n\n<p>On the other hand if your methods differ in the way that they call functions at different locations then I would suggest to keep them separate and not try to make one function with if's and else's that will not help readability of the code.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-11-09T06:52:32.703", "Id": "18385", "ParentId": "18379", "Score": "0" } }, { "body": "<p>Some things that I noticed that weren't talked about in previous answers that make me lean to delegates and/ or funcs:</p>\n\n<ol>\n<li>You're always calling a Get*N* before calling your Doers. Why not delegate that as well?</li>\n<li>The example has DoA1 with no parameters and DoA2 with parameters. If you can reconcile their signatures, you have a strong case for using delegates for all of your doers. </li>\n</ol>\n\n<p>These ideas are similar to @dreza's first example, but the execution is different. Here's a small program for you to examine:</p>\n\n<pre><code>internal class Program\n{\n private delegate void Doer(string input); \n private static void Main()\n {\n MethodRigger();\n }\n\n private static void MethodRigger()\n {\n Doer doers = DoA1 + DoA2;\n Func&lt;string&gt; getInput = GetA;\n bool value = true ; \n if (!value)\n {\n getInput = GetB;\n doers = DoB;\n }\n work(getInput, doers); \n }\n\n private static void work(Func&lt;string&gt; getInput, Doer doers)\n {\n DoX();\n var input = getInput();\n doers(input);\n DoY();\n }\n\n public static void DoX(){}\n public static void DoY(){}\n\n public static string GetA(){ return string.Empty;}\n public static string GetB() {return string.Empty;}\n\n private static Doer DoA1 = (input) =&gt; { };\n private static Doer DoA2 = (input) =&gt; { };\n private static Doer DoB = (input) =&gt; { };\n}\n</code></pre>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-11-09T16:46:38.753", "Id": "18410", "ParentId": "18379", "Score": "1" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "4", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-11-09T04:01:55.103", "Id": "18379", "Score": "3", "Tags": [ "c#" ], "Title": "How to remove code duplication that difference only a few lines?" }
18379
<p>I'm brand new at OOP PHP and I would like to get as many of the coding conventions right as fast as possible. I made this tiny guestbook script, and I would like to know if there's anything not done as it should.</p> <p><strong>Index.php:</strong></p> <pre><code>&lt;?php $username = "root"; $password = ""; $database = "oop"; $host = "localhost"; mysql_connect($host, $username, $password); mysql_select_db($database); ?&gt; &lt;html&gt; &lt;head&gt; &lt;/head&gt; &lt;body&gt; &lt;?php include("views/gaestebog.php"); ?&gt; &lt;/body&gt; &lt;/html&gt; </code></pre> <p><strong>Guestbook.php, the class:</strong></p> <pre><code>&lt;?php class Gaestebog { public function __contruct() { } public function getPosts() { $query = mysql_query("SELECT * FROM gaestebog"); while ($row = mysql_fetch_array($query)) { echo ' &lt;tr&gt; &lt;td&gt;'.$row['navn'].'&lt;/td&gt; &lt;/tr&gt; &lt;tr&gt; &lt;td&gt;'.$row['besked'].'&lt;/td&gt; &lt;/tr&gt; '; } } public function addPost($navn, $besked) { mysql_query("INSERT INTO gaestebog VALUES('', '$navn', '$besked')"); } } ?&gt; </code></pre> <p><strong>guestbook.php, the view:</strong></p> <pre><code>&lt;?php include("classes/Gaestebog.php"); $gaestebog = new Gaestebog(); if (isset($_POST['opret'])) { $navn = $_POST['navn']; $besked = $_POST['besked']; $gaestebog-&gt;addPost($navn, $besked); } ?&gt; &lt;table&gt; &lt;?php $gaestebog-&gt;getPosts(); ?&gt; &lt;/table&gt; &lt;hr /&gt; &lt;form action="" method="post"&gt; &lt;table&gt; &lt;tr&gt; &lt;td&gt;Navn:&lt;/td&gt; &lt;td&gt;&lt;input type="text" name="navn" value="Patrick" /&gt;&lt;/td&gt; &lt;/tr&gt; &lt;tr&gt; &lt;td&gt;Besked:&lt;/td&gt; &lt;td&gt;&lt;input type="text" name="besked" value="Hej med dig !!" /&gt;&lt;/td&gt; &lt;/tr&gt; &lt;tr&gt; &lt;td&gt;&lt;input type="submit" name="opret" value="Opret" /&gt;&lt;/td&gt; &lt;/tr&gt; &lt;/table&gt; &lt;/form&gt; </code></pre>
[ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-11-09T08:27:49.807", "Id": "29338", "Score": "0", "body": "You might want to take a look at the PHP manual online about your use of database operations for MySQL for example `mysql_query()` is no longer suggested http://php.net/manual/en/function.mysql-query.php one of the alternatives is to use the `mysqli` interface with is OOP." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-11-09T08:29:51.243", "Id": "29339", "Score": "0", "body": "instead of using `mysql` go for `mysqli` or `PDO`. Use parameterized query. make a use of database abstraction class instead of using core database functions in your classes. Thats all I can think of now" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-11-09T08:43:39.087", "Id": "29340", "Score": "0", "body": "When i use mysqli, should i be creating a new object inside every class of the mysqli connection?" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-11-09T09:28:32.447", "Id": "29341", "Score": "0", "body": "@PatrickReck: No, you create one instance, and pass it around you objects/methods." } ]
[ { "body": "<p>This is not at all OOP. guestbook.php has a class and contains few methods but that doesn't mean that you are applying OO concepts. I am afraid that your example has little scope to apply OO. Few improvements you can do here, separate presentation logic from getPosts(). </p>\n\n<p>Thus getPosts() will be responsible for retrieving posts from db and then create separate methods how you want to present the data, for example getPostInTabularFormat(), getPostInDivformat() etc...</p>\n\n<p>Also you can convert the Form in the view to a class. take a look at <a href=\"https://codereview.stackexchange.com/questions/18241/oop-php-form-ok\">this post</a></p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-11-09T18:09:45.643", "Id": "29358", "Score": "0", "body": "+1 but note that it's not necessarily a bad thing that this code isn't OOP..." } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-11-09T09:20:57.813", "Id": "18388", "ParentId": "18386", "Score": "3" } }, { "body": "<p>This is often called procedural programming with outdated libraries:</p>\n\n<pre><code>mysql_connect($host, $username, $password);\nmysql_select_db($database);\n</code></pre>\n\n<p>And that was only the beginning of your script. Maybe it's better you don't focus so much on fancy programming terms but instead just get the work done.</p>\n\n<p>Example <em><code>guestbook.php</code></em>:</p>\n\n<pre><code>&lt;?php\nrequire('bootstrap.php');\n\n$page = new Htmlpage('My Guestbook');\n$page-&gt;start($_SERVER['REQUEST_URI']);\n\n$gaestebog = new Gaestebog();\n\necho '&lt;table border=\"1\"&gt;';\n\nforeach ($gaestebog-&gt;getPosts() as $post)\n{\n $row = new Htmlencoded($post);\n\n echo &lt;&lt;&lt;OUT\n &lt;tr&gt;\n &lt;td&gt;$row['navn']&lt;/td&gt;\n &lt;/tr&gt;\n &lt;tr&gt;\n &lt;td&gt;$row['besked']&lt;/td&gt;\n &lt;/tr&gt;\nOUT;\n}\necho '&lt;/table&gt;';\n\n$page-&gt;closeRequest();\n?&gt;\n</code></pre>\n\n<p>Otherwise if you want to learn about object oriented programming, use object interfaces and practice, practice, practice.</p>\n\n<p>Start with something simple, like a <em>form field</em>. Not with a whole script.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-11-09T08:28:28.870", "Id": "18395", "ParentId": "18386", "Score": "6" } }, { "body": "<p>Yes, the first, and most obvious thing to note is your vulnerability to <strong>SQL injection</strong>.</p>\n\n<blockquote>\n <p><a href=\"http://bit.ly/phpmsql\"><strong>Please, don't use <code>mysql_*</code> functions in new\n code</strong></a>. They are no longer maintained and the\n <a href=\"http://j.mp/Rj2iVR\">deprecation process</a> has begun on it. See the\n <a href=\"http://j.mp/Te9zIL\"><strong>red box</strong></a>? Learn about <a href=\"http://j.mp/T9hLWi\"><em>prepared\n statements</em></a> instead, and use\n <a href=\"http://php.net/pdo\">PDO</a> or <a href=\"http://php.net/mysqli\">MySQLi</a> - <a href=\"http://j.mp/QEx8IB\">this\n article</a> will help you decide which. If you choose\n PDO, <a href=\"http://j.mp/PoWehJ\">here is a good tutorial</a>.</p>\n</blockquote>\n\n<p>Also, it's considered good practice to separate logic from presentation (i.e. PHP from HTML).</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-11-09T08:46:31.797", "Id": "29342", "Score": "0", "body": "How would i separate it even more than i've done here?" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-11-09T09:27:48.003", "Id": "29343", "Score": "0", "body": "@PatrickReck: Well, you need very little PHP code on your **view** or **template** (that's what it's called). Form processing, heavy business logic, database interactions, those should be on their own files, with zero HTML output on them." } ], "meta_data": { "CommentCount": "2", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-11-09T08:28:35.923", "Id": "18396", "ParentId": "18386", "Score": "7" } }, { "body": "<p>Couple of points:</p>\n\n<ul>\n<li>Don't use the deprecated mysql library, try PDO or MySQLi instead</li>\n<li><code>__contruct()</code> has a typo, should be <code>__construct()</code>.</li>\n<li>Don't return raw HTML from get methods such as <code>getPosts()</code>, instead return an array of posts and let the view create HTML if that's the output you want</li>\n<li>Protect against, SQL Injection, your <code>INSERT</code> query is vulnerable</li>\n</ul>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-11-09T08:31:31.800", "Id": "18397", "ParentId": "18386", "Score": "6" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "4", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-11-09T08:27:10.357", "Id": "18386", "Score": "3", "Tags": [ "php", "object-oriented" ], "Title": "Guestbook script" }
18386
<p>This is a simple demonstration of a singly linked list, from my class work:</p> <pre><code>#include &lt;stdio.h&gt; #include &lt;stdlib.h&gt; #include &lt;wctype.h&gt; #include &lt;errno.h&gt; #include &lt;assert.h&gt; #include &lt;ctype.h&gt; #include &lt;stddef.h&gt; #include &lt;wchar.h&gt; #include &lt;locale.h&gt; #include &lt;setjmp.h&gt; struct node { int info; struct node *link; }; typedef struct node* NODE; NODE main() { NODE first = NULL; int item, choice; for(;;) { printf("1.INSERT AT FRONT\n2.DISPLAY\n3.QUIT\n\nPLEASE ENTER YOUR CHOICE:"); scanf("%d",&amp;choice); switch (choice) { case 1: printf("\nEnter the item to be inserted:"); scanf("%d", &amp;item); first = insert_front(item,first); break; case 2: display(first); break; case 3: exit(0); } } } NODE getnode() { NODE x; x = (NODE) malloc(sizeof(struct node)); if(x == NULL) { printf("Out of memory"); exit(0); } return x; } int insert_front(int item, NODE first) { NODE temp; temp = getnode(); temp-&gt;info = item; temp-&gt;link = first; return temp; } void display(NODE first) { NODE temp; if(first == NULL) { printf("Empty"); return; } printf("\nThe contents are: "); temp = first; while(temp != NULL) { printf("%d ", temp-&gt;info); temp = temp-&gt;link; } printf("\n"); } </code></pre> <p>As you can see, this code demonstrates the working of a linked list. How can this program more smaller, better, more professional and much more good? If you were given a chance to modify this program, how would you do it? I wanna know how to think and how to train myself to modify programs like these. And as you see, I have learned most of C. I referred to and learned C from K.N Kings <em>The C programming language: A modern approach</em> and <em>Computer science: A structured approach using C</em> and data structures from <em>Data structures using C</em> by Tenenbaum.</p> <p>Now I have stretched my legs in learning C what can I do to create application that might be useful to me or to others. Say I want to create a small game like "snake" or create a small application that my father might use to do his business.</p>
[]
[ { "body": "<p>I'm not a C-guru at all but I believe I can give you a few advices to improve your code:</p>\n\n<ol>\n<li><p>Review your included libraries. Do you really need all those ones? Nope. <del>Chuck Testa</del> You only use <code>stdio.h</code> and <code>stdlib.h</code>.</p></li>\n<li><p><code>main()</code> should return <code>int</code> and you specify it actually returns <code>NODE</code>... but it isn't returning nothing at all! Double fail x( So... <code>int main() { return 0; }</code> FTW</p></li>\n<li><p>Naming consistency. You have written <code>getnode()</code> and <code>insert_front()</code>. You can name your members whatever you want (<code>getnode()</code>, <code>getNode()</code>, <code>get_node()</code>) but keep the patter for all of them (<code>insertfront()</code>, <code>insertFront()</code>, <code>insert_front()</code>). IMO, underscores are much C-style.</p></li>\n<li><p>Blank lines. Avoid inserting blank lines. They don't clarify the reading of your code, instead of that they expand your code unnecessarily. You can insert blank lines between your function definitions. This helps to delimit and group your functions and eases their location.</p></li>\n<li><p>What if I type <code>4</code> in your menu? The golden rule in programming is: <em>Users provide bad inputs</em>. So you always must to validate inputs. Don't matter if it seems trivial. <strong>Always</strong>.</p></li>\n<li><p>And for last and getting a bit cranky, you can get a temp node in one step within <code>insert_front()</code>:</p>\n\n<pre><code>NODE temp = get_node(); // I've changed `getnode()` name for you. You are welcome.\n</code></pre></li>\n</ol>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-11-09T10:00:00.323", "Id": "18390", "ParentId": "18387", "Score": "3" } }, { "body": "<p>Some more (append to jackflash's answer!):</p>\n\n<ol>\n<li><p>The <code>printf()</code> function has to scan the format string, and is therefore less efficient than <code>puts()</code>. In a similar way, <code>printf(\"\\n\");</code> could be <code>puts(\"\\n\");</code> but really should be <code>putchar('\\n');</code>.</p></li>\n<li><p>It's hard to use <code>scanf()</code> while also implementing proper error handling. It's impossible to use \"scanf()\" properly without checking its (\"number of successful assignments\") returned value. Failure to check the return value is always a bug.</p></li>\n<li><p>Your <code>switch(choice)</code> needs a <code>default: puts(\"Bad option!\\n\");</code>.</p></li>\n<li><p>The <code>typedef struct node* NODE;</code> should probably be <code>typedef struct node NODE;</code> instead (with corresponding changes everywhere to suit). This makes it much easier for programmers to see when something is a pointer and when it's not. For example, consider <code>int foo(NODE *destNode, NODE srcNode);</code> where it's easy to see what is happening; and compare it to <code>int foo(NODE destNode, Um?? );</code> where the first parameter looks like \"pass by value\".</p></li>\n<li><p><code>getnode()</code> doesn't get/find a node, but creates a node instead. It should be named appropriately (e.g. <code>create_node()</code>).</p></li>\n<li><p><code>getnode()</code> could/should initialise the structure. E.g. <code>NODE *create_node(int info) { ...; x-&gt;link = NULL; x-&gt;info = info; return x; }</code>.</p></li>\n<li><p><code>int insert_front()</code> is buggy, because it returns a <code>pointer to struct node</code> and doesn't return an <code>int</code>. Your compiler should have complained loudly about this bug.</p></li>\n<li><p><code>insert_front()</code> could/should insert a previously created node, instead of mixing different operations (\"create\" and \"insert\"). Basically it'd be <code>NODE *insert_front(NODE *newNode, NODE *firstNode)</code> or perhaps <code>void insert_front(NODE **firstNode, NODE *newNode)</code>.</p></li>\n</ol>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-11-09T10:43:32.140", "Id": "29334", "Score": "0", "body": "Very good point!" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-11-09T13:22:20.197", "Id": "29346", "Score": "0", "body": "`puts` outputs its own `\\n`, IIRC. So, `puts(\"\");`?" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-11-10T05:33:57.033", "Id": "29391", "Score": "0", "body": "`putchar('\\n')` if you only want to output one character (to avoid the extra overhead of a pointless loop that searches for a string terminator). `fputs(\"string\", stdout);` if you want to output a string without the newline. `puts(\"string\");` if you want to output a string with a newline. `printf()` if you can't use any other option." } ], "meta_data": { "CommentCount": "3", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-11-09T10:32:50.920", "Id": "18392", "ParentId": "18387", "Score": "3" } }, { "body": "<p>Siddarth, here are some extra points to add to those from @JackFlash and @Brendan.</p>\n\n<ul>\n<li><p>Turn on more compiler warnings, for example with gcc I use the following:\n -Wall<br>\n-Wextra<br>\n-Wshadow<br>\n-Wstrict-prototypes \n-Wmissing-prototypes<br>\n-Wundef<br>\n-Wunreachable-code<br>\n-Wunused<br>\n-Wcast-qual</p></li>\n<li><p>With compiler warnings enabled you will get some warnings from your code because of missing prototypes.\nYou have no prototypes for functions. There are two options: either define\nall functions before (above) where they are used; or declare prototypes for\nfunctions that are used before they are defined. I usually take the former\napproach which means that <code>main()</code> is always defined at the end of the file.</p></li>\n<li><p>All functions, except <code>main()</code> that are used only within the file where they\nare defined should be defined as 'static': <code>static void display(NODE first)</code></p></li>\n<li><p>In a linked list, the pointer to the next node is perhaps more logically called <code>next</code></p></li>\n<li><p><code>main()</code> has the prototype <code>int main(int argc, char ** argv)</code>.</p></li>\n<li><p>Functions that take no parameters should have a 'void' parameter list, eg\n<code>static NODE get_node(void) {...}</code></p></li>\n<li><p>As stated by others, don't define pointer types.</p></li>\n<li><p>Upper case identifiers are normally reserved for preprocessor constants\n(defined with <code>#define</code>). For your node type, use <code>node</code> or perhaps <code>Node</code>,\nbut not <code>NODE</code>.</p></li>\n<li><p><code>getnode</code> (better get_node), being so small, is sensible as a separate function only if it is\nto be used more than once. In your code it is not, but I guess it might be\nif you added an <code>insert_end</code> to your existing <code>insert_front</code>. Otherwise I\nwould rename <code>insert_front</code> to <code>insert</code> and integrate the <code>malloc</code> there.</p></li>\n<li><p>the value returned from <code>malloc</code> should not be cast.</p></li>\n<li><p>'x' is a poor choice of name for a 'node'. 'n' would make more sense -\nwhatever you choose, be consistent. In <code>display</code> you use <code>temp</code>.</p></li>\n<li><p>combine the memory allocation and the declatation of the variable to hold the\npointer: <code>node *n = malloc(sizeof(node));</code></p></li>\n<li><p>Put a space after keywords (<code>if</code>, <code>else</code>, <code>while</code>, <code>for</code> etc) (my personal preference)</p></li>\n<li><p>Print errors to <code>stderr</code> not <code>stdout</code>. Use <code>perror</code> where you can (as in\nfailure of <code>malloc</code>): <code>perror(\"malloc\");</code></p></li>\n<li><p><code>exit</code> should use <code>EXIT_FAILURE</code> or <code>EXIT_SUCCESS</code>: <code>exit(EXIT_FAILURE);</code></p></li>\n<li><p><code>insert_front</code> should return a <code>node *</code> (or '<code>Node *</code>)</p></li>\n<li><p>in <code>display</code> your <code>while</code> loop could perhaps be done as a <code>for</code></p>\n\n<pre><code>for (node *n = first; n != 0; n = n-&gt;link) \n{\n printf(\"%d \", n-&gt;info);\n}\n</code></pre></li>\n</ul>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-11-09T14:18:00.730", "Id": "18402", "ParentId": "18387", "Score": "2" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-11-09T09:10:26.487", "Id": "18387", "Score": "2", "Tags": [ "c", "linked-list" ], "Title": "Demonstration of a singly linked list" }
18387
<p>It was written in Emacs Lisp and requires Common Lisp loop facility.</p> <p>Can this code be improved? Did I hit any anti-patterns along the way?</p> <pre><code>(defun combos (list) (let* ((a (car list)) (d (cdr list)) (s (and d (combos d))) (v (loop for c in s collect (cons a c)))) (cons (list a) (append s v)))) </code></pre>
[]
[ { "body": "<p>I would suggest handling a nil input explicitly. Then you can:</p>\n\n<ul>\n<li>strip out the <code>and</code> (in <code>s</code>'s binding), and just recurse directly</li>\n<li>strip out the <code>cons</code> at the bottom, leaving only the <code>append</code></li>\n</ul>\n\n<p>Here's the code I tested with (in Scheme, since I have neither Emacs nor a CL implementation installed):</p>\n\n<pre><code>;; Requires SRFI 26\n(define (combos lst)\n (if (null? lst) '(())\n (let* ((a (car lst))\n (d (cdr lst))\n (s (combos d))\n (v (map (cut cons a &lt;&gt;) s)))\n (append s v))))\n</code></pre>\n\n<p>And if you <em>really</em> can't bear to see the empty list as one of the combinations (though it really is), just take the <code>cdr</code> of the resulting list. It's always the first element.</p>\n\n<hr>\n\n<p><strong>Update:</strong> I installed Emacs now, so I was able to port my Scheme version to elisp and test it:</p>\n\n<pre><code>(defun combos (list)\n (if (null list) '(nil)\n (let* ((a (car list))\n (d (cdr list))\n (s (combos d))\n (v (mapcar (lambda (x) (cons a x)) s)))\n (append s v))))\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-11-27T22:31:02.343", "Id": "30488", "Score": "0", "body": "Elisp is a Lisp2, so there's no need to misspell `list` as `lst` just to avoid shadowing the built-in function." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-11-28T03:56:23.037", "Id": "30513", "Score": "0", "body": "@GarethRees Of course. But I'm a Schemer, and Scheme habits die hard. Like the tendency to want to do everything with a named `let` or `syntax-case` macros. ;-)" } ], "meta_data": { "CommentCount": "2", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-11-09T13:13:57.907", "Id": "18400", "ParentId": "18398", "Score": "5" } }, { "body": "<p>Two important problems:</p>\n\n<ol>\n<li><p>Your function could be better named: it returns a list of the non-empty subsets of its argument, so it should be called something like <code>non-empty-subsets</code>.</p></li>\n<li><p>There's no docstring.</p></li>\n</ol>\n\n<p>I think the most natural way to implement this function is to implement <code>subsets</code> (which is straightforward) and then drop the empty subset:</p>\n\n<pre><code>(defun subsets (list)\n \"Return a list of the subsets of LIST.\"\n (if (null list) '(nil)\n (let ((e (car list))\n (ss (subsets (cdr list))))\n (append ss (loop for s in ss collect (cons e s))))))\n\n(defun non-empty-subsets (list)\n \"Return a list of the non-empty subsets of LIST.\"\n (cdr (subsets list)))\n</code></pre>\n\n<p>But tastes differ, so you might legitimately prefer your original version.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-11-28T17:43:21.797", "Id": "30549", "Score": "0", "body": "Very succinct. I like." } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-11-28T10:04:58.043", "Id": "19102", "ParentId": "18398", "Score": "4" } } ]
{ "AcceptedAnswerId": "18400", "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-11-09T12:57:47.637", "Id": "18398", "Score": "6", "Tags": [ "combinatorics", "lisp", "elisp" ], "Title": "Combinations of list elements" }
18398
<p>I wrote a simple class implementing the <code>collections.Sequence</code> interface, that forwards calls to its items to member functions of its items.</p> <p>I'm requesting a review of the following code snippet.</p> <pre><code>import collections class ForwardSequence(collections.Sequence): def __init__(self, *args, **kw): super(ForwardSequence, self).__init__() self._sequence = tuple(*args) self._get = kw.pop('get', None) self._set = kw.pop('set', None) def __len__(self): return len(self._sequence) def __getitem__(self, item): if isinstance(item, slice): indices = item.indices(len(self)) return [self[i] for i in range(*indices)] return self._get(self._sequence[item]) def __setitem__(self, item, value): items = self._sequence[item] if not isinstance(items, collections.Sequence): items = (items,) for i in items: self._set(i, value) </code></pre> <p>E.g.</p> <pre><code>class Command(object): def query(self): # send and return query string. def write(self, value): #send write string. class Controller(object): '''A simple temperature controller.''' def __init__(self): self.temperature = ForwardSequence( (Command() for _ in range(10)), get=lambda x: x.query(), set=lambda x, v: x.write(v) ) ctrl = Controller() # calls the query method of the first 5 Commands and returns it's results print ctrl.temperature[0:5] </code></pre>
[]
[ { "body": "<pre><code>import collections\n\nclass ForwardSequence(collections.Sequence):\n def __init__(self, *args, **kw):\n super(ForwardSequence, self).__init__()\n self._sequence = tuple(*args)\n</code></pre>\n\n<p>A tuple only takes on argument, why are you passing a variable number of arguments?</p>\n\n<pre><code> self._get = kw.pop('get', None)\n self._set = kw.pop('set', None)\n</code></pre>\n\n<p>Why don't you use keyword arguments instead of <code>**kw</code>? As it stands you are asking for trouble by ignoring any arguments that aren't there. Also, do you really want to allow the user to avoid specifying <code>get</code> and <code>set</code>. It seems to me those will always need to be defined.</p>\n\n<pre><code> def __len__(self):\n return len(self._sequence)\n\n def __getitem__(self, item):\n if isinstance(item, slice):\n indices = item.indices(len(self))\n return [self[i] for i in range(*indices)]\n</code></pre>\n\n<p>I'd suggest </p>\n\n<pre><code>return map(self._get, self_sequence[item])\n</code></pre>\n\n<p>That should offload some of the work onto the underlying sequence. </p>\n\n<pre><code> return self._get(self._sequence[item])\n\n def __setitem__(self, item, value):\n items = self._sequence[item]\n if not isinstance(items, collections.Sequence):\n items = (items,)\n</code></pre>\n\n<p>I suggest checking <code>isinstance(item, slice)</code> instead of this. As it stands, it has confusing behaviour of sequence contains sequences. I'd also just call <code>self._set(item, value)</code>, as you aren't saving anything by storing the item in a one-length tuple</p>\n\n<pre><code> for i in items:\n self._set(i, value)\n</code></pre>\n\n<p>I'm not sure I like the class's interface. It seems to be doing something more complex while masquerading as a list. This seems problematic to me. But I'd have to see more about how you use to know for certain.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-11-09T16:35:31.787", "Id": "18408", "ParentId": "18399", "Score": "1" } } ]
{ "AcceptedAnswerId": "18408", "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-11-09T13:13:08.203", "Id": "18399", "Score": "3", "Tags": [ "python" ], "Title": "Forwarding sequence" }
18399
<p>I'm just starting to develop more in C# after being mainly a VB.NET developer and was looking for someone to critique my implementation of a NewtonSoft Json.Net serialiser.</p> <p>Can you provide some feedback on the following points:</p> <ol> <li>Is this a good way to build the class (using Unity)?</li> <li>Is it acceptable to be throwing an exception from the constructor?</li> <li>Is the Async/Await implementation correct?</li> </ol> <p><strong>Interface</strong></p> <pre><code>using System.Threading.Tasks; namespace Helper.Core.Serialisation { public interface ISerialiser { /// &lt;summary&gt; /// Serialise the passed in object with the Json.Net serialiser /// &lt;/summary&gt; /// &lt;typeparam name="T"&gt;Generic type of the serialised object&lt;/typeparam&gt; /// &lt;param name="serialseObject"&gt;The object to be serialised&lt;/param&gt; /// &lt;returns&gt;A serialised Json string&lt;/returns&gt; Task&lt;string&gt; SerialiseAsync&lt;T&gt;(T serialseObject); /// &lt;summary&gt; /// Serialise the passed in object with the Json.Net serialiser and compress the string using the IStreamCompression implementation /// &lt;/summary&gt; /// &lt;typeparam name="T"&gt;Generic type of the serialised object&lt;/typeparam&gt; /// &lt;param name="serialseObject"&gt;The object to be serialised&lt;/param&gt; /// &lt;returns&gt;A compressed byte array of the serialised object&lt;/returns&gt; Task&lt;byte[]&gt; SerailseAndCompressAsync&lt;T&gt;(T serialseObject); /// &lt;summary&gt; /// Deserialise the Json string into the generic object /// &lt;/summary&gt; /// &lt;typeparam name="T"&gt;Generic type of the serialised object&lt;/typeparam&gt; /// &lt;param name="serialseObject"&gt;The object to be serialised&lt;/param&gt; /// &lt;returns&gt;A deserialsied object of type T&lt;/returns&gt; Task&lt;T&gt; DeserialiseAsync&lt;T&gt;(string serialsedString); /// &lt;summary&gt; /// Uncompress and deserialise the Json string into the generic object /// &lt;/summary&gt; /// &lt;typeparam name="T"&gt;Generic type of the serialised object&lt;/typeparam&gt; /// &lt;param name="serialed"&gt;The object to be serialised&lt;/param&gt; /// &lt;returns&gt;An uncompressed &amp; deserialsied object of type T&lt;/returns&gt; Task&lt;T&gt; DeserialseAndUnCompressAsync&lt;T&gt;(byte[] serialed); } } </code></pre> <p><strong>Implementation</strong></p> <pre><code>using System; using System.Threading.Tasks; using Helper.Core.Compression; using Helper.Core.Logging; using Microsoft.Practices.Unity; using Newtonsoft.Json; namespace Helper.Core.Serialisation { /// &lt;summary&gt; /// Json.Net implementaiton of the ISerialiser interface /// &lt;/summary&gt; internal class JsonSerialiser : ISerialiser { private readonly IStreamCompression _streamCompressor; private readonly ILogger _logger; /// &lt;summary&gt; /// Creates a new instance of the Json.Net Serialiser implementaton /// &lt;/summary&gt; /// &lt;param name="streamCompressor"&gt;IStreamCompression implementation composed via the IOC container&lt;/param&gt; /// &lt;param name="logger"&gt;ILogger implementation composed via the IOC container&lt;/param&gt; [InjectionConstructor] public JsonSerialiser(IStreamCompression streamCompressor, ILogger logger) { if (streamCompressor == null) throw new ArgumentNullException("streamCompressor"); if (logger == null) throw new ArgumentNullException("logger"); this._streamCompressor = streamCompressor; this._logger = logger; } /// &lt;summary&gt; /// Serialise the passed in object with the Json.Net serialiser /// &lt;/summary&gt; /// &lt;typeparam name="T"&gt;Generic type of the serialised object&lt;/typeparam&gt; /// &lt;param name="serialseObject"&gt;The object to be serialised&lt;/param&gt; /// &lt;returns&gt;A serialised Json string&lt;/returns&gt; public async Task&lt;string&gt; SerialiseAsync&lt;T&gt;(T serialseObject) { if (serialseObject == null) throw new ArgumentNullException("serialseObject"); try { return await JsonConvert.SerializeObjectAsync(serialseObject); } catch (JsonSerializationException ex) { _logger.LogEntry(ex); throw new SerialisationException("Could Not Serialse The Object", ex); } } /// &lt;summary&gt; /// Serialise the passed in object with the Json.Net serialiser and compress the string using the IStreamCompression implementation /// &lt;/summary&gt; /// &lt;typeparam name="T"&gt;Generic type of the serialised object&lt;/typeparam&gt; /// &lt;param name="serialseObject"&gt;The object to be serialised&lt;/param&gt; /// &lt;returns&gt;A compressed byte array of the serialised object&lt;/returns&gt; public async Task&lt;byte[]&gt; SerailseAndCompressAsync&lt;T&gt;(T serialseObject) { if (serialseObject == null) throw new ArgumentNullException("serialseObject"); try { string serialised = await SerialiseAsync(serialseObject); return await _streamCompressor.CompressStringAsync(serialised); } catch (StreamCompressionException ex) { _logger.LogEntry(ex); throw new SerialisationException("Could Not Compress The Object", ex); } } /// &lt;summary&gt; /// Deserialise the Json string into the generic object /// &lt;/summary&gt; /// &lt;typeparam name="T"&gt;Generic type of the serialised object&lt;/typeparam&gt; /// &lt;param name="serialseObject"&gt;The object to be serialised&lt;/param&gt; /// &lt;returns&gt;A deserialsied object of type T&lt;/returns&gt; public async Task&lt;T&gt; DeserialiseAsync&lt;T&gt;(string serialsedString) { if (serialsedString == null) throw new ArgumentNullException("serialsedString"); try { return await JsonConvert.DeserializeObjectAsync&lt;T&gt;(serialsedString); } catch (JsonSerializationException ex) { _logger.LogEntry(ex); throw new SerialisationException("Could Not Deserialse The Object", ex); } } /// &lt;summary&gt; /// Uncompress and deserialise the Json string into the generic object /// &lt;/summary&gt; /// &lt;typeparam name="T"&gt;Generic type of the serialised object&lt;/typeparam&gt; /// &lt;param name="serialed"&gt;The object to be serialised&lt;/param&gt; /// &lt;returns&gt;An uncompressed &amp; deserialsied object of type T&lt;/returns&gt; public async Task&lt;T&gt; DeserialseAndUnCompressAsync&lt;T&gt;(byte[] serialed) { if (serialed == null) throw new ArgumentNullException("serialed"); try { string decompressedSerialised = await _streamCompressor.DecompressStringAsync(serialed); return await DeserialiseAsync&lt;T&gt;(decompressedSerialised); } catch (StreamCompressionException ex) { _logger.LogEntry(ex); throw new SerialisationException("Could Not Decompress The Object", ex); } } } } </code></pre>
[ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-11-10T03:39:22.470", "Id": "29388", "Score": "2", "body": "I don't see anything wrong with throwing the exception in the constructor. If the parameter is required, it's required. At least caught in the constructor you have a chance to review the call stack and find out why" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-11-12T07:07:22.267", "Id": "29469", "Score": "2", "body": "I agree with dreza , constructing an object should be avoided if some of necessary parameter are not present during constructing an object." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-11-14T07:25:00.020", "Id": "29603", "Score": "2", "body": "As all methods in interface has async postfix, maybe rename ISerializer to IAsyncSerializer and remove async postfix in methods names." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2015-05-07T13:31:21.927", "Id": "163293", "Score": "0", "body": "surely it would be better to allow a null stringcompressor/logger rather than throw an exception in a constructor. It seems simple and logical that null wont log or compress?" } ]
[ { "body": "<p>Code looks good, I like this IoC style.\n3 points to your consideration:</p>\n\n<ol>\n<li>You should <code>catch</code> an <code>AggregateException</code> over <code>await</code>.</li>\n<li>I wouldn't bother passing a <code>logger</code> to a <code>serializer</code> - that's none of his business. Let the serializer <code>throw</code> if he's not happy.</li>\n<li>Fix some typo in names and messages (\"Deserialse\" and so).</li>\n<li>I somewhat doubt the whole concept of async serialization. I take serialized data to be an object snapshot in a known 'time point'. But if it's useful for you go for it.</li>\n</ol>\n\n<p>(Oops didn't address your actual questions)</p>\n\n<ol>\n<li>Yes I think it's great.</li>\n<li>Sure. Lacking meaningful 'default object', you don't have many alternatives.</li>\n<li>This is probably the main issue here, and the hardest to answer. I have some doubts about returning a non-cancellable <code>Task</code>. I suspect if the object to be serialized has changed completely, the user may want to cancel the serialization. </li>\n</ol>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-11-13T19:16:26.753", "Id": "18556", "ParentId": "18401", "Score": "7" } }, { "body": "<p>A minor point, but what if you want to create a single threaded <code>Serializer</code> as well? </p>\n\n<p>I would rename your interface to something like <code>IAsyncSerializer</code> so that you could have a different interface <code>ISerializer</code>.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2015-05-06T22:45:27.760", "Id": "90007", "ParentId": "18401", "Score": "0" } } ]
{ "AcceptedAnswerId": "18556", "CommentCount": "4", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-11-09T13:22:21.203", "Id": "18401", "Score": "11", "Tags": [ "c#", "json", "serialization", "async-await", "json.net" ], "Title": "NewtonSoft Json.Net serialiser" }
18401
<p>I have been working on a Playfair Cipher in C++ for a final Project in a Cryptography class. I was hoping for some feedback on the project so far. I recently got a job programming before I've even graduated and I feel like I've already learned so much.</p> <p>I would just like some feedback on my code style, comments, formatting, and structure.</p> <p>The code below is the PlayfairCipher class. The code is fairly simple.</p> <pre><code>#include "PlayfairCipher.h" #include "Sanitizer.h" #include &lt;iostream&gt; #include &lt;string&gt; using namespace std; PlayfairCipher :: PlayfairCipher(void) { playfairMatrix.resize(5); for (int i = 0; i &lt; 5; ++i) { playfairMatrix[i].resize(5); } } void PlayfairCipher :: createKeyMatrix(string &amp;key) { string alphabet = "abcdefghiklmnopqrstuvwxyz"; string sanitizedKey = Sanitizer :: sanitizeInputKey(key); for(unsigned int i = 0; i &lt; sanitizedKey.size(); i++) { for(int j = 0; j &lt; alphabet.size(); j++) { if(sanitizedKey[i] == alphabet[j]) { alphabet.erase(j, 1); } } } sanitizedKey.append(alphabet); int index = 0; for(int row = 0; row &lt; 5; row++) { for(int column = 0; column &lt; 5; column++) { playfairMatrix[row][column] = sanitizedKey[index]; index++; } } } void PlayfairCipher :: print() { for(int row = 0; row &lt; 5; row++) { for(int column = 0; column &lt; 5; column++) { cout &lt;&lt; playfairMatrix[row][column] &lt;&lt; " "; } cout &lt;&lt; endl; } } Point * PlayfairCipher :: getPointOfLetter(char letter) { for(int row = 0; row &lt; 5; row++) { for(int column = 0; column &lt; 5; column++) { if(playfairMatrix[row][column] == letter) { return new Point(row, column); } } } return NULL; } char PlayfairCipher :: getLetterOfPoint(Point * a) { return playfairMatrix[a-&gt;row][a-&gt;column]; } ///////////////////////////////////////////////////////////////////////////////// /// First, a key matrix is created using the supplied key. /// /// Then the plaintext is sanitized to remove invalid characters. /// /// For each pair of characters in plainText, retrieve their coordinates from /// /// the key Matrix. The coordinates are then transformed. Finally, the newly /// /// transformed coordinates are used to retrieve the corresponding letter. /// ///////////////////////////////////////////////////////////////////////////////// string PlayfairCipher :: Encrypt(string plainText, string key) { createKeyMatrix(key); Sanitizer :: sanitizePlainText(plainText); for(unsigned int i = 0; i &lt; plainText.size() - 1; i+=2) { Point * a = getPointOfLetter(plainText[i]); Point * b = getPointOfLetter(plainText[i + 1]); encryptCoordinates(a, b); plainText[i] = getLetterOfPoint(a); plainText[i+1] = getLetterOfPoint(b); } return plainText; } ///////////////////////////////////////////////////////////////////////////////// /// First, a key matrix is created using the supplied key. /// /// Then the plaintext is sanitized to remove invalid characters. /// /// For each pair of characters in plainText, retrieve their coordinates from /// /// the key Matrix. The coordinates are then transformed. Finally, the newly /// /// transformed coordinates are used to retrieve the corresponding letter. /// ///////////////////////////////////////////////////////////////////////////////// string PlayfairCipher :: Decrypt(string cipherText, string key) { createKeyMatrix(key); for(unsigned int i = 0; i &lt; cipherText.size() - 1; i+=2) { Point * a = getPointOfLetter(cipherText[i]); Point * b = getPointOfLetter(cipherText[i + 1]); decryptCoordinates(a, b); cipherText[i] = getLetterOfPoint(a); cipherText[i+1] = getLetterOfPoint(b); } return cipherText; } void PlayfairCipher :: encryptCoordinates(Point * a, Point * b) { if(a-&gt;column == b-&gt;column) { a-&gt;row = (a-&gt;row + 1) % 5; b-&gt;row = (b-&gt;row + 1) % 5; } else if(a-&gt;row == b-&gt;row) { a-&gt;column = (a-&gt;column + 1) % 5; b-&gt;column = (b-&gt;column + 1) % 5; } else { int temp = a-&gt;column; a-&gt;column = b-&gt;column; b-&gt;column = temp; } } void PlayfairCipher :: decryptCoordinates(Point * a, Point * b) { if(a-&gt;column == b-&gt;column) { a-&gt;row = Mod(a-&gt;row - 1, 5); b-&gt;row = Mod(b-&gt;row - 1, 5); } else if(a-&gt;row == b-&gt;row) { a-&gt;column = Mod(a-&gt;column - 1, 5); b-&gt;column = Mod(b-&gt;column - 1, 5); } else { int temp = a-&gt;column; a-&gt;column = b-&gt;column; b-&gt;column = temp; } } int PlayfairCipher :: Mod(int x, int m) { int r = x % m; return r &lt; 0 ? r+m : r; } PlayfairCipher :: ~PlayfairCipher(void) { } </code></pre> <p>I have added the header file code as well:</p> <pre><code>#include &lt;string&gt; #include &lt;vector&gt; #include "Point.h" using namespace std; class PlayfairCipher { public: PlayfairCipher(void); string Encrypt(string plainText, string key); string Decrypt(string cipherText, string key); void print(); private: vector&lt;vector&lt;char&gt;&gt; playfairMatrix; void createKeyMatrix(string &amp;key); void encryptCoordinates(Point * a, Point * b); void decryptCoordinates(Point * a, Point * b); char getLetterOfPoint(Point * a); Point * getPointOfLetter(char letter); int Mod(int x, int m); virtual ~PlayfairCipher(void); }; </code></pre>
[ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-11-09T19:46:22.013", "Id": "29362", "Score": "0", "body": "Can you post the header file so we can see the interface." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-11-13T02:05:21.980", "Id": "29538", "Score": "0", "body": "So, what will happen if I encrypt the word \"jail\"? For that matter, what if I encrypt using the key \"jail\"?" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-11-13T02:35:23.407", "Id": "29539", "Score": "0", "body": "I didn't post it because I was just looking for comments on this class, but I have a another class called Sanitizer. This class has a few static methods that clean up input- whether it is the key or the plaintext. One method will translate all j's to i's. This technique is the one I've seen most often due to j's low letter frequency in the English language." } ]
[ { "body": "<p>Code looks clean and readable. 3 quick remarks:</p>\n\n<ol>\n<li>Magic numbers and string: Move'm aside. What's with that <code>5</code> ? Is that a cosmic constant, or something your boss may change tomorrow? Make it <code>#define</code> or <code>extern</code>.</li>\n<li>Defend your code. Your <code>Point*</code> creation method is allowed to return <code>NULL</code>, but you don't null-check your input.</li>\n<li>Code duplication - encrypt/decrypt coordinates are almost the same. Consider combining.</li>\n</ol>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-11-13T02:01:40.103", "Id": "29537", "Score": "2", "body": "5x5 is the size of the playfair cipher. I don't think it will change unless the number of letters in the English alphabet changes." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-11-13T02:36:24.963", "Id": "29540", "Score": "0", "body": "That is true, but I should have used a #define, it just makes it look a bit better, I think." } ], "meta_data": { "CommentCount": "2", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-11-10T10:49:16.760", "Id": "18446", "ParentId": "18407", "Score": "3" } } ]
{ "AcceptedAnswerId": "18446", "CommentCount": "3", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-11-09T16:18:58.577", "Id": "18407", "Score": "4", "Tags": [ "c++", "cryptography" ], "Title": "Playfair Cipher in C++" }
18407
<p>Below is a script I've written that uses AJAX to check if all links on the page are alive or dead. Could this be modified to be more efficient in any way? Thank you very much.</p> <pre><code>$(document).ready(function() { var liveLinks = []; var deadLinks = []; function updateLive() { $live = Number($('#liveLinkCount').text()) + 1; $('#liveLinkCount').text($live); } function updateDead() { $dead = Number($('#deadLinkCount').text()) + 1; $('#deadLinkCount').text($dead); } $('body').prepend("&lt;div id='linkChecker'&gt;&lt;span id='hideChecker'&gt;Hide&lt;/span&gt;&lt;button id='checkLinks'&gt;Check Links&lt;/button&gt;&lt;br /&gt;&lt;span&gt;Live: &lt;/span&gt;&lt;span id='liveLinkCount' style='color:green;'&gt;0&lt;/span&gt;&lt;span&gt; - Dead: &lt;/span&gt;&lt;span id='deadLinkCount' style='color:red;'&gt;0&lt;/span&gt;&lt;/div&gt;"); $('#linkChecker').css({ "width": "130px", "border": "1px solid black", "text-align": "center" }); $('#hideChecker').css({ "text-decoration": "underline", "float": "right", "padding": "1px", "cursor": "pointer" }); $('body').on('click', '#checkLinks', function() { $('#linkChecker').append("&lt;br /&gt;&lt;button id='logReport'&gt;Log Report&lt;/button&gt;"); $('a').each(function(i) { var self; self = this; $.ajax({ type: "post", url: $(self).prop('href'), success: function() { liveLinks.push($(self).prop('href')); updateLive(); $(self).css({ "color": "green" }); }, error: function() { deadLinks.push($(self).prop('href')); updateDead(); $(self).css({ "font-weight": "bold", "color": "red" }); } }); }); }); $('body').on('click', '#logReport', function() { console.log(new Array(24 + 1).join('\n')); console.log("Live Links:"); for (var i in liveLinks) { console.log(" " + liveLinks[i]); } console.log("Dead Links:"); for (var i in deadLinks) { console.log(" " + deadLinks[i]); } }); $('body').on('click', '#hideChecker', function() { $('#linkChecker').fadeOut(); }); }); </code></pre>
[ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-11-09T20:20:37.763", "Id": "29364", "Score": "0", "body": "For readability sake, you can remove the quotes around the JSON properties, i.e.: `width: \"130px\", border: \"1px solid black\"`" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-11-09T20:23:18.727", "Id": "29365", "Score": "0", "body": "Also, I don't really consider using inline styling as good practice. It makes code harder to maintain over time and can make troubleshooting CSS selector specificity more annoying." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-11-09T20:25:59.390", "Id": "29366", "Score": "1", "body": "Finally, is there any reason that variables `$live` and `$dead` have to be global?" } ]
[ { "body": "<p>First of all, jQuery's <code>error</code> callback gets invoked on network errors, parser errors, or 4xx/5xx <a href=\"http://httpstatus.es\" rel=\"nofollow\">HTTP status codes</a>.</p>\n\n<p>The status codes do not necessarily mean that a link is dead. At least there's a server at the other end. Of course, <code>404 Not found</code> or <code>410 Gone</code> are pretty unambiguous, but something like <code>403 Forbidden</code> could mean that you just aren't allowed to see a certain page - but others might be. Similarly, a <code>405 Method Not Allowed</code> would mean that your GET request was rejected, because the server expects a POST or something else (normally links mean GET of course, but the page might have some JS that turns a regular link into a POST form submission).</p>\n\n<p>Parser errors could also trip up your system. For instance a link to some malformed XML might cause an error because jQuery might try to parse it, but there is technically some content there, so the link's not exactly dead.</p>\n\n<p>In other words, don't rely on <code>error</code> to always mean \"dead link\".</p>\n\n<p>Second: Keep a list of URLs you've already checked, and avoid checking the same page twice. You can also do try making some informed guesses. E.g. if a link to \"example.com/foo\" gets a network error, there a good chance <em>all</em> links to example.com are down. It's not guaranteed of course, but worth considering.</p>\n\n<p>Third: You should ignore links that start with <code>#</code> since they are local to the page you're already on (or their behavior in defined with javascript, in which case you still don't want to check them). You'll also want to avoid those that don't have a href attribute at all, or better yet, report it as a different kind of issue (it's rare and not valid to have such links, but it happens).</p>\n\n<p>Depending on your needs, you could also have an option to skip all \"local\" links, and only check those that to other sites. E.g. I'm pretty confident that the links to other CodeReview questions on this page are all good, so I might want to limit the checking to external sites only. Or vice-versa.</p>\n\n<p>Fourth: <code>console.log(new Array(24 + 1).join('\\n'));</code><br>\nWhat? I'm pretty sure 24 + 1 will always be 25, so that's one definite optimization you can do. But what do you want with 25 blank lines anyway? Just curious.</p>\n\n<p>Fifth: This is debatable, but you may want to set <code>cache: false</code> in the ajax options. It will slow things down, but you'll also be sure you're checking \"for real\" and not just getting cached pages.</p>\n\n<p>Sixth: I'd advise you to keep the UI code and the actual checking \"engine\" more separate. Keeps the code cleaner.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-11-09T19:32:46.967", "Id": "18413", "ParentId": "18412", "Score": "2" } }, { "body": "<p>Firstly, <code>for...in</code> is <a href=\"https://stackoverflow.com/questions/500504/javascript-for-in-with-arrays\">used to enumerate over object properties, not to iterate through arrays</a>. You should use a traditional <code>for</code> loop for this.</p>\n\n<p>Secondly, you could probably refine your console logging portion a bit. It may not have any impact to application performance, but it would make your console look prettier.</p>\n\n<pre><code>$('body').on('click', '#logReport', function() {\n var i, j, k, l;\n\n console.group(\"Live Links:\");\n for (i=0, j=liveLinks.length; i&lt;j; i++) {\n console.log(liveLinks[i]);\n }\n console.groupEnd();\n console.group(\"Dead Links:\");\n for (k=0, l=deadLinks.length; k&lt;l; k++) {\n console.log(deadLinks[k]);\n }\n console.groupEnd();\n});\n</code></pre>\n\n<p>As far as I know, this works for both Google Chrome and Mozilla Firefox (FireBug). See <a href=\"https://developer.mozilla.org/en-US/docs/DOM/console#Using_groups_in_the_console\" rel=\"nofollow noreferrer\">here</a> for more information.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-11-09T20:17:43.510", "Id": "18417", "ParentId": "18412", "Score": "3" } } ]
{ "AcceptedAnswerId": "18413", "CommentCount": "3", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-11-09T18:35:51.167", "Id": "18412", "Score": "1", "Tags": [ "javascript", "jquery", "ajax" ], "Title": "Optimize JQuery/JavaScript Link Checker" }
18412
<p>Here's some code that removes the specified character, <code>ch</code>, from the string passed in. Is there a better way to do this? Specifically, one that's more efficient and/or portable?</p> <pre><code>//returns string without any 'ch' characters in it, if any. #include &lt;string&gt; using namespace std; string strip(string str, const char ch) { size_t p = 0; //position of any 'ch' while ((p = str.find(ch, p)) != string::npos) str.erase(p, 1); return str; } </code></pre>
[ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-11-10T01:21:51.500", "Id": "29381", "Score": "1", "body": "Where is iostream involved in this? Also, there's a one-liner version of it, though I'm not quite sure how the performance will compare: `str.erase(std::remove(str.begin(), str.end(), ch), str.end());`" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-11-10T01:37:54.790", "Id": "29382", "Score": "0", "body": "@Corbin: You could put that as an answer." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-11-10T13:11:14.827", "Id": "29402", "Score": "0", "body": "@Corbin, Not sure why I said iostream. Fixed." } ]
[ { "body": "<p>I'm not entirely sure how the performance will compare, but the standard way to accomplish this would be the <a href=\"http://en.wikipedia.org/wiki/Erase-remove_idiom\" rel=\"nofollow\">erase-remove idiom</a>:</p>\n\n<pre><code>str.erase(std::remove(str.begin(). str.end(), ch), str.end());\n</code></pre>\n\n<p>Unless the performance proves to be a bottleneck, it's typically better to stick with the C++ style of doing things. I can't imagine that this would be significantly less efficient than the other method. (In fact, I wouldn't be surprised if this is a bit faster for long strings with a high amount of the removed character -- though my assumption of that depends on quite a few non-guaranteed implementation choices, and a rather rough estimation of the cost of different low level operations.)</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-11-10T13:13:57.927", "Id": "29404", "Score": "0", "body": "Never heard of this idiom before now. Thanks. One question though: How is this C++ style? Because of the use of iterators rather than the loop?" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-11-10T20:54:49.197", "Id": "29417", "Score": "0", "body": "@Nick It's hard to explain. It's partly because of the iterators, but also partly because it uses the standard library instead of a custom loop. For the same reason that people avoid creating their own sorting methods, people try to use the standard library as much as possible (within reason of course). It's just more idiomatic to C++. (This was a pretty terrible explanation, but hopefully it made a little sense :).)" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-11-10T21:06:10.793", "Id": "29418", "Score": "0", "body": "Nope, I got it. Thanks. I was actually hoping there was a standard library function for this, but didn't see one. But now I see that one of the other overloads is what I needed!" } ], "meta_data": { "CommentCount": "3", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-11-10T05:56:53.033", "Id": "18444", "ParentId": "18415", "Score": "5" } }, { "body": "<p>My way (probably sloppy/inefficient ):</p>\n\n<pre><code>std::string StripCharacter( __in std::string StdString, __in const char Character )\n{\n std::string Result = \"\";\n for( unsigned int Index = 0; Index != StdString.length( ); ++ Index )\n if( StdString[ Index ] != Character )\n Result += StdString[ Index ];\n return ( Result );\n}\n</code></pre>\n\n<p>or...</p>\n\n<pre><code>std::string StripCharacter( __in std::string StdString,\n __in const char Character,\n __in unsigned int Start,\n __in unsigned int End )\n{\n if( Start &gt;= End )\n return ( StdString );\n\n std::string Result = \"\";\n\n if( Start &gt; 0 )\n Result += StdString.substr( 0, Start );\n\n for( unsigned int Index = Start; Index != End; ++ Index )\n if( StdString[ Index ] != Character )\n Result += StdString[ Index ];\n\n if( End &lt; StdString.length( ) )\n Result += StdString.substr( End, StdString.length( ) - End );\n\n return ( Result );\n}\n</code></pre>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-11-17T04:58:17.660", "Id": "18726", "ParentId": "18415", "Score": "2" } } ]
{ "AcceptedAnswerId": "18444", "CommentCount": "3", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-11-09T19:51:56.037", "Id": "18415", "Score": "3", "Tags": [ "c++" ], "Title": "Stripping specified character" }
18415
<p>I'm using linear algebra as my basis. One very specific change I'd like to make is to allow for equality tests between points and vectors with an unequal number of components by assuming that all undefined components are zero (all points and vectors have infinite components; equality tests stop testing once a check for both components return 'undefined'). Mostly I'd like to do this just because it seems kind of cool to do, so it is not remarkably important.</p> <p>But in essence, I really just want someone to rip this code apart and tell me why I'm doing everything wrong (or tell me that I'm doing things pretty alright). The goal is just to have a nice, sane <code>Point</code> and <code>Vector</code> system that is very flexible and can be understood by anyone--and used by anyone--for any purpose they'd like. Everything I'm building will rely on the following code, so I want to make sure that my design patterns are reasonable and flexible.</p> <pre><code>import math, sys, os TOLERANCE = 0.00001 class SizeError(Exception): def __init__(self, *args): self.args = args print "Size Error between " + str(args) class P(object): def __init__(self, *args): if len(args) == 1: try: self.components = tuple(args[0]) self.size = len(args[0]) except TypeError: self.components = tuple(args) self.size = len(args) else: self.components = args self.size = len(args) def __getitem__(self, key): return self.components[key] def __repr__(self): result = "" for i in range(0, self.size): result += str(self[i]) + ", " return "&lt;Point (" + str(self.size) + ") : " + result[:-2] + "&gt;" def __eq__(self, other): if self.size != other.size: raise SizeError(self, other) for i in range(0, self.size): result = self[i] - other[i] if math.fabs(result) &gt; TOLERANCE: return False return True def __add__(self, other): if other.size != self.size: raise SizeError(self, other) result = [] for i in range(0, self.size): result.append(self[i] + other[i]) return P(result) def __sub__(self, other): if other.size != self.size: raise SizeError(self, other) result = [] for i in range(0, self.size): result.append(self[i] - other[i]) return V(result) class V(P): def __repr__(self): result = "" for i in range(0, self.size): result += str(self[i]) + ", " return "&lt;Vector (" + str(self.size) + ") : " + result[:-2] + "&gt;" def __add__(self, other): if other.size != self.size: raise SizeError(self, other) result = [] for i in range(0, self.size): result.append(self[i] + other[i]) return V(result) def __mul__(self, scalar): result = [] for i in range(0, self.size): result.append(self[i] * scalar) return V(result) def __neg__(self): return self * -1 def dotProduct(self, other): result = 0 if self.size != other.size: raise SizeError(self, other) for i in range(0, self.size): result += self[i] * other[i] return result def normalize(self): result = [] length = self.getLength() if math.fabs(length) &lt; TOLERANCE: return self.getZero() for i in range(0, self.size): result.append(self[i] / length) return V(result) def getLength(self): result = 0 for i in range(0, self.size): result += self[i]**2 return math.sqrt(result) def getZero(self): return self * 0 def isZero(self): zero = self.getZero() return self == zero </code></pre>
[ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-11-09T20:29:31.037", "Id": "29367", "Score": "0", "body": "Why don't you use numpy? It's fast, reliable and extremely powerful." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-11-09T20:46:27.617", "Id": "29369", "Score": "0", "body": "To be honest, I expect that that's precisely what I'll eventually end up doing. But I want to make sure I understand good architecture before I start relying on other people's *excellent* architecture." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-11-10T07:24:11.657", "Id": "29395", "Score": "0", "body": "You got good feedback. My 2 cents - I don't see how vector 'is-a' point - the hierarchy doesn't make sense." } ]
[ { "body": "<pre><code>import math, sys, os\n\nTOLERANCE = 0.00001\n\nclass SizeError(Exception):\n def __init__(self, *args):\n self.args = args\n print \"Size Error between \" + str(args)\n</code></pre>\n\n<p>You shouldn't print in an exception constructor. At most, you should define a <code>__repr__</code> for printing purposes. But you can probably get away with not doing that and trusting the default.</p>\n\n<pre><code>class P(object):\n</code></pre>\n\n<p>The name doesn't give me much clue as to what this class is.</p>\n\n<pre><code> def __init__(self, *args):\n if len(args) == 1:\n try:\n self.components = tuple(args[0])\n self.size = len(args[0])\n except TypeError:\n self.components = tuple(args)\n self.size = len(args)\n else:\n self.components = args\n self.size = len(args)\n</code></pre>\n\n<p>Instead of assigning size three times, use <code>self.size = len(self.components)</code> at the end. In fact, consider not storing the size at all and just looking at the size of the components. I'd also suggest not accepting three different ways of passing in the parameters. Pick one and make it be used everywhere.</p>\n\n<pre><code> def __getitem__(self, key):\n return self.components[key]\n def __repr__(self):\n result = \"\"\n for i in range(0, self.size):\n result += str(self[i]) + \", \"\n</code></pre>\n\n<p>Add strings is expensive. But python has a really nice join function. So you could do:</p>\n\n<p>result = \",\".join(map(str,self))</p>\n\n<p>And it'll actually take care of everything else for you</p>\n\n<pre><code> return \"&lt;Point (\" + str(self.size) + \") : \" + result[:-2] + \"&gt;\"\n def __eq__(self, other):\n if self.size != other.size:\n raise SizeError(self, other)\n for i in range(0, self.size):\n</code></pre>\n\n<p>You don't need the zero.</p>\n\n<pre><code> result = self[i] - other[i]\n if math.fabs(result) &gt; TOLERANCE:\n</code></pre>\n\n<p>I'd combine those two lines</p>\n\n<pre><code> return False\n return True\n def __add__(self, other):\n if other.size != self.size:\n raise SizeError(self, other)\n result = []\n for i in range(0, self.size):\n result.append(self[i] + other[i])\n</code></pre>\n\n<p>Use zip, and it'll be a bit faster to use a list comprehension: </p>\n\n<p>result = [x+y for x, y in zip(self, other)]</p>\n\n<pre><code> return P(result)\n def __sub__(self, other):\n if other.size != self.size:\n raise SizeError(self, other)\n result = []\n for i in range(0, self.size):\n result.append(self[i] - other[i])\n return V(result)\n\nclass V(P):\n</code></pre>\n\n<p>I wouldn't have vector inherit from point. I'd have them both inherit from some other more generic class. A vector is not a point, coding like it is one could be confusing. </p>\n\n<pre><code> def dotProduct(self, other):\n</code></pre>\n\n<p>Python convention is to have names which are lowercase_with_underscores for methods.</p>\n\n<pre><code> result = 0\n if self.size != other.size:\n raise SizeError(self, other)\n for i in range(0, self.size):\n result += self[i] * other[i]\n return result\n</code></pre>\n\n<p>Here I'd use</p>\n\n<pre><code>return sum(x * y for x, y in zip(self, other))\n\n\n def normalize(self):\n result = []\n length = self.getLength()\n if math.fabs(length) &lt; TOLERANCE: return self.getZero()\n for i in range(0, self.size):\n result.append(self[i] / length)\n return V(result)\n def getLength(self):\n result = 0\n for i in range(0, self.size):\n result += self[i]**2\n return math.sqrt(result)\n\n def getZero(self):\n return self * 0\n def isZero(self):\n zero = self.getZero()\n return self == zero\n</code></pre>\n\n<p>Both of these will be inefficent implementations. They should work, but they'll be relatively slow. The fact being any Point/Vector class implemented in python will be unforgivably slow. That's why we typically implement such things in extensions like numpy.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-11-09T23:27:15.383", "Id": "18429", "ParentId": "18418", "Score": "2" } } ]
{ "AcceptedAnswerId": "18429", "CommentCount": "3", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-11-09T20:20:45.593", "Id": "18418", "Score": "1", "Tags": [ "python", "beginner" ], "Title": "Linear algebra architecture" }
18418
<p>I made this Rock Paper Scissors game and I would like for this to be critiqued.</p> <pre><code>import System.IO import System.Random import Control.Monad import Control.Arrow data Throw = Rock | Paper | Scissors deriving (Show, Read, Enum, Bounded) instance Random Throw where random g = first toEnum $ randomR (a, b) g where a = fromEnum (minBound :: Throw) b = fromEnum (maxBound :: Throw) randomR (a, b) g = first toEnum $ randomR (a', b') g where a' = fromEnum a b' = fromEnum b beats :: Throw -&gt; Throw -&gt; Bool Rock `beats` Scissors = True Paper `beats` Rock = True Scissors `beats` Paper = True _ `beats` _ = False play :: Throw -&gt; Throw -&gt; String play p1 p2 | p1 `beats` p2 = "You win!" | p2 `beats` p1 = "You lose." | otherwise = "Tie." main :: IO () main = do putStr "Enter your move [Rock, Paper, or Scissors]: " hFlush stdout p1 &lt;- getLine &gt;&gt;= readIO p2 &lt;- liftM (fst . random) getStdGen putStrLn $ show p1 ++ " vs. " ++ show p2 putStrLn $ play p1 p2 </code></pre>
[ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-11-10T09:06:47.403", "Id": "29397", "Score": "0", "body": "I can't see any way to improve. Well done! Hackage should have a template Haskell library to derive of `Random` instances but as far as I know it doesn't have yet." } ]
[ { "body": "<p>The style is pretty good, I can just see two minor improvements you could do: Firstly, you can define <code>random</code> in terms of your own <code>randomR</code> in order to save a few keystrokes:</p>\n\n<pre><code>instance Random Throw where\n random = randomR (minBound, maxBound)\n randomR (a, b) g = ...\n</code></pre>\n\n<p>At this point Haskell's typing even derives the type of <code>minBound</code> for you, so you can lose the explicit annotations.</p>\n\n<p>Second, you should probably use <code>randomIO</code> instead of <code>liftM (fst . random) getStdGen</code>. That is not only shorter, but also updates the generator state, which means that you won't get the same result if you call it twice in the program.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-11-10T15:44:06.600", "Id": "18449", "ParentId": "18422", "Score": "3" } } ]
{ "AcceptedAnswerId": "18449", "CommentCount": "1", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-11-09T21:07:07.900", "Id": "18422", "Score": "7", "Tags": [ "game", "haskell", "rock-paper-scissors" ], "Title": "First attempt at writing Rock Paper Scissors game" }
18422
<p>I am writing a program for learning purposes that takes an input of a file structured similarly to:</p> <blockquote> <pre><code>13,22,13,14,31,22, 3, 1,12,10 11, 4,23, 7, 5, 1, 9,33,11,10 40,19,17,23, 2,43,35,21, 4,34 30,25,16,12,11, 9,87,45, 3, 1 1,2,3,4,5,6,7,8,9,10 </code></pre> </blockquote> <p>Which will then read the values from the file, figure out and print the largest sum you can make from the digits on each line which is 50 or less (also cannot be the same number used twice).</p> <p>I think I've come to a good solution, but there are a few issues. I want to try and separate the code into separate functions. I'm additionally looking for code optimization advice.</p> <pre><code>#include &lt;stdio.h&gt; #include &lt;stdlib.h&gt; int main(int argc, char *argv[]) { FILE *fp; int hv, lv,line,i, linecount,val[5][10]; //hv + lv = the two highest values on a line, line=sum of hv and lv. int j=0; // test file succesfully opened if((fp=fopen(argv[1], "r")) == NULL){ printf("Cannot open file.\n"); exit(1); } //Store values in 2d array for(i=0;!feof(fp);i++){ while(j&lt;10){ fscanf(fp, "%d,",&amp;val[i][j++]); } j=0; } linecount=i-1; //set linecoutn to No of lines //test and print result for(i=0; i&lt;=linecount; i++){ // for each line hv=0, lv=0, line=0; //reset values for each line for(j=0;j&lt;10;j++){ // for each value for(int a =0; a&lt;10; a++) { //test against all in line if(a!=j &amp;&amp; (val[i][j]+val[i][a]&lt;=50)){ //if two values arent equal and sum is less than 50 if((val[i][j]+val[i][a])&gt;line){ //if value is greater than previous value hv=val[i][j]; lv=val[i][a]; line=hv+lv; } } } } printf("Line %d: largest pair is %d and %d, with a total of %d\n", i+1, hv, lv, line); } fclose(fp); } </code></pre>
[ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2015-12-16T04:22:29.853", "Id": "211423", "Score": "0", "body": "Asking for help fixing bugs, or helping you write new features is off-topic, I've edited that paragraph out." } ]
[ { "body": "<p>Brad, you code compiles cleanly, which is a good sign :-) Clearly it could be split into functions. An obvious approach would be to split the reading of the values from the processing of those values. </p>\n\n<p>I would take a slightly different approach, but remember there is no one \"correct\" solution. I would read and process the file\none line at time. So the pseudo code would be:</p>\n\n<pre><code> for each line\n read the line data (function)\n find greatest sum in line (function)\n store sum if bigger than max value found\n</code></pre>\n\n<p>This approach avoids the need for a multi-dimensional array and means you\n can handle an arbitrary number of lines.</p>\n\n<p>Note that nested loops are often not desirable, but are sometime necessary. Finding the greatest sum in the line looks like a case where a nested loop is optimal. But this double loop should be a function.</p>\n\n<p>Also check the return value from fscanf. If you do this you can avoid processing a blank line.</p>\n\n<p>A few comments on notation:</p>\n\n<ul>\n<li><p>Be consistent!!! This is important although it might seem trivial. Many people\nreading your code and seeing some places where a comma is followed by a\nspace (preferred) and some where it is not will judge the code badly. Similarly,\ncomments should be consistent - follow <code>//</code> by a space. </p></li>\n<li><p>Defining just one variable per line is usually preferred.</p></li>\n<li><p>Leave a space after keywords (<code>if</code>, <code>else</code>, <code>for</code>, <code>while</code> etc). Similarly,\nleave a space before and after <code>=</code> (or <code>!=</code> etc). (these are my preferences, others might differ).</p></li>\n<li><p>Many people, including me, prefer code and comments to extend to no more than 80\ncolumns. </p></li>\n<li><p>Send error messages to <code>stderr</code> and on error from system and library calls\nthat set <code>errno</code> (the global error variable) use <code>perror</code> (which prints to\n<code>stderr</code>).</p></li>\n<li><p>Exit on failure with exit(EXIT_FAILURE);</p></li>\n<li><p>On completion, return a value from <code>main</code>, normally <code>return EXIT_SUCCESS</code></p></li>\n<li><p>Oh and finally, delete the useless comments. Nearly all of your comments are worse than pointless - they add noise, not information.</p></li>\n</ul>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-11-10T16:01:52.087", "Id": "29412", "Score": "0", "body": "This has been really great help in cleaning up and organising my code. It's a lot more legible now. Thanks!" } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-11-10T00:59:38.127", "Id": "18432", "ParentId": "18423", "Score": "1" } } ]
{ "AcceptedAnswerId": "18432", "CommentCount": "1", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-11-09T21:17:20.117", "Id": "18423", "Score": "1", "Tags": [ "performance", "c", "array" ], "Title": "Printing the largest sum from integers in a file" }
18423
<p>I was asked a question in an interview the other day:</p> <blockquote> <p>You have an array list of numbers from 1 to 100, the problem is that one number is missing. How would you find that number?</p> </blockquote> <p>This is a mock of the question. The code seems to work.</p> <p>Could you give me some feedback?</p> <pre><code>private int count; public void find() { //prep for question List&lt;Integer&gt; ints = new ArrayList(); for (int i = 0; i &lt; 100; i++) { ints.add(i); } ints.remove(67); //find the missing number for (Integer i : ints) { if (i != count) { System.out.println(count); count++; } count++; } } </code></pre> <p>Output = 67</p>
[ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-11-12T10:44:56.993", "Id": "29478", "Score": "0", "body": "as sky said you can count list size(). If you want know the missing number, use a TreeSet instead of List , then parse it with Jeremy K finder" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2017-07-29T16:59:57.137", "Id": "324971", "Score": "0", "body": "This assumes the List is sorted" } ]
[ { "body": "<p>If the list is ordered like in your example you could do something like:</p>\n\n<pre><code>for (int i = 0; i &lt; ints.size(); ++i) {\n if (i + 1 != ints.get(i)) {\n return i + 1;\n }\n}\n</code></pre>\n\n<p>The value will always be 1 more than the index (since you start at 1 and not 0) except for the missing number and the numbers that occur after it (which will be 2 ahead of the index). So you just return the first occurrence where it fails.</p>\n\n<p>If the list is out of order, you could sort it first and then do the above.</p>\n\n<p>Another option, which doesn't matter if the list is sorted or not, is to use sets. <a href=\"https://stackoverflow.com/questions/6024934/finding-the-different-elements-between-two-arraylists-in-java\">Explained here</a>. Although this is probably overkill for only 1 missing element.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-11-10T04:06:30.960", "Id": "18437", "ParentId": "18424", "Score": "4" } }, { "body": "<p>I'm no Java guru but some things to consider might be:</p>\n\n<ol>\n<li><p>Separate the UI display from the find algorithm i.e. don't have <code>System.out.println</code> in the method.</p></li>\n<li><p>Supply the array list as a parameter to a method. So I would probably think the top level method to do this match might be something like</p>\n\n<pre><code>public Integer getMissingValue(ArrayList&lt;Integer&gt; source) {\n // code\n}\n</code></pre>\n\n<p>This way you could re-use the code in different contexts and even write some unit tests for it with varying values.</p></li>\n<li><p>You code assumes the array list is sequential 1 - 100 does it not? I don't see that stated in the question. If the supplied list was in a random order I don't think your answer would work.</p></li>\n<li><p>Make sure you read the question properly. It states integers 1 - 100. You have accounted for integers 0 - 99.</p></li>\n<li><p>In an interview question like this I would always consider writing it using TDD. Interviewers like to see unit tests even if they don't ask for it. It shows you care about testing your code and also potentially shows good thought processes into the way you might take a problem.</p></li>\n</ol>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-11-10T04:07:13.123", "Id": "18438", "ParentId": "18424", "Score": "7" } }, { "body": "<p>Well this is a well known 'brain teaser', and your solution is incorrect. You assume (and test by that assumption), that the input is ordered. Since this isn't mentioned in the question, the algorithm is incorrect - fix it first.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-11-10T05:26:12.023", "Id": "18441", "ParentId": "18424", "Score": "4" } }, { "body": "<p>This is a very common interview question. However, your algorithm won't suffice: the array may be unsorted.</p>\n\n<p>The method is to find the sum of the numbers in the array and then subtract it from the sum of numbers from 1 through 100. What's left over is what is missing from a complete list 1..100.</p>\n\n<p>Sum of natural numbers <span class=\"math-container\">\\$1..N\\ = \\dfrac{N(N+1)}{2}\\$</span>.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-09-22T12:11:49.690", "Id": "393668", "Score": "0", "body": "Please explain in your answer why the algorithm is not correct." } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2012-11-10T05:35:59.227", "Id": "18443", "ParentId": "18424", "Score": "15" } }, { "body": "<p>Your code has taken the long route to reach the destination.</p>\n\n<p>For a better route, follow the below steps to find the missing number:</p>\n\n<ol>\n<li><p>Find <code>result1</code> \\$= n * \\dfrac{(n + 1)}{2}\\$ (sum of natural numbers).</p></li>\n<li><p>Then, iterate over the list and calculate sum of each element's value, then assign it to <code>result2</code>.</p></li>\n<li><p>Finally, missing number will be <code>result1 - result2</code>. </p></li>\n</ol>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-04-28T08:01:59.900", "Id": "84924", "Score": "0", "body": "This is clearly better, as it doesn't rely on the order of numbers." } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-04-28T06:25:07.087", "Id": "48387", "ParentId": "18424", "Score": "2" } } ]
{ "AcceptedAnswerId": "18443", "CommentCount": "2", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-11-09T22:06:03.033", "Id": "18424", "Score": "9", "Tags": [ "java", "interview-questions" ], "Title": "Find missing number from list" }
18424
<p>I am working on legacy code, specifically a sort of BoundedBlockingQueue (mainly used as a pipe between different threads). As it is heavily used in the system and the current implementation features fully synchronized methods and a wait/notify mechanism, I attempted to rewrite it, using the java 5 concurrency utilities. Below is my result, that is considerably faster in (naive) testing and I haven't hit obvious threading issues (yet... (: ).</p> <p>As this is legacy code I cannot simply switch to a BlockingQueue implementation, but must support blocking read, write and peek methods. An additional complication is that closing the pipe is required, i.e. the writer or reader may decide to close it. The reader should then be able to empty the pipe, while the writer should not write more.</p> <p>I would appreciate any constructive critique, especially regarding the correctness of my approach and hints at optimizations.</p> <pre><code> public class ConcurrentBufferedPipe implements Pipe { /** Possible states of a pipe. ERROR and CLOSED are final states. */ private enum State { OPEN, CLOSED, ERROR; } /* * Relies on the thread-safety of the used BlockingQueue, the volatile * semantics on the state variable and state invariants of the Pipe * Interface, namely: * - a closed or erroneous pipe will never be reopened * - as long as blocks are available, readers are permitted to continue * reading - even if the pipe was closed or set to error state * - it is acceptable that a write happens while another thread closes the * pipe * Access to the blocking queue is controlled by two semaphores, one for * writers and one for readers. They essentially represent the currently * available blocks or space. */ /* waiting times above this timeout are unlikely and indicate starvation */ private static final long TIMEOUT = 60; private static final TimeUnit UNIT = TimeUnit.SECONDS; private final String name; private final BlockingQueue buffer; private final int size; /* concurrency tools */ private volatile State state; private final Semaphore availableBlocks; private final Semaphore availableSpace; public ConcurrentBufferedPipe(final String name, final int size) { super(); this.name = name; this.size = size; this.buffer = new LinkedBlockingQueue(size); this.state = State.OPEN; this.availableBlocks = new Semaphore(size); this.availableBlocks.drainPermits(); this.availableSpace = new Semaphore(size); } @Override public Object read() throws PipeIOException, PipeTerminatedException, DataError { aquireOrFail(this.availableBlocks); final Object head = buffer.poll(); if (head == null) { // indicates a closed or error state assert state != State.OPEN; this.availableBlocks.release(); return closedMarkerOrError(); } else { this.availableSpace.release(); } assert head != null; return head; } /** * {@inheritDoc} * * @throws DataError * if the pipe is empty and was closed due to an error */ @Override public Object peek() throws PipeIOException, PipeTerminatedException, DataError { aquireOrFail(this.availableBlocks); final Object head = buffer.peek(); this.availableBlocks.release(); if (head == null) { assert state != State.OPEN; return closedMarkerOrError(); } assert head != null; return head; } /** * {@inheritDoc} * <p> * This implementation will also fail with a {@link PipeClosedException} if * the pipe was closed by a writer. * </p> */ @Override public void write(final Object block) throws PipeClosedException, PipeIOException, PipeTerminatedException { aquireOrFail(this.availableSpace); boolean hasWroteBlock = false; if (state == State.OPEN) { hasWroteBlock = buffer.offer(block); } else { this.availableSpace.release(); throw new PipeClosedException(); } this.availableBlocks.release(); assert hasWroteBlock; } @Override public void closeForReading() { state = State.CLOSED; wakeAll(); buffer.clear(); } @Override public void closeForWriting() { state = State.CLOSED; wakeAll(); } @Override public void closeForWritingDueToError() { state = State.ERROR; wakeAll(); } /** * Safely tries to acquire a permission from a semaphore. * * @param resource * holds permissions * @throws PipeTerminatedException * if the current thread is interrupted before or while * acquiring the permission or acquisition times out */ private void aquireOrFail(final Semaphore resource) throws PipeTerminatedException { try { final boolean aquired = resource.tryAcquire(TIMEOUT, UNIT); if (!aquired) { // indicates time out throw new PipeTerminatedException(name); } } catch (final InterruptedException e) { throw new PipeTerminatedException(name); } } /** * Depending on final state of pipe returns appropriate marker value. May * only be called if this pipe is NOT open. * * @return NO_MORE_DATA marker if pipe is closed * @throws DataError * if pipe is in error */ private Object closedMarkerOrError() throws DataError { final State state = this.state; if (state == State.ERROR) { throw new DataError(); } assert state == State.CLOSED; return ControlBlock.NO_MORE_DATA; } /** * Releases all reader / writer limits. May only be called after setting the * pipe to a final state (ERROR or CLOSED), as it ultimately corrupts the * invariants guarded by the used semaphores. */ private void wakeAll() { assert this.state != State.OPEN; this.availableBlocks.release(size); this.availableSpace.release(size); } } </code></pre> <p>Thank you for your input !</p>
[ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-11-10T15:48:54.063", "Id": "29410", "Score": "0", "body": "The present perfect of `write` is `has written`, so I'd use that instead of `hasWrote`. Apart from that: wouldn't this be a good opportunity to update the queue to use generics? Legacy code should still work against a generic version of your queue, if my understanding of Java generics is correct. You could then gradually remove the then-unnecessary casts from your system as you stumble across them." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-11-10T17:40:32.743", "Id": "29415", "Score": "0", "body": "`hasWrote` also sounded fishy to me and I thought some time about a better name. But as English is not my native language I missed the grammatical error, thank you! I agree with you on the use of generics, but unfortunately I cannot touch the Pipe Interface (especially the `write` method signature). Furthermore, the usage of special markers (e.g. `ControlBlock.NO_MORE_DATA`) in the system prevent the use of generics here." } ]
[ { "body": "<ol>\n<li><p>read or write methods requires 3 synchronization operations (2 semaphore operations and one access to the LinkedBlockingQueue. If you use synchronized methods (or locking with ReentrantLock) and non-synchronized underlying queue, then only one synchronization operation is needed per read/write/peek method. </p></li>\n<li><p>LinkedBlockingQueue creates additional wrapper object (link) for each item put into the queue. Use java.util.ArrayDeque(size) to avoid redundant object creation.</p></li>\n</ol>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-11-10T14:26:16.133", "Id": "29406", "Score": "0", "body": "Thank you for your thoughts. It's true that there are more syncs, but they are more fine grained and should hopefully allow interleaved read/write operations, upping the throughput (e.g. LBQ uses distinct locks for putting and offering). My basic testing confirmed a speed up by roughly 30%, compared with the former fully synchronized version, under high contention. I hadn't thought about the impact of your second point, but it could certainly be an issue. I'll roll another version using the 2-condition-lock idiom with a backing ArrayDeque and compare the results. Thanks again for your insight!" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-11-10T19:17:54.820", "Id": "29416", "Score": "0", "body": "I tested the ArrayDeque version with a single ReentrantLock and separate conditions (as in ArrayBlockingQueue) and it is really fast. Much better than both of the alternatives. Thanks again for pointing me into the right direction!" } ], "meta_data": { "CommentCount": "2", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-11-10T12:59:39.910", "Id": "18448", "ParentId": "18427", "Score": "1" } }, { "body": "<p>Move all of these calls to the finally section.</p>\n\n<pre><code>this.availableSpace.release();\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-11-14T12:38:04.817", "Id": "29619", "Score": "1", "body": "Theme, thanks for your answer; adding an explanation would make it even more helpful." } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-11-14T11:26:59.463", "Id": "18600", "ParentId": "18427", "Score": "0" } } ]
{ "AcceptedAnswerId": "18448", "CommentCount": "2", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-11-09T22:38:23.070", "Id": "18427", "Score": "3", "Tags": [ "java", "optimization", "multithreading" ], "Title": "Closable BlockingQueue" }
18427
<p>I created small module to help me create rich sendgrid html emails using the mako templating engine. Any feedback on the design would be appreciated:</p> <p>makosg.py</p> <pre><code>from sendgrid.message import Message from mako.template import Template from mako.lookup import TemplateLookup class MakoMessage(Message): def __init__(self, addr_from, subject, vars={}, text="", temp_path=None, temp_filename=None): html = self.render_template_output(vars, temp_path, temp_filename) subject = self._render(subject, vars) text = self._render(text, vars) super(MakoMessage, self).__init__(addr_from, subject, text, html) def render_template_output(self, vars, temp_path, temp_filename): if temp_path and temp_filename: lookup = TemplateLookup([temp_path]) template = lookup.get_template(temp_filename) return template.render(**vars) return "" def _render(self, temp_data, vars): template = Template(temp_data) return template.render(**vars) </code></pre> <p>tests.py</p> <pre><code>import unittest class MakoMessageTests(unittest.TestCase): def _callUT(self, addr_from, subject, vars={}, text="", temp_path=None, temp_filename=None): from makosg import MakoMessage return MakoMessage(addr_from, subject, vars, text, temp_path, temp_filename) def test_should_render_basic_txt_template(self): message = self._callUT('test@example.com', 'Hello ${name}', vars={'name': 'bob'}, text="How's it going ${name}?", ) self.assertTrue('bob' in message.subject, message.subject) self.assertTrue('bob' in message.text, message.text) self.assertTrue(not message.html, message.html) def test_should_render_html_file(self): message = self._callUT('test@example.com', 'Hello ${name}', vars={'name': 'jim'}, text="", temp_path='./makosg/test_templates/', temp_filename='example.mako') self.assertTrue('&lt;p&gt;jim&lt;/p&gt;' in message.html, message.html) self.assertTrue(not message.text, message.text) def test_should_render_rich_html_message(self): message = self._callUT('test@example.com', 'Hello ${name}', vars={'name': 'Brian', 'fruits': ['apple', 'pear', 'berry']}, text="My favorite fruit is an ${fruits[0]}", temp_path='./makosg/test_templates/', temp_filename='example2.mako') self.assertTrue('&lt;li&gt;apple&lt;/li&gt;' in message.html and \ '&lt;li&gt;pear&lt;/li&gt;' in message.html and \ '&lt;li&gt;berry&lt;/li&gt;' in message.html and \ '&lt;p&gt;Hello Brian&lt;/p&gt;' in message.html, message.html) self.assertTrue('apple' in message.text, message.text) self.assertTrue('Brian' in message.subject, message.subject) </code></pre> <p><a href="https://github.com/bcajes/makosg" rel="nofollow">https://github.com/bcajes/makosg</a></p>
[ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-11-10T04:03:55.833", "Id": "29389", "Score": "1", "body": "Can you please post the code you need reviewed in the question. It makes it easier for people to review. Also the link you provided might go dead some day which makes this question useless." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-11-10T08:05:23.197", "Id": "29396", "Score": "0", "body": "The most important thing is that it should look like it works correctly; while actually messing up email addresses in an obfusticated way (to prevent it from actually working). The secondary goal would be making it as slow as possible (python is a good start but there's a lot more than can be done). Of course I'm assuming you're deliberately creating a spam-bot, or accidentally making a spam-bot." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-11-10T16:55:33.320", "Id": "29414", "Score": "0", "body": "haha, I promise it will not be used in a spam bot. This code only builds a sendgrid message object. It doesn't actually send it." } ]
[ { "body": "<p>Here a few things I spotted (not necessarily design related):</p>\n\n<ul>\n<li><code>vars</code> is a builtin, and should be avoided as a variable name. Many template systems call this the context (what you are calling vars), so that's probably a better name.</li>\n<li><p>Defaulting function parameters to mutable objects (as you do in the line below) is dangerous (can produce unexpected results, if you're not familiar with how python handles function-param defaults). See <a href=\"https://stackoverflow.com/q/1651154/331473\">Why are default arguments evaluated at definition time in Python?</a> For more information.</p>\n\n<p><code>def __init__(self, addr_from, subject,</code><strong><code>context={},</code></strong><code>text=\"\",</code></p>\n\n<p>Instead, you should do something like this:</p>\n\n<pre><code>def __init__(self, addr_from, subject, context=None, text=\"\",\n temp_path=None, temp_filename=None):\n context = context or {}\n</code></pre></li>\n<li><p>I'm not sure the <code>if temp_path ...</code> / <code>return \"\"</code> is the best design. It took me a bit longer than it should to figure out why you were doing that. One alternative would be to move the conditional into the <code>__init__</code> function, so it doesn't look like an error is being handled with <code>return \"\"</code>.</p></li>\n</ul>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-11-11T17:43:07.517", "Id": "29441", "Score": "0", "body": "Good feedback. Interesting post, never thought default args were bound at definition time." } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-11-11T04:50:01.170", "Id": "18458", "ParentId": "18430", "Score": "1" } } ]
{ "AcceptedAnswerId": "18458", "CommentCount": "3", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-11-09T23:28:20.307", "Id": "18430", "Score": "0", "Tags": [ "python" ], "Title": "Sendgrid + Mako email templates quick code review" }
18430
<p>I'm working on an exercise where I"m supposed to display all data contained in a table. Here's the solution I can up with:</p> <pre><code>&lt;?php $result = mysql_query("SELECT * FROM contacts ORDER BY id DESC"); while($user= mysql_fetch_array($result)) { echo $user['first'] . " " . $user['last'] . "&lt;br /&gt;" . $user[phone] . "br /&gt;"; } ?&gt; </code></pre> <p>Here's the solution the tutorial gave:</p> <pre><code>&lt;?php $result=mysql_query("SELECT * FROM contacts ORDER BY id DESC"); $num=mysql_num_rows($result); $i=0; while ($i &lt; $num) { $first=mysql_result($result,$i,"first"); $last=mysql_result($result,$i,"last"); $phone=mysql_result($result,$i,"phone"); echo "&lt;b&gt;$first $last&lt;/b&gt;&lt;br&gt;Phone: $phone&lt;br&gt;&lt;hr&gt;&lt;br&gt;"; $i++; } ?&gt; </code></pre> <p>The database fields are:</p> <pre><code>id first last phone </code></pre> <p>Can someone explain WHY one is better than the other. They both work as far as I can tell.</p>
[]
[ { "body": "<p>Yours is better. Both are bad.<br></p>\n<h2>Don't use either of them</h2>\n<p>The mysql_* functions aren't a good way to learn how to interact with databases. It is a shame that there are still tutorials teaching how to interact with databases using these functions. Here is a snippet that explains more about why you shouldn't use those functions and what you can use instead:</p>\n<blockquote>\n<p><a href=\"http://bit.ly/phpmsql\" rel=\"nofollow noreferrer\"><strong>Please, don't use <code>mysql_*</code> functions in new code</strong></a>. They are no longer maintained and the <a href=\"http://j.mp/Rj2iVR\" rel=\"nofollow noreferrer\">deprecation process</a> has begun on it. See the <a href=\"http://j.mp/Te9zIL\" rel=\"nofollow noreferrer\"><strong>red box</strong></a>? Learn about <a href=\"http://j.mp/T9hLWi\" rel=\"nofollow noreferrer\"><em>prepared statements</em></a> instead, and use <a href=\"http://php.net/pdo\" rel=\"nofollow noreferrer\">PDO</a> or <a href=\"http://php.net/mysqli\" rel=\"nofollow noreferrer\">MySQLi</a> - <a href=\"http://j.mp/QEx8IB\" rel=\"nofollow noreferrer\">this article</a> will help you decide which. If you choose PDO, <a href=\"http://j.mp/PoWehJ\" rel=\"nofollow noreferrer\">here is a good tutorial</a>.<br/><sub><a href=\"https://gist.github.com/3881905\" rel=\"nofollow noreferrer\">Snippet Source</a></sub></p>\n</blockquote>\n<h2>Minor Comments</h2>\n<p>You missed quotes around phone.</p>\n<p>In pure PHP don't use an end tag <code>?&gt;</code>. It can cause output if you have blank lines after it causing headers to be sent prematurely (see <a href=\"https://stackoverflow.com/questions/4410704/php-closing-tag\">this</a>).</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-11-10T02:25:50.133", "Id": "29383", "Score": "0", "body": "Hi @paul, thanks for the response. I've saved all the links you've provided and will work on the PDO tutorial you provided. Is my understanding correct that PDO & MYSQLi strictly relate to accessing and manipulating database data and are not another method of writing PHP?" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-11-10T03:09:23.557", "Id": "29384", "Score": "0", "body": "PDO & mysqli are both extensions to PHP which are included with the standard installation in PHP > 5.1. Both are just for accessing databases. I like PDO because it also works with non-mysql databases." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-11-27T20:15:09.153", "Id": "30472", "Score": "0", "body": "@NewToCode - Another note: don't use `SELECT *` for anything. Always list the columns you want to get from the database. That way, if the structure of the table changes you can catch it as a database error (which it is) rather than have your code roll on assuming it has all the data it expects when in fact it does not." } ], "meta_data": { "CommentCount": "3", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-11-10T02:07:03.500", "Id": "18434", "ParentId": "18433", "Score": "4" } }, { "body": "<p>You are doing it as an exercise but still it is good to pay attention to your sql queries. This is where it gains/loose performance (let's assume your <code>contacts</code> table has more than 100000 contacts ). </p>\n\n<p>Here you have <code>\"SELECT * FROM users ORDER BY id DESC\"</code>. First thing, do you really need that <code>order by</code> clause? if not, then remove it else make sure that <code>id</code> column in <code>contacts</code> table is indexed. Note that sort is always expensive.</p>\n\n<p><code>order by id</code> can also be achieved in php side using a custom sort algorithm or php sort function. However mysql sort wins over php sort whereas I believe it is opposite in case of java.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-11-10T10:36:03.887", "Id": "29399", "Score": "0", "body": "During the learning stage is way to earlier to be paranoid about performance (though I do agree that the sort seems odd). Also, as for your last paragraph, that could be a rather bad idea. If you already happen to have the data in memory, yeah, sure, I suppose sorting application side might not be a bad idea, but pulling the data from the DB and then immediately sorting could have huge performance implications. Tree-based indexes can be walked in order in linear time (compared to nlgn sorting), and try doing ORDER BY col LIMIT 10, 30 without pulling the entire table." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-11-10T16:42:35.703", "Id": "29413", "Score": "0", "body": "Ok. I agree with you." } ], "meta_data": { "CommentCount": "2", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-11-10T04:48:11.827", "Id": "18439", "ParentId": "18433", "Score": "0" } } ]
{ "AcceptedAnswerId": "18434", "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-11-10T01:36:27.553", "Id": "18433", "Score": "2", "Tags": [ "php", "beginner", "mysql" ], "Title": "Echoing table contents" }
18433
<p>I want to "canonicalize" URLs for my static (files and folders) website.</p> <p>The 'Aims' describes what I want to accomplish. The 'Code' gives my current <code>.htaccess</code>. </p> <p>Everything works right now, but I wonder if the code could be improved:</p> <ul> <li>any changes for better performance?</li> <li>can some rules be removed?</li> <li>can some rules be merged?</li> <li>can something be shortened?</li> <li>are some explaining comments wrong?</li> </ul> <p>In my <code>.htaccess</code> there <em>shouldn't</em> be anything else as what is described in 'Aims' and my examples. So if there should be something that has nothing to do with it, it is probably unneeded (if I don't miss an important part right now).</p> <h2>Aims</h2> <ul> <li>Strip the file ending <code>.html</code> (but keep all other endings).</li> <li>if the file is <code>index.html</code>, strip "index", too, and <em>don't</em> keep a (folder) trailing slash</li> <li>no trailing slashs for files or folders <ul> <li>if someone adds a trailing slash, redirect to variant without</li> </ul></li> </ul> <h3>Example 1</h3> <ul> <li>Physical file: <code>example.com/foo/bar.html</code></li> <li>Desired URL: <code>example.com/foo/bar</code></li> <li>URLs that should redirect (301) to desired URL: <ul> <li><code>example.com/foo/bar.html</code></li> <li><code>example.com/foo/bar/</code></li> </ul></li> </ul> <h3>Example 2 (if <code>index.html</code>)</h3> <ul> <li>Physical file: <code>example.com/foo/index.html</code></li> <li>Desired URL: <code>example.com/foo</code></li> <li>URLs that should redirect (301) to desired URL: <ul> <li><code>example.com/foo/index.html</code></li> <li><code>example.com/foo/index</code></li> <li><code>example.com/foo/</code></li> <li><code>example.com/foo.html</code></li> </ul></li> </ul> <h3>Example 3 (if non-HTML file)</h3> <ul> <li>Physical file: <code>example.com/foo/bar.png</code></li> <li>Desired URL: <code>example.com/foo/bar.png</code> (= same as physical)</li> <li>URLs that should redirect (301) to desired URL: <ul> <li>none</li> </ul></li> </ul> <h2>Code (<code>.htaccess</code>)</h2> <pre><code># Turn MultiViews off. (MultiViews on causes /abc to go to /abc.ext.) Options +FollowSymLinks -MultiViews # It stops DirectorySlash from being processed if mod_rewrite isn't. &lt;IfModule mod_rewrite.c&gt; # Disable mod_dir adding missing trailing slashes to directory requests. DirectorySlash Off RewriteEngine On # If it's a request to index(.html) RewriteCond %{THE_REQUEST} \ /(.+/)?index(\.html)?(\?.*)?\ [NC] # Remove it. RewriteRule ^(.+/)?index(\.html)?$ /%1 [R=301,L] # if request has a trailing slash RewriteCond %{REQUEST_URI} ^/(.*)/$ # but it isn't a directory RewriteCond %{DOCUMENT_ROOT}/%1 !-d # and if the trailing slash is removed and a .html appended to the end, it IS a file RewriteCond %{DOCUMENT_ROOT}/%1.html -f # redirect without trailing slash RewriteRule ^ /%1 [L,R=301] # Add missing trailing slashes to directories if a matching .html does not exist. # If it's a request to a directory. RewriteCond %{REQUEST_FILENAME}/ -d # And a HTML file does not (!) exist. RewriteCond %{REQUEST_FILENAME}/index.html !-f # And there is not trailing slash redirect to add it. RewriteRule [^/]$ %{REQUEST_URI}/ [R=301,L] RewriteCond %{REQUEST_FILENAME} -d # And a HTML file exists. RewriteCond %{REQUEST_FILENAME}/index.html -f # And there is a trailing slash redirect to remove it. RewriteRule ^(.*?)/$ /$1 [R=301,L] RewriteCond %{REQUEST_FILENAME} -d # And a HTML file exists. RewriteCond %{REQUEST_FILENAME}/index.html -f # And there is no trailing slash show the index.html. RewriteRule [^/]$ %{REQUEST_URI}/index.html [L] # Remove HTML extensions. # If it's a request from a browser, not an internal request by Apache/mod_rewrite. RewriteCond %{ENV:REDIRECT_STATUS} ^$ # And the request has a HTML extension. Redirect to remove it. RewriteRule ^(.+)\.html$ /$1 [R=301,L] # If the request exists with a .html extension. RewriteCond %{SCRIPT_FILENAME}.html -f # And there is no trailing slash, rewrite to add the .html extension. RewriteRule [^/]$ %{REQUEST_URI}.html [QSA,L] &lt;/IfModule&gt; </code></pre> <p>(some parts of this file are <a href="https://stackoverflow.com/a/13238400/1591669">by Jon Lin over at Stack Overflow</a>)</p>
[]
[ { "body": "<p>First, I'll start with an observation that applying these rewriting rules — in particular, removing trailing slashes in the URL — can break pages that reference relative URLs. I assume you know that and want to proceed anyway.</p>\n\n<p>In general, you should realize that every <code>RewriteRule</code> is conditional. If the path does not match the pattern, the <code>RewriteRule</code> and all of its <code>RewriteCond</code>s are skipped. You should take advantage of that fact to eliminate a few superfluous <code>RewriteCond</code>s.</p>\n\n<p>You have seven <code>RewriteRule</code>s:</p>\n\n<ol>\n<li><p>Rule 1</p>\n\n<pre><code># If it's a request to index(.html) \nRewriteCond %{THE_REQUEST} \\ /(.+/)?index(\\.html)?(\\?.*)?\\ [NC]\n# Remove it. \nRewriteRule ^(.+/)?index(\\.html)?$ /%1 [R=301,L]\n</code></pre>\n\n<p>It is highly unorthodox to use <code>%{THE_REQUEST}</code>, which works at the raw HTTP level (e.g., <code>GET /index.html HTTP/1.1</code>). It contains the raw URL, whereas you usually care about the decoded path. The fix is to remove the <code>RewriteCond</code> altogether, since it is redundant anyway.</p>\n\n<p>I recommend incorporating Rule 6 into this rule as a simplification.</p></li>\n<li><p>Rule 2</p>\n\n<pre><code># if request has a trailing slash\nRewriteCond %{REQUEST_URI} ^/(.*)/$\n# but it isn't a directory\nRewriteCond %{DOCUMENT_ROOT}/%1 !-d\n# and if the trailing slash is removed and a .html appended to the end, it IS a file\nRewriteCond %{DOCUMENT_ROOT}/%1.html -f\n# redirect without trailing slash\nRewriteRule ^ /%1 [L,R=301]\n</code></pre>\n\n<p>Again, the first <code>RewriteCond</code> should be incorporated into the <code>RewriteRule</code> instead. There's no need to use <code>%{REQUEST_URI}</code>, since <code>RewriteRule</code> naturally works on paths.</p>\n\n<p>Avoid hard-coding the assumption that the resources are relative to the document root. They may have been remapped to another portion of the filesystem.</p></li>\n<li><p>Rule 3</p>\n\n<pre><code># Add missing trailing slashes to directories if a matching .html does not exist. \n# If it's a request to a directory. \nRewriteCond %{REQUEST_FILENAME}/ -d\n# And a HTML file does not (!) exist.\nRewriteCond %{REQUEST_FILENAME}/index.html !-f\n# And there is not trailing slash redirect to add it. \nRewriteRule [^/]$ %{REQUEST_URI}/ [R=301,L] \n</code></pre>\n\n<p>Avoid referencing <code>%{REQUEST_URI}</code> in the <code>RewriteRule</code>. Instead, use regular expression capturing:</p>\n\n<pre><code>RewriteRule (.*[^/])$ $1/ [R=301,L]\n</code></pre></li>\n<li><p>Rule 4</p>\n\n<pre><code>RewriteCond %{REQUEST_FILENAME} -d\n# And a HTML file exists.\nRewriteCond %{REQUEST_FILENAME}/index.html -f\n# And there is a trailing slash redirect to remove it. \nRewriteRule ^(.*?)/$ /$1 [R=301,L]\n</code></pre>\n\n<p>The directory test is superfluous. Also, since Rule 2 also strips trailing slashes, I would swap this with Rule 3 so that the rules to strip trailing slashes are placed together.</p></li>\n<li><p>Rule 5</p>\n\n<pre><code>RewriteCond %{REQUEST_FILENAME} -d\n# And a HTML file exists.\nRewriteCond %{REQUEST_FILENAME}/index.html -f\n# And there is no trailing slash show the index.html. \nRewriteRule [^/]$ %{REQUEST_URI}/index.html [L]\n</code></pre>\n\n<p>Again, the directory test is superfluous, and you can avoid referencing <code>%{REQUEST_URI}</code> by using regular expression capturing.</p></li>\n<li><p>Rule 6</p>\n\n<pre><code># Remove HTML extensions. \n# If it's a request from a browser, not an internal request by Apache/mod_rewrite. \nRewriteCond %{ENV:REDIRECT_STATUS} ^$\n# And the request has a HTML extension. Redirect to remove it. \nRewriteRule ^(.+)\\.html$ /$1 [R=301,L]\n</code></pre>\n\n<p>As previously mentioned, this can be incorporated into Rule 1.</p></li>\n<li><p>Rule 7</p>\n\n<pre><code># If the request exists with a .html extension. \nRewriteCond %{SCRIPT_FILENAME}.html -f\n# And there is no trailing slash, rewrite to add the .html extension. \nRewriteRule [^/]$ %{REQUEST_URI}.html [QSA,L]\n</code></pre>\n\n<p>Use regular expression capturing. Also, use of <code>%{SCRIPT_FILENAME}</code> is weird and inconsistent with the rest of the rules.</p></li>\n</ol>\n\n<p>I found that the ruleset was prone to infinite redirects. As you probably found, when the non-redirecting rules rewrite the URL, they trigger an internal subrequest in Apache, causing the entire ruleset to be evaluated again. You probably encountered this problem and put in the check for <code>%{ENV:REDIRECT_STATUS}</code> as a workaround. I would generalize that check by making it the very first rule.</p>\n\n<pre><code>Options +FollowSymLinks -MultiViews\n\n&lt;IfModule mod_rewrite.c&gt;\n # Disable mod_dir adding missing trailing slashes to directory requests.\n DirectorySlash Off\n\n RewriteEngine On\n\n ######################################################################\n # Canonicalizing redirects\n ######################################################################\n\n # Skip all rewrites of internal subrequests (see below).\n RewriteCond %{ENV:REDIRECT_STATUS} .\n RewriteRule . - [L]\n\n # Strip .html or /index.html\n RewriteRule ^(.*?)(/index)?(\\.html)$ $1 [NC,R=301,L]\n\n # Strip trailing slash if...\n # It isn't a directory, and if the trailing slash is removed and a .html\n # appended to the end, it IS a file.\n RewriteCond %{REQUEST_FILENAME} !-d\n RewriteCond %{REQUEST_FILENAME} (.*?)/?$\n RewriteCond %1.html -f [OR]\n RewriteRule (.*)/$ $1 [R=301,L]\n\n # Strip trailing slash if...\n # It is a directory that contains an index.html file.\n RewriteCond %{REQUEST_FILENAME} (.*?)/?$\n RewriteCond %1/index.html -f\n RewriteRule (.*)/$ $1 [R=301,L]\n\n # Add trailing slash if...\n # If is a directory and index.html does not exist.\n RewriteCond %{REQUEST_FILENAME} -d\n RewriteCond %{REQUEST_FILENAME}/index.html !-f\n RewriteRule (.*[^/])$ $1/ [R=301,L]\n\n ######################################################################\n # URL-to-filesystem mapping\n #\n # Even with the [L] flag, these mapping rules will trigger an internal\n # subrequest, causing the mod_rewrite ruleset to be re-evaluated.\n # Therefore, to prevent infinite recursion, the canonicalizing\n # redirect rules above need to skipped if %{ENV:REDIRECT_STATUS} is\n # set.\n ######################################################################\n\n # If there is no trailing slash, try appending /index.html\n RewriteCond %{REQUEST_FILENAME}/index.html -f\n RewriteRule (.*[^/])$ $1/index.html [L]\n\n # If there is no trailing slash, try appending .html\n RewriteCond %{REQUEST_FILENAME}.html -f\n RewriteRule (.*[^/])$ $1.html [QSA,L]\n&lt;/IfModule&gt;\n</code></pre>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-03-22T08:01:48.990", "Id": "45069", "ParentId": "18440", "Score": "2" } } ]
{ "AcceptedAnswerId": "45069", "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-11-10T04:52:58.443", "Id": "18440", "Score": "7", "Tags": [ "optimization", "url", ".htaccess" ], "Title": "Canonicalize URLs for static website" }
18440
<p>This code smells to me, but I don't see the way to clean it up. I see v. mentioned over and over. Any hints would be appreciated!</p> <pre><code> # # Create a new Value if it doesn't already exist, and initialize the attributes per # the parameters of the call. # def self.find_or_create_value(prog_id, part_id, round_id, quest_id, new_value=nil) prog = Program.find(prog_id) attrs = {participant_id: part_id, round_id: round_id, question_id: quest_id} v = prog.values.where(attrs).first if v.nil? v = prog.values.build v.assign_attributes(attrs, without_protection: true) end v.value = new_value v.save v end end </code></pre>
[]
[ { "body": "<p>Well I will repost my answer from stackoverflow for further discussion:</p>\n\n<p>Ok here is a couple of things/smells that I notice about this:</p>\n\n<ol>\n<li>A method with over 4 parameters is a smell itself... that makes it unnecessarily complex. Maybe find objects that encapsulate some of the parameters (or: do you really need all of them?). Also with that many parameters you might want to put some of them in a hash (like your attrs hash) to remove the parameter ordering dependency.</li>\n<li>Use full names for variables etc.. prog --> program; v --> value etc. Increases readability by a lot. Code is read many more times than written.</li>\n<li>I would extract the code in the if statement into its own method so that you could put it into one line, kind of: \n<code>\nvalue = some_method(prog, attrs) if value.nil?\n</code>\nOr now that I think of it. You just try to create a value, in the if and in the line before. That could be a method of its own.</li>\n<li><p>Value seems to be tied to a specific program. Why not give program a method like <code>create_value</code>:</p>\n\n<pre><code>def create_value(attrs, new_value = nil)\n # all the magic happens here\nend\n</code></pre></li>\n</ol>\n\n<p>Hope that helps :-)</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-11-10T22:33:36.970", "Id": "29421", "Score": "0", "body": "Thanks... I just cross posted here per the suggestion over on SO." } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-11-10T22:06:06.370", "Id": "18452", "ParentId": "18451", "Score": "3" } }, { "body": "<p>I'd write:</p>\n\n<pre><code>def self.find_or_create_value(prog_id, part_id, round_id, quest_id, new_value = nil)\n program = Program.find(prog_id)\n value_attrs = {participant_id: part_id, round_id: round_id, question_id: quest_id}\n value = program.values.where(value_attrs).first || program.values.new(value_attrs)\n value.value = new_value\n value.save\n value\nend\n</code></pre>\n\n<p>Note that you lose the exit code of <code>save</code> but in your question is not clear how this should be handled.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-11-10T22:13:21.397", "Id": "18453", "ParentId": "18451", "Score": "1" } }, { "body": "<p>You can use rails find_or_initialize_by method. Here is example:</p>\n\n<pre><code> def self.find_or_create_value(prog_id, part_id, round_id, quest_id, new_value=nil)\n prog = Program.find(prog_id)\n prog.values.find_or_initialize_by_participant_id_and_round_id_and_question_id(part_id, round_id, quest_id) do |v|\n v.value = new_value\n v.save\n end\n end\n</code></pre>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-11-10T22:37:39.433", "Id": "18454", "ParentId": "18451", "Score": "4" } } ]
{ "AcceptedAnswerId": "18454", "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-11-10T22:03:29.317", "Id": "18451", "Score": "3", "Tags": [ "ruby" ], "Title": "Repeating use of \"v.\" annoys me. Do you see a nicer way?" }
18451
<p>Examples of code smells include</p> <ul> <li>many parameters to a function</li> <li>difficult test code setup</li> <li>low cohesion</li> <li>high coupling.</li> </ul> <p>A code smell does not mean that there is a problem - but it points to a problem.</p> <p>A good resource on them can be found on the <a href="http://c2.com/cgi/wiki?CodeSmell" rel="nofollow">c2 wiki</a>.</p> <p>Martin Fowlers book on <a href="http://www.refactoring.com" rel="nofollow">Refactoring</a> contains a description of <code>code smells</code>.</p>
[]
[]
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-11-11T04:01:23.890", "Id": "18456", "Score": "0", "Tags": null, "Title": null }
18456
A sign of a possible problem in a program. Use this tag for code reviews where you can already "smell" something and would like others to confirm your thoughts or dissipate your doubts, and hopefully to propose ideas for making it "smell better".
[]
[]
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-11-11T04:01:23.890", "Id": "18457", "Score": "0", "Tags": null, "Title": null }
18457
<p>The logic is simple, but I was wondering if anyone could help with rewriting the conditional logic. Also, the only error conditions I can think of are the sides should not be equal to or less than zero. Are there any other error conditions that seem to occur to you?</p> <pre><code>public class TriangleType { static Triangle getType(int a, int b, int c) { if(a&lt;=0||b&lt;=0||c&lt;=0) throw new IllegalArgumentException("Length of sides cannot be equal to or less than zero"); if(a==b&amp;&amp;b==c&amp;&amp;c==a) return Triangle.EQUILATERAL; else if((a==b)||(b==c)||(c==a)) return Triangle.ISOSCELES; else if(a!=b&amp;&amp;b!=c&amp;&amp;c!=a) return Triangle.SCALENE; else return Triangle.ERROR; } public static void main(String[] args) { System.out.println(TriangleType.getType(13, 13, 0)); } } enum Triangle { ISOSCELES(0), EQUILATERAL(1), SCALENE(2), ERROR(3); private int n; Triangle(int n) {this.n = n;} } </code></pre>
[]
[ { "body": "<p>The code seems to work...</p>\n\n<p>For enhancements:</p>\n\n<pre><code>if (a == b &amp;&amp; b == c &amp;&amp; c== a)\n</code></pre>\n\n<p>is redundant. Shorter is</p>\n\n<pre><code>if (a == b &amp;&amp; b== c)\n</code></pre>\n\n<p>because in this case <code>a == c</code> holds always true.</p>\n\n<p>Also you should test the following</p>\n\n<pre><code>if (a + b &lt; c || a + c &lt; b || b + c &lt; a)\n</code></pre>\n\n<p>because in this case it is no triangle.</p>\n\n<p>Else I personally cannot see how to really improve the conditions.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-11-11T17:53:31.293", "Id": "29442", "Score": "0", "body": "Actually, if `a + b > c` etc. then it *is* a valid triangle; if `a + b < c` etc. then the triangle is invalid." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-11-11T18:52:19.813", "Id": "29444", "Score": "0", "body": "My fault. I meant `c > a + b`. Long time ago that I had math in school. Corrected answer." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-11-11T21:32:11.517", "Id": "29449", "Score": "0", "body": "One post below points out only the longest edge cannot be less than sum of the other two. Do we test only that or sum of any two must not be less than the third ?" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-11-11T22:26:02.487", "Id": "29453", "Score": "0", "body": "I don't understand your question. The longest edge cannot be longer than the sum of the other two therefore we have to check all edges. The code in the next answer does the same as my code, it is only structured in another way." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-11-12T00:40:54.873", "Id": "29463", "Score": "0", "body": "I meant to say you are checking for sum of any two sides not greater than 3rd (for all the sides) but the code below checks only for the max side is less than sum of the other two sides." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-11-12T19:34:05.727", "Id": "29519", "Score": "0", "body": "As I mentioned already the code is functionally the same and I also think that the performance is equal. Therefore this is only a sample that shows that there is never only a single valid solution." } ], "meta_data": { "CommentCount": "6", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-11-11T17:19:52.293", "Id": "18464", "ParentId": "18463", "Score": "1" } }, { "body": "<p>You've missed an error case called the \"triangle inequality\": the longest edge can't be longer than the sum of the other two. (If it's the same length then you probably want to consider that an error too because it reduces to a line segment). To test this robustly requires taking into account overflow.</p>\n\n<p>It's a bit odd that you throw an Exception for some errors but return an error value for others. Since you're writing Java rather than C, favour throwing exceptions for exceptional cases.</p>\n\n<pre><code> static Triangle getType(int a, int b, int c)\n {\n if(a&lt;=0||b&lt;=0||c&lt;=0)\n throw new IllegalArgumentException(\"Length of sides cannot be equal to or less than zero\");\n\n int max = Math.max(Math.max(a, b), c); // Or use :? if you prefer\n if (max == a)\n checkTriangleInequality(a, b, c);\n else if (max == b)\n checkTriangleInequality(b, a, c);\n else checkTriangleInequality(c, a, b);\n\n if(a==b&amp;&amp;b==c)\n return Triangle.EQUILATERAL;\n else if((a==b)||(b==c)||(c==a))\n return Triangle.ISOSCELES;\n else return Triangle.SCALENE;\n }\n\n private static void checkTriangleInequality(int max, int x, int y)\n {\n // Assume that we've already checked all three are &gt; 0.\n // Therefore if x + y &lt; 0 the sum overflowed and is greater than max.\n if (x + y &gt; 0 &amp;&amp; x + y &lt;= max)\n throw new IllegalArgumentException(\"Triangle inequality violated\");\n }\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-11-11T18:18:47.997", "Id": "29443", "Score": "0", "body": "Thanks for the input. How would you deal with overflow ?" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-11-11T23:07:11.680", "Id": "29456", "Score": "0", "body": "@Phoenix, see the comment in `checkTriangleInequality`." } ], "meta_data": { "CommentCount": "2", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-11-11T17:27:33.860", "Id": "18465", "ParentId": "18463", "Score": "3" } }, { "body": "<p>You could encapsulate the conditions in a <code>PotentialTriangle</code> class. Note that the fields are of type <code>long</code> to avoid overflow when calculating whether triangle inequality is violated.</p>\n\n<pre><code>public class PotentialTriangle {\n private final long a, b, c;\n\n public PotentialTriangle(int sideA, int sideB, int sideC) {\n a = sideA;\n b = sideB;\n c = sideC;\n }\n\n public boolean isAnySideTooShort() {\n return a &lt;= 0 || b &lt;= 0 || c &lt;= 0;\n }\n\n public boolean violatesTriangleInequality() {\n return a &gt; b + c || b &gt; a + c || c &gt; a + b;\n }\n\n public boolean areSidesEqual() {\n return a == b &amp;&amp; b == c;\n }\n\n public boolean areAtLeastTwoSidesEqual() {\n return a == b || b == c || c == a;\n }\n}\n</code></pre>\n\n<p>This would vastly simplify your enum selection code, which I would put directly into the enum:</p>\n\n<pre><code>public enum TriangleType {\n ISOSCELES,\n EQUILATERAL,\n SCALENE;\n\n public static TriangleType ofPotentialTriangle(PotentialTriangle triangle) {\n throwIf(triangle.isAnySideTooShort(), \n \"Length of sides cannot be equal to or less than zero\");\n throwIf(triangle.violatesTriangleInequality(), \n \"Sum of any two sides must be larger than the remaining side\");\n\n if (triangle.areSidesEqual()) {\n return EQUILATERAL;\n }\n if (triangle.areAtLeastTwoSidesEqual()) {\n return ISOSCELES;\n }\n return SCALENE;\n }\n\n private static void throwIf(boolean condition, String message) {\n if (condition) {\n throw new IllegalArgumentException(message);\n }\n }\n}\n</code></pre>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-11-11T18:37:10.530", "Id": "18467", "ParentId": "18463", "Score": "6" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-11-11T16:57:39.390", "Id": "18463", "Score": "8", "Tags": [ "java" ], "Title": "Determining triangle type from three integer inputs" }
18463
<p>I'm looking for a good and easy to use solution for creating MultiSelectLists in MVC for many-to-many relationships.</p> <p>I have this following example code and it works fine, but it just takes a lot of code. It would be cool if it were shorter, smarter, or even made generic somehow, so that it's easy to create <code>MultiSelectList</code>s in future projects.</p> <p><strong>My Database using Entity Framework Code First:</strong></p> <p>Books, and authors, where one book, can have multiple authors.</p> <pre><code>public class DataContext : DbContext { public DbSet&lt;Book&gt; Books { get; set; } public DbSet&lt;Author&gt; Authors { get; set; } } public class Book { public int Id { get; set; } public string Name { get; set; } //Allows multiple authors for one book. public virtual ICollection&lt;Author&gt; Authors { get; set; } } public class Author { public int Id { get; set; } public string Name { get; set; } [NotMapped] public int[] SelectedBooks { get; set; } public virtual ICollection&lt;Book&gt; Books { get; set; } } </code></pre> <p><strong>Controller</strong></p> <pre><code> public ActionResult Edit(int id = 0) { Author author = db.Authors.Find(id); if (author == null) { return HttpNotFound(); } ViewData["BooksList"] = new MultiSelectList(db.Books, "Id", "Name", author.Books.Select(x =&gt; x.Id).ToArray()); return View(author); } [HttpPost] public ActionResult Edit(Author author) { ViewData["BooksList"] = new MultiSelectList(db.Books, "Id", "Name", author.SelectedBooks); if (ModelState.IsValid) { //Update all the other values. Author edit = db.Authors.Find(author.Id); edit.Name = auther.Name; //------------ //Make adding items possible if (edit.Books == null) edit.Books = new List&lt;Book&gt;(); //Remove the old, add the new, instead of finding out what to remove, and what to add, and what to leave be. foreach (var item in edit.Books.ToList()) { edit.Books.Remove(item); } foreach (var item in author.SelectedBooks) { edit.Books.Add(db.Books.Find(item)); } //------------- // This is the code i want to simplify // Would be cool with a generic extention method like this: // db.ParseNewEntities(edit.Books, author.SelectedBooks); // I just don't know how to code it. db.SaveChanges(); return RedirectToAction("Index"); } return View(author); } </code></pre> <p><strong>View</strong></p> <pre><code> @Html.ListBox("SelectedBooks",(MultiSelectList)ViewData["BooksList"]) </code></pre>
[]
[ { "body": "<p>Rather than using ViewData I might consider using ViewBag (if on MVC 3 and above) or even wrapping Author within a ViewModel. That what you won't need the cast on the view (if using a viewModel).</p>\n\n<p>Otherwise your MultiSelectList code is only one line. Don't see you getting much better than that :)</p>\n\n<p>Your viewmodel might look like</p>\n\n<pre><code>public class AuthorViewModel \n{\n public Author BookAuthor { get; set; }\n public MultiSelectList BookList { get; set; }\n}\n\n[HttpGet]\npublic ActionResult Edit(int id = 0)\n{\n Author author = db.Authors.Find(id);\n if (author == null)\n {\n return HttpNotFound();\n }\n\n var viewModel = new AuthorViewModel \n {\n BookAuthor = author;\n BookList = new MultiSelectList(db.Books, \"Id\", \"Name\", author.Books.Select(x =&gt; x.Id).ToArray());\n }\n\n return View(viewModel);\n}\n</code></pre>\n\n<p>Your view will need to be typed to the view model and you could then write</p>\n\n<pre><code>Html.ListBox(\"SelectedBooks\",Model.BookList);\n</code></pre>\n\n<p>I'm not 100% sure then if you need to re-bind it back on the post if there is a problem. If you do, I would consider doing that after the Model.IsValid unless of course your \"Index\" action usings the ViewData[\"BookList\"] value?</p>\n\n<p>EDIT:\nOk, what about this then.</p>\n\n<pre><code> internal class BookEqualityComparer : IEqualityComparer&lt;Book&gt;\n {\n public bool Equals(Book x, Book y)\n {\n return x.Id == y.Id;\n }\n\n public int GetHashCode(Book obj)\n {\n return obj.GetHashCode();\n }\n }\n</code></pre>\n\n<p>Then your code in the Post will be:</p>\n\n<pre><code> // Take the values common to both lists based on the EqualityComparer\n edit.Books.Union(author.SelectedBooks, new BookEqualityComparer ());\n</code></pre>\n\n<p>And I would consider making the Books DbSet lazy loaded.</p>\n\n<pre><code>public class DataContext : DbContext\n{\n private DbSet&lt;Book&gt; _books;\n public DbSet&lt;Book&gt; Books \n { \n get { return _books ?? (_book = new DbSet&lt;Book&gt;()); } // TBH not 100% sure you can set DbSet like this but worth a shot \n set { _books = value; } \n }\n\n public DbSet&lt;Author&gt; Authors { get; set; }\n}\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-11-11T21:41:02.587", "Id": "29450", "Score": "0", "body": "True, but i actually don't mind casting the values, the real is in the [HttpPost] method.. I've updated the question with some inline comments to show you what part i'm interested in shortening :)" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-11-11T22:04:57.420", "Id": "29451", "Score": "0", "body": "@BjarkeCK Union might be an option you could consider. I've updated my answer for it's usage" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-11-11T22:11:15.613", "Id": "29452", "Score": "0", "body": "Wow there's a lot of unfamiliar code there, lazy load and IEqualityComparer. i willd need to do some research on those, thanks :)" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-11-11T22:30:45.673", "Id": "29454", "Score": "0", "body": "But i can see that it is not generic, can you make it generic ?" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-11-11T22:31:38.853", "Id": "29455", "Score": "0", "body": "Instead of IEqualityComparer<Book> just go IEqualityComparer<T> ? I'll research, then ask.. :p" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-11-12T19:49:54.137", "Id": "29520", "Score": "0", "body": "@BjarkeCK Just realised that Lazy might not work in this instance as you can't set the variable. However is still good reading to know it's around. Updated my code slightly" } ], "meta_data": { "CommentCount": "6", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-11-11T20:37:58.250", "Id": "18472", "ParentId": "18466", "Score": "3" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-11-11T18:31:02.257", "Id": "18466", "Score": "6", "Tags": [ "c#", ".net", "mvc", "entity-framework", "asp.net-mvc-4" ], "Title": "ListBox for a many-to-many relationship" }
18466
<p>I wrote some code to validate a form, I'm using live validation, as the user types, here is the snippet that I wrote just for the live validation, but I think I'm repeating too much and I'm looking for some advices:</p> <pre><code> $('form input').focus(function(){ var inp = $(this).attr('name'); switch(inp) { case 'password2': var theIn = $(this).parent().prev().find('input'); if(!theIn.val() != '') { theIn.addClass('error'); }else{ theIn.removeClass('error'); } var theInp = $(this).parent().prevAll().find('input,select'); theInp.each(function(){ if((!$(this).val()) || ($(this).val() == '-1')) { $(this).addClass('error'); }else{ $(this).removeClass('error'); } }); break; default: //Find all previous inputs and see if they are OK var theInp = $(this).parent().prevAll().find('input,select'); theInp.each(function(){ if((!$(this).val()) || ($(this).val() == '-1')) { $(this).addClass('error'); }else{ $(this).removeClass('error'); } }); } }); /* * Register front on keypress */ $('form input,form select').each(function(){ //Select &lt;select&gt; $(this).change(function(){ if($(this).val() == '-1') { $(this).addClass('error'); }else{ $(this).removeClass('error'); } }); $(this).keyup(function(e){ var type = $(this).attr('name'); $(this).parent().find('span.preloader').css('visibility','hidden'); switch(type) { case 'email': var pattern = /^[-a-z0-9~!$%^&amp;*_=+}{\'?]+(\.[-a-z0-9~!$%^&amp;*_=+}{\'?]+)*@([a-z0-9_][-a-z0-9_]*(\.[-a-z0-9_]+)*\.(aero|arpa|biz|com|coop|edu|gov|info|int|mil|museum|name|net|org|pro|travel|mobi|[a-z][a-z])|([0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}))(:[0-9]{1,5})?$/i; if(!$(this).val().match(pattern)) { $(this).addClass('error'); }else{ $(this).removeClass('error'); } break; case 'password2': if($(this).val() != $(this).parent().prev().find('input').val()) { $(this).addClass('error'); $(this).parent().prev().find('input').addClass('error'); }else{ $(this).removeClass('error'); $(this).parent().prev().find('input').removeClass('error'); } break; case 'password': if($(this).val() == $(this).parent().next().find('input').val()) { $(this).parent().next().find('input').removeClass('error'); $(this).removeClass('error'); }else{ $(this).addClass('error'); } return true; break; default: if((!$(this).val()) || ($(this).val() == '-1')) { $(this).addClass('error'); }else{ $(this).removeClass('error'); } } }); }); </code></pre>
[]
[ { "body": "<p>Overall, I see the following issues with your code</p>\n\n<ul>\n<li>It's coupled way to tightly to the markup</li>\n<li>It's overly complex</li>\n<li>You call <code>$(this)</code> again and again without ever caching the result</li>\n<li>It's repetitive</li>\n</ul>\n\n<p>I won't be posting fully revised code, as there's a lot I'd do differently. Instead, I'll try to explain the steps you could take.</p>\n\n<p>Right now, you're relying on the markup <em>never, ever changing</em>. For instance, you're using <code>$(this).parent().prev().find('input')</code> to find the other password field, but if the markup changes just slightly, your code will no longer find the right input. You'd have to change your code each time you change your markup. Obviously, that's not very maintainable.</p>\n\n<p>You're doing a similar thing to find all other inputs/selects in the form - again, this will break if the markup changes.</p>\n\n<p>Instead, do something like</p>\n\n<pre><code>$(\"form\").each(function () {\n var form = $(this),\n fields = form.find(\"input, select\");\n\n // ... everything here has access to the form and fields variables\n});\n</code></pre>\n\n<p>Or at the very least use <code>$(this).closest(\"form\").find(\"input, select\")</code></p>\n\n<p>In either case, you greatly reduce the coupling between markup and code.</p>\n\n<p>Also, do not rely an input's name to tell you its intended type. A name can be anything. For instance, you could have a field called \"recipient\" which should be an email-address, but then you'd have to update your code to look for that.</p>\n\n<p>In the case of email-addresses specifically, HTML5 has a <code>type</code>-attribute value you can use:</p>\n\n<pre><code>&lt;input name=\"whatever\" type=\"email\"&gt;\n</code></pre>\n\n<p>Your other checks seem to be about checking presence of any value - i.e. required fields. Again, HTML5 has an attribute for that:</p>\n\n<pre><code>&lt;input name=\"whatever\" type=\"email\" required&gt;\n</code></pre>\n\n<p>So now, your code can check the input's type to determine it's intended type, and check for the required attribute to determine if it's required (seems logical, right?)</p>\n\n<p>Depending on the browser, it might actually \"help out\" should your validation fail. For instance, Chrome respects and enforces the <code>email</code> type, and so requires the user to type an email-address.</p>\n\n<p>Incidentally, it makes more sense to use an empty string <code>\"\"</code> as the nothing-selected value in the <code>select</code> element. -1 <em>is</em> a value, whereas an empty string is, well, an empty string; no value at all. JavaScript itself considers <code>\"\" == false</code> but considers <code>-1 == true</code>.</p>\n\n<p>Last up is the password and password repeat. Instead of the complex jQuery selector chain to find the other password field, use HTML5's <code>data-*</code> attributes to say what you should check against. For instance:</p>\n\n<pre><code>&lt;input id=\"password\" type=\"password\" data-match=\"password_confirmation\"&gt;\n\n&lt;input id=\"password_confirmation\" type=\"password\" data-match=\"password\"&gt;\n</code></pre>\n\n<p>Now each element can tell you what its counterpart is, regardless of how your markup is put together.</p>\n\n<p>As for structure and repetition: Don't use the <code>switch</code> statement for big blocks of code. It's hard to read, and hard to maintain. Instead, DRY (Don't Repeat Yourself) you code, by breaking it into functions. For instance, you could have functions like <code>checkEmail</code> and <code>checkSelection</code> that you can pass an element to, and they'll report true or false, depending on element's value.</p>\n\n<p>Do the same for the bit of code that adds the <code>error</code> class: Have a function, like, say</p>\n\n<pre><code>function markElement(element, valid) {\n if(valid) {\n $(element).removeClass(\"error\");\n } else {\n $(element).addClass(\"error\");\n }\n}\n</code></pre>\n\n<p>Now you have some more generic building blocks.</p>\n\n<p>Lastly, don't do all the validation logic in the event handlers themselves. The validation logic is the same regardless of how/why something needs to be validated. Instead, write the validation code separately and use the event handlers to call it.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-11-13T01:52:47.860", "Id": "18521", "ParentId": "18468", "Score": "3" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-11-11T19:02:22.217", "Id": "18468", "Score": "1", "Tags": [ "javascript", "jquery", "html" ], "Title": "Code refactory for a form validation" }
18468
<p>I have a small function for filtering data from users. I'd like a review on logical mistakes I've made and if I'm somewhat protected using it.</p> <pre><code>public static function filtru($str, $filtre = []){ if(is_array($str)){//verifica daca datele trimise spre curatare sant array $str_curat = []; foreach($str as $key =&gt; $value){//selectam fiecare valoare din array-ul trimis spre curatare foreach($filtre as $fitru){//aplicam fiecare filtru, daca se folosesc mai multe switch($fitru){ case 'trim': $value = htmlentities(trim(strip_tags($value)), ENT_QUOTES, 'utf-8'); break; case 'int': $value = intval($value); break; case 'nu': $text = $value;$striptags = true; $search = ["40","41","58","65","66","67","68","69","70", "71","72","73","74","75","76","77","78","79","80","81", "82","83","84","85","86","87","88","89","90","97","98", "99","100","101","102","103","104","105","106","107", "108","109","110","111","112","113","114","115","116", "117","118","119","120","121","122" ]; $replace = ["(",")",":","a","b","c","d","e","f","g","h", "i","j","k","l","m","n","o","p","q","r","s","t","u", "v","w","x","y","z","a","b","c","d","e","f","g","h", "i","j","k","l","m","n","o","p","q","r","s","t","u", "v","w","x","y","z" ]; $entities = count($search); for ($i=0; $i &lt; $entities; $i++) { $text = preg_replace("#(&amp;\#)(0*".$search[$i]."+);*#si", $replace[$i], $text); } $text = preg_replace('#(&amp;\#x)([0-9A-F]+);*#si', "", $text); $text = preg_replace('#(&lt;[^&gt;]+[/\"\'\s])(onmouseover|onmousedown|onmouseup|onmouseout|onmousemove|onclick|ondblclick|onfocus|onload|xmlns)[^&gt;]*&gt;#iU', "&gt;", $text); $text = preg_replace('#([a-z]*)=([\`\'\"]*)script:#iU', '$1=$2nojscript...', $text); $text = preg_replace('#([a-z]*)=([\`\'\"]*)javascript:#iU', '$1=$2nojavascript...', $text); $text = preg_replace('#([a-z]*)=([\'\"]*)vbscript:#iU', '$1=$2novbscript...', $text); $text = preg_replace('#(&lt;[^&gt;]+)style=([\`\'\"]*).*expression\([^&gt;]*&gt;#iU', "$1&gt;", $text); $text = preg_replace('#(&lt;[^&gt;]+)style=([\`\'\"]*).*behaviour\([^&gt;]*&gt;#iU', "$1&gt;", $text); if ($striptags) { do { $thistext = $text; $text = preg_replace('#&lt;/*(applet|meta|xml|blink|link|style|script|embed|object|iframe|frame|frameset|ilayer|layer|bgsound|title|base|body)[^&gt;]*&gt;#i', "", $text); } while ($thistext != $text); } $value = $text; $value = preg_replace('#(alert|cmd|passthru|eval|exec|expression|system|fopen|fsockopen|file|file_get_contents|file_put_contents|readfile|unlink|shell_exec)(\s*)\((.*?)\)#si', "\\1\\2&amp;#40;\\3&amp;#41;", $value); break; default: $value = $fitru($value); }// switch }//bucla pt fiecare filtru $str_curat[$key] = $value; }//bucla pt fiecare valoare }else{ foreach($filtre as $fitru){ switch($fitru){ case 'trim': $str = htmlentities(trim(strip_tags($str)), ENT_QUOTES, 'utf-8'); break; case 'int': $str = intval($str); break; case 'nu': $text = $str;$striptags = true; $search = ["40","41","58","65","66","67","68","69","70", "71","72","73","74","75","76","77","78","79","80","81", "82","83","84","85","86","87","88","89","90","97","98", "99","100","101","102","103","104","105","106","107", "108","109","110","111","112","113","114","115","116", "117","118","119","120","121","122" ]; $replace = ["(",")",":","a","b","c","d","e","f","g","h", "i","j","k","l","m","n","o","p","q","r","s","t","u", "v","w","x","y","z","a","b","c","d","e","f","g","h", "i","j","k","l","m","n","o","p","q","r","s","t","u", "v","w","x","y","z" ]; $entities = count($search); for ($i=0; $i &lt; $entities; $i++) { $text = preg_replace("#(&amp;\#)(0*".$search[$i]."+);*#si", $replace[$i], $text); } $text = preg_replace('#(&amp;\#x)([0-9A-F]+);*#si', "", $text); $text = preg_replace('#(&lt;[^&gt;]+[/\"\'\s])(onmouseover|onmousedown|onmouseup|onmouseout|onmousemove|onclick|ondblclick|onfocus|onload|xmlns)[^&gt;]*&gt;#iU', "&gt;", $text); $text = preg_replace('#([a-z]*)=([\`\'\"]*)script:#iU', '$1=$2nojscript...', $text); $text = preg_replace('#([a-z]*)=([\`\'\"]*)javascript:#iU', '$1=$2nojavascript...', $text); $text = preg_replace('#([a-z]*)=([\'\"]*)vbscript:#iU', '$1=$2novbscript...', $text); $text = preg_replace('#(&lt;[^&gt;]+)style=([\`\'\"]*).*expression\([^&gt;]*&gt;#iU', "$1&gt;", $text); $text = preg_replace('#(&lt;[^&gt;]+)style=([\`\'\"]*).*behaviour\([^&gt;]*&gt;#iU', "$1&gt;", $text); if ($striptags) { do { $thistext = $text; $text = preg_replace('#&lt;/*(applet|meta|xml|blink|link|style|script|embed|object|iframe|frame|frameset|ilayer|layer|bgsound|title|base|body)[^&gt;]*&gt;#i', "", $text); } while ($thistext != $text); } $str = $text; $str = preg_replace('#(alert|cmd|passthru|eval|exec|expression|system|fopen|fsockopen|file|file_get_contents|file_put_contents|readfile|unlink|shell_exec)(\s*)\((.*?)\)#si', "\\1\\2&amp;#40;\\3&amp;#41;", $str); break; default: $str = $fitru($value); }// switch }//foreach pt filtre $str_curat = $str; } return $str_curat; }//end filtru </code></pre>
[ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-11-11T23:12:47.867", "Id": "29458", "Score": "3", "body": "This function isn't small; by modern standards, it's huge and should be split up." } ]
[ { "body": "<ul>\n<li>Your function should be broken into many more functions. Each different type of escaping should be its own function.</li>\n<li>You should either use separate functions where the array version calls the non-array version, or youo should try to fold your array and non array logic into one\n<ul>\n<li><code>$wasArray = is_array($str); if (!$wasArray) { $str = array($str); } foreach ($str as $s) { ... } return ($wasArray) ? $str : array_shift($str);</code></li>\n</ul></li>\n<li>Your <code>trim</code> method is a lie -- it doesn't <em>just</em> trim. What if you want to trim without html escaping?</li>\n<li>If you did leave them all in one method, consider using class constants instead of strings to control the behavior. That's a lot less error prone, and it makes it easier to trace usage through code (and if you rename something later, it will be a million times easier).</li>\n<li>What is your <code>nu</code> sanitation doing? It's like it's processing HTML, PHP and JavaScript?\n<ul>\n<li>With HTML, you're typically better off with a whitelist than trying to sanitize, and then escaping everything else.</li>\n<li>With PHP, you're typically better off just not running code that you don't 100% trust</li>\n<li>JS falls into the HTML category. If HTML is whitelisted, it should be impossible for a user to get JS through.</li>\n</ul></li>\n</ul>\n\n<p>You should consider if you really need all of this. In a lot of situations, it's sufficient to simply escape and not sanitize (though one could argue that escape is a form of sanitizing).</p>\n\n<p>(There are of course situations where you really do have to process the hell out of user input though. Consider the StackExchange questions/answers/comments. They allow a very limited subset of HTML which means that their processor has to be aware of what to escape, what to leave alone.)</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-11-12T10:43:28.567", "Id": "29477", "Score": "0", "body": "I will remove each filter as a separate function, i avoid using constants knowing that they are slower. Nice explanation with array_shift i'll use it.I need to rethink all logic. Thank you very much for response" } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-11-11T23:13:56.163", "Id": "18475", "ParentId": "18471", "Score": "3" } }, { "body": "<ul>\n<li>First, break your function into pieces. One function should be doing one thing and correctly.</li>\n<li>Try to give functions, variables a meaningful name. Here the function name \"filteru\" doesn't make any sense. same goes for \"$str_curat\".</li>\n<li>you have huge if block \n<pre>\nif (is_array($str)) {\n // lot of code...\n}\n</pre>\nInstead you can write a simple check at the beginning of the function\n<pre>\nif (!is_array($str)) { return; } \n// rest of the code goes here...\n</pre>\nThis way you can avoid a huge if block.</li>\n<li>At the end of the curly braces you have comments like \n<pre> }// switch </pre>\n<pre> }//foreach pt filtre </pre>\n<pre> }//end filtru </pre>\nThese are useless.</li>\n<li>you have two foreach blocks. one foreach inside another foreach\n<pre>\nforeach($str as $key => $value) {\n foreach($filtre as $fitru) {\n // code ...\n }\n}\n</pre>\nTry rewriting the logic so that you can avoid this nested loop.</li>\n</ul>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-11-12T07:18:29.920", "Id": "29470", "Score": "1", "body": "The variable names and comments *do* make sense in romanian." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-11-12T07:30:15.607", "Id": "29471", "Score": "1", "body": "Then It is fine if the variable names make sense in romanian. For the comments, what I wanted to say is that it is useless to comment the end of curly braces the way it is done here - \"} //switch\", \"}//foreach pt filtre\" etc" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-11-12T10:50:49.330", "Id": "29479", "Score": "0", "body": "I used a poorly text editor when i made the function. It didn't had matching curly braces. I forgot to remove comments\nI'll rethink the function(logic). str_curat = clean string" } ], "meta_data": { "CommentCount": "3", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-11-12T03:50:57.797", "Id": "18480", "ParentId": "18471", "Score": "1" } }, { "body": "<h2>DRY - Write less handle more</h2>\n<p>You can make your function half the size by designing it to work with scalar vars only, and handling arrays with a loop:</p>\n<pre><code>public static function filtru($var) {\n if (is_array($var)) {\n foreach ($var as &amp;$val) {\n $val = static::filtru($val);\n } \n return $var;\n } \n\n // $var is not an array - it is number/string etc.\n ...\n\n return $var; \n}\n</code></pre>\n<p>In the above example, an array, a scalar or even a nested array can all be handled by the same function.</p>\n<h2>Use PHP's built in filters</h2>\n<p>Rather than write your own filters, you're better off using <a href=\"http://www.php.net/manual/en/filter.examples.sanitization.php\" rel=\"nofollow noreferrer\">PHP's sanitization filters</a>. For common cases, your code becomes therefore (assuming this is implemented):</p>\n<pre><code>$arrayIntOut = Foo::filtru($arrayMixedIn, FILTER_SANITIZE_NUMBER_INT);\n</code></pre>\n<p>But, especially with the above example, it's more work to use the filtru function than it is to just write:</p>\n<pre><code>$arrayIntOut = array_map('intval', $arrayMixedIn);\n</code></pre>\n<p>Putting all your logic in one place is not necessarily the best idea, when the alternative is to write concise (and more efficient) code using php's function directly in functions. As such, consider 'just' using PHP instead of wrapping php functions in some more logic.</p>\n<h2>Make &quot;nu&quot; a separate function</h2>\n<p>Each case you want to handle should really be a protected specific function. Once you do that, consider deleting any functions that are just one line of code as it's better to just use php's own functions. The 'nu' function however, is likely to warrants it's own function.</p>\n<p>It looks like the main purpose is to strip out XSS attacks. Unless you have exhaustive tests for this logic, it is very likely it doesn't cater for all possibilities - therefore make it a separate function and if you haven't already it'd be in your interest to write some tests to at least cover <a href=\"https://www.owasp.org/index.php/XSS_Filter_Evasion_Cheat_Sheet\" rel=\"nofollow noreferrer\">the most common XSS attacks</a>.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-11-12T11:04:00.357", "Id": "29480", "Score": "0", "body": "that's a really long list :D and it's just the common ones" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-11-12T11:47:50.220", "Id": "29482", "Score": "0", "body": "actually it's probably quite complete being owasp, but there can never truly be a complete xss list as new attacks are found/invented as time goes by." } ], "meta_data": { "CommentCount": "2", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-11-12T10:43:44.977", "Id": "18488", "ParentId": "18471", "Score": "2" } } ]
{ "AcceptedAnswerId": "18488", "CommentCount": "1", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-11-11T20:08:33.770", "Id": "18471", "Score": "4", "Tags": [ "php", "security" ], "Title": "Filtering data from users" }
18471
<p>So I have a function which creates a Playlist object. Currently, this function accepts two paramaters: id and name. However, it also exposes a method called 'loadData' which can set the entire object after construction. I'm realizing this is a poor way to go about things and would like to modify my code such that the constructor accepts a config object.</p> <p>I am wondering a couple of things:</p> <ul> <li>How can I prevent a caller from extending my Playlist object with additional, unintended properties? Should I even worry about this?</li> <li>I could use some advice on how to best consume my config object. Should I just called jQuery extend?</li> </ul> <p>Here's what my code looks like before refactoring:</p> <pre><code>define(['yt_helper', 'song_builder'], function(ytHelper, songBuilder){ //Maintains a list of song objects as an array and exposes methods to affect those objects to Player. return function(id, name) { "use strict"; var playlist = { id: id ? id : Helpers.generateGuid(), title: name ? name : "New Playlist", selected: false, shuffledSongs: [], songHistory: [], relatedVideos: [], songs: [] }; return { loadData: function(data){ playlist = data; } }; }; }; //TODO: Just pass in the object and extend a playlist. //Load default playlists. var grizPlaylist = new playlistFunc(); grizPlaylist.loadData({ id:"d6103404-1568-4d18-922b-058656302b22", title:"GRiZ", selected:true, shuffledSongs:[{"id":"4696c63f-8dae-4803-8e19-2b89c339f478","videoId":"CI-p4OkT3qE","url":"http://youtu.be/CI-p4OkT3qE","title":"Griz - Smash The Funk | Mad Liberation (2/12)","duration":"411"},{"id":"2ef29e04-d038-44f9-b3a4-ad163bbec459","videoId":"G5w7MIKwSO0","url":"http://youtu.be/G5w7MIKwSO0","title":"GRiZ - Vision of Happiness [HD]","duration":"198"},{"id":"27492b00-8230-48c4-90b9-237be3f07502","videoId":"xvtNnCs6EFY","url":"http://youtu.be/xvtNnCs6EFY","title":"GRiZ - Wheres The Love?","duration":"374"},{"id":"c278ea8e-6877-4658-a017-0a6ea5ccbff3","videoId":"0Gz96ACc45U","url":"http://youtu.be/0Gz96ACc45U","title":"Griz - Mr. B (feat. Dominic Lalli) | Mad Liberation (7/12)","duration":"349"}], songHistory:[], songs:[{"id":"a207502e-e68e-40e2-a5b1-a94e638a731b","videoId":"3AXu6l3GOYE","url":"http://youtu.be/3AXu6l3GOYE","title":"Griz - Blastaa | Mad Liberation (4/12)","duration":"269"},{"id":"4696c63f-8dae-4803-8e19-2b89c339f478","videoId":"CI-p4OkT3qE","url":"http://youtu.be/CI-p4OkT3qE","title":"Griz - Smash The Funk | Mad Liberation (2/12)","duration":"411"},{"id":"c278ea8e-6877-4658-a017-0a6ea5ccbff3","videoId":"0Gz96ACc45U","url":"http://youtu.be/0Gz96ACc45U","title":"Griz - Mr. B (feat. Dominic Lalli) | Mad Liberation (7/12)","duration":"349"},{"id":"27492b00-8230-48c4-90b9-237be3f07502","videoId":"xvtNnCs6EFY","url":"http://youtu.be/xvtNnCs6EFY","title":"GRiZ - Wheres The Love?","duration":"374"},{"id":"2ef29e04-d038-44f9-b3a4-ad163bbec459","videoId":"G5w7MIKwSO0","url":"http://youtu.be/G5w7MIKwSO0","title":"GRiZ - Vision of Happiness [HD]","duration":"198"}] }); </code></pre> <p>Here's how I think it should look afterward:</p> <pre><code>define(['yt_helper', 'song_builder'], function(ytHelper, songBuilder){ //Maintains a list of song objects as an array and exposes methods to affect those objects to Player. return function(config) { "use strict"; var playlist = $.extend({ id: Helpers.generateGuid(), title: "New Playlist", selected: false, shuffledSongs: [], songHistory: [], relatedVideos: [], songs: [] }, config); } } var grizPlaylist = new playlistFunc({ id:"d6103404-1568-4d18-922b-058656302b22", title:"GRiZ", selected:true, shuffledSongs:[{"id":"4696c63f-8dae-4803-8e19-2b89c339f478","videoId":"CI-p4OkT3qE","url":"http://youtu.be/CI-p4OkT3qE","title":"Griz - Smash The Funk | Mad Liberation (2/12)","duration":"411"},{"id":"2ef29e04-d038-44f9-b3a4-ad163bbec459","videoId":"G5w7MIKwSO0","url":"http://youtu.be/G5w7MIKwSO0","title":"GRiZ - Vision of Happiness [HD]","duration":"198"},{"id":"27492b00-8230-48c4-90b9-237be3f07502","videoId":"xvtNnCs6EFY","url":"http://youtu.be/xvtNnCs6EFY","title":"GRiZ - Wheres The Love?","duration":"374"},{"id":"c278ea8e-6877-4658-a017-0a6ea5ccbff3","videoId":"0Gz96ACc45U","url":"http://youtu.be/0Gz96ACc45U","title":"Griz - Mr. B (feat. Dominic Lalli) | Mad Liberation (7/12)","duration":"349"}], songHistory:[], songs:[{"id":"a207502e-e68e-40e2-a5b1-a94e638a731b","videoId":"3AXu6l3GOYE","url":"http://youtu.be/3AXu6l3GOYE","title":"Griz - Blastaa | Mad Liberation (4/12)","duration":"269"},{"id":"4696c63f-8dae-4803-8e19-2b89c339f478","videoId":"CI-p4OkT3qE","url":"http://youtu.be/CI-p4OkT3qE","title":"Griz - Smash The Funk | Mad Liberation (2/12)","duration":"411"},{"id":"c278ea8e-6877-4658-a017-0a6ea5ccbff3","videoId":"0Gz96ACc45U","url":"http://youtu.be/0Gz96ACc45U","title":"Griz - Mr. B (feat. Dominic Lalli) | Mad Liberation (7/12)","duration":"349"},{"id":"27492b00-8230-48c4-90b9-237be3f07502","videoId":"xvtNnCs6EFY","url":"http://youtu.be/xvtNnCs6EFY","title":"GRiZ - Wheres The Love?","duration":"374"},{"id":"2ef29e04-d038-44f9-b3a4-ad163bbec459","videoId":"G5w7MIKwSO0","url":"http://youtu.be/G5w7MIKwSO0","title":"GRiZ - Vision of Happiness [HD]","duration":"198"}] }); </code></pre>
[ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-11-12T12:29:18.997", "Id": "29489", "Score": "2", "body": "Why is it important to prevent `a caller from extending my Playlist object with additional, unintended properties`?" } ]
[ { "body": "<p>You could use <code>||</code> instead of <code>$.extend</code>. eg:</p>\n\n<pre><code>id: config.id || Helpers.generateGuid(),\n</code></pre>\n\n<p>That has the benefit of not creating properties you don't use.</p>\n\n<p>Also, did you strip out some code? Because it seems like all you're doing is storing a reference to an object. Why not just use the object?</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-11-12T09:50:54.310", "Id": "18486", "ParentId": "18474", "Score": "1" } }, { "body": "<p>As for your question:</p>\n\n<blockquote>\n <p>How can I prevent a caller from extending my Playlist object with additional, unintended properties? Should I even worry about this?</p>\n</blockquote>\n\n<p>I wouldn't worry about this too much. If you don't want the API consumer to inject additional properties through config object, use the construct st-boost suggested. If you don't want the consumer to access the Playlist internals at all, contain it in a closure and only expose functions that do work on this object. </p>\n\n<p>That said, however, JavaScript's properties as a language encourage a different mindset than the one you might have when working with languages that have extensive access control capabilities, like Java or C#. There, it is considered the API designer's responsibility to prevent any possible misuse of the API. In JavaScript, the mindset is more \"junk in, junk out\", and it's more of the caller's responsibility to ensure that he's not doing anything stupid, simply because JavaScript gives him more power to do stupid things.</p>\n\n<p>Looking back at your problem, you might have grounds to worry if you're iterating over all properties of the Playlist object for some reason and your code might break if there are some unaccounted for properties. I don't see a case for something like that here, however.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-11-18T10:26:12.373", "Id": "18759", "ParentId": "18474", "Score": "2" } } ]
{ "AcceptedAnswerId": "18759", "CommentCount": "1", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-11-11T22:39:49.233", "Id": "18474", "Score": "0", "Tags": [ "javascript", "jquery", "require.js" ], "Title": "Refactoring a constructor to accept a config object" }
18474
<p>I'm a Python newbie and I'd like to know how I could clean this up/optimize it (but nothing too advanced, please).</p> <p>As far as I know, it's working as it should, but if you see any errors then please point it out! This is a numerical guessing game with two symbols in front. You can pretty much see how it works by looking at the print messages.</p> <pre><code>from random import randint, choice import string maxguesses = 11 # Default number of max guesses wins = 0 losses = 0 points = 0 # Points accumulated games = 0 # Games played numguesses = 0 # Number of guesses flag = True allowed = list(string.digits + '+' + '*') guesses = '' # Track wrong guesses, resets every game when formula is regenerated letters = set() partial = '' # Current progress of guesses def genform(): # Generate secret formula global secret, maxguesses sym = choice(['++','**','+*','*+']) # Pick operation symbols num = '' max = randint(3,9) # Set max between 3 &amp; 9 for i in range(max): # Range of max variable num = num + str(randint(0,9)) secret = sym + num # Assign secret formula maxguesses = len(secret)+2 # Max guesses based on length of formula return secret def evaluate(formula): evaluated = '' s1,s2 = secret[:2] for i in range(2,len(secret)-1): # Loop after two symbols evaluated = evaluated + secret[i] evaluated = (evaluated + s1) if not (i%2) else (evaluated + s2) # Place symbols appropriately evaluated = evaluated + secret[-1] # Put together return evaluated def takeguess(ch): global numguesses, wins, points, games, partial, guesses numguesses = numguesses + 1 # Add guess print 'Remaining Guesses: ' + str(maxguesses-numguesses) if (ch in partial) or (ch in guesses): # Check if already guessed print "\nYou've already guessed '%s'. Try again: " % ch elif ch not in secret: guesses = guesses + ch print 'Wrong, guess again.' elif ch in secret: # If in formula letters.add(ch) # Add guess to set print "\nGood guess, it's in the secret formula!" partial = ''.join([l if l in letters else '-' for l in secret]) print 'Formula so far: ' + partial if partial == secret: # If guesses are complete print 'You win!' wins = wins + 1 points = points + 2 games = games + 1 bonus = raw_input("Evaluate the formula for 10 bonus points: ") # Ask bonus question if bonus == str(eval(evaluate(secret))): # Calculate result points = points + 10 print "That's correct! +10 points." print eval(evaluate(secret)) #REMOVE AFTER play_again() else: # If bonus answer is wrong print "That's incorrect. The right answer is", eval(evaluate(secret)) play_again() def play_again(): global numguesses, guesses, partial, letters, flag letters = set() # Clear set if points &lt; 2: # Check points print "\nYou don't have enough points to play again.\nGames Played: " + str(games) + '\nPoints: ' + str(points) else: # Good to go ans = raw_input('Would you like to play again? [y/n] \n') if ans in ('yY'): numguesses = 0 guesses = '' partial = '' play() elif ans in ('nN'): flag = False print '\nOkay, goodbye.\nWins: %s \nLosses: %s \nPoints: %s' % (wins, losses, points) else: print 'Invalid input.' play_again() def play(): global points, games, losses genform() # Generate new formula print 'Unsolved formula: ' + ('-'*len(secret)) print 'You have %s guesses.' % maxguesses print secret #REMOVE AFTER while (numguesses &lt; maxguesses) and flag: # Enough guesses and run OK guess = raw_input('\nEnter a guess: ') # Receive guess if guess not in allowed: # Check if valid print '\nInvalid guess, please enter a single digit, *, or +. Try again: ' elif partial != secret: # Process guess takeguess(guess) print guesses # REMOVE AFTER if numguesses == maxguesses: # Guess limit reached points = points - 2 games = games + 1 losses = losses + 1 print '\nSorry, you lose. The answer is: ' + secret play_again() # Ask for replay return print 'Welcome to Numerical Hangman!\n' play() </code></pre>
[ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-11-11T23:47:18.563", "Id": "29459", "Score": "4", "body": "A good start would be not using globals - there is always a better way. In this case, pass more arguments and return more values." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-11-11T23:47:22.247", "Id": "29460", "Score": "3", "body": "My first suggestion is getting rid of the global variables. Is there any reason why you can't pass those as function parameters? If you need to keep more complicated state, then maybe you can create a class to represent it or use a dictionary." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-11-11T23:48:01.963", "Id": "29461", "Score": "0", "body": "I believe the phrase is *great minds think alike* ;)" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-11-12T00:19:25.173", "Id": "29462", "Score": "0", "body": "I've only learned the very basics of global variables and I don't know about alternatives. Could an example be done for one of my global variables so I can visually see what is meant?" } ]
[ { "body": "<ul>\n<li><p>Not good:</p>\n\n<pre><code>points = points - 2 # lots of this kind of code\n</code></pre>\n\n<p>Good:</p>\n\n<pre><code>points -= 2\n</code></pre></li>\n<li><p>Not good:</p>\n\n<pre><code>allowed = list(string.digits + '+' + '*')\n</code></pre>\n\n<p>Good:</p>\n\n<pre><code>allowed = string.digits + '+*' #You don't need list in this case\n</code></pre></li>\n<li><p>Not good:</p>\n\n<pre><code>max = randint(3,9)\n</code></pre>\n\n<p>Good:</p>\n\n<pre><code>_max = randint(3,9) # max is a function in standard namespace\n</code></pre></li>\n<li><p>Not good:</p>\n\n<pre><code>print 'Remaining Guesses: ' + str(maxguesses-numguesses)\n</code></pre>\n\n<p>Good:</p>\n\n<pre><code>print 'Remaining Guesses: {}'.format(maxguesses-numguesses)\n</code></pre></li>\n<li><p>Not good:</p>\n\n<pre><code>if bonus == str(eval(evaluate(secret))): # what do you mean here?\n</code></pre></li>\n<li><p>Not good:</p>\n\n<pre><code>def evaluate(formula): \n...\n</code></pre>\n\n<p>Your local var <code>formula</code> was not used in this function. Instead of this, you're using global <code>secret</code>.</p></li>\n<li><p>Not good:</p>\n\n<pre><code>genform() \n... \nreturn secret\n</code></pre>\n\n<p>You're returning <code>secret</code> in this function, but you don't use it in your app. <code>secret</code> is global anyway.</p></li>\n</ul>\n\n<p>That's a briefly view. Please read <a href=\"http://google-styleguide.googlecode.com/svn/trunk/pyguide.html\" rel=\"nofollow\">Google’s Python style guide</a>.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-11-13T14:41:17.820", "Id": "29565", "Score": "1", "body": "Some of the information at that link is outdated. For example, they advocate using `%` for string formatting when people should be using `str.format()` now. (actually, that is the only problem I saw)" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-12-14T04:34:13.087", "Id": "31369", "Score": "0", "body": "`string.digits.join` creates lots of duplicate copies of `'+*'` in the `allowed` string which, while not erroneous, is probably not what you meant. You also probably want it to be a `set`." } ], "meta_data": { "CommentCount": "2", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-11-13T10:50:04.880", "Id": "18533", "ParentId": "18476", "Score": "5" } } ]
{ "AcceptedAnswerId": "18533", "CommentCount": "4", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-11-11T23:34:37.937", "Id": "18476", "Score": "8", "Tags": [ "python", "optimization", "beginner", "game" ], "Title": "Cleaning up/optimizing numerical guessing game" }
18476
<p>I have a class that delegates some responsibilities to another helper class which is abstract. When instantiating the class the user needs to provide a pointer to a concrete instance of the abstract helper class. I'm wondering who should be responsible for deleting the helper class instance, the user, or the class itself? </p> <p>It seems to me that it is better for the class to delete the helper since it ensures that the lifetime of the helper class instance is the same as the lifetime of the class thats using it.</p> <p>P.S. I know shared pointers can help but I'd rather avoid them here.</p> <p>Specifically which is better, this:</p> <p>classifier.h</p> <pre><code>class Classifier { public: Classifier(const Trainer* trainer); Train(const RecordList&amp; training_records); ~Classifier(); private: const Trainer* trainer_; Vector parameters_; } </code></pre> <p>classifier.cpp</p> <pre><code>Classifier::Classifier(const Trainer* trainer) : trainer_(trainer); Classifier::Train(const RecordList&amp; training_records) { parameters = trainer_-&gt;UpdateParameters(training_records); } Classifier::~Classifier() { delete trainer_; } </code></pre> <p>main.cpp</p> <pre><code>int main() { Classifier classifier(new SgdTrainer()); } </code></pre> <p>Or is this better?</p> <p>classifier.h</p> <pre><code>class Classifier { public: Classifier(const Trainer* trainer); Train(const RecordList&amp; training_records); private: const Trainer* trainer_; Vector parameters_; } </code></pre> <p>classifier.cpp</p> <pre><code>Classifier::Classifier(const Trainer* trainer) : trainer_(trainer); Classifier::Train(const RecordList&amp; training_records) { parameters = trainer_-&gt;UpdateParameters(training_records); } </code></pre> <p>main.cpp</p> <pre><code>int main() { SgdTrainer trainer(); Classifier classifier(&amp;trainer); } </code></pre>
[]
[ { "body": "<p>It depends. (By the way, as things are your <code>Classifier::Train</code> function is ill-formed due to missing a return type; I'll assume <code>void</code>.)</p>\n\n<p>If you expect the value to need dynamic storage duration, use the first method, but use a smart pointer (<code>std::unique_ptr</code>, <code>boost::scoped_ptr</code> or similar). That may remove the need for an explicitly-defined destructor; if not, remember the rule of three.</p>\n\n<p>If you do not expect the value to need dynamic storage duration, use the second form. I recommend passing <code>trainer</code> by const reference, but it really doesn't matter all that much.</p>\n\n<p>If you can't decide, use the latter unless you have a compelling reason to use the former.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-11-12T03:42:53.083", "Id": "29464", "Score": "0", "body": "Thank you. Trainer itself is an abstract class (it has pure virtual methods). Can I still pass it by const reference?" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-11-12T05:08:31.213", "Id": "29465", "Score": "0", "body": "@padawan: Yes, why not?" } ], "meta_data": { "CommentCount": "2", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-11-12T03:27:40.530", "Id": "18479", "ParentId": "18477", "Score": "5" } } ]
{ "AcceptedAnswerId": "18479", "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-11-12T02:52:03.223", "Id": "18477", "Score": "2", "Tags": [ "c++", "object-oriented" ], "Title": "Ownership and deletion responsibility" }
18477
<p>Recently I had to lock collections (of type <code>List&lt;T&gt;</code>) when items were added or removed. Because several collections were used in given code instead of creating helper methods for each collection, I made an extension methods:</p> <pre><code>public static class MyExtension { public static void AddThreadSafely&lt;T&gt;(this ICollection&lt;T&gt; collection, T item) { if (collection == null) throw new ArgumentNullException("collection"); bool locked = false; try { System.Threading.Monitor.Enter(collection, ref locked); collection.Add(item); } finally { if (locked) System.Threading.Monitor.Exit(collection); } } //The same with remove } </code></pre> <p>and then simply replaced <code>Add</code> with <code>AddThreadSafely</code>.</p> <p>I like the simplicity of this solution but... What are the drawbacks of using this method? Will it be good idea to use this method of locking collections in future projects?</p>
[]
[ { "body": "<p><strong>EDIT</strong>: +1 for throwing on null in extension method. That's the right way to go.</p>\n\n<ol>\n<li>Use <a href=\"http://msdn.microsoft.com/en-us/library/dd267312.aspx\" rel=\"nofollow\"><code>BlockingCollection</code></a> (starting .Net 4) - that's what it is for.</li>\n<li>Not sure you need that flag. Why don't <code>Monitor.Enter(collection)</code>, and always <code>Monitor.Exit()</code> on the finally block?</li>\n</ol>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-11-12T11:07:36.203", "Id": "29481", "Score": "2", "body": "1. Thanks for `BlockingCollection`. 2. If collection is `null` extension method will be called because extension methods don't make virtual call (uses `call` il instruction, not `callvirt`). 4. If there were no exceptions thrown means that item was added. So, IMO, returning boolean is odd here. Thanks for idea, BTW." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-11-12T12:06:22.583", "Id": "29488", "Score": "0", "body": "I need that flag because compiler generates no-op instruction between `Enter` and `try-finally` so if lock is added and then happens exception before try block, you will never release lock so you get deadlock." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-11-12T14:09:16.023", "Id": "29495", "Score": "4", "body": "@PLB Instead of the whole `try`/`catch`, you should have just used `lock`. On .Net 4+, it compiles to exactly the same IL, with less written code and better compatibility (that overload of `Monitor.Enter()` doesn't exist in .Net 3.5)." } ], "meta_data": { "CommentCount": "3", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-11-12T10:55:44.167", "Id": "18489", "ParentId": "18483", "Score": "3" } }, { "body": "<p>I would advise against this approach, you are correct in the fact that it is simple, however it's not foolproof. There is nothing actually ensuring that someone doesn't just call <code>.Add()</code> on the collection bypassing your extension method which allows for difficult to find bugs/race conditions.</p>\n\n<p>Don't forget that all <code>Monitor.Enter</code> does is ensure that if multiple threads call <code>Monitor.Enter</code> that only 1 can <em>enter</em> a code block at a time. It doesn't prevent a caller on another thread mutating the collection if they don't call <code>Monitor.Enter</code> on the same obejct.</p>\n\n<p>You would be better off either creating a custom collection which inherits from <a href=\"http://msdn.microsoft.com/en-us/library/system.collections.collectionbase.aspx\">CollectionBase</a> and encapsulating the lock logic in there so that any caller calling <code>.Add()</code> goes through the lock and is unable to bypass it.</p>\n\n<p>Or if you are using .NET 4.0+, look at one of the collections in <a href=\"http://msdn.microsoft.com/en-us/library/system.collections.concurrent.aspx\">System.Collections.Concurrent</a> as they are designed for this sort of activity in the first place.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-11-12T12:04:51.787", "Id": "18493", "ParentId": "18483", "Score": "20" } } ]
{ "AcceptedAnswerId": "18493", "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-11-12T08:50:40.553", "Id": "18483", "Score": "12", "Tags": [ "c#", "thread-safety", "collections" ], "Title": "Add/Remove items thread-safely in List<T>" }
18483
<p>I've got one multimap: <code>mm1</code> and a map: <code>mm2</code>. The size of <code>mm1</code> is <em>usually</em> expected to be smaller than <code>mm2</code>. So I begin by iterating through <code>mm1</code>, and for each key in <code>mm1</code> that also exists in <code>mm2</code>, will print the values of them. e.g. in the following example, first I come up with 2 in <code>mm1</code>, which also exists in <code>mm2</code>; therefor I print "aa" and "bb" from <code>mm1</code> and "b" from <code>mm2</code>. If we encounter any key in <code>mm1</code> that cannot be found in <code>mm2</code>, the whole process will be stopped. Example:</p> <p>(in each pair, number is key, string is value)</p> <p>mm1:</p> <blockquote> <p>2, "aa"<br> 2, "bb"<br> 4, "cc"<br> 4, "dd"<br> 5, "ee"</p> </blockquote> <p>mm2:</p> <blockquote> <p>1, "a"<br> 2, "b"<br> 3, "c"<br> 4, "d"<br> 6, "e"</p> </blockquote> <p>output should be:</p> <blockquote> <p>aa<br> bb<br> b<br> cc<br> dd<br> d</p> </blockquote> <p>For the following input, 4 is not found in the second map and therefore we stop printing values after 2 (even though 5 exists in both of them, it's not printed).</p> <p>mm1:</p> <blockquote> <p>2, "aa"<br> 2, "bb"<br> 4, "cc"<br> 4, "dd"<br> 5, "ee"</p> </blockquote> <p>mm2:</p> <blockquote> <p>1, "a"<br> 2, "b"<br> 3, "c"<br> 5, "d"</p> </blockquote> <p>output should be:</p> <blockquote> <p>aa<br> bb<br> b</p> </blockquote> <p>And here is my code:</p> <pre><code>#include &lt;map&gt; #include &lt;string&gt; #include &lt;iostream&gt; using namespace std; int main() { multimap&lt;int,string&gt; mm1; mm1.insert(make_pair(2, "aa")); mm1.insert(make_pair(2, "bb")); mm1.insert(make_pair(4, "cc")); mm1.insert(make_pair(4, "dd")); mm1.insert(make_pair(5, "ee")); map&lt;int,string&gt; mm2; mm2.insert(make_pair(1, "a")); mm2.insert(make_pair(2, "b")); mm2.insert(make_pair(3, "c")); mm2.insert(make_pair(4, "d")); mm2.insert(make_pair(5, "e")); typedef multimap&lt;int,string&gt;::iterator Iter; pair&lt;Iter, Iter&gt; range1(mm1.begin(), mm1.begin()); Iter next1 = mm1.begin(); map&lt;int,string&gt;::iterator next2 = mm2.begin(); range1 = mm1.equal_range(next1-&gt;first); while (!(range1.first == mm1.end() &amp;&amp; range1.second == mm1.end())) { next2 = mm2.find(next1-&gt;first); if(next2 == mm2.end()) break; for (Iter itr = range1.first;itr!=range1.second;itr++) { cout &lt;&lt; itr-&gt;second &lt;&lt; endl; } cout &lt;&lt; next2-&gt;second &lt;&lt; endl; next1 = range1.second; next2++; if(next1 == mm1.end() || next2 == mm2.end()) break; range1 = mm1.equal_range(next1-&gt;first); } return 0; } </code></pre> <p>My intention was to iterate over each map only once. Any advice on improving the performance and size of this program would be appreciated!</p>
[ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-11-12T17:23:16.897", "Id": "29507", "Score": "0", "body": "I don't understand what you are trying to achieve. The English description does not seem to match the first example. The key \"aa\" in mm1 is not in mm2 so why is it in the expected output?" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-11-12T18:25:33.170", "Id": "29512", "Score": "0", "body": "@LokiAstari \"aa\" is not a key, it's a value. The numbers are keys." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-11-12T18:36:54.513", "Id": "29513", "Score": "0", "body": "@LokiAstari Updated my question to make it more clear." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-11-12T19:18:11.853", "Id": "29516", "Score": "0", "body": "Sorry. Misread that. Totally my mistake." } ]
[ { "body": "<p>You can merge both maps to a \"list\". That should give you O(n) complexity solution where n is a total number of elements in both maps.<br>\nmap elements are sorted from lower to higher, so simple iteration would yield an ordered list.<br>\nTo merge maps, you need to iterate both of the maps, instead of insertion to a list, you can just output values to the screen.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-11-13T04:55:33.217", "Id": "29542", "Score": "0", "body": "There is no need to merge the two maps. It does not make anything more efficient either. Even if I merge the two, there will be no way to know which keys have been available in both maps. Please read the question again." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-11-13T05:57:36.000", "Id": "29544", "Score": "0", "body": "As I've noted earlier, you do not have to create the list, but output values to the screen.\nOnce you hit a condition when the current value does not exist in the second map, you stop processing.\nThis way your code would visit each maps' element only once." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-11-13T06:39:19.377", "Id": "29546", "Score": "0", "body": "Isn't this what I have already done in my code? I am iterating only once." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-11-13T09:57:58.170", "Id": "29553", "Score": "0", "body": "`mm2.find` does a binary search with O(log n) complexity, so strictly speaking your are iterating more than once on mm2" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-11-13T10:23:37.797", "Id": "29555", "Score": "0", "body": "You are right, `mm2.find` is always searching from the first element which is not necessary. Thank you" } ], "meta_data": { "CommentCount": "5", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-11-12T22:11:01.037", "Id": "18515", "ParentId": "18490", "Score": "1" } }, { "body": "<p>A simple variation on the classic 'find common entries in 2 sorted lists' will do:</p>\n\n<pre><code>void printIntersection(multimap&lt;int,string&gt; mm1, map&lt;int,string&gt; mm2)\n{\n map&lt;int,string&gt;::iterator iter1 = mm1.begin(), iter2 = mm2.begin();\n while (iter1 != mm1.end() &amp;&amp; iter2 != mm2.end()) {\n if (iter1-&gt;first &lt; iter2-&gt;first)\n iter1++;\n else if (iter1-&gt;first &gt; iter2-&gt;first)\n iter2++;\n else { // equal keys, print values\n while (iter1 != mm1.end() &amp;&amp; iter1-&gt;first == iter2-&gt;first)\n cout &lt;&lt; iter1++-&gt;second &lt;&lt; endl;\n cout &lt;&lt; iter2++-&gt;second &lt;&lt; endl; // unique map key, no need to loop\n } // else\n } // while\n}\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-11-13T06:34:03.350", "Id": "29545", "Score": "0", "body": "Upon reaching a key in `mm1` which is not available in `mm2`, the iteration should stop." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-11-13T06:53:44.453", "Id": "29547", "Score": "0", "body": "so replace `iter1++` with `return`" } ], "meta_data": { "CommentCount": "2", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-11-13T05:10:21.987", "Id": "18522", "ParentId": "18490", "Score": "1" } } ]
{ "AcceptedAnswerId": "18522", "CommentCount": "4", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-11-12T11:13:04.957", "Id": "18490", "Score": "0", "Tags": [ "c++" ], "Title": "Iterating through one map and one multimap and printing the vlaue of common keys" }
18490
<p>I've been learning Haskell, and a while ago I created this Hangman game. I've been working on using a library for terminal output, so no more hardcoded escape codes, but in the meantime I'd like some comments on what I have until now.</p> <p>Is this readable, correct Haskell code with no obvious performance problems?</p> <p>The code depends on a file being present named after the language (EN or NL) containing linebreak-separated words that is easily created.</p> <pre><code>import System.Random (randomRIO) import Data.Char (isAlpha, toUpper) import Data.List (intersperse) import System.IO (hSetBuffering, stdin, BufferMode (NoBuffering) ) lang = EN main :: IO () main = do hSetBuffering stdin NoBuffering f &lt;- readFile $ show lang startplaying $ lines f startplaying :: [String] -&gt; IO () startplaying words = do index &lt;- randomRIO (0,length words - 1) playgame (words !! index) [] putStrLn $ strings lang Another ans &lt;- getChar case ans of 'n' -&gt; return () _ -&gt; startplaying words playgame :: String -&gt; [Char] -&gt; IO () playgame word guessed | complete = printState word guessed Won "" | guessedwrong word guessed &gt;= length hangman -1 = printState word guessed Lost word | otherwise = do printState word guessed Pick "" l &lt;- fmap toUpper getChar let guessed' | not (isAlpha l) = guessed | l `elem` guessed = guessed | otherwise = l : guessed playgame word guessed' where complete :: Bool complete = all (`elem` guessed) (map toUpper word) guessedwrong :: String -&gt; [Char] -&gt; Int guessedwrong word guessed = length $ filter (`notElem` map toUpper word) guessed printState :: String -&gt; [Char] -&gt; Message -&gt; String -&gt; IO () printState word guessed message string = putStrLn $ "\ESC[2J" ++ unlines [ hangman !! (guessedwrong word guessed) , map (\x -&gt; if (elem (toUpper x) guessed) then x else '_') word , (strings lang Used) ++ intersperse ' ' guessed , strings lang message ++ string ] strings :: Language -&gt; Message -&gt; String strings NL m = case m of Another -&gt; "Wil je nog een keer spelen? [Y/n]" Won -&gt; "Gefeliciteerd! Je hebt het woord geraden!" Lost -&gt; "Je bent dood. Het woord was " Pick -&gt; "Kies een letter" Used -&gt; "Gebruikte letters: " strings EN m = case m of Another -&gt; "Play another game? [Y/n]" Won -&gt; "Congratulations! You got it!" Lost -&gt; "You're dead. The word was " Pick -&gt; "Pick a letter" Used -&gt; "Used letters: " data Message = Another | Won | Lost | Pick | Used data Language = NL | EN deriving (Show) hangman = [ unlines [ "" , "" , "" , "" , "" , "" , "" , "" ] , unlines [ "" , "" , "" , "" , "" , "" , "" , " ___" ] , unlines [ "" , "|" , "|" , "|" , "|" , "|" , "|" , "|___" ] , unlines [ "_________" , "|" , "|" , "|" , "|" , "|" , "|" , "|___" ] , unlines [ "_________" , "|/" , "|" , "|" , "|" , "|" , "|" , "|___" ] , unlines [ "_________" , "|/ |" , "|" , "|" , "|" , "|" , "|" , "|___" ] , unlines [ "_________" , "|/ |" , "| (_)" , "|" , "|" , "|" , "|" , "|___" ] , unlines [ "_________" , "|/ |" , "| (_)" , "| |" , "| |" , "|" , "|" , "|___" ] , unlines [ "_________" , "|/ |" , "| (_)" , "| /|" , "| |" , "|" , "|" , "|___" ] , unlines [ "_________" , "|/ |" , "| (_)" , "| /|\\" , "| |" , "|" , "|" , "|___" ] , unlines [ "_________" , "|/ |" , "| (_)" , "| /|\\" , "| |" , "| /" , "|" , "|___" ] , unlines [ "_________" , "|/ |" , "| (_)" , "| /|\\" , "| |" , "| / \\" , "|" , "|___" ] ] </code></pre>
[ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-11-13T23:06:55.603", "Id": "29585", "Score": "2", "body": "`startplaying words = do index <- randomRIO (0,length words)` should be `startplaying words = do index <- randomRIO (0,length words - 1)` so you don't go off the end of the list." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-11-13T23:09:39.573", "Id": "29587", "Score": "1", "body": "Consider failing with a more helpful message if the language-specific file isn't there, perhaps as part of allowing the user to choose the language at start up." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-11-13T23:16:57.490", "Id": "29588", "Score": "1", "body": "It suffers from the `getChar` bug in ghc under windows (but is OK in WinHugs, and the fix causes a bug in WinHugs). This might not matter to you. See [this stack overflow question](http://stackoverflow.com/questions/2983974/haskell-read-input-character-from-console-immediately-not-after-newline/13370293#13370293)" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-11-14T15:49:52.987", "Id": "29633", "Score": "0", "body": "@AndrewC: Thank you. I fixed the off-by-one error (d'oh). I was planning on making the language selectable as part of separating the UI code and using a terminal library. I'm aware of the Windows bug, but since this is just a toy program I didn't really worry about it." } ]
[ { "body": "<p>Why do you have so much redundant data in <code>State</code>? That just means you have to put a lot of effort into keeping everything up-to-date - which doesn't just make your program longer, but is also prone to mistakes.</p>\n\n<p>By eliminating all redundancy as well as replacing the explicit state variable by control flow, the <code>playgame</code> function can be simplified down to pretty much the following:</p>\n\n<pre><code>count_duds :: String -&gt; [Char] -&gt; Int\ncount_duds word guessed = length $ filter (`notElem` map toUpper word) guessed\n\nplaygame :: String -&gt; [Char] -&gt; IO ()\nplaygame word guessed\n | all (`elem` guessed) (map toUpper word) = putStrLn $ header \"Won\"\n | count_duds word guessed + 1 &gt;= length hangman = putStrLn $ header \"Lost\" ++ word\n | otherwise = do putStrLn $ header \"Pick\"\n l &lt;- fmap toUpper getChar\n let guessed' | not (isAlpha l) = guessed\n | l `elem` guessed = guessed\n | otherwise = l:guessed\n playgame word guessed'\n where header msg = formatState word guessed ++ \"\\n\" ++ strings lang msg\n</code></pre>\n\n<p>Admittedly, this does quite a bit of re-computation, especially on the \"duds\". Yet we can probably expect both words and game lengths to be small, therefore it is better to go with a more compact program.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-11-14T15:42:41.793", "Id": "29631", "Score": "0", "body": "Thank you! I agree, my version was much too verbose and error-prone. I guess I was subconsciously porting an earlier C# version too literally, which had all these state variables as member variables.\n\nI tried implementing your suggestions myself, in order to learn from them. I changed my code in the question. Do you think I implemented your ideas well?" } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-11-13T17:22:30.260", "Id": "18549", "ParentId": "18497", "Score": "3" } } ]
{ "AcceptedAnswerId": "18549", "CommentCount": "4", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2012-11-12T14:41:57.220", "Id": "18497", "Score": "6", "Tags": [ "game", "haskell", "hangman" ], "Title": "Small Haskell Hangman game" }
18497
<p>Below is a simplified version of some code I am using to execute a function after all asynchronous calls complete. Is this a reasonable piece of code? It seems to work. Nothing would break if <code>DoStuff()</code> was called twice, though that would be very inefficient.</p> <pre><code>var i = 0; var done = function () { i++; if (i &lt; 2) return; //Everything is done DoStuff(); }; elem1.executeAsync(function () { done(); }); elem2.executeAsync(function () { done(); }); </code></pre>
[ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-11-12T15:43:19.903", "Id": "29502", "Score": "0", "body": "So you want `DoStuff()` called only when *both* are done?" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-11-12T16:18:55.110", "Id": "29503", "Score": "0", "body": "@SomeKittens: Yes." } ]
[ { "body": "<p>The approach itself (i.e. using a counter) is reasonable, but the hard-coded <code>2</code> and <code>DoStuff</code> limits its use.</p>\n\n<p>You could do something like this, to derive more generic implementation:</p>\n\n<pre><code>function createCounter(count, callback) {\n count || (count = 1); // default to 1\n (typeof callback === 'function') || (callback = function () {}); // default to no-op\n return function () {\n --count || callback();\n };\n}\n</code></pre>\n\n<p>Now you have a function that returns a specialized \"done\" function. Use like so:</p>\n\n<pre><code>var done = createCounter(2, DoStuff);\n\nelem1.executeAsync(function () {\n done();\n});\n\nelem2.executeAsync(function () {\n done();\n});\n</code></pre>\n\n<p>Incidentally, this can be shortened to:</p>\n\n<pre><code>var done = createCounter(2, DoStuff);\n\nelem1.executeAsync(done);\nelem2.executeAsync(done);\n</code></pre>\n\n<p>(of course, your actual code is likely more complex)</p>\n\n<p>However, I'd say you should also look into the <a href=\"http://wiki.commonjs.org/wiki/Promises\">Promise/Deferred patterns</a>.<br>\nFor instance, using jQuery's implementation (and assuming <code>executeAsync</code> returns a promise) you can do this</p>\n\n<pre><code>$.when(elem1.executeAsync(), elem2.executeAsync()).then(DoStuff);\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-11-12T16:22:17.817", "Id": "29504", "Score": "0", "body": "executeAsync is not under my control." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-11-12T16:31:08.150", "Id": "29505", "Score": "0", "body": "@Brian Ok, but apart from the last bit about promises, that doesn't affect my answer." } ], "meta_data": { "CommentCount": "2", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-11-12T15:50:08.483", "Id": "18500", "ParentId": "18499", "Score": "5" } } ]
{ "AcceptedAnswerId": "18500", "CommentCount": "2", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-11-12T15:24:30.137", "Id": "18499", "Score": "1", "Tags": [ "javascript", "asynchronous", "callback" ], "Title": "Calling a function when all asynchronous calls complete" }
18499
<p>I had to create an executable to search and replace strings in a file. This is to be used in my installer for text file manipulation. I have various placeholders in configuration files that I need to replace with proper values after querying the end user system.</p> <p>I have written the following code. This being my first real experience with C#, I do not expect the code to be any good. I have come up with this code based upon a couple of hours of reading MSDN and stackoverflow. I needed someone to review this. There is no one greater than the community to do this.</p> <p>Please review this and let me know what modification are necessary. I am specifically concerned about the exception handling. I have included two try-catch blocks.</p> <p>My logic:</p> <p>If I have all operations under one try-catch block, the failure of one process will block the execution of all others. That is, if my </p> <pre><code>text = Regex.Replace(text, args[1], args[2]); </code></pre> <p>has an exception and if I have </p> <pre><code>WriteLog(args[0], args[1], args[2], strException, intStatus); </code></pre> <p>also in the same try block, it will not execute and I will not have any logs.</p> <p>Also, if I have the </p> <pre><code>WriteLog(args[0], args[1], args[2], strException, intStatus); </code></pre> <p>in the catch block, any exception in that method cannot be caught. Yes I can have try-catch in the <strong>WriteLog</strong> method but I see no problems in my approach too.</p> <p>So first, I have a try-catch for file manipulation and then another for log write.</p> <p>Please ignore the log path(hardcoded as D:).</p> <pre><code>class Program { static int Main(string[] args) { //args[0] = The file that needs modification //args[1] = The string to replace //args[2] = The string with which to replace args[1] int intStatus = 0; string strException = ""; //Get out immediately if no/improper arguments are found if (args.Length &lt; 3) { intStatus = 1; return intStatus; } try { StreamReader streamReader = new StreamReader(args[0]); String text = streamReader.ReadToEnd(); streamReader.Close(); text = Regex.Replace(text, args[1], args[2]); StreamWriter streamWriter = new StreamWriter(args[0]); streamWriter.Write(text); streamWriter.Close(); } catch (Exception ex) { //text file manipulation failed strException = ex.ToString(); intStatus = 2; } try { WriteLog(args[0], args[1], args[2], strException, intStatus); } catch { //log write failed if (intStatus == 0) { intStatus = 3; //if intStatus = 1 when we get here, no need to modify the value(its a complete failure) //if intStatus = 0 when we get here, make intStatus = 2 so as to clearly distinguish a "log write failed" //error from a "text file manipulation failed" error } } return intStatus; } //The new Logger for the exe static void WriteLog(string arg0, string arg1, string arg2, string exception, int status) { string strGrepLogFileName = string.Format("D:\\TempLogs\\Grep-{0:yyyy-MM-dd_hh-mm-ss-tt}.log", DateTime.Now); StreamWriter GrepLog = new StreamWriter(strGrepLogFileName, true); GrepLog.WriteLine("Argument 1: " + arg0); GrepLog.WriteLine("Argument 2: " + arg1); GrepLog.WriteLine("Argument 3: " + arg2); GrepLog.WriteLine("Status: " + status.ToString()); GrepLog.WriteLine("Exception: " + exception); GrepLog.Close(); } } </code></pre> <p>EDIT 1: It is an absolute pity that I cannot mark multiple answers.</p>
[]
[ { "body": "<h2>Use the <code>params</code> keyword</h2>\n\n<pre><code>//The new Logger for the exe\nstatic void WriteLog(string exception, int status, params string[] arguments)\n{\n string logFile = string.Format(\"D:\\\\TempLogs\\\\Grep-{0:yyyy-MM-dd_hh-mm-ss-tt}.log\", DateTime.Now);\n StreamWriter grepLog = new StreamWriter(logFile, true);\n grepLog.WriteLine(\"Status: \" + status.ToString() + \" (0 for PASS, 1 for FAIL)\");\n grepLog.WriteLine(\"Exception: \" + exception);\n // TODO: Consider logging \"no arguments\" if that is the case.\n for(int i=0; i&lt;arguments.Length; i++)\n {\n grepLog.WriteLine(\"Argument \" + i + \": \" + arguments[i]);\n }\n grepLog.Close();\n}\n</code></pre>\n\n<h2>Use an <code>enum</code> for status</h2>\n\n<p>Since the status has 3 states, use an <code>enum</code> for it. This will help you avoid mistakes.</p>\n\n<h2>Why do you try-catch while logging?</h2>\n\n<p>If you don't see any particular possibility for the log to fail, then simply assume it and don't try-catch the logging.</p>\n\n<p>If you want the logging to no matter what <strong>not</strong> break the application with exceptions, and you cannot fix those exceptions (why?), then I would suggest putting the try-catch inside the logging method.</p>\n\n<h2>Main - exception should catch, log, and return</h2>\n\n<p>I would have the exception log the error and return, instead of continuing normally.</p>\n\n<p>Alternatively, I would catch, log, and re-throw: <code>try { ... } catch (Exception e) { WriteLog(...); throw; }</code></p>\n\n<h2>Use camelCase for local variables</h2>\n\n<p><code>StreamWriter grepLog;</code><br>\nUsing a starting underscore (<code>_grepLog</code>) is also common for private fields.</p>\n\n<p>Follow the de-facto conventions. (See e.g. <a href=\"https://stackoverflow.com/questions/2976627/on-c-sharp-naming-conventions-for-member-variables\">https://stackoverflow.com/questions/2976627/on-c-sharp-naming-conventions-for-member-variables</a> )</p>\n\n<h2>Avoid Hungarian Notation</h2>\n\n<p>In <code>string strGrepLogFileName</code>, the part \"str\" brings nothing new.<br>\nIf you change the variable's type (e.g. to an <code>Uri</code>) without changing its meaning, you should not have to rename the variable, and using Hungarian Notation you do.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-11-12T17:31:36.823", "Id": "29508", "Score": "0", "body": "Hi ANeves, These are great tips. Many things have started making sense now. Also, do you mean to say that the code is good apart from these style pointers?" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-11-13T09:09:42.070", "Id": "29550", "Score": "0", "body": "Yes, I do think it is a good start. There are lots of other things to improve, and many are addresses by the good suggestions of improvement in the thread; you will learn lots with this experience. :)" } ], "meta_data": { "CommentCount": "2", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-11-12T17:00:59.103", "Id": "18503", "ParentId": "18501", "Score": "10" } }, { "body": "<p>To add some style pointers:</p>\n\n<ul>\n<li><code>string</code> should be used consistently over <code>String</code>. Some also prefer the use of <code>string.Empty</code> over an empty literal(<code>\"\"</code>). See <a href=\"http://stylecop.codeplex.com/\">StyleCop</a></li>\n<li><p>If the logging function isn't expected to fail, then handle everything internally to that method. Additionally, take advantage of a using block to handle the resource:</p>\n\n<pre><code>using(StreamWriter grepLog = new StreamWriter(fileName, true))\n{\n // ...log code here\n}\n</code></pre></li>\n<li><p>Your resources in the first try block will not close if they fail to read/write. Either combine a <code>using</code> in there with the <code>try</code> or close them in a <code>finally</code> block. I would suggest adding an additional pre-condition that verifies that the file exists before attempting to read it:</p>\n\n<pre><code>if(!File.Exists(args[0]))\n{\n // Log error and return\n}\n</code></pre></li>\n</ul>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-11-12T18:47:42.240", "Id": "29515", "Score": "0", "body": "Can you explain preferring string.Empty to \"\" ? I know StyleCop defaults to having that rule enabled, but there's lots of rules in StyleCop that seem more opinion than best practice." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-11-12T19:23:24.127", "Id": "29517", "Score": "0", "body": "I think it's just that, a preference. As long as you are consistent, I don't think it matters. The reference to StyleCop was more or less a suggestion to help with style checking in general.\n\nMy preference is for string.Empty because it's explicit, if a little wordy. That way \"\" isn't accidentally written as \" \" or some other similar mistake." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-11-12T19:30:13.020", "Id": "29518", "Score": "1", "body": "Related: http://stackoverflow.com/questions/263191/in-c-should-i-use-string-empty-or-string-empty-or" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-11-13T12:35:05.377", "Id": "29562", "Score": "2", "body": "The reader of `string.Empty` can have a very high confidence that the writer meant 'the empty string'. The reader of `\"\"` might have a nagging suspicion that `\" \"` or `\" \"` or even `\".\"` was meant, but mistyped..." } ], "meta_data": { "CommentCount": "4", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-11-12T17:16:14.387", "Id": "18504", "ParentId": "18501", "Score": "10" } }, { "body": "<p>The biggest tip I can give is to use the <code>using</code> construct to make sure your <code>IDisposable</code> resources are properly disposed. These are your <code>StreamReader</code>s and <code>StreamWriter</code>s. I also think what <a href=\"https://codereview.stackexchange.com/posts/18503/revisions\">ANeves</a> <a href=\"https://codereview.stackexchange.com/a/18503/6172\">says</a> is spot-on for the stylistic pieces. Here's a cut:</p>\n\n<pre><code>internal static class Program\n{\n private enum Status\n {\n Success,\n\n ImproperOrNoArgumentsFound,\n\n TextFileManipulationFailed,\n\n LogWriteFailed\n }\n\n private static int Main(string[] args)\n {\n // args[0] = The file that needs modification\n // args[1] = The string to replace\n // args[2] = The string with which to replace args[1]\n var status = Status.Success;\n var exception = string.Empty;\n\n // Get out immediately if no/improper arguments are found\n if (args.Length &lt; 3)\n {\n return (int)Status.ImproperOrNoArgumentsFound;\n }\n\n try\n {\n string text;\n\n using (var streamReader = new StreamReader(args[0]))\n {\n text = streamReader.ReadToEnd();\n }\n\n text = Regex.Replace(text, args[1], args[2]);\n using (var streamWriter = new StreamWriter(args[0]))\n {\n streamWriter.Write(text);\n }\n }\n catch (Exception ex)\n {\n // text file manipulation failed\n exception = ex.ToString();\n status = Status.TextFileManipulationFailed;\n }\n\n try\n {\n WriteLog(args[0], args[1], args[2], exception, status);\n }\n catch\n {\n // log write failed\n if (status == Status.Success)\n {\n status = Status.LogWriteFailed; // if intStatus = 1 when we get here, no need to modify the value(its a complete failure)\n // if intStatus = 0 when we get here, make intStatus = 2 so as to clearly distinguish a \"log write failed\"\n // error from a \"text file manipulation failed\" error\n }\n }\n\n return (int)status;\n }\n\n // The new Logger for the exe\n private static void WriteLog(string arg0, string arg1, string arg2, string exception, Status status)\n {\n var logFileName = string.Format(\"D:\\\\TempLogs\\\\Grep-{0:yyyy-MM-dd_hh-mm-ss-tt}.log\", DateTime.Now);\n\n using (var log = new StreamWriter(logFileName, true))\n {\n log.WriteLine(\"Argument 1: \" + arg0);\n log.WriteLine(\"Argument 2: \" + arg1);\n log.WriteLine(\"Argument 3: \" + arg2);\n log.WriteLine(\"Status: \" + status);\n log.WriteLine(\"Exception: \" + exception);\n }\n }\n}\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-11-12T18:00:35.343", "Id": "29511", "Score": "0", "body": "Thank you Jesse. I do a lot of stuff but am new to OO programming. Your help will ease my troubles." } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-11-12T17:24:42.573", "Id": "18505", "ParentId": "18501", "Score": "5" } }, { "body": "<p>Along with what E-Man, ANeves and Jesse have contributed I would suggest the following...</p>\n\n<p>Put your arguments into variables at the top so the rest of the code is self-documenting. I recognize that you put comments at the top which describe the parameters, but variables names could better describe the information.</p>\n\n<p>To make these more robust I would also do a bit more validation. I understand that exceptions will be thrown if the information is invalid but to me exceptions should only be thrown for unhandled problems, and invalid user input is something that should be handled.</p>\n\n<p>Thirdly, if you want to catch exceptions when writing logs you might consider encapsulating that in the WriteLog method. Then you can return a bool indicating whether the log write was successful.</p>\n\n<p>Putting it all together (including everyones suggestions). See what you think of this...</p>\n\n<pre><code>class Program\n{\n private enum Status\n {\n Success,\n FileNotFound,\n ImproperOrNoArgumentsFound,\n TextFileManipulationFailed,\n LogWriteFailed\n }\n\n static int Main(string[] args)\n {\n Status status = Status.Success;\n string strException = string.Empty;\n\n //Get out immediately if no/improper arguments are found\n if (args.Length &lt; 3)\n {\n return (int)Status.ImproperOrNoArgumentsFound;\n }\n\n string fileName = args[0];\n if (!File.Exists(fileName))\n {\n return (int)Status.FileNotFound;\n }\n\n string pattern = args[1];\n string replacementValue = args[2];\n\n try\n {\n using (StreamReader streamReader = new StreamReader(fileName))\n {\n string text = streamReader.ReadToEnd();\n text = Regex.Replace(text, pattern, replacementValue);\n using (StreamWriter streamWriter = new StreamWriter(streamReader))\n {\n streamWriter.Write(text);\n }\n }\n }\n catch (Exception ex)\n {\n //text file manipulation failed\n strException = ex.ToString();\n status = Status.TextFileManipulationFailed;\n }\n\n if (!WriteLog(strException, status, fileName, pattern, replacementValue))\n {\n if (status == Status.Success)\n {\n status = Status.LogWriteFailed;\n }\n }\n\n return (int)status;\n }\n\n //The new Logger for the exe\n static bool WriteLog(string exception, Status status, params string[] arguments)\n {\n bool success = true;\n\n try\n {\n string logFile = string.Format(\"D:\\\\TempLogs\\\\Grep-{0:yyyy-MM-dd_hh-mm-ss-tt}.log\", DateTime.Now);\n using (StreamWriter grepLog = new StreamWriter(logFile, true))\n {\n grepLog.WriteLine(string.Format(\"Status: {0} (0 for PASS, 1 for FAIL)\", status));\n grepLog.WriteLine(\"Exception: \" + exception);\n // TODO: Consider logging \"no arguments\" if that is the case.\n for (int i = 0; i &lt; arguments.Length; i++)\n {\n grepLog.WriteLine(\"Argument \" + i + \": \" + arguments[i]);\n }\n }\n }\n catch (Exception)\n {\n success = false;\n }\n\n return success;\n }\n}\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-11-12T17:58:50.263", "Id": "29509", "Score": "0", "body": "Hi Gene, thanks for replying. This being my first C# code, do you see this as a good starting? Just want to assess myself?" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-11-12T19:54:31.947", "Id": "29521", "Score": "1", "body": "It's a good starting point. The only big concern is not using the `using` clause. That could have caused problems without it. More importantly though is that you are reaching out to learn. In my view, that is what makes defines a good developer." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-11-13T09:39:58.983", "Id": "29552", "Score": "0", "body": "I think I found a small bug in the code given by you. I have added an answer to the chain. Have a look at it." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-11-13T14:56:15.987", "Id": "29566", "Score": "0", "body": "That is very possible since I wrote it in NotePad. Sorry, should have included that disclaimer in my answer." } ], "meta_data": { "CommentCount": "4", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-11-12T17:53:38.190", "Id": "18508", "ParentId": "18501", "Score": "2" } }, { "body": "<p>Others have written in detail how you can improve your exception handling, which is really important, but your core logic can be reduced to the following:</p>\n\n<pre><code>private static void ReplaceInFile(string path, string pattern, string replacement)\n{\n string contents = File.ReadAllText(path);\n string replaced = Regex.Replace(contents, pattern, replacement);\n File.WriteAllText(path, replaced);\n}\n</code></pre>\n\n<h2>A note on Performance</h2>\n\n<p>If you have a small number of relatively short files, your current approach should work. However, it's suboptimal for larger amounts of data as you need to execute your program once for each file, always keeping the entire file in memory.</p>\n\n<p>However, you should not change to a more complicated approach unless you experience serious performance issues. In that case, you should explore <code>File.ReadLines</code> (which will only read a few lines into memory at once) and <code>IEnumerable&lt;T&gt;.AsParallel</code> (which allows you to process several files at once (you'd have to use temporary files to store the results). </p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-11-17T22:06:48.480", "Id": "29878", "Score": "0", "body": "I am still at the beginning of my exploration of C#. I will learn the stuff you mentioned and update the post. Thanks." } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-11-12T19:28:35.957", "Id": "18510", "ParentId": "18501", "Score": "4" } }, { "body": "<p>None of the other answers touch upon this...</p>\n\n<p>Your main function does too much. Specifically, the main function should ONLY do your initial validation -- do you have the right number of parameters? If possible verify that those parameters are valid. Then call a method that does the actual work. </p>\n\n<p>Code reuse, whether that is done via copy/paste, inheritance or a library, works best when you have discrete methods, that have little to no dependencies.</p>\n\n<p>In addition, given your usage I would change your writelog function to TryWriteLog and have it returns success or failure (ie it eats any exceptions and then returns an appropriate boolean). Exceptions should be handled at the earliest point that knows what to do in order to recover or continue. Given that you aren't doing anything with it, handling it in the logging function makes the most sense.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-11-12T19:55:12.960", "Id": "18512", "ParentId": "18501", "Score": "6" } }, { "body": "<p>I searched extensively on stackoverflow and MSDN to comprehend all the technical stuff other community members pointed me to.</p>\n\n<p>Specifically the following post was wonderful:</p>\n\n<p><a href=\"https://stackoverflow.com/questions/538060/proper-use-of-the-idisposable-interface\">https://stackoverflow.com/questions/538060/proper-use-of-the-idisposable-interface</a></p>\n\n<p>I am amazed at how such a small piece of code could have so much to learn from.</p>\n\n<p>Gene S had given a code snippet which was beautifully done but had a small issue.</p>\n\n<p>The following part of the code, I believe, has a small bug</p>\n\n<pre><code>try\n {\n using (StreamReader streamReader = new StreamReader(fileName))\n {\n string text = streamReader.ReadToEnd();\n text = Regex.Replace(text, pattern, replacementValue);\n using (StreamWriter streamWriter = new StreamWriter(fileName))\n {\n streamWriter.Write(text);\n }\n }\n }\n</code></pre>\n\n<p>The StreamReader has StreamWriter inside it. The StreamReader has not released the input file when StreamWriter is trying to write to it. This causes a \"File is in use by another process\" error.</p>\n\n<p>I have modified the code:</p>\n\n<pre><code>class Program\n{\n private enum Status\n {\n Success,\n FileNotFound,\n ImproperOrNoArgumentsFound,\n TextFileManipulationFailed,\n LogWriteFailedButJobPASS,\n LogWriteFailedAndJobFAIL\n }\n\n static int Main(string[] args)\n {\n //--------------------------------------------------------\n // args[0]=File to be manipulated\n // args[1]=String to be replaced or PATTERN\n // args[2]=String with which to replace args[1]\n //--------------------------------------------------------\n string fileName = args[0];\n string pattern = args[1];\n string replacementValue = args[2];\n\n Status status = Status.Success;\n string strException = string.Empty;\n\n //Get out immediately if no/improper arguments are found\n if (args.Length &lt; 3)\n {\n status = Status.ImproperOrNoArgumentsFound;\n strException = \"ImproperOrNoArgumentsFound\";\n //Do not care if logging succeeded or not.\n //This is premature failing and return value is actually enough for installer.\n WriteLog(strException, status, fileName, pattern, replacementValue);\n return (int)status;\n }\n\n if (!File.Exists(fileName))\n {\n status = Status.FileNotFound;\n strException = \"FileNotFound\";\n //Do not care if logging succeeded or not.\n //This is premature failing and return value is actually enough for installer\n WriteLog(strException, status, fileName, pattern, replacementValue);\n return (int)status;\n }\n\n try\n {\n string text = string.Empty;\n using (StreamReader streamReader = new StreamReader(fileName))\n {\n text = streamReader.ReadToEnd();\n text = Regex.Replace(text, pattern, replacementValue);\n }\n\n using (StreamWriter streamWriter = new StreamWriter(fileName))\n {\n streamWriter.Write(text);\n }\n }\n catch (Exception ex)\n {\n //Text file manipulation failed\n strException = ex.ToString();\n status = Status.TextFileManipulationFailed;\n }\n\n //Really care about the success of logging.\n //What all happened have to be logged for installer troubleshooting etc...\n if (!WriteLog(strException, status, fileName, pattern, replacementValue))\n {\n if (status == Status.Success)\n {\n status = Status.LogWriteFailedButJobPASS;\n }\n else\n {\n status = Status.LogWriteFailedAndJobFAIL;\n }\n }\n return (int)status;\n }\n\n //The Logger for the exe\n static bool WriteLog(string exception, Status status, params string[] arguments)\n {\n bool success = true;\n\n try\n {\n string logFile = string.Format(\"D:\\\\TempLogs\\\\Grep.log\", DateTime.Now);\n using (StreamWriter grepLog = new StreamWriter(logFile, true))\n {\n grepLog.WriteLine(\"---------------------------------------------------------------\");\n grepLog.WriteLine(string.Format(\"{0:yyyy-MM-dd hh-mm-ss-tt}\", DateTime.Now));\n for (int i = 0; i &lt; arguments.Length; i++)\n {\n grepLog.WriteLine(\"Argument \" + i + \": \" + arguments[i]);\n }\n grepLog.WriteLine(string.Format(\"Status: {0}\", status));\n grepLog.WriteLine(\"Exception Stack: \" + exception);\n grepLog.WriteLine(\"---------------------------------------------------------------\");\n }\n }\n catch (Exception)\n {\n success = false;\n }\n\n return success;\n }\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-11-13T15:06:17.053", "Id": "29570", "Score": "1", "body": "Another possibility is look using the FileStream object, then you can pass that object into the StreamReader and StreamWriter. Or look at passing the StreamReader into the StreamWriter constructor to see if you can avoid the exception in that manner. There are several ways to achieve the same goal. Some might give you better performance then others." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-11-13T15:10:09.617", "Id": "29572", "Score": "1", "body": "Will you ever be working with really huge files that won't fit into memory? If that is the case you may need to need read and write the file in sections instead of all at once. Of course, that will be much more difficult if your pattern can reach across words or lines of text." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-11-13T16:10:03.173", "Id": "29577", "Score": "0", "body": "No. My files are guaranteed to be small. But I have started to look into the big files scenario too." } ], "meta_data": { "CommentCount": "3", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-11-13T09:38:13.280", "Id": "18528", "ParentId": "18501", "Score": "1" } }, { "body": "<p>In OO programming every class has a single purpose. I would like to put file read and write in seperate class. </p>\n\n<p>Here is how I would like to do this.</p>\n\n<pre><code>private static int Main(string[] args)\n{\n FileManager fileAgent = new FileManager();\n Status status = Status.Success;\n string errMessage = string.Empty;\n\n if (args.Length &lt; 3)\n {\n status = Status.ImproperOrNoArgumentsFound;\n fileAgent.Log(args, status, errMessage);\n return (int)status;\n }\n\n fileAgent.FileName = args[0];\n\n try\n {\n string text = fileAgent.ReadText();\n text = Regex.Replace(text, args[1], args[2]);\n fileAgent.WriteText(text);\n }\n catch (Exception ex)\n {\n status = Status.TextFileManipulationFailed;\n errMessage = ex.ToString();\n }\n\n fileAgent.Log(args, status, errMessage);\n return (int)status;\n}\n</code></pre>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-12-17T21:56:45.170", "Id": "37630", "ParentId": "18501", "Score": "0" } } ]
{ "AcceptedAnswerId": "18503", "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-11-12T16:04:32.803", "Id": "18501", "Score": "10", "Tags": [ "c#", "strings", "beginner", "exception-handling", "file" ], "Title": "Replace strings in a file" }
18501
<p>Are there any security vulnerabilities in this code?</p> <p> <pre><code>class Session { private $id = array(); private $data = array(); private $name = 'session'; public function __construct() { session_start(); global $db; $this-&gt;id = isset($_COOKIE[$this-&gt;name]) ? $_COOKIE[$this-&gt;name] : $this-&gt;create_id(); $id = $this-&gt;id; $ip = $_SERVER['REMOTE_ADDR']; $user_agent = $_SERVER['HTTP_USER_AGENT']; $check = $db-&gt;query("SELECT session_data FROM sessions WHERE session_id = ? AND user_ip = ? AND user_agent = ?"); $db-&gt;execute(array($id, $ip, $user_agent)); if ($db-&gt;row_count() != 0) { $this-&gt;data = $db-&gt;fetch_column(); $this-&gt;data = unserialize($this-&gt;data); } else { $this-&gt;id = $this-&gt;create_id(); $id = $this-&gt;id; $data = serialize($this-&gt;data); $time = time(); $ip = $_SERVER['REMOTE_ADDR']; $user_agent = $_SERVER['HTTP_USER_AGENT']; $current_page = $_SERVER['REQUEST_URI']; $insertion_data = array( 'session_id' =&gt; $id, 'session_data' =&gt; $data, 'session_last_activity' =&gt; $time, 'user_ip' =&gt; $ip, 'user_agent' =&gt; $user_agent, 'user_current_page' =&gt; $current_page ); $db-&gt;insert('sessions', $insertion_data); } } public function end() { global $db; $this-&gt;garbage(); $id = $this-&gt;id; $data = serialize($this-&gt;data); $time = time(); $ip = $_SERVER['REMOTE_ADDR']; $user_agent = $_SERVER['HTTP_USER_AGENT']; $current_page = $_SERVER['REQUEST_URI']; $name = $this-&gt;name; // note to self: create update function in db class $db-&gt;query("UPDATE sessions SET session_data = ?, session_last_activity = ?, user_ip = ?, user_agent = ?, user_current_page = ? WHERE session_id = ?"); $db-&gt;execute(array($data, $time, $ip, $user_agent, $current_page, $id)); @setcookie($name, $id, time()+3600, '/', ''); } public function create_id() { return strtoupper(md5(rand(-1000000, 1000000))); } public function garbage() { global $db; $expiration = time() - '2419200'; $db-&gt;query("DELETE FROM sessions WHERE session_last_activity &lt; ?"); return $db-&gt;execute(array($expiration)); } public function regenerate() { global $db; $old_id = $this-&gt;id; $new_id = $this-&gt;create_id(); $this-&gt;id = $new_id; $db-&gt;query("UPDATE sessions SET session_id = ? WHERE session_id = ?"); return $db-&gt;execute(array($new_id, $old_id)); } } </code></pre>
[]
[ { "body": "<p>Nope. Let's walk through it from a hypothetical attackers point of view.</p>\n\n<blockquote>\n <p>Okay. It's sending an identification cookie. It's hex. 32 digits long.\n Probably an md5 hash. I wonder what's hashed? I'll throw it in\n oclHashcat to check. I can make a billion guesses a second, so if it's\n a hash of something simple, I'll find out.</p>\n \n <p>&lt;3 seconds later></p>\n \n <p>Huh. It's a number. Lemme grab another session and see if that's a\n number too.</p>\n \n <p>Yep.</p>\n \n <p>It looks like these are all 6 digit numbers. I'll grab 10 more to\n check. </p>\n \n <p>Okay, 6 digits AND they can be positive or negative.</p>\n \n <p>That's a keyspace of about 2^21. If there are 8 sessions going right\n now, then it costs, on average,</p>\n \n <p>2^(21 - 1 - 3) requests * 1 KB per request * 0.08 $/GB<br>\n ...<br>\n =1.01 cents to crack a session.\n Alright, I'll start on that and see what I have in the morning.</p>\n</blockquote>\n\n<p>So: Add more entropy.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-11-12T21:31:39.157", "Id": "29523", "Score": "0", "body": "Thanks, definitely useful! Could you be so kind as to give a bit more detail on how to prevent this? I understand what's going on, but not how to stop it from occurring. :S" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-11-12T21:35:01.440", "Id": "29525", "Score": "0", "body": "Don't use MD5, use Blowfish." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-11-12T21:40:58.337", "Id": "29526", "Score": "0", "body": "@user555 so that's all it requires and I'll be (more or less) protected from attacks? That simple? o.o" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-11-12T21:47:26.560", "Id": "29527", "Score": "0", "body": "Also use a unique random salt. This will prevent rainbow attacks and make the cracking more expensive. See \"Don't use MD5\" under my answer." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-11-12T22:07:48.460", "Id": "29528", "Score": "0", "body": "I'm slightly confused. I did a little research on the subject, multiple websites said that encrypting the session ID is pointless. The MD5 is only there to make the random string 32 chars in length." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-11-12T23:05:00.777", "Id": "29534", "Score": "0", "body": "On second thought your correct. You should probably drop MD5 and rand() in favor of session_regenerate_id(). The important part here is to make each session id random, so one session id can not be used to guess another one. Based on the new research I have edited my answer." } ], "meta_data": { "CommentCount": "6", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-11-12T17:26:37.783", "Id": "18506", "ParentId": "18502", "Score": "2" } }, { "body": "<h2>Rand() is not random</h2>\n\n<p>You should be aware that rand() is not as random as one might think. What if you create a session id that already exists? Consider replacing rand() or checking if the session id already exists. </p>\n\n<h2>Bruteforce</h2>\n\n<p>Your session id is too easy to bruteforce. A session id should be treated as a password from a security point of view. The longer and more complex the session id is, the harder it is to bruteforce. Use session_regenerate_id() as it will give you a fairly good alpha-numeric ID.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-11-12T21:32:22.900", "Id": "29524", "Score": "0", "body": "Ah, damn! I was going to add a check to see if the session already existed, must've forgotten. Thanks for the points. :)" } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-11-12T17:52:44.040", "Id": "18507", "ParentId": "18502", "Score": "2" } } ]
{ "AcceptedAnswerId": "18507", "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-11-12T16:53:48.707", "Id": "18502", "Score": "1", "Tags": [ "php", "security", "session" ], "Title": "Is this session handler secure?" }
18502
<p>I'm working on an app that downloads some SVG paths from a server and draws them. </p> <p>Anything in here is open to critique, but specifically I'd like to review my use of a module pattern and my implementation and use of promise objects.</p> <p>The "modules" are each a file, and the aim is to limit and explicitly declare dependencies. My use of promises is to simplify the use of ajax.</p> <p>My 3 files are:</p> <ul> <li>init.js - the main application. </li> <li>promise.js - my implementation of promises </li> <li>ajax.js - ajax functionality </li> </ul> <p><strong>init.js:</strong></p> <pre><code>(function (window, document, bigmap, ajax) { "use strict"; var attr = { fill: "#fafafa", stroke: "#505050", "stroke-width": 1, "stroke-linejoin": "round" }; var drawings, svg_canvas; svg_canvas = bigmap.initialize("map", window.innerWidth - 21, window.innerHeight - 21); ajax.post("php/paths.php", null) .then(function (value) { drawings = JSON.parse(value); }) .then(function () { bigmap.draw(svg_canvas, drawings.walls, null); }) .then(function () { bigmap.draw(svg_canvas, drawings.depts, attr); }); }(this, this.document, parent.bigmap, parent.ajax)); </code></pre> <p><strong>promise.js:</strong></p> <pre><code>var promise = function () { "use strict"; var pending = [], ready = false, result; var then = function (callback) { if (typeof callback === "function") { if (ready === false) { pending.push(callback); } else { callback(result); } } return this; }; var keep = function (response) { if (ready === false) { ready = true; pending.forEach(function (value, index, ar) { result = response; value(result); }); pending = undefined; } }; var isReady = function () { return ready; }; return { keep: keep, share: { then: then, isReady: isReady } }; }; </code></pre> <p><strong>ajax.js:</strong></p> <pre><code>var ajax = (function (XMLHttpRequest, promise) { "use strict"; var done = 4, ok = 200; function post(url, parameters) { var XHR = new XMLHttpRequest(); var p = promise(); if (parameters === false || parameters === null || parameters === undefined) { parameters = ""; } XHR.open("post", url, true); XHR.setRequestHeader("content-type", "application/x-www-form-urlencoded"); XHR.setRequestHeader('X-Requested-With', 'XMLHttpRequest'); XHR.onreadystatechange = function () { if (XHR.readyState === done &amp;&amp; XHR.status === ok) { p.keep(XHR.responseText); } }; XHR.send(parameters); return p.share; } return { post: post }; }(parent.XMLHttpRequest, parent.promise)); </code></pre> <p>Thanks.</p>
[ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-11-12T21:18:49.133", "Id": "29522", "Score": "0", "body": "You shouldn't be using keywords like `then` as variable names. Most browsers will be ok with it, but it's by no means guaranteed." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-11-13T06:57:56.137", "Id": "29548", "Score": "3", "body": "`then` is not a reserved word in javascript." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-11-13T08:57:41.407", "Id": "62829", "Score": "0", "body": "As for modules, I'd use [RequireJS](http://requirejs.org/) if I were you." } ]
[ { "body": "<p>I assume that you are not going to use readily available third-party libraries for this one. If I had the option to, I'd be using jQuery as it already supports promises, and AJAX.</p>\n\n<p>Anyways, let's start reviewing. I pretty much explain in the comments so watch out for them. Any explanations are usually out of the comments though.</p>\n\n<pre><code>//actually, there is no point doing the localization thing since they \n//are objects (and passed by reference). Anything that changes the \n//original object, these references you have here also change\n//\n//However, it's still useful for assigning aliases so I'll let this one pass\n(function (window, document, bigmap, ajax) {\n \"use strict\";\n\n //personal preference though\n //I prefer chaining the vars with commas\n //declarations on top, those with values last\n //also, you can merge declarations and assignments, like in svg_canvas\n var drawings, \n svg_canvas = bigmap.initialize(\"map\", window.innerWidth - 21, window.innerHeight - 21),\n attr = {\n fill: \"#fafafa\",\n stroke: \"#505050\",\n \"stroke-width\": 1,\n \"stroke-linejoin\": \"round\"\n };\n\n //promises are used for async to maintain a \"sync\" feeling in the code\n //however, if operations are not async, avoid using a promise\n //if bigmap.draw is not async, then I'd avoid chaining them in .then()'s\n //because it's overhead\n //\n //but I assume they are async since they are SVG drawing operations\n ajax.post(\"php/paths.php\", null)\n .then(function (value) { \n drawings = JSON.parse(value); \n })\n .then(function () { \n bigmap.draw(svg_canvas, drawings.walls, null); \n })\n .then(function () { \n bigmap.draw(svg_canvas, drawings.depts, attr); \n });\n\n}(this, this.document, parent.bigmap, parent.ajax));\n</code></pre>\n\n<p>On the promises, I'd avoid the module pattern and use prototypes. Imagine this: Every call to promise() returns an object with it's own properties <em>as well as functions</em>. When using prototypes, each promise will have it's own properties, but will share the functions. Forget privates, this one saves memory. However, just like me, if you hate the <code>new Constructor()</code> approach, you can mask the operation in a function call.</p>\n\n<pre><code>//constructor\nfunction PromiseBuilder(){\n this.pending = [];\n this.ready = false;\n this.result;\n}\n\n//our shared functions\n\n//this one stores the callback\nPromiseBuilder.prototype.then = function (callback) {\n //personal preference, but I use single quotes\n if (typeof callback === 'function') {\n //ready is boolean. instead of checking for false,\n //you can use loose checking and ! which means *if not* ready\n if (!ready) {\n this.pending.push(callback);\n } else {\n //so you won't lose the instance, use call and pass this\n //as \"this\" in your function\n callback.call(this,result);\n }\n }\n //according to the PromisesA spec [http://wiki.commonjs.org/wiki/Promises/A]\n //each then should return a new promise\n //I haven't read the full spec or try implementing it\n //but you should, if you want it to become a proper PromiseA type promise\n return this;\n};\n\n//I guess this one acts as the \"resolve\" - you should name it that way\nPromiseBuilder.prototype.resolve = function () {\n\n //saving the instance and all arguments\n var instance = this,\n resolveArgs = arguments;\n\n if (!ready) {\n\n ready = true;\n\n //ES5 foreach? or are you using a shim/fix?\n this.pending.forEach(function (value, index, ar) {\n\n //instead of being restrained in one argument,\n //why not pass the entire arguments array to the callback\n //by using .apply()\n value.apply(instance,resolveArgs);\n });\n\n this.pending = undefined;\n }\n};\n\nPromiseBuilder.prototype.isReady = function () {\n return this.ready;\n};\n\n//our masking function\nfunction promise() {\n return new PromiseBuilder(); \n};\n</code></pre>\n\n<p>Same as well for AJAX, we use literal namespacing instead. since the ajax response is now bound to the promise there is no need to have instances for our ajax.</p>\n\n<pre><code>var ajax = {\n post : function(url,parameters){\n var XHR = new XMLHttpRequest(),\n p = promise(),\n parameters = params || ''; //parameters is either itself or blank if none\n\n XHR.open(\"post\", url, true);\n XHR.setRequestHeader(\"content-type\", \"application/x-www-form-urlencoded\");\n XHR.setRequestHeader('X-Requested-With', 'XMLHttpRequest');\n XHR.onreadystatechange = function () {\n if (XHR.readyState === 4 &amp;&amp; XHR.status === 200) {\n promise.keep(XHR.responseText);\n }\n };\n XHR.send(parameters);\n\n return promise;\n }\n}\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-11-18T15:08:17.240", "Id": "29913", "Score": "0", "body": "I'm not using 3rd party libraries because I want to understand everything that's going on while I learn. Also, the `forEach` I use is from ES5." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-11-18T15:09:42.183", "Id": "29914", "Score": "0", "body": "I've seen prototypes before, but I didn't realize that all instances of that object share the same functions (so you're not copying around function definitions that you don't have to). Also, that's a great idea of wrapping the `new Constructor()` in a function. I hadn't thought of that." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-11-18T15:15:04.400", "Id": "29916", "Score": "0", "body": "Finally, I wasn't aware that the `then` method is supposed to return a **new** promise. Does that mean that when you chain `then` calls together (`promise1.then(something).then(something).then(something);`) there are 3 separate promises, each with one callback in the `pending` array? And that if you **don't** chain them together (`promise1.then(something); promise1.then(something); promise1.then(something);`) you end up with one promise that has 3 callbacks in the `pending` array? Any idea what the benefit of this is? Either way, I'll go dig into the PromiseA spec." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-11-19T12:00:36.827", "Id": "29967", "Score": "1", "body": "The idea of new promises was [explained in this gist](https://gist.github.com/3889970). And yes, methods attached to the prototype of an object is shared across instances, saving memory. However, properties should live in the instance. Shared properties is possible but discouraged as unexpected things may occur." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-11-19T13:52:46.817", "Id": "29973", "Score": "0", "body": "Thanks for the link to the gist. That's very helpful. If anyone else is looking for good links explaining promises implementation, [here's](https://github.com/kriskowal/q/blob/master/design/README.js) another one." } ], "meta_data": { "CommentCount": "5", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-11-18T00:52:57.377", "Id": "18755", "ParentId": "18513", "Score": "3" } } ]
{ "AcceptedAnswerId": "18755", "CommentCount": "3", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-11-12T20:19:06.937", "Id": "18513", "Score": "4", "Tags": [ "javascript", "design-patterns", "ajax", "modules" ], "Title": "How are my javascript module pattern and promise pattern?" }
18513
<p>Ran across this question today:</p> <blockquote> <p>write a class Tool which will have a function void type() that every derived class should implement . A function Action() that every derived class can override . function init() which is available to only Tool and variable Name which will tell which class`s instance is this object</p> </blockquote> <p>Here is my solution (based on other solutions I've found):</p> <pre><code>#include &lt;typeinfo&gt; class Tool{ public: string name; Tool() { name = typeid(*this).name(); }; virtual void type() = 0; virtual void Action(); private: void init(); }; </code></pre> <p>Could someone double check this please?</p>
[ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-11-12T22:16:52.890", "Id": "29529", "Score": "2", "body": "One minor thing I noticed is that you don't include std::string" } ]
[ { "body": "<p>Your code does not work: <a href=\"http://codepad.org/OtKa9Aki\" rel=\"nofollow\">http://codepad.org/OtKa9Aki</a></p>\n\n<p>Just like calls to virtual functions in a constructor call the base class function, such usage of typeid also does not recognise the derived class. You could have the <code>Tool</code> constructor take an <code>std::string</code> and assign that to <code>name</code>. </p>\n\n<p>Alternatively, you could be pedantic and claim that the instance of <code>B</code> will always be an instance of <code>B</code>, and that the derived classes are simply accessing this instance when they do <code>d.name</code>. I doubt, however, that this would be appreciated.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-11-13T01:47:19.167", "Id": "29536", "Score": "0", "body": "Not really sure what you mean by have the Tool constructor take an std::string and assign it to name. The problem wants the variable name to hold the name of the class - I don't think we're allowed to pass anything into the constructor." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-11-13T11:30:29.857", "Id": "29559", "Score": "0", "body": "If you cannot pass anything to the constructor, what you are being asked to do is not possible. As you can see, calling `typeid` does not give the desired result." } ], "meta_data": { "CommentCount": "2", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-11-12T23:42:35.363", "Id": "18518", "ParentId": "18514", "Score": "0" } }, { "body": "<p>I would strongly recommend making <code>name</code> field const. Also, <code>typeid(*this).name()</code> won't look nice and pretty in some compilers.\nYou should probably try something like:</p>\n\n<pre><code>class Tool {\npublic:\n const std::string name;\n &lt;...&gt;\nprotected:\n Tool(const char* className) : name(className) {}\nprivate:\n &lt;...&gt;\n}\n</code></pre>\n\n<p>BTW, do NOT expect <code>typeid(*this).name();</code> to be called for deriven object. Even virtual functions won't help, so you can't write something like <code>virtual const char* getMyName() = 0;</code>, because any kind of \"virtual\" behavior will not work in constructor.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-11-13T10:27:19.160", "Id": "18530", "ParentId": "18514", "Score": "4" } }, { "body": "<p>I suggest adding virtual destructor. Your polymorphic class can be used threw the pointer to the base class:</p>\n\n<pre><code>Tool* base = new Derived();\ndelete base; // virtual destructor is required here\n</code></pre>\n\n<p>As suggested by @random-guy-from-internets, it is worth adding constructor which gets human-readable type name parameter. I'd suggest only to make it explicit:</p>\n\n<pre><code>class Tool {\npublic:\n virtual ~Tool() {}\nprotected:\n explicit Tool(const char* className) : name(className) {}\nprivate:\n &lt;...&gt;\n};\n</code></pre>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-11-13T11:59:29.850", "Id": "18535", "ParentId": "18514", "Score": "3" } }, { "body": "<p>You can use templates to know what is the derived class:</p>\n\n<pre><code>#include &lt;typeinfo&gt;\n#include &lt;string&gt;\n\nclass ToolBase {\n public:\n std::string name;\n explicit ToolBase(const std::string&amp; classname):name(classname){}\n virtual ~ToolBase() {}\n virtual void type() = 0; \n virtual void Action() {}\n private:\n void init(); \n};\n\ntemplate &lt;typename Child&gt;\nclass Tool : public ToolBase {\n public:\n Tool():ToolBase(typeid(Child).name()){}\n};\n</code></pre>\n\n<p>And you use it like this:</p>\n\n<pre><code>class Derived : public Tool&lt;Derived&gt;\n{\n public:\n Derived() {}\n ~Derived() {}\n void type(){\n //implementation could call Action\n Action();\n }\n};\n</code></pre>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-11-16T01:03:41.280", "Id": "18688", "ParentId": "18514", "Score": "1" } } ]
{ "AcceptedAnswerId": "18530", "CommentCount": "1", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-11-12T22:03:10.150", "Id": "18514", "Score": "1", "Tags": [ "c++" ], "Title": "C++ Class Writing Interview Query" }
18514
<p>I have been looking everywhere to find good real world examples of the new Async and Await features in .net 4.5. I have come up with the following code to download a list of files and limit the number of concurrent downloads. I would appreciate any best practices or ways to improve/optimize this code.</p> <p>We are calling the below code using the following statement. </p> <pre><code>await this.asyncDownloadManager.DownloadFiles(this.applicationShellViewModel.StartupAudioFiles, this.applicationShellViewModel.SecurityCookie, securityCookieDomain).ConfigureAwait(false); </code></pre> <p>We are then using events to add the downloaded files to an observablecollection (new thread safe version in .net 4.5) on the ViewModel.</p> <pre><code>public class AsyncDownloadManager { public event EventHandler&lt;DownloadedEventArgs&gt; FileDownloaded; public async Task DownloadFiles(string[] fileIds, string securityCookieString, string securityCookieDomain) { List&lt;Task&gt; allTasks = new List&lt;Task&gt;(); //Limits Concurrent Downloads SemaphoreSlim throttler = new SemaphoreSlim(initialCount: Properties.Settings.Default.maxConcurrentDownloads); var urls = CreateUrls(fileIds); foreach (var url in urls) { await throttler.WaitAsync(); allTasks.Add(Task.Run(async () =&gt; { try { HttpClientHandler httpClientHandler = new HttpClientHandler(); if (!string.IsNullOrEmpty(securityCookieString)) { Cookie securityCookie; securityCookie = new Cookie(FormsAuthentication.FormsCookieName, securityCookieString); securityCookie.Domain = securityCookieDomain; httpClientHandler.CookieContainer.Add(securityCookie); } await DownloadFile(url, httpClientHandler).ConfigureAwait(false); } finally { throttler.Release(); } })); } await Task.WhenAll(allTasks).ConfigureAwait(false); } async Task DownloadFile(string url, HttpClientHandler clientHandler) { HttpClient client = new HttpClient(clientHandler); DownloadedFile downloadedFile = new DownloadedFile(); try { HttpResponseMessage responseMessage = await client.GetAsync(url).ConfigureAwait(false); var byteArray = await responseMessage.Content.ReadAsByteArrayAsync().ConfigureAwait(false); if (responseMessage.Content.Headers.ContentDisposition != null) { downloadedFile.FileName = Path.Combine(Properties.Settings.Default.workingDirectory, responseMessage.Content.Headers.ContentDisposition.FileName); } else { return; } if (!Directory.Exists(Properties.Settings.Default.workingDirectory)) { Directory.CreateDirectory(Properties.Settings.Default.workingDirectory); } using (FileStream filestream = new FileStream(downloadedFile.FileName, FileMode.Create, FileAccess.Write, FileShare.None, bufferSize: 4096, useAsync: true)) { await filestream.WriteAsync(byteArray, 0, byteArray.Length); } } catch(Exception ex) { return; } OnFileDownloaded(downloadedFile); } private void OnFileDownloaded(DownloadedFile downloadedFile) { if (this.FileDownloaded != null) { this.FileDownloaded(this, new DownloadedEventArgs(downloadedFile)); } } public class DownloadedEventArgs : EventArgs { public DownloadedEventArgs(DownloadedFile downloadedFile) { DownloadedFile = downloadedFile; } public DownloadedFile DownloadedFile { get; set; } } </code></pre> <ol> <li>What is the affect of embedding Async / Await in other Async / Await methods? (Write filestream to disk inside an Async / Await method. </li> <li>Is the ConfigureAwait(False) used properly or should we use it more liberally? </li> <li>Should a httpclient be used for each separate task or should they share a singe one? 4. Are events a good way to "send" the downloaded file reference to the viewmodel? </li> <li>Is the await Task.WhenAll(allTasks).ConfigureAwait(false); the best way to run all tasks concurrently limited by the SemaphoreSlim throttle.</li> </ol>
[]
[ { "body": "<p>Sorry, I did not look thoroughly through your code, but regarding \"good real world examples of the new Async and Await features\":</p>\n\n<p>Writing simple windows 8 store (ex-\"Metro-style\") application helped me greatly to understand and get used to async/await pattern.</p>\n\n<p>Basically, in their new API everything that can be time-consuming (disk IO, network IO, etc) is now async. You just can't call it synchronously.</p>\n\n<p>I think this is aimed to force us writing responsive apps which do not block UI thread.\nFor example, you need to download a file and save it to disk, and display busy indicator in UI. In your ViewModel you then say something like:</p>\n\n<pre><code>void DoTheJob()\n{\n IsBusy=true;\n var text = await DownloadText();\n ProgressText=\"Saving...\";\n await SaveText(text);\n IsBusy=false;\n}\n</code></pre>\n\n<p>I'd say this is a good real world example (my \"dictionary\" app uses this approach to load translations from disk). </p>\n\n<p>This is a really cool way to deal with UI, in contrast to old BackgroundWorkers/ThreadPool and Dispatcher.BeginInvoke hassle.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-11-13T20:40:17.573", "Id": "29580", "Score": "5", "body": "Note that for your code to compile, you would need to add the `async` modifier to your method. Also, it would be preferable if you changed its return type to `Task`, so that your method could be `await`ed in turn." } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-11-13T11:07:13.977", "Id": "18534", "ParentId": "18519", "Score": "3" } }, { "body": "<p>First, some smaller things (in terms of the size of code changed):</p>\n\n<ol>\n<li>I think you should use <code>var</code> more, especially when it's clear what type the object has, because you're just creating it.</li>\n<li>You shouldn't read the response as a single byte array. Instead, you should use <code>Stream</code>s where possible (it certainly is possible in your case), because they are more efficient.</li>\n<li>Don't just ignore unknown exceptions. If there are some exceptions which you want to ignore (e.g. when a website returns 404), specify them explicitly.</li>\n</ol>\n\n<p>The big thing I would change about your code is how you throttle your code and how you return the results. While throttling your code using <code>Semaphore</code> will work fine, I think you should let some library for asynchronous handling of collections do that for you. Such libraries include Rx and TPL Dataflow. Doing that will also let you avoid using an event, because your method will return “asynchronous collection” instead (<code>IObservable&lt;T&gt;</code> in Rx, <code>ISourceBlock&lt;T&gt;</code> in TPL Dataflow).</p>\n\n<p>With TPL Dataflow, your code could look something like:</p>\n\n<pre><code>public ISourceBlock&lt;DownloadedFile&gt; DownloadFiles(string[] fileIds, string securityCookieString, string securityCookieDomain)\n{\n var urls = CreateUrls(fileIds);\n\n // we have to use TransformManyBlock here, because we want to be able to return 0 or 1 items\n var block = new TransformManyBlock&lt;string, DownloadedFile&gt;(\n async url =&gt;\n {\n var httpClientHandler = new HttpClientHandler();\n if (!string.IsNullOrEmpty(securityCookieString))\n {\n var securityCookie = new Cookie(FormsAuthentication.FormsCookieName, securityCookieString);\n securityCookie.Domain = securityCookieDomain;\n httpClientHandler.CookieContainer.Add(securityCookie);\n }\n\n return await DownloadFile(url, httpClientHandler);\n }, new ExecutionDataflowBlockOptions { MaxDegreeOfParallelism = Properties.Settings.Default.maxConcurrentDownloads });\n\n foreach (var url in urls)\n block.Post(url);\n\n block.Complete();\n\n return block;\n}\n\nprivate static async Task&lt;DownloadedFile[]&gt; DownloadFile(string url, HttpClientHandler clientHandler)\n{\n var client = new HttpClient(clientHandler);\n var downloadedFile = new DownloadedFile();\n\n try\n {\n HttpResponseMessage responseMessage = await client.GetAsync(url);\n\n if (responseMessage.Content.Headers.ContentDisposition == null)\n return new DownloadedFile[0];\n\n downloadedFile.FileName = Path.Combine(\n Properties.Settings.Default.workingDirectory, responseMessage.Content.Headers.ContentDisposition.FileName);\n\n if (!Directory.Exists(Properties.Settings.Default.workingDirectory))\n {\n Directory.CreateDirectory(Properties.Settings.Default.workingDirectory);\n }\n\n using (var httpStream = await responseMessage.Content.ReadAsStreamAsync())\n using (var filestream = new FileStream(\n downloadedFile.FileName, FileMode.Create, FileAccess.Write, FileShare.None, bufferSize: 4096, useAsync: true))\n {\n await httpStream.CopyToAsync(filestream, 4096);\n }\n }\n // TODO: improve\n catch (Exception ex)\n {\n return new DownloadedFile[0];\n }\n\n return new[] { downloadedFile };\n}\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-11-20T01:03:12.333", "Id": "30018", "Score": "0", "body": "Thanks for the code. I tend to not use var when posting samples. I was thinking that stream was a much better way to consume than the bytearray, but I was worried about the async nature. I see how your code would work perfectly dealing with the streams. Finally - it seems like I need to really research Rx and TPL more. I had thought that they were somewhat obsolete with Async/Await, but it looks like I was mistaken. New releases for both. You would recommend TPL for this scenario?" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-11-20T01:15:43.193", "Id": "30019", "Score": "1", "body": "TPL is certainly not obsolete in any way by async, party because async is actually built on top of TPL (the `Task` type) and partly because they are doing different things (e.g. there is no direct async alternative to `Parallel.ForEach()`). But I was talking specifically about TPL Dataflow, which is new in .Net 4.5 and was written to take advantage of async. And Rx is not obsolete either, its uses are mostly different than plain async (though there is some overlap)." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-12-18T16:43:37.193", "Id": "62520", "Score": "1", "body": "Any reason you are not using [this](http://msdn.microsoft.com/en-us/library/hh551757(v=vs.110).aspx) `GetAsync` overload with `HttpCompletionOption.ResponseHeadersRead` and then consume the response with `ReadAsStreamAsync()`?" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-12-18T17:23:44.247", "Id": "62524", "Score": "0", "body": "@G.Stoynev I just copied that code from the question. I don't actually know `HttpClient` that well." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2016-04-25T18:40:14.320", "Id": "236697", "Score": "0", "body": "@AceInfinity I think [your suggestions](http://codereview.stackexchange.com/review/suggested-edits/55767) are good, but since a lot of them are modifying code that I copied from the question, I think you should post them as a separate review answer." } ], "meta_data": { "CommentCount": "5", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-11-15T21:18:32.667", "Id": "18679", "ParentId": "18519", "Score": "15" } } ]
{ "AcceptedAnswerId": "18679", "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-11-13T01:24:50.080", "Id": "18519", "Score": "25", "Tags": [ "c#", "asynchronous" ], "Title": "Real World Async and Await Code Example" }
18519
<p>I am wondering if in particular the function called <code>AssignDBStatusMessage</code> and <code>TryDataBaseAction</code> are unnecessary. It seems to me that the logic is more cluttered if i do away with those functions. Please provide me with your ideas and thoughts.</p> <p>If you have other thoughts please let me know.</p> <p><strong>man</strong> is an entity class generated by entity framework. <strong>TestDataBaseEntities</strong> is the DBcontext item.</p> <pre><code>public class DataAccess { // ============================ // CRUD FUNCTIONS for MAN TABLE // ============================ public bool CreateMan(TestDatabaseEntities dbEntities, out string StatusMessage, Man M) { string ErrorMessage; bool bSuccessful; bSuccessful = TryDataBaseAction(dbEntities, out ErrorMessage, () =&gt; { dbEntities.Men.Add(new Man { ManID = M.ManID, Name = M.Name }); }); StatusMessage = AssignDBStatusMessage("Records created successfully", ErrorMessage, bSuccessful); return bSuccessful; } public bool UpdateMan(TestDatabaseEntities dbEntities, IQueryable&lt;Man&gt; query, out string StatusMessage, Man man) { string ErrorMessage; bool bSuccessful; bSuccessful = TryDataBaseAction(dbEntities, out ErrorMessage, () =&gt; { foreach (Man M in query) { M.Name = man.Name; } }); StatusMessage = AssignDBStatusMessage("Records updated successfully", ErrorMessage, bSuccessful); return bSuccessful; } public bool DeleteMan(TestDatabaseEntities dbEntities, IQueryable myQuery, out string StatusMessage) { string ErrorMessage; bool bSuccessful; bSuccessful = TryDataBaseAction(dbEntities, out ErrorMessage, () =&gt; { foreach (Man M in myQuery) { dbEntities.Men.Remove(M); } }); StatusMessage = AssignDBStatusMessage("Records deleted successfully", ErrorMessage, bSuccessful); return bSuccessful; } public bool ReadMan(TestDatabaseEntities dbEntities, IQueryable myQuery, out string StatusMessage, out string[,] Records) { string ErrorMessage; bool bSuccessful; string[,] TheseRecords = null; // hands an Action() to TryDataBase, as indicated by lambda expression in 3rd arguement. bSuccessful = TryDataBaseAction(dbEntities, out ErrorMessage, () =&gt; { List&lt;Man&gt; men = myQuery.OfType&lt;Man&gt;().ToList(); TheseRecords = new string[men.Count, 2]; for (int i = 0; i &lt; men.Count; i++) { TheseRecords[i, 0] = men[i].ManID.ToString(); TheseRecords[i, 1] = men[i].Name; } }); Records = TheseRecords; StatusMessage = AssignDBStatusMessage("Records read successfully", ErrorMessage, bSuccessful); return bSuccessful; } // ============================ // SAVECHANGES FUNCTION // ============================ public bool SaveChanges(TestDatabaseEntities dbEntities, out string StatusMessage) { bool bSuccessful; string ErrorMessage; bSuccessful = TryDataBaseAction(dbEntities, out ErrorMessage, () =&gt; dbEntities.SaveChanges()); StatusMessage = AssignDBStatusMessage("Save changes Sucessful", ErrorMessage, bSuccessful); return bSuccessful; } // ============================ // Helper functions? // ============================ public bool TryDataBaseAction(TestDatabaseEntities MyDBEntities, out string ErrorMessage, Action MyDBAction) { UserInterface MyUI = new UserInterface(); try { MyDBAction(); ErrorMessage = "No Errors"; return true; } catch (Exception e) { ErrorMessage = e.ToString(); return false; } } private string AssignDBStatusMessage(string SuccessMsg, string FailureMsg, bool bSuccessful) { if (bSuccessful) return SuccessMsg; else return FailureMsg; } } </code></pre>
[]
[ { "body": "<p>Not huge thoughts but a couple of things. </p>\n\n<ol>\n<li><p>I would probably consider making the entities object a class level parameter since it seems to be used in every method.</p></li>\n<li><p>I wouldn't put the success message in this class as that seems more caller dependant. Hence I would let the caller determine what success message they want on a true result. I would only supply a failed message to at least inform the user what happened.</p></li>\n<li><p>Is this sort of a repository pattern... not sure. But I might toy with the idea of changing DataAccess to ManRepository and getting rid of man in the function names so it's just Create, Update and Read.</p></li>\n</ol>\n\n<p>i.e.</p>\n\n<pre><code>public class ManRespository\n{\n private readonly TestDatabaseEntities _dbEntities;\n public ManRepository(TestDatabaseEntities dbEntities)\n {\n _dbEntities = dbEntities;\n }\n\n // Your Create, Update, Read methods here\n public DbResult Create(Man man) \n {\n // etc\n }\n}\n</code></pre>\n\n<ol>\n<li>In light of 2, I might consider not returning bool at all but rather a result class.</li>\n</ol>\n\n<p>Something like this perhaps:</p>\n\n<pre><code>public class DbResult\n{\n public bool Success { get; private set; }\n public String Message { get; private set; }\n\n private DbResult(boolean success, string message)\n {\n Success = success;\n Message = message;\n }\n\n public static DbResult Failed(string message) {\n return new DbResult(false, message);\n }\n\n public static DbResult Success(string message) {\n return new DbResult(true, message);\n }\n}\n</code></pre>\n\n<p>Then an example of the one of your methods might now be simplified to:</p>\n\n<pre><code>public DbResult Create(Man M)\n{\n return TryDataBaseAction(\n () =&gt;\n {\n _dbEntities.Men.Add(new Man { ManID = M.ManID, Name = M.Name });\n });\n}\n\npublic DbResult TryDataBaseAction(Action MyDBAction)\n{\n string errorMessage = string.Empty;\n\n try\n {\n // What was MyUI supposed to do here? I would think mixing UI\n // dependencies at this level was not a good idea unless it was through\n // an abstraction such as an Interface or Abstract class of some sort?\n UserInterface MyUI = new UserInterface();\n\n MyDBAction(); \n\n return DbResult.Success(string.Empty);\n }\n catch (Exception e)\n {\n errorMessage = e.ToString();\n }\n\n return DbResult.Failed(errorMessage);\n}\n</code></pre>\n\n<p>Note: <em>AssignDBStatusMessage</em> actually became redundant in this approach and <em>TryDataBaseAction</em> is seeming a bit weak now??</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-11-13T21:59:56.607", "Id": "29581", "Score": "0", "body": "MyUI was something I forgot to remove. In the original code, i had MyUI call its method to display output to user cause it seemed like going through less hoops and hurdles than passing it back to the main program." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-11-13T22:04:47.073", "Id": "29582", "Score": "0", "body": "On what occurances are you expecting the method to fail then? I think it would be best to do away with the TryDataBaseAction() action altogether and put that stuff into the individual Creates, Updates as I assume they fail for different reasons??" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-11-14T00:15:22.820", "Id": "29591", "Score": "0", "body": "Well, sometimes it's simply that the SQL server isn't up and running, in which case the CRUD methods would fail then. But yes, they'd fail for different reasons otherwise, Update and Delete could fail if the targeted Record ID wasn't found, Read? i don't know why it would. Create? possibly if the new record's ID already existed. (I still need to make a fix for that). I am trying to plan so that I can can possibly use the CRUD functions on an alternate entity Locations, which is also a table in my entity model. I was just trying to get a good foundation going for the man entity first." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-11-14T00:41:52.693", "Id": "29593", "Score": "0", "body": "@ArmorCode I quite like the repository pattern. Perhaps this might be an option to explore for yourself?" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-11-14T17:15:18.120", "Id": "29642", "Score": "0", "body": "I'll use it, It simplifies the code. But I'm still not clear on what constitutes a repository pattern. I am reading about it on this [MSDN Link](http://msdn.microsoft.com/en-us/library/ff649690.aspx), but I feel more confused after reading it and looking at the charts. Does this conflict with the MVC pattern I'm trying to implement? I say MVC because I want to show potential employers so that they see my code and say \"Ah, ok he understands what MVC is.\"" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-11-14T22:10:09.853", "Id": "29664", "Score": "0", "body": "I'm not sure I understand how the success message is more caller-dependent. I mean I understand that it depends on the method which called it to determine the success message, but the calling methods (CRUD methods, are defined in the DataAccess class. So being more caller-dependent and being that the callers are in the same class, and suggesting to define the messages outside the class is confusing to me." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-11-14T22:29:45.627", "Id": "29669", "Score": "1", "body": "My thoughts were that why do you need to supply a success message from this layer at all. If it succeeded that's great. If the caller wants to display a message then let them put one together.... Just my thoughts anyway." } ], "meta_data": { "CommentCount": "7", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-11-13T08:39:14.730", "Id": "18524", "ParentId": "18520", "Score": "2" } } ]
{ "AcceptedAnswerId": "18524", "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-11-13T01:39:06.397", "Id": "18520", "Score": "2", "Tags": [ "c#", "entity-framework" ], "Title": "Am I using too many functions in my DataAccess Class?" }
18520
<p>There at least 2 patterns of using <code>Stack.Pop</code></p> <ol> <li> <pre><code>private Stack&lt;T&gt; availableResources; ... if (availableResources.Count &gt; 0) { resource = availableResources.Pop(); ... } </code></pre></li> <li> <pre><code>private Stack&lt;T&gt; availableResources; ... try { resource = availableResources.Pop(); ... } catch (InvalidOperationException e) { ... } </code></pre></li> </ol> <p>I'd like to ask people, which of 2 is preferable? If possible, argument your answer.</p>
[ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-11-15T22:12:06.373", "Id": "29741", "Score": "0", "body": "Save your exceptions for exceptional cases you don't know how to handle. Patterns 2 is good for wrapping a method that can fail for various non-related or unknown reasons (`DownloadRemoteFile(url)`). Or for python." } ]
[ { "body": "<p>Program defensively and use option 1.</p>\n\n<p>Since the <code>Stack</code> class provides the ability to check whether it contains anything before trying to <code>Pop</code> a value from it, you should do the check and avoid using the exception for flow control.</p>\n\n<p>If you want to avoid doing the <code>if</code> check throughout your application, you could create a <code>TryPop</code> extension.</p>\n\n<pre><code>public static class StackExtensions\n{\n public static bool TryPop&lt;T&gt;(this Stack&lt;T&gt; stack, out T value)\n {\n if (stack.Count &gt; 0)\n {\n value = stack.Pop();\n return true;\n }\n\n value = default(T);\n return false;\n }\n}\n</code></pre>\n\n<p>It could be used in the following way:</p>\n\n<pre><code>T resource;\nif (availableResources.TryPop(out resource)) \n{\n // use `resource` for something\n}\n</code></pre>\n\n<p><em>It's worth noting that this approach is only suitable if the <code>Stack</code> is not accessed concurrently!</em> - If it is, and you are using .NET 4.0 onwards then you should use <a href=\"http://msdn.microsoft.com/en-us/library/dd267331.aspx\">ConcurrentStack</a>, otherwise create your own concurrent stack which encapsulates a <code>Stack</code> and manages access to it with locks.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-11-15T21:23:43.853", "Id": "29733", "Score": "3", "body": "Be careful when implementing your own concurrent stack. For example, checking `Count` before `Pop()` is not thread-safe, even if each of those methods is. You would need a thread-safe `TryPop()` and no `Pop()`, like .Net 4.0 `ConcurrentStack` does." } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-11-13T10:46:51.327", "Id": "18532", "ParentId": "18531", "Score": "17" } }, { "body": "<p>First we should check, is there concurrent access to stack, or not. \nIf it is, the first pattern doesn't handle an exception ('cause between the check and popping itself there can be an additional popping from the other thread), so consider using either ConcurrentStack&lt;> or double-checking lock. \nWithout them, in concurrent case, the second pattern is definitely better.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-11-20T18:59:18.270", "Id": "30067", "Score": "0", "body": "Stack.Pop might still destroy internal data structures when used concurrently without locks which makes Stack behave unpredictable. ConcurrentStack or locks." } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-11-13T13:39:56.767", "Id": "18540", "ParentId": "18531", "Score": "1" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "1", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-11-13T10:28:11.343", "Id": "18531", "Score": "9", "Tags": [ "c#", "stack" ], "Title": "Which is the most correct pattern for using Stack.Pop?" }
18531
<p>I wrote simple delegate in C++11 for my GUI project. I think that some parts can be optimized or cleaned.</p> <pre><code>#ifndef DELEGATE_H #define DELEGATE_H //Container interface template&lt;typename... Args&gt; class IContainer { public: virtual void Call(Args...) {} virtual ~IContainer() {} IContainer&lt;Args...&gt; *next; }; //Container realization template&lt; typename T, typename M, typename... Args &gt; class MContainer : public IContainer&lt;Args...&gt; { public: MContainer( T* c, M m ) : mClass( c ), mMethod( m ) {} void Call(Args... args) { (mClass-&gt;*mMethod)( args... ); } private: T *mClass; M mMethod; }; template&lt; typename M, typename... Args &gt; class FContainer : public IContainer&lt;Args...&gt; { public: FContainer( M m ) : mMethod( m ) {} void Call(Args... args) { (mMethod)( args... ); } private: M mMethod; }; //Delegate template&lt;typename... Args&gt; class Delegate { public: Delegate() { mContainerHead = new IContainer&lt;Args...&gt;(); mContainerTail = mContainerHead; mContainerHead-&gt;next = 0; } ~Delegate() { IContainer&lt;Args...&gt; *container = mContainerHead; while(container) { IContainer&lt;Args...&gt; *temp = container-&gt;next; delete container; container = temp; } } void Clear() { IContainer&lt;Args...&gt; *container = mContainerHead-&gt;next; while(container) { IContainer&lt;Args...&gt; *temp = container-&gt;next; delete container; container = temp; } mContainerHead-&gt;next = 0; mContainerTail = mContainerHead; } template&lt;typename T, typename M&gt; void Connect(T *c, M m) { mContainerTail-&gt;next = new MContainer&lt; T, M, Args... &gt;(c,m); mContainerTail-&gt;next-&gt;next = 0; mContainerTail = mContainerTail-&gt;next; } template&lt;typename M&gt; void Connect(M m) { mContainerTail-&gt;next = new FContainer&lt; M, Args... &gt;(m); mContainerTail-&gt;next-&gt;next = 0; mContainerTail = mContainerTail-&gt;next; } template&lt;typename T, typename M&gt; void Disconnect(T *c, M m) { IContainer&lt;Args...&gt; *container = mContainerHead; while(container-&gt;next) { MContainer&lt;T, M, Args...&gt; *temp = dynamic_cast&lt; MContainer&lt;T, M, Args...&gt;* &gt;(container-&gt;next); if(temp) { if(container-&gt;next == mContainerTail) { mContainerTail = container; } container-&gt;next = container-&gt;next-&gt;next; delete temp; break; } container = container-&gt;next; } } template&lt;typename M&gt; void Disconnect(M m) { IContainer&lt;Args...&gt; *container = mContainerHead; while(container-&gt;next) { FContainer&lt;M, Args...&gt; *temp = dynamic_cast&lt; FContainer&lt;M, Args...&gt;* &gt;(container-&gt;next); if(temp) { if(container-&gt;next == mContainerTail) { mContainerTail = container; } container-&gt;next = container-&gt;next-&gt;next; delete temp; break; } container = container-&gt;next; } } void operator ()(Args... args) { Call(args...); } void Call(Args... args) { IContainer&lt;Args...&gt; *container = mContainerHead; while(container) { container-&gt;Call(args...); container = container-&gt;next; } } private: IContainer&lt;Args...&gt; *mContainerHead; IContainer&lt;Args...&gt; *mContainerTail; }; #endif // DELEGATE_H </code></pre> <p>Using example:</p> <pre><code>struct TestClass1 { void hello(int a, int b) { std::cout &lt;&lt; a &lt;&lt; " + " &lt;&lt; b &lt;&lt; " = " &lt;&lt; a+b &lt;&lt; std::endl; }; }; struct TestClass2 { void hello(int a, int b) { std::cout &lt;&lt; a &lt;&lt; " - " &lt;&lt; b &lt;&lt; " = " &lt;&lt; a-b &lt;&lt; std::endl; }; }; struct TestClass3 { void hello(int a, int b) { std::cout &lt;&lt; a &lt;&lt; " * " &lt;&lt; b &lt;&lt; " = " &lt;&lt; a*b &lt;&lt; std::endl; }; }; int main() { TestClass1 t1; TestClass2 t2; TestClass3 t3; Delegate&lt;int, int&gt; d; d.Connect(&amp;t1, &amp;TestClass1::hello); d.Connect(&amp;t2, &amp;TestClass2::hello); d.Connect(&amp;t3, &amp;TestClass3::hello); d.Call(10,5); d.Disconnect(&amp;t2, &amp;TestClass2::hello); return 0; } </code></pre>
[]
[ { "body": "<h3>IContainer</h3>\n<p>In the class <code>IContainer</code> the member <code>next</code> is public. Which leads to potential incorrect useage.</p>\n<p>Non private members is a code smell they should be hidden behind access methods (not get/set but more like chain()). Also it would be easier if you used smart pointers to make sure that everything is correctly cleaned up.</p>\n<h3>Delegate</h3>\n<p>The <code>Delegate</code> class has owned raw pointers and does not <code>follow the rule of five</code> (google rule of three as it is more common but the rule of three was expanded to the rule of five with C++11).</p>\n<p>You can fix this be either implementing (or disabling) all the compiler generated methods. Or converting your owned raw pointers into smart pointers. My choice would be to convert them into smart pointers as correctly handing multiple RAW pointers with exceptions propagating is non trivial (a class with multiple owned RAW pointers is a Code smell even if you do implement the rule of five).</p>\n<p>The code ~Delegate() and Clear() is very similar (ie code duplication). You should refactor this to move common code to a single function. If the code changes you then only have a single location that will need fixing.</p>\n<p>In the method <code>Conect()</code> a lot of work is done that is usually associated with the constructor of the object. If you give IConnect an appropriate constructor this code becomes highly simplified and easier to follow.</p>\n<p>In the method <code>Disconnect()</code></p>\n<pre><code> IContainer&lt;Args...&gt; *container = mContainerHead;\n while(container-&gt;next)\n {\n // STUFF\n container = container-&gt;next;\n }\n</code></pre>\n<p>This looks more like a for(;;) loop.</p>\n<pre><code> for(IContainer&lt;Args...&gt; *container = mContainerHead; container-&gt;next; container = container-&gt;next)\n {\n // STUFF\n }\n</code></pre>\n<p>I think this does not read as well as it could.</p>\n<pre><code> container-&gt;next = container-&gt;next-&gt;next;\n\n // I would have done:\n container-&gt;next = temp-&gt;next;\n</code></pre>\n<p>There is no indication that anything was removed from the list. There is also the possibility that might be multiple objects in the list that match the input requirements. So even if you remove one item this does not mean there does not exist an item with the same properties.</p>\n<p>Here you have two options: 1) Add another bool parameter (that defaults to false) to indicate that all matching items should be removed from the list. 2) Return a boolean that indicates if anything was removed from the list (this allows the user to manually loop until all matching items have been removed if required).</p>\n<p>In method <code>Call()</code> again I would have used a for(;;) loop.</p>\n<p>You can also do one small optimization by not calling Call() on the actual head node (as you using sentinal that does nothing no point it calling the sentinal).</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-11-15T12:32:11.837", "Id": "29694", "Score": "0", "body": "thanks's for answer. But i don't know how to implement rule of five in this code)" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-11-15T16:03:55.893", "Id": "29713", "Score": "0", "body": "@RevenantX: Then use smart pointers. There is also a great place called stackoverflow where they answer questions like that: [rule of three becomes rule of five with c11](http://stackoverflow.com/questions/4782757/rule-of-three-becomes-rule-of-five-with-c11) and [how to actually implement the rule of five](http://stackoverflow.com/questions/5976459/how-to-actually-implement-the-rule-of-five)" } ], "meta_data": { "CommentCount": "2", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-11-13T16:24:39.480", "Id": "18547", "ParentId": "18537", "Score": "1" } } ]
{ "AcceptedAnswerId": "18547", "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-11-13T12:22:32.603", "Id": "18537", "Score": "2", "Tags": [ "c++", "optimization", "c++11", "delegates" ], "Title": "Delegate for GUI project" }
18537
<p>I'm still trying to learn how to write good tests (and write testable code).</p> <p>This is the function I want to verify, </p> <pre><code> void IAutoTisDal.UpdateRange(Range range) { using (var repo = _repositoryFactory.GetRepository(_baseline)) { var rangeqry = from r in repo.Query&lt;Range&gt;() where r.Id == range.Id select r; var rangeToUpdate = rangeqry.SingleOrDefault(); if (rangeToUpdate == null) throw new Exception(string.Format("Range ID {0} not found", range.Id)); rangeToUpdate.Status = range.Status; rangeToUpdate.FirstPsn = range.FirstPsn; rangeToUpdate.LastPsn = range.LastPsn; rangeToUpdate.PageCount = (int)(range.LastPsn - range.FirstPsn); rangeToUpdate.CourierId = range.CourierId; rangeToUpdate.WorkflowServer = range.WorkflowServer; rangeToUpdate.DoubleFeedInd = range.DoubleFeedInd; repo.Commit(); } } </code></pre> <p>And the unit test:</p> <pre><code> [TestMethod] public void UpdateRange_RangesPropertiesAreCopied() { var rangeToUpdate = new Range() { Id = 1, CourierId = 0, Status = 20, WorkflowServer = null, FirstPsn = -1, LastPsn = -1, PageCount = 0 }; var rangeToSave = new Range() { Id = 1, CourierId = 1234, Status = 40, WorkflowServer = new PhysicalStation(){ Id = 1, Name = "fakeserver"}, FirstPsn = 123, LastPsn = 456, PageCount = 333 }; var repoMock = new Mock&lt;IRepository&gt;(); repoMock.Setup(x =&gt; x.Query&lt;Range&gt;()).Returns(new List&lt;Range&gt;(new[] {rangeToUpdate}).AsQueryable()).Verifiable(); repoMock.Setup(x =&gt; x.Commit()).Verifiable(); var factoryMock = new Mock&lt;IRepositoryFactory&gt;(); factoryMock.Setup(x =&gt; x.GetRepository(It.IsAny&lt;string&gt;())).Returns(repoMock.Object); IAutoTisDal dal = new AutoTisDal(factoryMock.Object, ""); dal.UpdateRange(rangeToSave); repoMock.VerifyAll(); Assert.AreEqual(rangeToUpdate.Id, rangeToSave.Id); Assert.AreEqual(rangeToUpdate.CourierId, rangeToSave.CourierId); Assert.AreEqual(rangeToUpdate.LastPsn, rangeToSave.LastPsn); Assert.AreEqual(rangeToUpdate.FirstPsn, rangeToSave.FirstPsn); Assert.AreEqual(rangeToUpdate.PageCount, rangeToSave.LastPsn - rangeToSave.FirstPsn); Assert.AreSame(rangeToUpdate.WorkflowServer, rangeToSave.WorkflowServer); Assert.AreEqual(rangeToUpdate.Status, rangeToSave.Status); } </code></pre> <p>I know I need to write another test against the expected exception if no RangeId matches.</p> <p>I <em>also</em> realize I'm writing test after the code.</p>
[ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-11-13T14:40:39.223", "Id": "29564", "Score": "0", "body": "side topic: Would IAutoTisDal be a considered service layer or a data access layer? This is a problem-domain-specific interface that calls my `IRepository`. The concrete `IRepository` uses NHibernate to exposes `Query<T>()` and `Commit()`." } ]
[ { "body": "<p>First of all, your single method is doing multiple things:</p>\n\n<ol>\n<li>Get Range by id </li>\n<li>Copy properties from one instance to another</li>\n<li>Commit</li>\n</ol>\n\n<p>Let's try to separate responsibilities:</p>\n\n<pre><code> Range GetRangeById(Repository repo, int id)\n {\n return repo.Query&lt;Range&gt;().SingleOrDefault(r=&gt;r.Id == id);\n }\n\n void UpdateRange(Range rangeToUpdate, Range range)\n {\n // I'd even make this Range extension method\n rangeToUpdate.Status = range.Status;\n rangeToUpdate.FirstPsn = range.FirstPsn;\n rangeToUpdate.LastPsn = range.LastPsn;\n rangeToUpdate.PageCount = (int)(range.LastPsn - range.FirstPsn);\n rangeToUpdate.CourierId = range.CourierId;\n rangeToUpdate.WorkflowServer = range.WorkflowServer;\n rangeToUpdate.DoubleFeedInd = range.DoubleFeedInd;\n }\n\n void IAutoTisDal.UpdateRange(Range range)\n {\n using (var repo = _repositoryFactory.GetRepository(_baseline))\n {\n var rangeToUpdate = GetRangeById(range.Id);\n if (rangeToUpdate == null)\n throw new Exception(string.Format(\"Range ID {0} not found\", range.Id));\n\n UpdateRange(rangeToUpdate, range);\n repo.Commit();\n }\n }\n</code></pre>\n\n<p>Two new methods are already easier to understand and test. \nAnd, honestly, I don't think that writing test for IAutoTisDal.UpdateRange makes much sense. It won't provide much value.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-11-13T14:57:51.947", "Id": "29567", "Score": "0", "body": "Thanks for the input; It does make it a bit easier on the eyes. But why wouldn't the test provide much value? I added the test after realizing I forgot to set the `DoubleFeedInd` property (`Range` class has a couple dozen properties). Perhaps I could have written the test to include only my missing property." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-11-13T15:09:25.080", "Id": "29571", "Score": "1", "body": "I mean that after proposed refactoring this last method becomes quite simple. As I understand, tests provide value in (1) verify that newly written code works and (2) verify that it did not break after changes. In our case, last method is straightforward and relies on other (tested) methods. What can be verified there? That is throws an exception, or really updates db?" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-11-13T15:14:56.193", "Id": "29573", "Score": "1", "body": "Regarding forgotten property: your unit test won't detect the same bug when someone adds one more property to the Range entity. I think some metadata (reflection or data model or whatever - I'm not familiar with NHibernate, but I solved similar problem with Entity Framework) should be involved to verify that right properties are being copied (all public writeable except identity, probably)." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-11-13T15:46:31.343", "Id": "29575", "Score": "0", "body": "I agree about the way to verify all properties are mapped/writable. In this case, the value of the other properties aren't important." } ], "meta_data": { "CommentCount": "4", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-11-13T14:50:35.577", "Id": "18542", "ParentId": "18541", "Score": "5" } }, { "body": "<p>I dunno if I would use reflection for the range mapping to properties. I think this would be a great instance for <code>Func&lt;&gt;</code> lambda expressions. Or perhaps a dictionary key value implementation that can be iterated through..</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-11-14T06:15:12.993", "Id": "29599", "Score": "0", "body": "Can you please give an example how lambdas or dictionary can help to retrieve all db-mapped properties?" } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-11-13T23:08:52.230", "Id": "18568", "ParentId": "18541", "Score": "-1" } } ]
{ "AcceptedAnswerId": "18542", "CommentCount": "1", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-11-13T14:29:52.940", "Id": "18541", "Score": "6", "Tags": [ "c#", "unit-testing", "moq" ], "Title": "Is this UnitTest for updating an object in data-access layer sensible?" }
18541
<p>I'm new to Erlang and this is my first code in that. As Erlang has no loop statements, the only way I could think of doing this is as follows:</p> <pre><code>-module(verschickten). -export([f/0]). f() -&gt; io:format("~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p", [1,3,5,7,9,11,13,15,17,19,21,23,25,27,29,31,33,35,37,39,41,43,45,47,49,51,53,55,57,59,61,63,65,67,69,71,73,75,77,79,81,83,85,87,89,91,93,95,97,99,101,103,105,107,109,111,113,115,117,119,121,123,125,127,129,131,133,135,137,139,141,143,145,147,149,151,153,155,157,159,161,163,165,167,169,171,173,175,177,179,181,183,185,187,189,191,193,195,197,199,201,203,205,207,209,211,213,215,217,219,221,223,225,227,229,231,233,235,237,239,241,243,245,247,249,251,253,255,257,259,261,263,265,267,269,271,273,275,277,279,281,283,285,287,289,291,293,295,297,299,301,303,305,307,309,311,313,315,317,319,321,323,325,327,329,331,333,335,337,339,341,343,345,347,349,351,353,355,357,359,361,363,365,367,369,371,373,375,377,379,381,383,385,387,389,391,393,395,397,399,401,403,405,407,409,411,413,415,417,419,421,423,425,427,429,431,433,435,437,439,441,443,445,447,449,451,453,455,457,459,461,463,465,467,469,471,473,475,477,479,481,483,485,487,489,491,493,495,497,499,501,503,505,507,509,511,513,515,517,519,521,523,525,527,529,531,533,535,537,539,541,543,545,547,549,551,553,555,557,559,561,563,565,567,569,571,573,575,577,579,581,583,585,587,589,591,593,595,597,599,601,603,605,607,609,611,613,615,617,619,621,623,625,627,629,631,633,635,637,639,641,643,645,647,649,651,653,655,657,659,661,663,665,667,669,671,673,675,677,679,681,683,685,687,689,691,693,695,697,699,701,703,705,707,709,711,713,715,717,719,721,723,725,727,729,731,733,735,737,739,741,743,745,747,749,751,753,755,757,759,761,763,765,767,769,771,773,775,777,779,781,783,785,787,789,791,793,795,797,799,801,803,805,807,809,811,813,815,817,819,821,823,825,827,829,831,833,835,837,839,841,843,845,847,849,851,853,855,857,859,861,863,865,867,869,871,873,875,877,879,881,883,885,887,889,891,893,895,897,899,901,903,905,907,909,911,913,915,917,919,921,923,925,927,929,931,933,935,937,939,941,943,945,947,949,951,953,955,957,959,961,963,965,967,969,971,973,975,977,979,981,983,985,987,989,991,993,995,997,999,1001,1003,1005,1007,1009,1011,1013,1015,1017,1019,1021,1023,1025,1027,1029,1031,1033,1035,1037,1039,1041,1043,1045,1047,1049,1051,1053,1055,1057,1059,1061,1063,1065,1067,1069,1071,1073,1075,1077,1079,1081,1083,1085,1087,1089,1091,1093,1095,1097,1099,1101,1103,1105,1107,1109,1111,1113,1115,1117,1119,1121,1123,1125,1127,1129,1131,1133,1135,1137,1139,1141,1143,1145,1147,1149,1151,1153,1155,1157,1159,1161,1163,1165,1167,1169,1171,1173,1175,1177,1179,1181,1183,1185,1187,1189,1191,1193,1195,1197,1199,1201,1203,1205,1207,1209,1211,1213,1215,1217,1219,1221,1223,1225,1227,1229,1231,1233,1235,1237,1239,1241,1243,1245,1247,1249,1251,1253,1255,1257,1259,1261,1263,1265,1267,1269,1271,1273,1275,1277,1279,1281,1283,1285,1287,1289,1291,1293,1295,1297,1299,1301,1303,1305,1307,1309,1311,1313,1315,1317,1319,1321,1323,1325,1327,1329,1331,1333,1335,1337,1339,1341,1343,1345,1347,1349,1351,1353,1355,1357,1359,1361,1363,1365,1367,1369,1371,1373,1375,1377,1379,1381,1383,1385,1387,1389,1391,1393,1395,1397,1399,1401,1403,1405,1407,1409,1411,1413,1415,1417,1419,1421,1423,1425,1427,1429,1431,1433,1435,1437,1439,1441,1443,1445,1447,1449,1451,1453,1455,1457,1459,1461,1463,1465,1467,1469,1471,1473,1475,1477,1479,1481,1483,1485,1487,1489,1491,1493,1495,1497,1499,1501,1503,1505,1507,1509,1511,1513,1515,1517,1519,1521,1523,1525,1527,1529,1531,1533,1535,1537,1539,1541,1543,1545,1547,1549,1551,1553,1555,1557,1559,1561,1563,1565,1567,1569,1571,1573,1575,1577,1579,1581,1583,1585,1587,1589,1591,1593,1595,1597,1599,1601,1603,1605,1607,1609,1611,1613,1615,1617,1619,1621,1623,1625,1627,1629,1631,1633,1635,1637,1639,1641,1643,1645,1647,1649,1651,1653,1655,1657,1659,1661,1663,1665,1667,1669,1671,1673,1675,1677,1679,1681,1683,1685,1687,1689,1691,1693,1695,1697,1699,1701,1703,1705,1707,1709,1711,1713,1715,1717,1719,1721,1723,1725,1727,1729,1731,1733,1735,1737,1739,1741,1743,1745,1747,1749,1751,1753,1755,1757,1759,1761,1763,1765,1767,1769,1771,1773,1775,1777,1779,1781,1783,1785,1787,1789,1791,1793,1795,1797,1799,1801,1803,1805,1807,1809,1811,1813,1815,1817,1819,1821,1823,1825,1827,1829,1831,1833,1835,1837,1839,1841,1843,1845,1847,1849,1851,1853,1855,1857,1859,1861,1863,1865,1867,1869,1871,1873,1875,1877,1879,1881,1883,1885,1887,1889,1891,1893,1895,1897,1899,1901,1903,1905,1907,1909,1911,1913,1915,1917,1919,1921,1923,1925,1927,1929,1931,1933,1935,1937,1939,1941,1943,1945,1947,1949,1951,1953,1955,1957,1959,1961,1963,1965,1967,1969,1971,1973,1975,1977,1979,1981,1983,1985,1987,1989,1991,1993,1995,1997,1999,2001,2003,2005,2007,2009,2011,2013,2015,2017,2019,2021,2023,2025,2027,2029,2031,2033,2035,2037,2039,2041,2043,2045,2047,2049,2051,2053,2055,2057,2059,2061,2063,2065,2067,2069,2071,2073,2075,2077,2079,2081,2083,2085,2087,2089,2091,2093,2095,2097,2099,2101,2103,2105,2107,2109,2111,2113,2115,2117,2119,2121,2123,2125,2127,2129,2131,2133,2135,2137,2139,2141,2143,2145,2147,2149,2151,2153,2155,2157,2159,2161,2163,2165,2167,2169,2171,2173,2175,2177,2179,2181,2183,2185,2187,2189,2191,2193,2195,2197,2199,2201,2203,2205,2207,2209,2211,2213,2215,2217,2219,2221,2223,2225,2227,2229,2231,2233,2235,2237,2239,2241,2243,2245,2247,2249,2251,2253,2255,2257,2259,2261,2263,2265,2267,2269,2271,2273,2275,2277,2279,2281,2283,2285,2287,2289,2291,2293,2295,2297,2299,2301,2303,2305,2307,2309,2311,2313,2315,2317,2319,2321,2323,2325,2327,2329,2331,2333,2335,2337,2339,2341,2343,2345,2347,2349,2351,2353,2355,2357,2359,2361,2363,2365,2367,2369,2371,2373,2375,2377,2379,2381,2383,2385,2387,2389,2391,2393,2395,2397,2399,2401,2403,2405,2407,2409,2411,2413,2415,2417,2419,2421,2423,2425,2427,2429,2431,2433,2435,2437,2439,2441,2443,2445,2447,2449,2451,2453,2455,2457,2459,2461,2463,2465,2467,2469,2471,2473,2475,2477,2479,2481,2483,2485,2487,2489,2491,2493,2495,2497,2499,2501,2503,2505,2507,2509,2511,2513,2515,2517,2519,2521,2523,2525,2527,2529,2531,2533,2535,2537,2539,2541,2543,2545,2547,2549,2551,2553,2555,2557,2559,2561,2563,2565,2567,2569,2571,2573,2575,2577,2579,2581,2583,2585,2587,2589,2591,2593,2595,2597,2599,2601,2603,2605,2607,2609,2611,2613,2615,2617,2619,2621,2623,2625,2627,2629,2631,2633,2635,2637,2639,2641,2643,2645,2647,2649,2651,2653,2655,2657,2659,2661,2663,2665,2667,2669,2671,2673,2675,2677,2679,2681,2683,2685,2687,2689,2691,2693,2695,2697,2699,2701,2703,2705,2707,2709,2711,2713,2715,2717,2719,2721,2723,2725,2727,2729,2731,2733,2735,2737,2739,2741,2743,2745,2747,2749,2751,2753,2755,2757,2759,2761,2763,2765,2767,2769,2771,2773,2775,2777,2779,2781,2783,2785,2787,2789,2791,2793,2795,2797,2799,2801,2803,2805,2807,2809,2811,2813,2815,2817,2819,2821,2823,2825,2827,2829,2831,2833,2835,2837,2839,2841,2843,2845,2847,2849,2851,2853,2855,2857,2859,2861,2863,2865,2867,2869,2871,2873,2875,2877,2879,2881,2883,2885,2887,2889,2891,2893,2895,2897,2899,2901,2903,2905,2907,2909,2911,2913,2915,2917,2919,2921,2923,2925,2927,2929,2931,2933,2935,2937,2939,2941,2943,2945,2947,2949,2951,2953,2955,2957,2959,2961,2963,2965,2967,2969,2971,2973,2975,2977,2979,2981,2983,2985,2987,2989,2991,2993,2995,2997,2999,3001,3003,3005,3007,3009,3011,3013,3015,3017,3019,3021,3023,3025,3027,3029,3031,3033,3035,3037,3039,3041,3043,3045,3047,3049,3051,3053,3055,3057,3059,3061,3063,3065,3067,3069,3071,3073,3075,3077,3079,3081,3083,3085,3087,3089,3091,3093,3095,3097,3099,3101,3103,3105,3107,3109,3111,3113,3115,3117,3119,3121,3123,3125,3127,3129,3131,3133,3135,3137,3139,3141,3143,3145,3147,3149,3151,3153,3155,3157,3159,3161,3163,3165,3167,3169,3171,3173,3175,3177,3179,3181,3183,3185,3187,3189,3191,3193,3195,3197,3199,3201,3203,3205,3207,3209,3211,3213,3215,3217,3219,3221,3223,3225,3227,3229,3231,3233,3235,3237,3239,3241,3243,3245,3247,3249,3251,3253,3255,3257,3259,3261,3263,3265,3267,3269,3271,3273,3275,3277,3279,3281,3283,3285,3287,3289,3291,3293,3295,3297,3299,3301,3303,3305,3307,3309,3311,3313,3315,3317,3319,3321,3323,3325,3327,3329,3331,3333,3335,3337,3339,3341,3343,3345,3347,3349,3351,3353,3355,3357,3359,3361,3363,3365,3367,3369,3371,3373,3375,3377,3379,3381,3383,3385,3387,3389,3391,3393,3395,3397,3399,3401,3403,3405,3407,3409,3411,3413,3415,3417,3419,3421,3423,3425,3427,3429,3431,3433,3435,3437,3439,3441,3443,3445,3447,3449,3451,3453,3455,3457,3459,3461,3463,3465,3467,3469,3471,3473,3475,3477,3479,3481,3483,3485,3487,3489,3491,3493,3495,3497,3499,3501,3503,3505,3507,3509,3511,3513,3515,3517,3519,3521,3523,3525,3527,3529,3531,3533,3535,3537,3539,3541,3543,3545,3547,3549,3551,3553,3555,3557,3559,3561,3563,3565,3567,3569,3571,3573,3575,3577,3579,3581,3583,3585,3587,3589,3591,3593,3595,3597,3599,3601,3603,3605,3607,3609,3611,3613,3615,3617,3619,3621,3623,3625,3627,3629,3631,3633,3635,3637,3639,3641,3643,3645,3647,3649,3651,3653,3655,3657,3659,3661,3663,3665,3667,3669,3671,3673,3675,3677,3679,3681,3683,3685,3687,3689,3691,3693,3695,3697,3699,3701,3703,3705,3707,3709,3711,3713,3715,3717,3719,3721,3723,3725,3727,3729,3731,3733,3735,3737,3739,3741,3743,3745,3747,3749,3751,3753,3755,3757,3759,3761,3763,3765,3767,3769,3771,3773,3775,3777,3779,3781,3783,3785,3787,3789,3791,3793,3795,3797,3799,3801,3803,3805,3807,3809,3811,3813,3815,3817,3819,3821,3823,3825,3827,3829,3831,3833,3835,3837,3839,3841,3843,3845,3847,3849,3851,3853,3855,3857,3859,3861,3863,3865,3867,3869,3871,3873,3875,3877,3879,3881,3883,3885,3887,3889,3891,3893,3895,3897,3899,3901,3903,3905,3907,3909,3911,3913,3915,3917,3919,3921,3923,3925,3927,3929,3931,3933,3935,3937,3939,3941,3943,3945,3947,3949,3951,3953,3955,3957,3959,3961,3963,3965,3967,3969,3971,3973,3975,3977,3979,3981,3983,3985,3987,3989,3991,3993,3995,3997,3999,4001,4003,4005,4007,4009,4011,4013,4015,4017,4019,4021,4023,4025,4027,4029,4031,4033,4035,4037,4039,4041,4043,4045,4047,4049,4051,4053,4055,4057,4059,4061,4063,4065,4067,4069,4071,4073,4075,4077,4079,4081,4083,4085,4087,4089,4091,4093,4095,4097,4099,4101,4103,4105,4107,4109,4111,4113,4115,4117,4119,4121,4123,4125,4127,4129,4131,4133,4135,4137,4139,4141,4143,4145,4147,4149,4151,4153,4155,4157,4159,4161,4163,4165,4167,4169,4171,4173,4175,4177,4179,4181,4183,4185,4187,4189,4191,4193,4195,4197,4199,4201,4203,4205,4207,4209,4211,4213,4215,4217,4219,4221,4223,4225,4227,4229,4231,4233,4235,4237,4239,4241,4243,4245,4247,4249,4251,4253,4255,4257,4259,4261,4263,4265,4267,4269,4271,4273,4275,4277,4279,4281,4283,4285,4287,4289,4291,4293,4295,4297,4299,4301,4303,4305,4307,4309,4311,4313,4315,4317,4319,4321,4323,4325,4327,4329,4331,4333,4335,4337,4339,4341,4343,4345,4347,4349,4351,4353,4355,4357,4359,4361,4363,4365,4367,4369,4371,4373,4375,4377,4379,4381,4383,4385,4387,4389,4391,4393,4395,4397,4399,4401,4403,4405,4407,4409,4411,4413,4415,4417,4419,4421,4423,4425,4427,4429,4431,4433,4435,4437,4439,4441,4443,4445,4447,4449,4451,4453,4455,4457,4459,4461,4463,4465,4467,4469,4471,4473,4475,4477,4479,4481,4483,4485,4487,4489,4491,4493,4495,4497,4499,4501,4503,4505,4507,4509,4511,4513,4515,4517,4519,4521,4523,4525,4527,4529,4531,4533,4535,4537,4539,4541,4543,4545,4547,4549,4551,4553,4555,4557,4559,4561,4563,4565,4567,4569,4571,4573,4575,4577,4579,4581,4583,4585,4587,4589,4591,4593,4595,4597,4599,4601,4603,4605,4607,4609,4611,4613,4615,4617,4619,4621,4623,4625,4627,4629,4631,4633,4635,4637,4639,4641,4643,4645,4647,4649,4651,4653,4655,4657,4659,4661,4663,4665,4667,4669,4671,4673,4675,4677,4679,4681,4683,4685,4687,4689,4691,4693,4695,4697,4699,4701,4703,4705,4707,4709,4711,4713,4715,4717,4719,4721,4723,4725,4727,4729,4731,4733,4735,4737,4739,4741,4743,4745,4747,4749,4751,4753,4755,4757,4759,4761,4763,4765,4767,4769,4771,4773,4775,4777,4779,4781,4783,4785,4787,4789,4791,4793,4795,4797,4799,4801,4803,4805,4807,4809,4811,4813,4815,4817,4819,4821,4823,4825,4827,4829,4831,4833,4835,4837,4839,4841,4843,4845,4847,4849,4851,4853,4855,4857,4859,4861,4863,4865,4867,4869,4871,4873,4875,4877,4879,4881,4883,4885,4887,4889,4891,4893,4895,4897,4899,4901,4903,4905,4907,4909,4911,4913,4915,4917,4919,4921,4923,4925,4927,4929,4931,4933,4935,4937,4939,4941,4943,4945,4947,4949,4951,4953,4955,4957,4959,4961,4963,4965,4967,4969,4971,4973,4975,4977,4979,4981,4983,4985,4987,4989,4991,4993,4995,4997,4999,5001,5003,5005,5007,5009,5011,5013,5015,5017,5019,5021,5023,5025,5027,5029,5031,5033,5035,5037,5039,5041,5043,5045,5047,5049,5051,5053,5055,5057,5059,5061,5063,5065,5067,5069,5071,5073,5075,5077,5079,5081,5083,5085,5087,5089,5091,5093,5095,5097,5099,5101,5103,5105,5107,5109,5111,5113,5115,5117,5119,5121,5123,5125,5127,5129,5131,5133,5135,5137,5139,5141,5143,5145,5147,5149,5151,5153,5155,5157,5159,5161,5163,5165,5167,5169,5171,5173,5175,5177,5179,5181,5183,5185,5187,5189,5191,5193,5195,5197,5199,5201,5203,5205,5207,5209,5211,5213,5215,5217,5219,5221,5223,5225,5227,5229,5231,5233,5235,5237,5239,5241,5243,5245,5247,5249,5251,5253,5255,5257,5259,5261,5263,5265,5267,5269,5271,5273,5275,5277,5279,5281,5283,5285,5287,5289,5291,5293,5295,5297,5299,5301,5303,5305,5307,5309,5311,5313,5315,5317,5319,5321,5323,5325,5327,5329,5331,5333,5335,5337,5339,5341,5343,5345,5347,5349,5351,5353,5355,5357,5359,5361,5363,5365,5367,5369,5371,5373,5375,5377,5379,5381,5383,5385,5387,5389,5391,5393,5395,5397,5399,5401,5403,5405,5407,5409,5411,5413,5415,5417,5419,5421,5423,5425,5427,5429,5431,5433,5435,5437,5439,5441,5443,5445,5447,5449,5451,5453,5455,5457,5459,5461,5463,5465,5467,5469,5471,5473,5475,5477,5479,5481,5483,5485,5487,5489,5491,5493,5495,5497,5499,5501,5503,5505,5507,5509,5511,5513,5515,5517,5519,5521,5523,5525,5527,5529,5531,5533,5535,5537,5539,5541,5543,5545,5547,5549,5551,5553,5555,5557,5559,5561,5563,5565,5567,5569,5571,5573,5575,5577,5579,5581,5583,5585,5587,5589,5591,5593,5595,5597,5599,5601,5603,5605,5607,5609,5611,5613,5615,5617,5619,5621,5623,5625,5627,5629,5631,5633,5635,5637,5639,5641,5643,5645,5647,5649,5651,5653,5655,5657,5659,5661,5663,5665,5667,5669,5671,5673,5675,5677,5679,5681,5683,5685,5687,5689,5691,5693,5695,5697,5699,5701,5703,5705,5707,5709,5711,5713,5715,5717,5719,5721,5723,5725,5727,5729,5731,5733,5735,5737,5739,5741,5743,5745,5747,5749,5751,5753,5755,5757,5759,5761,5763,5765,5767,5769,5771,5773,5775,5777,5779,5781,5783,5785,5787,5789,5791,5793,5795,5797,5799,5801,5803,5805,5807,5809,5811,5813,5815,5817,5819,5821,5823,5825,5827,5829,5831,5833,5835,5837,5839,5841,5843,5845,5847,5849,5851,5853,5855,5857,5859,5861,5863,5865,5867,5869,5871,5873,5875,5877,5879,5881,5883,5885,5887,5889,5891,5893,5895,5897,5899,5901,5903,5905,5907,5909,5911,5913,5915,5917,5919,5921,5923,5925,5927,5929,5931,5933,5935,5937,5939,5941,5943,5945,5947,5949,5951,5953,5955,5957,5959,5961,5963,5965,5967,5969,5971,5973,5975,5977,5979,5981,5983,5985,5987,5989,5991,5993,5995,5997,5999,6001,6003,6005,6007,6009,6011,6013,6015,6017,6019,6021,6023,6025,6027,6029,6031,6033,6035,6037,6039,6041,6043,6045,6047,6049,6051,6053,6055,6057,6059,6061,6063,6065,6067,6069,6071,6073,6075,6077,6079,6081,6083,6085,6087,6089,6091,6093,6095,6097,6099,6101,6103,6105,6107,6109,6111,6113,6115,6117,6119,6121,6123,6125,6127,6129,6131,6133,6135,6137,6139,6141,6143,6145,6147,6149,6151,6153,6155,6157,6159,6161,6163,6165,6167,6169,6171,6173,6175,6177,6179,6181,6183,6185,6187,6189,6191,6193,6195,6197,6199,6201,6203,6205,6207,6209,6211,6213,6215,6217,6219,6221,6223,6225,6227,6229,6231,6233,6235,6237,6239,6241,6243,6245,6247,6249,6251,6253,6255,6257,6259,6261,6263,6265,6267,6269,6271,6273,6275,6277,6279,6281,6283,6285,6287,6289,6291,6293,6295,6297,6299,6301,6303,6305,6307,6309,6311,6313,6315,6317,6319,6321,6323,6325,6327,6329,6331,6333,6335,6337,6339,6341,6343,6345,6347,6349,6351,6353,6355,6357,6359,6361,6363,6365,6367,6369,6371,6373,6375,6377,6379,6381,6383,6385,6387,6389,6391,6393,6395,6397,6399,6401,6403,6405,6407,6409,6411,6413,6415,6417,6419,6421,6423,6425,6427,6429,6431,6433,6435,6437,6439,6441,6443,6445,6447,6449,6451,6453,6455,6457,6459,6461,6463,6465,6467,6469,6471,6473,6475,6477,6479,6481,6483,6485,6487,6489,6491,6493,6495,6497,6499,6501,6503,6505,6507,6509,6511,6513,6515,6517,6519,6521,6523,6525,6527,6529,6531,6533,6535,6537,6539,6541,6543,6545,6547,6549,6551,6553,6555,6557,6559,6561,6563,6565,6567,6569,6571,6573,6575,6577,6579,6581,6583,6585,6587,6589,6591,6593,6595,6597,6599,6601,6603,6605,6607,6609,6611,6613,6615,6617,6619,6621,6623,6625,6627,6629,6631,6633,6635,6637,6639,6641,6643,6645,6647,6649,6651,6653,6655,6657,6659,6661,6663,6665,6667,6669,6671,6673,6675,6677,6679,6681,6683,6685,6687,6689,6691,6693,6695,6697,6699,6701,6703,6705,6707,6709,6711,6713,6715,6717,6719,6721,6723,6725,6727,6729,6731,6733,6735,6737,6739,6741,6743,6745,6747,6749,6751,6753,6755,6757,6759,6761,6763,6765,6767,6769,6771,6773,6775,6777,6779,6781,6783,6785,6787,6789,6791,6793,6795,6797,6799,6801,6803,6805,6807,6809,6811,6813,6815,6817,6819,6821,6823,6825,6827,6829,6831,6833,6835,6837,6839,6841,6843,6845,6847,6849,6851,6853,6855,6857,6859,6861,6863,6865,6867,6869,6871,6873,6875,6877,6879,6881,6883,6885,6887,6889,6891,6893,6895,6897,6899,6901,6903,6905,6907,6909,6911,6913,6915,6917,6919,6921,6923,6925,6927,6929,6931,6933,6935,6937,6939,6941,6943,6945,6947,6949,6951,6953,6955,6957,6959,6961,6963,6965,6967,6969,6971,6973,6975,6977,6979,6981,6983,6985,6987,6989,6991,6993,6995,6997,6999,7001,7003,7005,7007,7009,7011,7013,7015,7017,7019,7021,7023,7025,7027,7029,7031,7033,7035,7037,7039,7041,7043,7045,7047,7049,7051,7053,7055,7057,7059,7061,7063,7065,7067,7069,7071,7073,7075,7077,7079,7081,7083,7085,7087,7089,7091,7093,7095,7097,7099,7101,7103,7105,7107,7109,7111,7113,7115,7117,7119,7121,7123,7125,7127,7129,7131,7133,7135,7137,7139,7141,7143,7145,7147,7149,7151,7153,7155,7157,7159,7161,7163,7165,7167,7169,7171,7173,7175,7177,7179,7181,7183,7185,7187,7189,7191,7193,7195,7197,7199,7201,7203,7205,7207,7209,7211,7213,7215,7217,7219,7221,7223,7225,7227,7229,7231,7233,7235,7237,7239,7241,7243,7245,7247,7249,7251,7253,7255,7257,7259,7261,7263,7265,7267,7269,7271,7273,7275,7277,7279,7281,7283,7285,7287,7289,7291,7293,7295,7297,7299,7301,7303,7305,7307,7309,7311,7313,7315,7317,7319,7321,7323,7325,7327,7329,7331,7333,7335,7337,7339,7341,7343,7345,7347,7349,7351,7353,7355,7357,7359,7361,7363,7365,7367,7369,7371,7373,7375,7377,7379,7381,7383,7385,7387,7389,7391,7393,7395,7397,7399,7401,7403,7405,7407,7409,7411,7413,7415,7417,7419,7421,7423,7425,7427,7429,7431,7433,7435,7437,7439,7441,7443,7445,7447,7449,7451,7453,7455,7457,7459,7461,7463,7465,7467,7469,7471,7473,7475,7477,7479,7481,7483,7485,7487,7489,7491,7493,7495,7497,7499,7501,7503,7505,7507,7509,7511,7513,7515,7517,7519,7521,7523,7525,7527,7529,7531,7533,7535,7537,7539,7541,7543,7545,7547,7549,7551,7553,7555,7557,7559,7561]). </code></pre> <p>How could I write it better?</p>
[]
[ { "body": "<p>I would use recursion here:</p>\n\n<pre><code>-module(arith_progr).\n-export([progr/3]).\n\nprogr(Start, _Increment, End) when Start &gt; End -&gt;\n io:format(\"~n\");\nprogr(Start, Increment, End) -&gt;\n io:format(\"~p \", [Start]),\n progr(Start+Increment, Increment, End).\n</code></pre>\n\n<p>This will print numbers from Start with increment=Increment until number is beyond End.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-11-14T15:40:23.307", "Id": "29629", "Score": "0", "body": "this will use up all stack" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-03-02T20:57:20.757", "Id": "36006", "Score": "0", "body": "It shouldn't. The Erlang compiler is optimized for tail recursion; see http://learnyousomeerlang.com/recursion" } ], "meta_data": { "CommentCount": "2", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-11-14T06:46:46.570", "Id": "18583", "ParentId": "18543", "Score": "1" } }, { "body": "<p>Use <code>lists:seq</code> and <code>lists:map</code> they were made for that purpose. These are basic functional building blocks and as important as recursion. Also look at <code>lists:foldl</code> and <code>lists:foldr</code> and lambda-expressions (fun()->...).</p>\n\n<pre><code>-module(verschickten).\n-export([f/0]).\n\nf() -&gt; lists:map(fun(I) -&gt; io:format(\"~p \", [I]) end, lists:seq(1, 7561, 2)). \n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-11-14T08:25:33.493", "Id": "29609", "Score": "1", "body": "This would be even better if you use `lists:foreach/2` instead of `lists:map/2`, as you do not care about/use the return values." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-11-14T08:30:52.373", "Id": "29611", "Score": "0", "body": "yes, that's correct" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-11-14T15:41:44.923", "Id": "29630", "Score": "0", "body": "worked for me thx" } ], "meta_data": { "CommentCount": "3", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-11-14T08:09:21.180", "Id": "18586", "ParentId": "18543", "Score": "1" } } ]
{ "AcceptedAnswerId": "18586", "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-11-13T14:53:07.490", "Id": "18543", "Score": "2", "Tags": [ "beginner", "erlang" ], "Title": "Arithmetic progression to 7561" }
18543
<p>I'm making my first steps in ELisp programming and I want to know is there a better solution for this problem:</p> <p>I have a file with two columns, that are separated by one or more spaces, ex.:</p> <pre><code>One 1 Two 2 Three 3 Four 4 </code></pre> <p>I'd like to make some alignment (columns are separated by at least two spaces):</p> <pre><code>One 1 Two 2 Three 3 Four 4 </code></pre> <p>My solution is:</p> <pre><code>(defun align-config-file () "Align two-columned config file in a pretty manner" (interactive) (let* ((strings (split-string (buffer-string) "\n")) (data (mapcar (lambda (line) (split-string line " ")) strings)) (first-col-lengths (mapcar (lambda (item) (length (car item))) data)) (first-col-length (+ 2 (apply 'max first-col-lengths)))) (erase-buffer) (while data (let* ((this-line (car data)) (first-col (car this-line)) (last-col (car (nthcdr (- (length this-line) 1) this-line))) (amount-of-spaces (- first-col-length (length first-col))) (spaces-inserted 0)) (insert first-col) (while (&lt; spaces-inserted amount-of-spaces) (insert " ") (set 'spaces-inserted (+ 1 spaces-inserted))) (insert last-col) (insert "\n")) (set 'data (cdr data))))) </code></pre> <p>It is not beautiful, but it works. Is it ok?</p>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-09-19T10:09:09.187", "Id": "393286", "Score": "0", "body": "You are aware of the `align` command, that comes with Emacs? You seem to be addressing a solved problem." } ]
[ { "body": "<p>You should use <code>dolist</code> </p>\n\n<blockquote>\n <p>(dolist (VAR LIST [RESULT]) BODY...)</p>\n</blockquote>\n\n<p>and <code>insert-char</code> </p>\n\n<blockquote>\n <p>(insert-char CHARACTER &amp;optional COUNT INHERIT)</p>\n</blockquote>\n\n<p>instead of the <code>while</code> constructs.</p>\n\n<p>You can also insert more than one string with <code>insert</code></p>\n\n<blockquote>\n <p>(insert &amp;rest ARGS)</p>\n</blockquote>\n\n<p>You could use <code>reduce</code> instead of <code>mapcar '(car + length + max)</code>.</p>\n\n<blockquote>\n <p>(reduce FUNCTION SEQ [KEYWORD VALUE]...)</p>\n</blockquote>\n\n<pre><code>(reduce '(lambda (acc el)\n (max acc (length el)))\n '((\"one\" \"two\") (\"three\" \"four\") (\"five\" \"six\"))\n :initial-value 0\n :key 'car)\n → 5\n</code></pre>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-11-13T18:34:14.383", "Id": "18552", "ParentId": "18548", "Score": "1" } }, { "body": "<h3>1. Design</h3>\n\n<p>The design is not very Emacs-like. In particular:</p>\n\n<ol>\n<li><p>The command operates on the entire buffer contents. This means that if you want to line up some columns in a region (without affecting the rest of the buffer), you can't use your command. (At least not without copying the region to a new buffer, running the command, and then copying the result back again.)</p>\n\n<p>It would be better if the function operated on the contents of the current region: then it would be much more flexible.</p></li>\n<li><p>Your command doesn't respect the current <a href=\"http://www.gnu.org/software/emacs/manual/html_node/elisp/Narrowing.html\" rel=\"nofollow noreferrer\">narrowing</a> of the buffer. If you look at the docstring for <a href=\"https://www.gnu.org/software/emacs/manual/html_node/elisp/Deletion.html\" rel=\"nofollow noreferrer\"><code>erase-buffer</code></a>, it says:</p>\n\n<blockquote>\n <p>Any narrowing restriction in effect (see <a href=\"https://www.gnu.org/software/emacs/manual/html_node/elisp/Narrowing.html\" rel=\"nofollow noreferrer\"><code>narrow-to-region</code></a>) is removed,\n so the buffer is truly empty after this.</p>\n</blockquote>\n\n<p>This would come as an unpleasant surprise to a user who had a narrowing in effect. It would be better to operate only on the narrowed part of the buffer, by calling</p>\n\n<pre><code>(delete-region (point-min) (point-max))\n</code></pre>\n\n<p>instead of <code>(erase-buffer)</code>. (But in fact there are better ways to do it, which I'll describe below.)</p></li>\n<li><p>Your command doesn't preserve the position of point. After running the command, point is always at the end of the buffer. It's always worth preserving the position of point (if appropriate) because that makes a function's behaviour predictable, and more useful in Lisp code and in macros.</p></li>\n</ol>\n\n<h3>2. Implementation</h3>\n\n<ol>\n<li><p>The command reads the entire buffer contents into strings, processes the strings in various ways, and then writes them back to the buffer.</p>\n\n<p>If you've recently come to Emacs Lisp from another language, then you're probably thinking that a buffer is a bit like a file, and so the right way to process it is to read the file contents into memory as string, process the contents, and then write it out.</p>\n\n<p>I can't stress enough that <em>you won't get the full benefits of Emacs if you persist with this approach</em>! A buffer in Emacs is not like a file. It's a highly flexible string-like data structure that supports a much wider set of operations than a string. So you should organize your code to operate directly on the buffer contents, using the same (or similar) functions that you would use as an interactive user.</p></li>\n<li><p>There are some useful functions in the Emacs toolbox that you could use to simplify your code. If you look at the revised code you'll see that I made use of <a href=\"https://www.gnu.org/software/emacs/manual/html_node/elisp/Skipping-Characters.html\" rel=\"nofollow noreferrer\"><code>skip-chars-forward</code></a>, the (poorly named) <a href=\"https://www.gnu.org/software/emacs/manual/html_node/elisp/User_002dLevel-Deletion.html\" rel=\"nofollow noreferrer\"><code>just-one-space</code></a>, and <code>(cl-loop ... maximize ...)</code> to do maximization without constructing an intermediate list in memory.</p></li>\n</ol>\n\n<h3>3. Minor points</h3>\n\n<ol>\n<li><p>The name <code>align-config-file</code> seems wrong: it's not limited to configuration files, and it doesn't operate on a file (it operates on buffer contents). I think a better name would be something like <code>align-two-columns</code>.</p></li>\n<li><p>The docstring says \"in a pretty manner\" which seems rather vague. What does it actually do?</p></li>\n<li><p>The command ensures that there are at least two spaces between the columns. The number 2 seems rather arbitrary: why not make it an argument to the command, so that the user can supply it as a prefix argument?</p></li>\n</ol>\n\n<h3>4. Revised code</h3>\n\n<p>(Ask if you can't figure out how this works.)</p>\n\n<pre class=\"lang-lisp prettyprint-override\"><code>(require 'cl-macs) ; for the \"cl-loop\" facility\n\n(defun align-two-columns (begin end spaces)\n \"Align two columns between BEGIN and END, ensuring that the\nsecond column is vertically aligned, and there are SPACES spaces\nbetween the columns.\"\n (interactive \"r\\np\")\n (save-excursion\n (save-restriction\n (narrow-to-region begin end)\n (goto-char (point-min))\n ;; Determine the width of the first column.\n (let ((width (cl-loop while (not (eobp))\n maximize (skip-chars-forward \"^ \\t\\n\")\n do (forward-line 1))))\n ;; Back to the top and adjust the spaces.\n (goto-char (point-min))\n (while (not (eobp))\n (let ((col (skip-chars-forward \"^ \\t\\n\")))\n (unless (eolp)\n (just-one-space (+ spaces (- width col)))))\n (forward-line 1))))))\n</code></pre>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2012-11-29T13:24:56.710", "Id": "19150", "ParentId": "18548", "Score": "3" } } ]
{ "AcceptedAnswerId": "19150", "CommentCount": "1", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-11-13T16:30:31.130", "Id": "18548", "Score": "4", "Tags": [ "elisp" ], "Title": "Emacs column alignment command" }
18548
<p>I'm currently writing Report's system. I have about 20 different users with different access. Am I doing it correctly? Can I improve my style of writing this code? All my reports based on the same structure.</p> <p>In my Report's Controller:</p> <pre><code>function my_report_name() { //current week by default $dates['from'] = $this-&gt;uri-&gt;segment(3,date('Y-m-d',strtotime(date('o-\\WW'))-60*60*24*7)); $dates['to'] = $this-&gt;uri-&gt;segment(4,date("Y-m-d", strtotime($dates['from']) + 6 * 24* 60 * 60)); $data['report_name']=$this-&gt;Reports_model-&gt;getMyReportDescriptionSummary($dates); $data['title'] = "My Report Name Description"; //view in 'view/report' folder to use //name of view always the same as name of function $data['main'] = "report/my_report_name"; $data['menuReport'] = "class='current'"; $data['panel'] = "panel/panel"; $this-&gt;load-&gt;vars($data); //load template $this-&gt;load-&gt;view('template/t_main_full', $data); } </code></pre> <p>In my Model:</p> <pre><code>function getMyReportDescriptionSummary($dates) { $this-&gt;db-&gt;select("some_data, some_data_2, some_data_3" ); $this-&gt;db-&gt;join("table1"); $this-&gt;db-&gt;join("table2"); $this-&gt;db-&gt;where("some_params"); $Q = $this-&gt;db-&gt;get(); if($Q-&gt;num_rows() &gt; 0) { return $Q-&gt;result_array(); } else { return false; } } </code></pre> <p>In my repots layout page:</p> <pre><code>//function to check permissions &lt;? if($this-&gt;Model_Users-&gt;accessVerify('my_report_name')) {?&gt; &lt;tr&gt;My report&lt;/tr&gt; &lt;?}?&gt; </code></pre>
[]
[ { "body": "<p>The code is fine, but why are you passing from date and to date to model ? Its not being used at model. May be you are trying to add a condition to filter the data set under specified dates. Anyway, your starting is good. Good luck.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-12-18T10:43:17.337", "Id": "19731", "ParentId": "18555", "Score": "0" } }, { "body": "<p>From a CodeIgniter point of view, this is fine but CI isn't really MVC. in MVC proper, the controller would be doing very little (See: <a href=\"https://stackoverflow.com/questions/13813046/how-is-mvc-supposed-to-work-in-codeigniter\">https://stackoverflow.com/questions/13813046/how-is-mvc-supposed-to-work-in-codeigniter</a> ). However in CodeIgniter's implementation you still want to strive for \"Fat model, thin controller\", which you're doing for the most part. This will give you far greater reusability as the logic isn't tied to a specific controller. I'd argue that most of the things in the $data array are actually stateful or display logic (e.g. which panel to display) so don't belong in the controller.</p>\n\n<p>MVC strives for a high separation of concerns with reusable components and although CodeIgniter goes against this philosophy slightly, you can still work around it. Keep your views and models reusable. </p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-02-18T16:14:07.193", "Id": "72323", "Score": "0", "body": "would you like to take a look at http://codereview.stackexchange.com/questions/41959/codeigniter-best-practice-for-generating-jquery-dynamical-content" } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-12-18T10:52:22.847", "Id": "19732", "ParentId": "18555", "Score": "3" } } ]
{ "AcceptedAnswerId": "19732", "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-11-13T19:01:00.497", "Id": "18555", "Score": "4", "Tags": [ "php", "mvc", "codeigniter" ], "Title": "Am I using MVC Codeigniter correctly?" }
18555
<p>I have been working with PHP sessions and login protected pages for some time, but I want to start using some AJAX for managing some actions inside login protected pages (easy way with jQuery).</p> <p>Here is what I want to do:</p> <p>The user logs in (classic no-AJAX method), and wants to submit a message. I make a request with AJAX to another page, where the session is checked and the message is saved.</p> <p>Here is how the start page looks:</p> <pre><code>&lt;?php session_name('NEWSESSION'); session_start(); session_regenerate_id(true); if(!$_SESSION['user_logged']){ header("location: login.php"); } $sessionTTL = time() - $_SESSION["timeout"]; if ($sessionTTL &gt; SES_LENGHT) { session_destroy(); header("location: login.php"); } ?&gt; &lt;!-- page header and all other html things here --&gt; &lt;div id="returned_message"&gt;&lt;/div&gt; &lt;textarea id="message"&gt;TEST&lt;/textarea&gt; &lt;input type="" id="submit" value="Submit message"&gt; &lt;script&gt; $("#submit").click(function(){ $.ajax({ type: 'POST', data: { action: 'submit_message', message: $("#message").val(); }, url: '/save.php', success: function(data) { $('#returned_message').html(data); } }); }); &lt;/script&gt; </code></pre> <p>And this is save.php where I send the request (and sends a "msg saved" alert):</p> <pre><code>&lt;?php session_name('NEWSESSION'); session_start(); session_regenerate_id(true); if(!$_SESSION['user_logged']){ header("location: login.php"); } $sessionTTL = time() - $_SESSION["timeout"]; if ($sessionTTL &gt; SES_LENGHT) { session_destroy(); header("location: login.php"); } $username = $_SESSION['user_username']; if($_POST["action"] == "save_message"){ /* PHP code for saving message */ echo "Message saved!"; } ?&gt; </code></pre> <p>Is this the right way to do this? And how vulnerable is this (is it more vulnerable than to do it with classic PHP methods, with no fancy AJAX things)? All suggestions are welcome.</p>
[]
[ { "body": "<h2>Consider adding User Agent check</h2>\n\n<p>Adding a User Agent check will add another layer of security. This will slow down Session Hijacking a bit.</p>\n\n<h2>AJAX alone is not a security issue</h2>\n\n<p>AJAX is no more vulnerable then regular access when it comes to sessions. </p>\n\n<h2>SES_LENGHT is not defined</h2>\n\n<p>The constant <code>SES_LENGHT</code> is not defined anywhere. Is your code snippet complete?</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-11-14T08:30:08.337", "Id": "29610", "Score": "0", "body": "Tnx for your answer. Regarding SES_LENGHT, it is defined in included file (just i removed that include to simplify example and make it more clear)." } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-11-13T23:22:43.353", "Id": "18569", "ParentId": "18564", "Score": "1" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-11-13T21:44:09.860", "Id": "18564", "Score": "2", "Tags": [ "php", "security", "ajax", "session" ], "Title": "Using AJAX to secure sessions and save messages" }
18564
<p>The basic idea is not to allow the same text and add +1 at the end.</p> <p>Imagine that I have a datagrid (WPF) with names, and every time I click the add button, I will put a new name on the list automatically by running this method to ensure that no two names are alike.</p> <p>My standard used: if there is repeated text, add to the end "(" + count + ")", similar to Windows Explorer.</p> <p>Are there ways to make this using LINQ or Regex?</p> <pre><code>private void Test() { var result = CreateText("t", new string[] { "t", "t(1)", "t(2)", "t(3)", "t(4)", "t(5)", "t(6)", "t(7)", "t(8)", "t(9)", "t(10)" }); Assert.IsTrue(result == "t(11)"); } public static String CreateText(string newText, String[] texts) { int addCount = 0; foreach (String text in texts) { if (text.IndexOf(newText) == 0) { if (text == newText &amp;&amp; addCount == 0) { addCount = 1; continue; } else { if (text.LastIndexOf('(') == newText.Length &amp;&amp; text.LastIndexOf(')') == text.Length - 1) { try { var initial = text.LastIndexOf('(') + 1; var size = text.LastIndexOf(')') - initial; int count = Int16.Parse(text.Substring(initial, size)); if (addCount &lt;= count) { addCount = count + 1; } } catch (Exception) { addCount = 0; } } } } } if (addCount &gt; 0) { newText += "(" + addCount + ")"; } return newText; } </code></pre>
[ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-11-14T07:56:00.957", "Id": "29605", "Score": "0", "body": "It looks kind of under specified to me. What is the output of {\"t(1)\", \"a(2)\"}? {\"t(t(1))\", \"T(42)\"}? {\"hello\",\"world\"}? Your test suggests you didn't clarify to yourself what are the requirements here." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-11-14T10:01:56.973", "Id": "29614", "Score": "0", "body": "@avip sorry, I will clarify the operation" } ]
[ { "body": "<p>Here's a way. Not fully Linq but using a little bit in the for loop. Also passes a few more unit tests than your original.</p>\n\n<p><strong>[EDIT]</strong>: After re-reading your question and some comments by other reviewers I added a few more unit tests and low and behold my original answer broke. So I've re-worked it and now made it even more complicated :) but passes the new unit tests I put in 10,11 and 12.</p>\n\n<p>Whether your code needs to pass thoses tests or not though I'll leave that for you to decide.</p>\n\n<p>As for optimization. I haven't profiled it so can't comment there.</p>\n\n<pre><code> [TestMethod]\n public void Test()\n {\n var result = CreateText(\"t\", new string[] { \"t\", \"t(1)\", \"t(2)\", \"t(3)\", \"t(4)\", \"t(5)\", \"t(6)\", \"t(7)\", \"t(8)\", \"t(9)\", \"t(10)\" });\n Assert.IsTrue(result == \"t(11)\");\n }\n [TestMethod]\n public void Test1()\n {\n var result = CreateText(\"t\", new string[] { \"t\" });\n Assert.AreEqual(\"t(1)\", result);\n }\n\n [TestMethod]\n public void Test2()\n {\n var result = CreateText(\"t\", new string[] { \"t\", \"t(4)\", \"t(2)\", \"z(3)\", \"t (45)\", \"t5)\", \"t(10)\", \"t(12)\", \"t( 89 ),ttt, t, t(23), t(8, t(we\", \"t( 89 )\", \"t(23)\", \"t(8\", \"t(we\" });\n Assert.AreEqual(\"t(90)\", result);\n }\n\n [TestMethod]\n public void Test3()\n {\n var result = CreateText(\"t\", new string[] { });\n Assert.IsTrue(result == \"t\");\n }\n\n [TestMethod]\n public void Test4()\n {\n var result = CreateText(\"z\", new string[] { \"t(1)\" });\n Assert.AreEqual(\"z\", result);\n }\n\n [TestMethod]\n public void Test5()\n {\n var result = CreateText(\"z\", new string[] { \"t(-1)\" });\n Assert.AreEqual(\"z\", result);\n }\n\n [TestMethod]\n public void Test6()\n {\n var result = CreateText(\"t\", new string[] { \" t(0)\" });\n Assert.AreEqual(\"t(1)\", result);\n }\n\n [TestMethod]\n public void Test7()\n {\n var result = CreateText(\"t\", new string[] { \" t(9) \" });\n Assert.AreEqual(\"t(10)\", result);\n }\n\n [TestMethod]\n public void Test8()\n {\n var result = CreateText(\"t\", new string[] { \"t(1)\", \"t(2)\", \"t(3)\", \"t(4)\", \"t(5)\", \"t(6)\", \"t(7)\", \"t(8)\", \"t(9)\", \"test(10)\" });\n Assert.AreEqual(\"t(10)\", result);\n }\n\n [TestMethod]\n public void Test9()\n {\n var result = CreateText(\"t\", new string[] { \"t(1)\", \"t(2)\", \"t(3)\", \"t(4)\", \"t(5)\", \"t(6)\", \"t(7)\", \"t(8)\", \"t (9)\", \"test(10)\" });\n Assert.AreEqual(\"t(10)\", result);\n }\n\n [TestMethod]\n public void Test10()\n {\n var result = CreateText(\"t\", new string[] { \"t(1)\", \"t(2)\", \"t(3)\", \"t(4)\", \"t(5)\", \"t(6)\", \"t(7)\", \"t t(8)\", \"t (9)\", \"test(10)\" });\n Assert.AreEqual(\"t(10)\", result);\n }\n\n [TestMethod]\n public void Test11()\n {\n var result = CreateText(\"t\", new string[] { \"t(1)\", \"t(2)\", \"t(3)\", \"t(4)\", \"t((((24)\", \"ttt(22)\", \"t(7)\", \"t t(8)\", \"t (9)\", \"t(1)\" });\n Assert.AreEqual(\"t(10)\", result);\n }\n\n [TestMethod]\n public void Test12()\n {\n var result = CreateText(\"t\", new string[] { \"t(1)\", \"t(2)\", \"t(3)\", \"t(4)\", \"t((((24)\", \"ttt(22)\", \"t(29)) ))\", \"t t(8)\", \"t (9)\", \"t(1)\" });\n Assert.AreEqual(\"t(30)\", result);\n }\n\n private static String CreateText(string textIdentifier, IEnumerable&lt;string&gt; texts)\n {\n const char startDeliminator = '(';\n const char endDeliminator = ')';\n\n int nextCount = 0;\n\n foreach (String text in texts.Select(p =&gt; p.Trim()).Where(p =&gt; p.StartsWith(textIdentifier)))\n {\n short addCount = 0;\n\n var startDelminatorIndex = text.LastIndexOf(startDeliminator);\n\n // there must be at least one start deliminator\n if (startDelminatorIndex &gt;= 0)\n {\n var endDeliminatorIndex = text.IndexOf(endDeliminator, startDelminatorIndex);\n var textName = text.Substring(0, startDelminatorIndex).Trim();\n\n if (textName.Equals(textIdentifier, StringComparison.CurrentCultureIgnoreCase))\n {\n if (endDeliminatorIndex &gt; startDelminatorIndex)\n {\n startDelminatorIndex++; // get past the (\n var size = endDeliminatorIndex - startDelminatorIndex;\n Int16.TryParse(text.Substring(startDelminatorIndex, size).Trim(), out addCount);\n }\n }\n }\n\n nextCount = Math.Max(nextCount, addCount + 1);\n }\n\n return nextCount == 0 ? textIdentifier : string.Format(\"{0}({1})\", textIdentifier, nextCount);\n }\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-11-14T00:48:29.363", "Id": "29594", "Score": "0", "body": "good idea to use the linq before the loop, although I think that horrible \"p.Trim()\"" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-11-14T01:11:38.143", "Id": "29596", "Score": "0", "body": "Yeah, unless you don't need to worry about whitespace i.e. assume it's already trimmed you could remove it. However without Test7 and Test6 don't pass." } ], "meta_data": { "CommentCount": "2", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-11-14T00:33:56.783", "Id": "18571", "ParentId": "18570", "Score": "2" } }, { "body": "<p>Here is shorter method with regex</p>\n\n<pre><code> private static String CreateText(string textIdentifier, IEnumerable&lt;string&gt; texts)\n {\n const int defaultNumber = 1;\n\n Regex regex = new Regex(@\"\\(\\s*(?&lt;num&gt;\\d+)\\s*\\)\");\n\n var numbers = \n texts.Select(p =&gt; p.Trim()).Where(p =&gt; p.StartsWith(textIdentifier))\n .Select(str =&gt; { var m = regex.Match(str); return m.Success ? int.Parse(m.Groups[\"num\"].Value) + 1 : defaultNumber; });\n\n int max = numbers.Any() ? numbers.Max() : 0;\n\n return max == 0 ? textIdentifier : string.Format(\"{0}({1})\", textIdentifier, max);\n }\n</code></pre>\n\n<p>+1 to @dreza for tests ;)</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-11-14T10:48:24.663", "Id": "18597", "ParentId": "18570", "Score": "4" } }, { "body": "<p>There might be one problem with @Danil code. Although it passes the unit test that was provided what if the array contained values of <code>\"t\", \"t(1)\", \"t(2)\", \"t(3)\", \"t(4)\", \"t(5)\", \"t(6)\", \"t(7)\", \"t(8)\", \"t(9)\", \"test(10)\"</code></p>\n\n<p>In this case I would think you would want the return value to be <code>t(10)</code>. Maybe the above scenerio is not possible, but if it is, here is a revision to @Danil code which would handle it.</p>\n\n<pre><code>private static String CreateText(string textIdentifier, IEnumerable&lt;string&gt; texts)\n{\n const int defaultNumber = 0;\n\n Regex regex = new Regex(\"^\" + textIdentifier + @\"\\(\\s*(?&lt;num&gt;\\d+)\\s*\\)\");\n\n var max = \n texts.Select(p =&gt; p.Trim())\n .Select(str =&gt; { var m = regex.Match(str); return m.Success ? int.Parse(m.Groups[\"num\"].Value) + 1 : defaultNumber; })\n .Max();\n\n return max == 0 ? textIdentifier : string.Format(\"{0}({1})\", textIdentifier, max);\n}\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-11-14T14:58:41.197", "Id": "29625", "Score": "0", "body": "Yep, you are right. I've missed it." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-11-26T16:21:43.813", "Id": "30358", "Score": "0", "body": "worked well in tests. but looking now, this code does not meet one of the requirements. it still lets texts exactly alike." } ], "meta_data": { "CommentCount": "2", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-11-14T14:18:51.893", "Id": "18612", "ParentId": "18570", "Score": "3" } } ]
{ "AcceptedAnswerId": "18597", "CommentCount": "2", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-11-13T23:44:13.903", "Id": "18570", "Score": "4", "Tags": [ "c#", "optimization", "algorithm" ], "Title": "Creating text without repetition" }
18570
<p>My friend wrote a program which compares random arrangements of die faces to find the one with the most evenly distributed faces - especially when the faces are not a mere sequence.</p> <p>I translated his program into haskell because I've been looking for a reason to talk someone's ear off about how cool haskell is. However, I am not very proficient with haskell (it took me forever to write this and it has undergone a couple giant refactorings) and so I have two problems.</p> <ol> <li>he has been big on optimizing his versions, and this is not very fast, and it does not scale linearly. It goes from 415 checks/s to 97 checks/s when I go from 1000 to 20000 checks. Did I mess up some tail recursion or is it some kind of larger problem?</li> <li>the code that came out of this isn't actually as elegant as I had predicted. I want this to be a solid showcase of Haskell, if you have any ideas on how to simplify it I am all ears</li> </ol> <p>This is the most relevant code:</p> <pre><code>-- _CENTERS :: [{ x :: Float, y :: Float, z :: Float}] -- _VALUES :: [Num] -- Basically just (repeat $ map rand [0.._SIDES]), but never using a seed twice randstates from = (take _SIDES (infrand from)) : randstates newseed where infrand seed = seed : infrand (shuffle seed) newseed = (infrand from) !! (_SIDES + 1) -- yates shuffle yates _ (last:[]) = [last] yates (rand:pass) (swap:order) = choice:yates pass rorder where choice = order !! index index = (randfrom rand) `mod` (length order) rorder = take (index) order ++ swap : drop (index + 1) order arrangements seed = map arrange $ randstates seed where arrange rands = yates rands [0.._SIDES - 2] -- fns comparing arrangements -- arcLength i j = 1 / (1 + _WEIGHT * acos(dot3D / _VEC_LEN_SQUARED)) where dot3D = apply x + apply y + apply z apply fn = (fn i) * (fn j) matrix arr = map crosscmp arr where crosscmp s1 = [ value s1 * (distance s1 s2) | s2 &lt;- arr ] distance a b = arcLength (_CENTERS !! a) (_CENTERS !! b) value s = fromInteger $ _VALUES !! s variance arr = sum $ map perside (matrix arr) where perside s = (sum s - mean) ^ 2 mean = (sum (concat $ matrix arr)) / (sides + 1) sides = fromInteger $ toInteger _SIDES maxDistr = maximumBy (\a b -&gt; variance a `compare` variance b) </code></pre> <p>Main is basically just</p> <pre><code>print $ maxDistr $ take _TRIALS $ arrangements seed </code></pre>
[]
[ { "body": "<p>Just a quick observation: as the length of values and centers increase, the list indexes (!!) are increasingly inefficient. Try values :: Vector Float, centers :: Vector Center with Data.Vector.(!) and see if performance improves.</p>\n\n<p>I'm trying to see what other improvements can be made, I have a few in mind but its difficult to understand how your code works without the full program. Would you mind linking to a pastebin?</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-01-23T15:40:13.397", "Id": "20826", "ParentId": "18574", "Score": "2" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-11-14T02:25:26.340", "Id": "18574", "Score": "3", "Tags": [ "performance", "haskell", "recursion" ], "Title": "Haskell tips/why doesnt this scale linearly?" }
18574
<p>I am taking a data structures course. I would like to check whether my <code>BinaryTree</code> code is perfect, fine or has lots of mistakes.</p> <p>I would like any kind of advice on this code so I can learn from my mistakes (syntax, techniques, style, etc...).</p> <p><strong>Note: This is not a binary search tree.</strong></p> <p><code>BinaryTree</code> class:</p> <pre><code>/** * @uniersity Saint Joseph's University * @college College of Arts and Sciences * @department Computer Science * @course CSC 550: Object Oriented Design &amp; Data Structures */ package mih1406.csc550.trees; import java.io.Serializable; // To make life easier... // &lt;E extends Integer&gt; to simplify it if any method requires Integer // eg: getSum, countLessThan public class BinaryTree&lt;E extends Integer&gt; implements Serializable { // Inner Class protected class Node&lt;E extends Integer&gt; implements Serializable { protected E data; protected Node&lt;E&gt; left; protected Node&lt;E&gt; right; public Node(E data) { this.data = data; left = null; right = null; } public String toString() { return data.toString(); } } // Data Fields protected Node&lt;E&gt; root; // Constructors public BinaryTree() { root = null; } protected BinaryTree(Node&lt;E&gt; root) { this.root = root; } public BinaryTree(E data, BinaryTree&lt;E&gt; leftTree, BinaryTree&lt;E&gt; rightTree) { root = new Node(data); if(leftTree == null || leftTree.root == null) root.left = null; else root.left = leftTree.root; if(rightTree == null || rightTree.root == null) root.right = null; else root.right = rightTree.root; } // Methods public BinaryTree&lt;E&gt; getLeftSubtree() { if(root == null) return new BinaryTree&lt;E&gt;(null); else return new BinaryTree&lt;E&gt;(root.left); } public BinaryTree&lt;E&gt; getRightSubtree() { if(root == null) return new BinaryTree&lt;E&gt;(null); else return new BinaryTree&lt;E&gt;(root.right); } public E getData() { if(root == null) return null; else return root.data; } public boolean isLeaf() { if(root == null) return false; else { if(root.left == null &amp;&amp; root.right == null) return true; else return false; } } public String toString() { StringBuilder sb = new StringBuilder(); sb.append("Pre-Order Traversal:\n"); preOrderTraversal(root, 1, sb); sb.append("\n"); sb.append("In-Order Traversal:\n"); inOrderTraversal(root, 1, sb); sb.append("\n"); sb.append("Post-Order Traversal:\n"); postOrderTraversal(root, 1, sb); return sb.toString(); } private void preOrderTraversal(Node&lt;E&gt; node, int depth, StringBuilder sb) { for(int i = 1; i &lt; depth; i++) sb.append("."); if(node == null) { sb.append("null\n"); return; } sb.append(node.data); sb.append("\n"); preOrderTraversal(node.left, depth + 1, sb); preOrderTraversal(node.right, depth + 1, sb); } private void inOrderTraversal(Node&lt;E&gt; node, int depth, StringBuilder sb) { if(node == null) { for(int i = 1; i &lt; depth; i++) sb.append("."); sb.append("null\n"); return; } else { inOrderTraversal(node.left, depth + 1, sb); for(int i = 1; i &lt; depth; i++) sb.append("."); sb.append(node.data); sb.append("\n"); inOrderTraversal(node.right, depth + 1, sb); } } private void postOrderTraversal(Node&lt;E&gt; node, int depth, StringBuilder sb) { if(node == null) { for(int i = 1; i &lt; depth; i++) sb.append("."); sb.append("null\n"); return; } else { postOrderTraversal(node.left, depth + 1, sb); postOrderTraversal(node.right, depth + 1, sb); for(int i = 1; i &lt; depth; i++) sb.append("."); sb.append(node.data); sb.append("\n"); } } // Gets the height of the tree public int getHeight() { return getHeight(root); } private int getHeight(Node&lt;E&gt; node) { if(node == null) return 0; else { int L = getHeight(node.left); int R = getHeight(node.right); return Math.max(L, R) + 1; } } // Gets the sum of all nodes in the tree public int getSum() { return getSum(root); } private int getSum(Node&lt;E&gt; node) { if(node == null) return 0; int S = node.data; int L = getSum(node.left); int R = getSum(node.right); return S + L + R; } // Counts how many items less than the given target public int countLessThan(E target) { return countLessThan(root, target); } private int countLessThan(Node&lt;E&gt; node, E target) { if(node == null) return 0; else { int S = (node.data &lt; target) ? 1 : 0; // or int S = (node.data.compareTo(target) &lt; 0) ? 1 : 0; int L = countLessThan(node.left, target); int R = countLessThan(node.right, target); return S + L + R; } } public static void main(String[] args) { //Tests goes here of course :) } // The following methods *should* produce the same // result as their identically named ones with the class // BinaryTree, but they cannot access nodes directly // Gets the sum of all nodes in the tree public static int getSum(BinaryTree&lt;Integer&gt; T) { if(T.getData() == null) return 0; int S = T.getData(); int L = getSum(T.getLeftSubtree()); int R = getSum(T.getRightSubtree()); return S + L + R; } // Counts how many items less than the given target public static int countLessThan(BinaryTree&lt;Integer&gt; T, int target) { if(T == null || T.getData() == null) return 0; else { int S = (T.getData() &lt; target) ? 1 : 0; // or int S = (T.getData().compareTo(target) &lt; 0) ? 1 : 0; int L = countLessThan(T.getLeftSubtree(), target); int R = countLessThan(T.getRightSubtree(), target); return S + L + R; } } } </code></pre>
[ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-11-14T08:24:41.850", "Id": "29608", "Score": "0", "body": "In terms of generics, there should be no reason why you would be bounding it by `Integer` (which is `final` and doesn't make sense) -- it should be bounded by `Number` (`public class BinaryTree<E extends Number>`) instead. Your inner class shouldn't need generics, if it does for some reason it shouldn't be hiding it (e.g. `Node<T>` vs `Node<E>`." } ]
[ { "body": "<p>This is a good start. Here's what I have to say about it.</p>\n\n<ul>\n<li><p>There really is no point in making <code>E</code> constrained on <code>Integer</code>. The Integer class is <code>final</code> so it can't be anything but an <code>Integer</code>. Either remove that constraint or remove the use of generics here and make it an <code>Integer</code>.</p></li>\n<li><p>Your inner class could be made static. A node here doesn't need the outer class to mean anything and can exist on its own.</p></li>\n<li><p>Pretty much all members in your classes that are <code>protected</code> probably should be <code>private</code>. Don't get into the habit of using <code>protected</code> over <code>private</code> just because. Only do it because you <em>intend</em> for it to be overridden or used in a derived class.</p></li>\n<li><p>Personally, I wouldn't allow for the possibility of having a null root node. It will help simplify your code so you don't have to put null checks everywhere you need to operate on the root.</p></li>\n<li><p>Your <code>toString()</code> method should return a string representation of a single tree. What you have there (and in other related methods) is the kind of code I would expect to see in a \"printTree\" method. It doesn't belong there.</p></li>\n<li><p>Consider making your different traversal methods either return an iterator that iterates over the nodes in the appropriate order or use them to apply the visitor pattern on what operations you want to do on your tree. It would make them more useful in general rather than just only for filling a string buffer.</p></li>\n<li><p>Local variables should be in camelCase at most, not Capitalized.</p></li>\n</ul>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-11-14T05:00:08.813", "Id": "18579", "ParentId": "18575", "Score": "3" } }, { "body": "<p>Your code has the trees be mostly immutable, which is a good idea, but to be more elegant, you should</p>\n\n<ol>\n<li><p>Make all fields <code>final</code>.</p></li>\n<li><p>Use <code>null</code> for leaves, and change the <code>Node</code> constructor to take the data and left and right.</p></li>\n<li><p><code>isLeaf</code> should be true just for <code>root=null</code>, and all accessors on leaves should (implicitly or explicitly) throw a <code>NPE</code>.</p></li>\n<li><p>As previous commentators have said: get rid of useless generics (best, get rid of <code>extends Integer</code>), implement real iterators for traversals and fix <code>toString</code>. You can then write <code>sum</code> using an iterator.</p></li>\n<li><p>Write <code>equals(Object)</code> and <code>hashCode()</code>.</p></li>\n</ol>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-02-01T09:28:33.037", "Id": "40604", "ParentId": "18575", "Score": "1" } } ]
{ "AcceptedAnswerId": "18579", "CommentCount": "1", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-11-14T02:35:01.243", "Id": "18575", "Score": "3", "Tags": [ "java", "classes", "tree" ], "Title": "BinaryTree class with extra methods" }
18575
<pre><code> class session{ //variabile folosite private static $_sessionStarted = false; private static $_crypt = 'qwerty347658@$%AdfSV045*&amp;erT2Erb%6w!07&amp;[.?;ru'; private static $_salt = 'qwertyAF347658@$%AdfSV045*&amp;erTyUsdfYtrLmncBGhu'; private static $_rand = 'abcdefghijklmnoqprstuvxwz0123456789!@#$%^&amp;*()_-=;:&lt;&gt;,.'; private static $_rand_pass; //pornire sesiune, setari(http only, folosire cookie,generare pass random, modificare folder sesiuni) public static function start(){ ini_set('session.cookie_httponly',1); ini_set('session.use_only_cookies',1); session_save_path(SESS_PATH); ini_set('session.gc_probability', 2); ini_set('session.gc_divisor', 100); ini_set('session.gc_maxlifetime', 1440); if(self::$_sessionStarted == false){ session_start(); self::$_sessionStarted = true; self::rand_pass(self::$_rand); self::set('bad_ideea:D', self::$_rand_pass); } session_regenerate_id(true); } //sesion destroy, stergem toate sesiunile public static function stop(){ if(self::$_sessionStarted == true){ foreach($_SESSION as $k){ unset($_SESSION[$k]); } session_destroy(); } } //setare sesiuni, folosim array asociativ multidimensional public static function set($key, $value){ $_SESSION[$key] = $value; } //setare array associtiv doar criptat folosind aes 128 biti(pt informatii confidentiale) public static function set_e($key, $value){ $_SESSION[$key] = self::encrypt($value); } // returnam valoare aaray asociativ multidimensional public static function get($key, $secondKey = false){ if($secondKey == true){ if(isset($_SESSION[$key][$secondKey])){ return $_SESSION[$key][$secondKey]; } }else{ if(isset($_SESSION[$key])){ return $_SESSION[$key]; } } return false; } //returnam valoare decriptata array asociativ public static function get_e($key, $secondKey = false){ if(isset($_SESSION[$key])){ return self::decrypt($_SESSION[$key]); } return false; } //verificam existenta cheii in array si verificam daca valoarea corespunde public static function check($key, $val){ foreach($key as $k){ if(!array_key_exists($k, $_SESSION) || $_SESSION[$k] != array_shift($val)){ return false; } } return true; } //facem unset la sesiuni parametru string sau array public static function clean($key){ if(is_array($key)){ foreach($key as $k){ unset($k); } }else{ unset($key); } } //hash ripemd320 pt valori importante la care avem nevoie doar de comparare(browser os ip etc) public static function sess_hash($key){ return hash('ripemd320', $key.self::$_crypt); } //generare parola aleatoare pt criptare si stocare in $_rand_pass private static function rand_pass(){ for($i = 0; $i &lt;= 20; $i++){ $tmp[] = self::$_rand[rand(0, strlen(self::$_rand)-1)]; } self::$_rand_pass = implode('',$tmp); } //criptare private static function encrypt($decrypted) { $key = hash('SHA256', self::$_salt . self::$_rand_pass, true); srand(); $iv = mcrypt_create_iv(mcrypt_get_iv_size(MCRYPT_RIJNDAEL_128, MCRYPT_MODE_CBC), MCRYPT_RAND); if (strlen($iv_base64 = rtrim(base64_encode($iv), '=')) != 22) return false; $encrypted = base64_encode(mcrypt_encrypt(MCRYPT_RIJNDAEL_128, $key, $decrypted . md5($decrypted), MCRYPT_MODE_CBC, $iv)); return $iv_base64 . $encrypted; } //decriptare private static function decrypt($encrypted) { $key = hash('SHA256', self::$_salt . self::$_rand_pass, true); $iv = base64_decode(substr($encrypted, 0, 22) . '=='); $encrypted = substr($encrypted, 22); $decrypted = rtrim(mcrypt_decrypt(MCRYPT_RIJNDAEL_128, $key, base64_decode($encrypted), MCRYPT_MODE_CBC, $iv), "\0\4"); $hash = substr($decrypted, -32); $decrypted = substr($decrypted, 0, -32); if (md5($decrypted) != $hash) return false; return $decrypted; } //afisam arrayul $_SESSION pt debug public static function display(){ echo '&lt;pre&gt;'; print_r($_SESSION); echo '&lt;/pre&gt;'; } </code></pre> <p>I wrote a small session wrapper class. Is it good for something? For now I'm still trying to figure out where to store the encryption key. I guess MySQL is the best place to save it. I'm going to regenerate the key every 6-12 hours for each user.</p>
[ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-11-14T18:15:04.713", "Id": "29648", "Score": "1", "body": "What are you trying to accomplish by encrypting session keys?" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-11-14T19:43:34.133", "Id": "29655", "Score": "0", "body": "I'm just encrypting the value not the keys :d. I need encryption (a light one) for some sensitive data. For the moment i'm storing the ecnrytion key in the session file itself, until i find a good ideea where to save it. I know it's a bad ideea, but i's not final. When i finish the class i'm going to store the encryption key in the db or something like that. I was looking for a way to write to RAM, but i guess it's not possible just with php (simple). And sorry for bad english, i'm using gtranslate." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-11-15T00:28:47.817", "Id": "29672", "Score": "0", "body": "I still don't understand the point of your class. I hope your not planing to store sensitive data inside a session. You can't write to RAM with PHP. Imagine what could happen if you where be able to write to RAM on a shared host." } ]
[ { "body": "<ol>\n<li><p>You said in a comment that you're storing half of the encryption key alongside the data the data you're encrypting, and the other half in the code itself. What's the point of that? If they have access to the PHP files, they probably have access to the session files, too.</p></li>\n<li><p>There's basically no point in calling srand() with no arguments. It doesn't make its output \"more random\". <a href=\"https://security.stackexchange.com/questions/18033/how-insecure-are-phps-rand-functions\">Relevant</a></p></li>\n<li><p>The issue with calling session_regenerate_id with every page load is that if you have two pages loading from the same user at the same time, the user will get logged out. </p></li>\n</ol>\n\n<p>Here's an example:</p>\n\n<ol>\n<li>User sends \"GET /page1\" and \"Cookie: session=cookie1\" </li>\n<li>User sends \"GET /page2\" and \"Cookie: session=cookie1\" </li>\n<li>Server receives request for page1; Server changes cookie, sends back \"Set-Cookie: session=cookie2\". </li>\n<li>User receives new cookie and saves it, but it is too late. </li>\n<li>Server receives request for page2; since cookie1 != cookie2, the request fails and the user is redirected to the login page.</li>\n</ol>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-11-15T14:16:39.100", "Id": "29699", "Score": "0", "body": "If they got access to your php files, i guess session files are your last concern. And i store them in session files until i find a better place(ex:mysql)." } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-11-15T00:44:47.887", "Id": "18638", "ParentId": "18577", "Score": "4" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "3", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-11-14T04:35:10.550", "Id": "18577", "Score": "3", "Tags": [ "php", "session" ], "Title": "Php session wrapper class" }
18577
<p>I've never really done anything with concurrency, so I'm not sure if this is done correctly. </p> <p>Basically, I have a class that handles all messages from the server and decides what to do them. It uses a separate thread to keep looping through a list to check for any new messages it has to deal with. </p> <p>The main server thread needs to be able to add messages to the <code>ArrayList</code> without causing a concurrency error, and so far it seems ok but I don't have that many messages coming in.</p> <pre><code>public class MessageThread implements Runnable { public static ArrayList&lt;Message&gt; messages = new ArrayList&lt;Message&gt;(); @Override public void run() { while (true) { synchronized (messages) { for (Message m : messages) { } } } public static void addMessage(Message message) { synchronized (messages) { messages.add(message); } } public static void removeMessage(Message message) { synchronized (messages) { messages.remove(message); } } } </code></pre> <p>So as you can see, the server thread would use the <code>MessageThread.addMessage</code> method whenever it needs to add a message.</p>
[ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-11-14T08:14:28.707", "Id": "29607", "Score": "1", "body": "Minor quib, program to the interface (e.g. `List<Message> messages = new ArrayList<Message>();` also have you checked out using the `Collections` API? `Collections.synchronizedList(messages)`." } ]
[ { "body": "<p>Your ArrayList is correctly guarded from access by multiple threads but you've got another problem. The busy wait in your run method is going to hog the CPU and might even starve the other threads that would be trying to put a message in the queue. You'll need some way of signaling that the queue is non-empty so that the run function can wait on the signal. In .NET it would be a ManualResetEvent. I don't know the java equivalent. Or better yet, have a look at BlockingQueue.</p>\n\n<pre><code>@Override\npublic void run() {\n while (true) {\n queueFullEvent.waitOne();\n synchronized (messages) {\n for (Message m : messages) {\n // messages should be removed here\n messages.remove(m);\n if (messages.isEmpty)\n queueFullEvent.reset(); \n }\n }\n }\n}\n\npublic static void addMessage(Message message) {\n synchronized (messages) {\n messages.add(message);\n queueFullEvent.set();\n }\n}\n\npublic static void removeMessage(Message message) {\n // would require additional syncronization objects to avoid a race.\n}\n</code></pre>\n\n<p>}</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-11-14T06:20:05.963", "Id": "29600", "Score": "0", "body": "where you would put the ManualResetEvent on which method? Could you please show it in code?" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-11-14T06:38:15.653", "Id": "29601", "Score": "0", "body": "I updated my original answer." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-11-14T06:52:30.750", "Id": "29602", "Score": "0", "body": "thank you, it's nice example, I'm actually new to multithreading and it would be nice to see, very nice examples, no matter on which language. btw: i'm a .net developer" } ], "meta_data": { "CommentCount": "3", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-11-14T05:37:46.517", "Id": "18580", "ParentId": "18578", "Score": "4" } }, { "body": "<ol>\n<li><code>public static ArrayList&lt;Message&gt; messages ...</code>. It is classic <em>confined object escape</em>. It means that since your synchronization object is <code>public</code>, somebody else can acquire its monitor outside <code>MessageThread</code> class, and cause a deadlock. Use proper encapsulation for your intrinsic locks.</li>\n<li>It is not clear why <code>public static void removeMessage(Message message)</code> is a part of your public API. Am I understand right that the server thread is supposed to call <code>MessageThread.addMessage</code> first, then somehow it must figure out that the message has been already processed, and then call <code>MessageThread.removeMessage</code> ? \nProbably, it should be a <code>MessageThread</code>'s responsibility to clean up completed messages from the underlying data structure ?</li>\n<li>There is an existing Java API for such use case. Please, take a look at <code>java.util.concurrent.ArrayBlockingQueue</code> class. Also consider using <code>java.util.concurrent.Executors</code> to process messages asynchronously, if needed.</li>\n</ol>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-11-14T05:57:45.750", "Id": "18581", "ParentId": "18578", "Score": "3" } }, { "body": "<p>Java synchronizes on objects (and not references), as such it is always good to make any reference that you will later use for synchronization final. so </p>\n\n<pre><code>public static ArrayList&lt;Message&gt; messages = new ArrayList&lt;Message&gt;();\n</code></pre>\n\n<p>should be</p>\n\n<pre><code>public static final ArrayList&lt;Message&gt; messages = new ArrayList&lt;Message&gt;();\n</code></pre>\n\n<p>This is because if in one your synchronized code blocks you do <code>messages = anotherListOfMessages</code> then other code blocks waiting on the lock might think it has been released when actually it (the reference) is now pointing to another object. The behavior that follows will most likely be something you don't expect.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-11-14T07:15:15.157", "Id": "18585", "ParentId": "18578", "Score": "2" } }, { "body": "<p>I'm surprised no one has mentioned this yet, but before going to far down the road you should really check out <a href=\"http://www.javaconcurrencyinpractice.com/\" rel=\"nofollow\">Java Concurrency In Practice</a>. It is by far the best resource for learning about concurrency on the JVM. It will cover the fundamental concurrency problems, idiosyncracies of the JVM platform and all the utility classes available.</p>\n\n<p>As for your implementation specifically, there are a number of suspicious things in this class... First of all there is probably no need for the internal message queue to be public. The number one source of concurrency errors is shared mutable state. So the less you share and the less that is mutable the better off you will be. </p>\n\n<p>While it doesn't directly affect the concurrency, is there a reason for choosing to make everything static? Generally static-ness can make it harder to reason about concurrency issues, so unless there is a compelling reason to do so I would make this class not static and then inject/provide instances where needed.</p>\n\n<p>Finally, it has been mentioned but Java has a suite of concurrency related utilities and classes in the <a href=\"http://docs.oracle.com/javase/1.5.0/docs/api/java/util/concurrent/package-summary.html\" rel=\"nofollow\">java.util.concurrent package</a>. Concurrency, like security is best left to the \"professionals\" and until you are one the best advice is to stick to the util classes provided and avoid making your own clever concurrency designs.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-11-19T19:36:53.367", "Id": "18810", "ParentId": "18578", "Score": "1" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "1", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-11-14T04:51:28.873", "Id": "18578", "Score": "7", "Tags": [ "java", "synchronization" ], "Title": "Handling messages from a server" }
18578
<p><strong>I would really love to hear your critiques on:</strong></p> <ul> <li>Code quality</li> <li>Code clarity</li> <li>More efficient alternative code</li> </ul> <p>Code:</p> <pre><code>function array_mask(array $source, array $filter){ foreach ($source as $key =&gt; $value){ if (!isset($filter[$key])){ if (array_search($key, $filter) !== false){ continue; } unset($source[$key]); } else { if (is_array($source[$key])){ $source[$key] = array_mask($source[$key], $filter[$key]); } } } return $source; } $source = array( 'page' =&gt; array( 'q' =&gt; 'alkflsdj', 'x' =&gt; 1, 9 =&gt; 'm' ), 'news' =&gt; 7 ); $filter = array( 'page' =&gt; array( 9 ), 'news' ); $result = array_mask($source, $filter); var_dump($result); </code></pre> <p>Result:</p> <pre> array 'page' => array 9 => string 'm' (length=1) 'news' => int 7 </pre>
[]
[ { "body": "<p>Looks good to me, but you can make a small optimization:</p>\n\n<p>change this</p>\n\n<pre><code> if (array_search($key, $filter) !== false){\n continue;\n }\n unset($source[$key]);\n</code></pre>\n\n<p>to </p>\n\n<pre><code> if (array_search($key, $filter) === false){\n unset($source[$key]);\n }\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-11-14T17:01:27.543", "Id": "29640", "Score": "1", "body": "Just a suggestion, you might want to explain why you are suggesting the change. Doing so will greatly increase the value of this answer." } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-11-14T10:42:40.443", "Id": "18595", "ParentId": "18582", "Score": "0" } }, { "body": "<p>You can use built-in functions instead. Like this for example:</p>\n\n<pre><code>function array_mask(array $source, array $filter)\n{\n $source = array_intersect_key($source, $filter);\n\n foreach ($source as $key =&gt; $value)\n if (is_array($value))\n $source[$key] = array_mask($source[$key], $filter[$key]);\n\n return $source;\n}\n\n$source = array(\n 'page' =&gt; array(\n 'q' =&gt; 'alkflsdj',\n 'x' =&gt; 1,\n 9 =&gt; 'm'\n ),\n 'news' =&gt; 7\n);\n$filter = array(\n 'page' =&gt; array(\n 9 =&gt; ''\n ),\n 'news' =&gt; ''\n);\n\nvar_dump (array_mask($source, $filter));\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-11-14T17:20:37.170", "Id": "29644", "Score": "0", "body": "I had this idea, but for some reason she didn't like. Now like normal." } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-11-14T12:48:25.127", "Id": "18603", "ParentId": "18582", "Score": "2" } } ]
{ "AcceptedAnswerId": "18603", "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-11-14T06:21:14.170", "Id": "18582", "Score": "2", "Tags": [ "php" ], "Title": "array_mask, Seeking alternative code" }
18582
<p>Both unit tests pass and they both test the same thing. The production code uses the right error codes.</p> <p>System Under Test (SUT)</p> <pre><code>public interface IRepository { string GetParameter(int id); } public class Repository { public string GetParameter(int id) { return "foo"; } } public class ErrorInfo{ public string ErrorMessage { get; set; } } public interface IErrorProvider { ErrorInfo BuildErrorMessage(string errorCodes); } public class ErrorProvider { public ErrorInfo BuildErrorMessage(string errorCodes) { return new ErrorInfo { ErrorMessage = errorCodes }; } } public class DomainClass { private readonly IRepository _repository; private readonly IErrorProvider _errorProvider; public DomainClass(IRepository repository, IErrorProvider errorProvider) { _repository = repository; _errorProvider = errorProvider; } public List&lt;ErrorInfo&gt; GetErrorList(int id) { var errorList = new List&lt;ErrorInfo&gt;(); string paramName = _repository.GetParameter(id); if (string.IsNullOrEmpty(paramName)) { string errorCodes = string.Format("{0}, {1}", 200, 201); var error = _errorProvider.BuildErrorMessage(errorCodes); errorList.Add(error); } return errorList; } } </code></pre> <p><strong>Unit test 1</strong></p> <pre><code>[TestMethod] public void GetErrorList_WhenParameterIsEmpty_ReturnsExpectedErrorCodes() { //Arrange var stubRepo = new Mock&lt;IRepository&gt;(); stubRepo.Setup(x =&gt; x.GetParameter(It.IsAny&lt;int&gt;())).Returns(string.Empty); const string expectedErrorCodes = "200, 201"; var stubErrorRepo = new Mock&lt;IErrorProvider&gt;(); stubErrorRepo.Setup(e =&gt; e.BuildErrorMessage(expectedErrorCodes)).Returns(new ErrorInfo() { ErrorMessage = expectedErrorCodes + " some error message" }); const int parameterId = 5; var sut = new DomainClass(stubRepo.Object, stubErrorRepo.Object); //Act var result = sut.GetErrorList(parameterId); //Assert Assert.IsTrue(result.Any(info =&gt; info.ErrorMessage.Contains(expectedErrorCodes))); } </code></pre> <p><strong>Unit test 2</strong></p> <pre><code>[TestMethod] public void GetErrorList_WhenParameterIsEmpty_VerifyTheCorrectErrorCodeBeingUsed() { //Arrange var stubRepo = new Mock&lt;IRepository&gt;(); stubRepo.Setup(x =&gt; x.GetParameter(It.IsAny&lt;int&gt;())).Returns(string.Empty); const string errorCodesPassedIn = "200, 201"; var errorRepoMock = new Mock&lt;IErrorProvider&gt;(); const int parameterId = 5; var sut = new DomainClass(stubRepo.Object, errorRepoMock.Object); //Act sut.GetErrorList(parameterId); //Assert errorRepoMock.Verify(x =&gt; x.BuildErrorMessage(errorCodesPassedIn)); } </code></pre> <p>Which test is correctly unit testing expected behaviour and why?</p> <p>More details:</p> <p>I don't seems to have the confidence on Test 1. It seems like the stub dictates what the production code should returns. </p> <p>For example, <code>stubErrorRepo</code> has the setup:</p> <pre><code>stubErrorRepo.Setup(e =&gt; e.BuildErrorMessage(expectedErrorCodes)).Returns(new ErrorInfo() { ErrorMessage = expectedErrorCodes + " some error message" }); </code></pre> <p>This causes production code to return the expected error codes. Then we Assert against the error codes to ensure the result message contains the expected error codes. If I change the value of the <code>expectedErrorCodes</code> variable to some other value, the test fails. Note that it is not the production error codes cause the test to fail, it is what have stubbed out <code>expectedErrorCodes</code>.</p> <p>This makes me think that this is not a true unit test. I believe the stubs should just provide canned answers to the test, and should not dictate the final outcome of the test. Can you call it a mock? I don't know.</p> <p>But I also think test describes what the production code should return. If you think test is as specification. For example, if the <code>expectedErrorCodes</code> codes are not returned, the test fails. Seems like a valid argument too. And of course if I change the production error codes, the test fails as well. But there is something fishy I cannot rule out why this test is not right.</p> <p>Test 2 uses the <code>mock.Verify</code> to ensure the correct parameters being used, which seems like a reasonable approach. But I cannot fault the first test either.</p> <p>Would you prefer Test 1, Test 2 or both?</p>
[]
[ { "body": "<p>They test the same \"action\". The semantic difference is:</p>\n\n<p>The first test verifies the values returned by the method being tested. </p>\n\n<p>The second verifies that it called a particular method.</p>\n\n<p>//disclaimer// I'm certainly no UnitTesting expert; I'm still learning, but I that's how I read those two tests.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-11-14T13:15:02.250", "Id": "18605", "ParentId": "18591", "Score": "0" } }, { "body": "<p>I think these two test test two different things. 1st test test correctness of error messages formatting, 2nd - that appropriate method was called.\nWhat I don't understand is why do you need expectedErrorCodes variable in tests in the fist place? 200, 201 error codes are just hard coded in your GetErrorList method. So assertion section of the 2nd test may look like</p>\n\n<pre><code> errorRepoMock.Verify(x =&gt; x.BuildErrorMessage(It.IsAny&lt;string&gt;()));\n</code></pre>\n\n<p>Tests don't need to know such details.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-11-14T13:49:00.530", "Id": "18608", "ParentId": "18591", "Score": "1" } }, { "body": "<p>This question demonstrates why Test-Driven Development (TDD) is a valuable discipline. If TDD had been strictly followed, the answer would have almost presented itself.</p>\n\n<p>To demonstrate that, I copied the tests only (not the 'production code') to a code base, and attempted to figure out what the implementation should be in order to pass each test. Keep in mind that an important principle in TDD is that you <strong>write only enough code to make the tests pass</strong>.</p>\n\n<p><strong>Initial state</strong></p>\n\n<p>In order to <em>compile</em>, the initial implementation of <code>DomainClass</code> looks like this:</p>\n\n<pre><code>public class DomainClass\n{\n public DomainClass(IRepository repository, IErrorProvider errorProvider)\n {\n }\n\n public IEnumerable&lt;ErrorInfo&gt; GetErrorList(int parameterId)\n {\n yield break;\n }\n}\n</code></pre>\n\n<p>Obviously this doesn't pass the tests, but at least the code compiles so that you can run the tests.</p>\n\n<p>Since the goal of this answer is to explore which test is most correct, I'll now isolate each test. I'll first delete <em>test 2</em> so that only <em>test 1</em> is left and see where that goes, and then the other way around. After that, I'll compare the two implementations to figure out which one is best.</p>\n\n<p><strong>Test 1</strong></p>\n\n<p>If <em>test 1</em> is the only test of <code>DomainClass</code>, then this implementation passes:</p>\n\n<pre><code>public class DomainClass\n{\n private readonly IErrorProvider errorProvider;\n\n public DomainClass(IRepository repository, IErrorProvider errorProvider)\n {\n this.errorProvider = errorProvider;\n }\n\n public IEnumerable&lt;ErrorInfo&gt; GetErrorList(int id)\n {\n yield return this.errorProvider.BuildErrorMessage(\"200, 201\");\n }\n}\n</code></pre>\n\n<p>Compared to the 'production code' in the OP, this is obviously not the full implementation of <code>GetErrorList</code>, but it <em>does</em> pass the test(s).</p>\n\n<p><strong>Test 2</strong></p>\n\n<p>If <em>test 2</em> is the only test of <code>DomainClass</code>, then this implementation passes:</p>\n\n<pre><code>public class DomainClass\n{\n private IErrorProvider errorProvider;\n\n public DomainClass(IRepository repository, IErrorProvider errorProvider)\n {\n this.errorProvider = errorProvider;\n }\n\n public IEnumerable&lt;ErrorInfo&gt; GetErrorList(int parameterId)\n {\n this.errorProvider.BuildErrorMessage(\"200, 201\");\n return new List&lt;ErrorInfo&gt;();\n }\n}\n</code></pre>\n\n<p>This implementation passes the test(s), but doesn't look correct to me. The <code>BuildErrorMessage</code> method is called, but the return value is ignored. That's probably not what was intended.</p>\n\n<p><strong>Stubs and Mocks</strong></p>\n\n<p>From <a href=\"http://amzn.to/SM8Yv0\">GOOS</a> comes this rule of thumb (paraphrased):</p>\n\n<blockquote>\n <p>Use Stubs for Queries and Mocks for Commands.</p>\n</blockquote>\n\n<p>Since the <code>BuildErrorMessage</code> method is a <a href=\"http://en.wikipedia.org/wiki/Command-query_separation\">Query</a> this rules states that a Stub should be used for testing. That indicates that <em>test 1</em> is more correct, which the two alternative implementations also seem to indicate.</p>\n\n<p><strong>Driving the Happy Path</strong></p>\n\n<p>Obviously, neither alternative implementation is correct as is, but if <em>test 1</em> is used as a foundation, a second unit test can exercise the 'Happy Path':</p>\n\n<pre><code>[Fact]\npublic void HappyPath()\n{\n // Fixture setup\n var repositoryStub = new Mock&lt;IRepository&gt;();\n repositoryStub.Setup(r =&gt; r.GetParameter(1)).Returns(\"foo\");\n\n var sut = new DomainClass(\n repositoryStub.Object,\n new Mock&lt;IErrorProvider&gt;().Object);\n // Exercise system\n var result = sut.GetErrorList(1);\n // Verify outcome\n Assert.False(result.Any());\n // Teardown\n}\n</code></pre>\n\n<p>Which, together with <em>test 1</em>, forces you to write code like this:</p>\n\n<pre><code>public class DomainClass\n{\n private readonly IRepository repository;\n private readonly IErrorProvider errorProvider;\n\n public DomainClass(IRepository repository, IErrorProvider errorProvider)\n {\n this.repository = repository;\n this.errorProvider = errorProvider;\n }\n\n public IEnumerable&lt;ErrorInfo&gt; GetErrorList(int id)\n {\n if (string.IsNullOrEmpty(this.repository.GetParameter(1)))\n yield return this.errorProvider.BuildErrorMessage(\"200, 201\");\n yield break;\n }\n}\n</code></pre>\n\n<p>You may, however, notice from the hard-coded <em>1</em> parameter that this can't be the final implementation yet. However, all tests are green at this point, so you must add more test cases.</p>\n\n<p>Here's the Happy Path test expanded as a Parameterized Test:</p>\n\n<pre><code>[Theory]\n[InlineData(1)]\n[InlineData(2)]\n[InlineData(3)]\npublic void HappyPath(int id)\n{\n // Fixture setup\n var repositoryStub = new Mock&lt;IRepository&gt;();\n repositoryStub.Setup(r =&gt; r.GetParameter(id)).Returns(\"foo\");\n\n var sut = new DomainClass(\n repositoryStub.Object,\n new Mock&lt;IErrorProvider&gt;().Object);\n // Exercise system\n var result = sut.GetErrorList(id);\n // Verify outcome\n Assert.False(result.Any());\n // Teardown\n}\n</code></pre>\n\n<p>This drives the implementation to this point in order to pass all tests:</p>\n\n<pre><code>public class DomainClass\n{\n private readonly IRepository repository;\n private readonly IErrorProvider errorProvider;\n\n public DomainClass(IRepository repository, IErrorProvider errorProvider)\n {\n this.repository = repository;\n this.errorProvider = errorProvider;\n }\n\n public IEnumerable&lt;ErrorInfo&gt; GetErrorList(int id)\n {\n if (string.IsNullOrEmpty(this.repository.GetParameter(id)))\n yield return this.errorProvider.BuildErrorMessage(\"200, 201\");\n yield break;\n }\n}\n</code></pre>\n\n<p>This is beginning to look more reasonable.</p>\n\n<p><strong>Summary</strong></p>\n\n<p><em>Test 1</em> is better because it specifies an expected <em>data flow</em> through the method. Since the <code>BuildErrorMessage</code> is a Query you must expect that it has no side effects. When that is the case, then why care that it was invoked?</p>\n\n<p>You should care, however, about what it <em>returns</em> if it <em>is</em> invoked, and that's what the Stub specifies.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-11-14T14:04:27.827", "Id": "18610", "ParentId": "18591", "Score": "28" } } ]
{ "AcceptedAnswerId": "18610", "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-11-14T09:43:22.623", "Id": "18591", "Score": "14", "Tags": [ "c#", "unit-testing", "error-handling", "comparative-review", "moq" ], "Title": "Unit tests for testing error codes" }
18591
<p>Inspired by <a href="https://codereview.stackexchange.com/q/18578/8953">this question</a>, I have a Java Enterprise application running in Glassfish 2.1 and a Java SE client that communicates with the server application.</p> <p>For this I have a bean that maintains a collection of jobs that is set by the server and the client then asks if his job is in the current list of jobs known to the bean.</p> <p>I want to ask if this code is good.</p> <p>The client uses this interface:</p> <pre><code>import javax.ejb.Remote; @Remote public interface GeneratorCancelledRemote { public boolean isJobCancelled(String jobId); } </code></pre> <p>The server uses this interface:</p> <pre><code>import java.util.Collection; import javax.ejb.Local; @Local public interface GeneratorCancelledLocal { public void setJobs(final Collection&lt;String&gt; jobs); } </code></pre> <p>And here's the implementation:</p> <pre><code>import java.util.Collection; import java.util.Collections; import java.util.HashSet; import javax.ejb.Stateless; @Stateless public class GeneratorCancelled implements GeneratorCancelledLocal, GeneratorCancelledRemote { private Collection&lt;String&gt; jobs; public void setJobs(final Collection&lt;String&gt; jobs) { this.jobs = Collections.synchronizedSet(new HashSet&lt;String&gt;()); this.jobs.addAll(jobs); } @Override public boolean isJobCancelled(final String jobId) { return jobs != null &amp;&amp; jobs.contains(jobId); } } </code></pre> <p>Obviously access to the collection of jobs has to be synchronized somehow. Is the use of <code>Collections.synchronizedSet</code> the best way to do this? The EJB gurus around here shun on the use of <code>synchronized</code> in an EE context.</p> <p>I found <a href="http://blog.holisticon.de/2010/11/synchronisation-und-nebenlaufigkeitskontrolle-mit-ejbs-leicht-gemacht/" rel="nofollow noreferrer">this</a> (in German), which also explains that <code>synchronized</code> is not allowed in EJB.</p>
[ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2015-05-19T00:26:58.157", "Id": "165254", "Score": "0", "body": "I don't know much about EJB, but the article looks horrible to me. I know quite a lot about concurrency in Java SE, and after reading the article I still don't know anything about concurrency in Java EE." } ]
[ { "body": "<ol>\n<li>Your <code>@Stateless</code> service contains a shared state. It looks weird for me.</li>\n<li><p>You never modify a state of <code>jobs</code>, you always create a new object</p>\n\n<pre><code>this.jobs = Collections.synchronizedSet(new HashSet&lt;String&gt;());\n</code></pre>\n\n<p>Could you please clarify why ?</p></li>\n<li>From synchronization standpoint you have a race condition in <code>setJobs</code> method, so it should be <code>synchronized</code>.</li>\n<li>Now, since your write operation (<code>setJobs</code> method) is protected by the intrinsic lock, all read operations should be also protected by the same lock to ensure data visibility. Make <code>isJobCancelled</code> synchronized too.</li>\n</ol>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-11-14T12:28:34.743", "Id": "29617", "Score": "0", "body": "2: `Collections.synchronizedSet` does not create a new object (the collection is not cloned), only a view. 3&4: As I say, the EJB-gurus here balk on the use of synchronized in beans." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-11-14T20:02:59.583", "Id": "29656", "Score": "1", "body": "Of course `Collections.synchronizedSet` does not create a new object. I'm talking about **new HashSet<String>()**." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2015-05-19T00:32:39.390", "Id": "165255", "Score": "0", "body": "Actually, `Collections.synchronizedSet` does create a new tiny object, but I see what you mean. The thing with `new HashSet<String>()` is defensive copy. Here, it's needed to ensure the stored collection doesn't change sneakily. It's strictly necessary here: If you work on a provided collection to which someone has unlimited unsynchronized access, then any synchronization is futile." } ], "meta_data": { "CommentCount": "3", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-11-14T11:57:03.360", "Id": "18601", "ParentId": "18592", "Score": "1" } }, { "body": "<blockquote>\n <p>Is the use of Collections.synchronizedSet the best way to do this?</p>\n</blockquote>\n\n<p>No way. It allows you to do some operations atomically, e.g., <code>addAll</code>, but what you'd need is to replace the whole content by e.g. <code>clear</code> and <code>addAll</code> executed atomically <em>together</em>.</p>\n\n<p>But there's a simple way to get rid of your race condition:</p>\n\n<pre><code>public void setJobs(final Collection&lt;String&gt; jobs) {\n Collection&lt;String&gt; copy = Collections.synchronizedSet(new HashSet&lt;String&gt;());\n copy.addAll(jobs);\n this.jobs = copy;\n}\n</code></pre>\n\n<p>As long as you keep you collection private to the method, there can be no race.</p>\n\n<p>However, it's still wrong, namely because of the second bug. If one thread writes <code>jobs</code>, there's no guarantee that another one sees the new value. It may see the old value for an indefinite amount of time.</p>\n\n<p>To the rescue, you could declare <code>jobs</code> as <code>volatile</code>. Or use an <code>AtomicReference</code> or whatever.</p>\n\n<p>Then it works, however, there are no operation on your set which would need it to be synchronized. The only writing happens to a local variable constrained to a single thread, the safe publication happens via <code>volatile</code>, and <code>contains</code> is reading only of an effectively immutable object and needs no synchronization.</p>\n\n<p><em>So there's no use for <code>Collections.synchronizedSet</code> here. Anyway, I strongly suggest to use the <code>synchronized</code> keyword (or equivalents provided by EJB) as it's the least error prone way. Note that even in these few lines there were two serious bugs. And debugging it is a real pain as it's all inherently non-deterministic.</em></p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2015-05-19T00:55:20.993", "Id": "91124", "ParentId": "18592", "Score": "1" } } ]
{ "AcceptedAnswerId": "18601", "CommentCount": "1", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-11-14T09:52:26.767", "Id": "18592", "Score": "1", "Tags": [ "java", "thread-safety" ], "Title": "Querying a list of jobs on a server using EJBs" }
18592
<p>I've been struggling to get to grips with <a href="http://joda-time.sourceforge.net/api-release/index.html" rel="nofollow">Joda-Time</a>, but feel that I've finnaly managed to get a grip on some of the functionality that I need.</p> <p>I have written a function that will convert a <code>DateTime</code> from one timezone to another. I've not done any unit testing on it (but have done my own testing), but would appreciate comments on if it could be improved. The code is in native Java.</p> <pre><code>import org.joda.time.*; import org.joda.time.format.*; public class testing { /** * @param args */ public static void main(String[] args) { public string ConvertTimeZones(String sFromTimeZone, String sToTimeZone, String sFromDateTime){ DateTimeZone oFromZone = DateTimeZone.forID(sFromTimeZone); DateTimeZone oToZone = DateTimeZone.forID(sToTimeZone); DateTime oDateTime = new DateTime(sFromDateTime); DateTime oFromDateTime = oDateTime.withZoneRetainFields(oFromZone); DateTime oToDateTime = new DateTime(oFromDateTime).withZone(oToZone); DateTimeFormatter oFormatter = new DateTimeFormat.forPattern("yyyy-MM-dd'T'H:mm:ss.SSSZ"); DateTimeFormatter2 = new DateTimeFormat.forPattern("yyyy-MM-dd H:mm:ss"); DateTime oNewDate = oFormatter.withOffsetParsed().parseDateTime(oToDateTime.toString()); return oFormatter2.withZone(oToZone).print(oNewDate.getMillis()); } } } </code></pre> <p>The arguments:</p> <pre><code>sFromTimeZone = UTC sToTimeZone = Europe/London sFromDateTime = 2012-05-08 18:00:00 </code></pre> <p>should produce a return of </p> <pre><code>2012-05-08 19:00:00 </code></pre>
[]
[ { "body": "<ol>\n<li><p>First of all, currently it does not compile. You should fix that, non-working codes are off-topic here.</p></li>\n<li><p>According to the <a href=\"http://www.oracle.com/technetwork/java/javase/documentation/codeconventions-135099.html#367\">Code Conventions for the Java Programming Language</a>, method names should start with lowercase letters and class names should start with uppercase letters. <code>ConvertTimeZones</code> should be <code>convertTimeZones</code>.</p>\n\n<ul>\n<li><a href=\"http://www.oracle.com/technetwork/java/javase/documentation/codeconventions-135099.html#367\">Code Conventions for the Java Programming Language, 9 - Naming Conventions</a></li>\n<li><em>Effective Java, 2nd edition</em>, <em>Item 56: Adhere to generally accepted naming conventions</em></li>\n</ul></li>\n<li><p>The <code>o</code> prefix is unnecessary for every variable.</p></li>\n<li><p>You could omit lots of intermediate objects. Here is a simplified version:</p>\n\n<pre><code>public static String convertTimeZones(final String fromTimeZoneString, \n final String toTimeZoneString, final String fromDateTime) {\n final DateTimeZone fromTimeZone = DateTimeZone.forID(fromTimeZoneString);\n final DateTimeZone toTimeZone = DateTimeZone.forID(toTimeZoneString);\n final DateTime dateTime = new DateTime(fromDateTime, fromTimeZone);\n\n final DateTimeFormatter outputFormatter \n = DateTimeFormat.forPattern(\"yyyy-MM-dd H:mm:ss\").withZone(toTimeZone);\n return outputFormatter.print(dateTime);\n}\n</code></pre></li>\n<li><p>Here are a few unit tests:</p>\n\n<pre><code>import static ...TimeZoneConverter.convertTimeZones;\nimport static org.junit.Assert.assertEquals;\n\nimport java.util.Arrays;\nimport java.util.Collection;\n\nimport org.junit.Test;\nimport org.junit.runner.RunWith;\nimport org.junit.runners.Parameterized;\nimport org.junit.runners.Parameterized.Parameters;\n\n@RunWith(value = Parameterized.class)\npublic class TimeZoneConverterTest {\n\n private final String expectedDatetime;\n private final String fromTimezone;\n private final String toTimezone;\n private final String inputDatetime;\n\n public TimeZoneConverterTest(final String expectedDatetime, \n final String fromTimezone, final String toTimezone,\n final String inputDatetime) {\n this.expectedDatetime = expectedDatetime;\n this.fromTimezone = fromTimezone;\n this.toTimezone = toTimezone;\n this.inputDatetime = inputDatetime;\n }\n\n @Parameters\n public static Collection&lt;Object[]&gt; data() {\n final Object[][] data = new Object[][] {\n { \"2012-05-08 19:00:00\", \n \"UTC\", \"Europe/London\", \"2012-05-08T18:00:00\" },\n { \"2012-05-08 17:00:00\", \n \"Europe/London\", \"UTC\", \"2012-05-08T18:00:00\" },\n { \"2012-05-08 20:00:00\", \n \"UTC\", \"CET\", \"2012-05-08T18:00:00\" },\n { \"2012-05-08 19:00:00\", \n \"America/Tijuana\", \"CET\", \"2012-05-08T10:00:00\" },\n { \"2012-11-08 21:00:00\", \n \"Europe/London\", \"Asia/Dubai\", \"2012-11-08T17:00:00\" },\n { \"2012-11-19 2:00:00\", \n \"Europe/London\", \"Asia/Tokyo\", \"2012-11-18T17:00:00\" } };\n return Arrays.asList(data);\n }\n\n @Test\n public void test() {\n assertEquals(expectedDatetime, \n convertTimeZones(fromTimezone, toTimezone, inputDatetime));\n }\n}\n</code></pre></li>\n</ol>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2015-03-25T20:09:24.183", "Id": "152998", "Score": "0", "body": "Hi. I am getting exception: `java.lang.IllegalArgumentException: Invalid format: \"2015-03-25 19:38:56\" is malformed at \" 19:38:56\"\n at org.joda.time.format.DateTimeParserBucket.doParseMillis(DateTimeParserBucket.java:187)\n at org.joda.time.format.DateTimeFormatter.parseMillis(DateTimeFormatter.java:780)\n at org.joda.time.convert.StringConverter.getInstantMillis(StringConverter.java:65)\n at org.joda.time.base.BaseDateTime.<init>(BaseDateTime.java:154)\n at org.joda.time.DateTime.<init>(DateTime.java:281)`" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2015-03-25T20:47:01.007", "Id": "153004", "Score": "0", "body": "@ShajeelAfzal: It seems to me that the code above still works well on my machine with Joda-Time 2.1. I guess it is quite old now so I've tried with 2.7 and it works as well. My guess it that you probably missed the `T` (it should be `2015-03-25T19:38:56`). If it's not help could you ask a question with some code and context information on Stack Overflow and drop me a link here?" } ], "meta_data": { "CommentCount": "2", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-11-19T19:52:22.070", "Id": "18812", "ParentId": "18599", "Score": "9" } }, { "body": "<p>I was also struggling to convert a DateTime from a specified DateTimeZone to another DateTimeZone. Here is how I managed it :</p>\n\n<pre><code> String myDate; // To initialise with the string you want to parse\n\n DateTimeFormatter formatter = DateTimeFormat.forPattern(myPattern);\n // Here, you can specify the original specified DateTimeZone of your String\n formatter = formatter.withZone(originalDateTimeZone);\n // Then, parse your String\n DateTime originalDateTime = formatter.parseDateTime(myDate);\n\n // Specify the new DateTimeZone and construct the new DateTime\n DateTime newDateTime = dateTime.toDateTime(newDateTimeZone);\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2018-03-19T17:15:06.057", "Id": "364296", "Score": "1", "body": "You have presented an alternative solution, but haven't reviewed the code. Please explain your reasoning (how your solution works and why it is better than the original) so that the author and other readers can learn from your thought process. Please read [How do I write a good answer?](https://codereview.stackexchange.com/help/how-to-answer), which states: \"_Every answer must make at least one **insightful observation** about the code in the question. Answers that merely provide an alternate solution with no explanation or justification do not constitute valid Code Review_\"" } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2018-03-19T16:56:15.747", "Id": "189950", "ParentId": "18599", "Score": "0" } } ]
{ "AcceptedAnswerId": "18812", "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-11-14T11:23:57.760", "Id": "18599", "Score": "3", "Tags": [ "java", "datetime", "jodatime" ], "Title": "Converting timedate timezones with Joda-Time" }
18599
<p>I inherited a lot of C code with many ellipsis (variadic) functions.</p> <p>I have a lots of API with the following signature:</p> <pre><code>void getXY(int foo, ...) // many parameters </code></pre> <p>and this is used in this way as usual:</p> <pre><code>getXY(1, "sizex", 12, "sizey", 24, 0); </code></pre> <p>Now I started to think about how I can replace it with a typesafe C++ API, and I came up with the following:</p> <pre><code>#include &lt;string&gt; #include &lt;iostream&gt; #include &lt;cstdarg&gt; #include &lt;vector&gt; class Test { struct GetParam { std::string name; int id; }; struct Attr { Attr(Test&amp; test) : test(test) { std::cout &lt;&lt; "Attr()" &lt;&lt; std::endl; test.get_params.clear(); } ~Attr() { std::cout &lt;&lt; "~Attr()" &lt;&lt; std::endl; test.end_get(); } Attr&amp; add(const std::string&amp; name, int id) { GetParam param = {name, id}; test.get_params.push_back(param); return *this; } Test&amp; test; }; void end_get() { for (auto get_param : get_params) std::cout &lt;&lt; "name:" &lt;&lt; get_param.name &lt;&lt; ", id:" &lt;&lt; get_param.id &lt;&lt; std::endl; } std::vector&lt;GetParam&gt; get_params; public: // old code void get1(int foo, ...) { va_list args; va_start(args, foo); const char* name = va_arg(args, const char *); for (; name != NULL; name = va_arg(args, const char *)) { int id = va_arg(args, int); std::cout &lt;&lt; "name:" &lt;&lt; name &lt;&lt; ", id:" &lt;&lt; id &lt;&lt; std::endl; } va_end(args); } // new code plan Attr get2(int foo) { Attr attr(*this); return attr; } private: }; int main() { Test test; test.get1(1, "sizex", 12, "sizey", 24, 0); // old style test.get2(1).add("sizex", 12).add("sizey", 24); // new style return 0; } </code></pre> <p>What do you think? Is there a simpler solution? How can I improve this?</p>
[]
[ { "body": "<p>If the arguments are that simple, what's wrong with a locally defined array?</p>\n\n<pre><code>Test t;\nconst Test args[] = { {\"sizex\", 12}, {\"sizey\", 24} };\nt.get(1, args, sizeof(args)/sizeof(*args));\n</code></pre>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-11-14T20:55:40.410", "Id": "18632", "ParentId": "18604", "Score": "2" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-11-14T12:56:58.680", "Id": "18604", "Score": "1", "Tags": [ "c++", "variadic" ], "Title": "C-style va_args replacement" }
18604
<p>I have a pretty common issue: I need to know the name of current user and also name of the current controller so I can highlight/disable some links.</p> <p>Here's some solutions I found by myself:</p> <ol> <li><p>Get all what's needed inside <code>PartialView</code>.</p> <p>I have a PartialView inside my page layout, that takes user name like this:</p> <pre><code>@{ var userName = Context.ToContext().GetUser&lt;Agent&gt;().Name; } </code></pre> <p>And here's the way I take controller name:</p> <pre><code>@{ var controllerName = HttpContext.Current.Request.RequestContext.RouteData.Values["controller"].ToString(); } </code></pre></li> </ol> <p>I have some problem with this code, for it is suspected to ruin MVC pattern. I have another solution, which I consider even more stupid.</p> <ol> <li><p>I've created new controller called like <code>ContextController</code>:</p> <pre><code>public class ContextController : BaseController // BaseController is just a facade { public string GetUserName() { return Context.GetUser&lt;Agent&gt;().Name; } } </code></pre> <p>Here's the problem: I cannot get controller name with this way, because it will always be like "Context", which is useless for me. And I also get the name on view like this:</p> <pre><code>@{ var userName = Html.Action("GetUserName", "Context"); } </code></pre></li> <li><p>The last way I figured out is to pass needed strings through <code>ViewData</code>. But I have about 18 controllers and some of 'em have like 3 methods, returning <code>ViewResult</code>. It's not bad design, it's just reality. And I don't actually want to create and pass <code>ViewDataDictionary</code> for every single method, that returns <code>ViewResult</code>. Maybe I could extend my <code>BaseController</code>, so <code>ViewDataDictionary</code> for every page will always have <code>userName</code> and <code>controllerName</code>?</p> <p>But here comes another problem: I have whole lot of AJAX in my project, and it seems to me not legit enough to pass unused data every time controller action is called.</p></li> </ol> <p>If you know of a better solution, I'd be happy to hear it.</p>
[]
[ { "body": "<p>I think it is controller's responsibility to decide what should be visible to user. So it looks to me like a good idea to pass some boolean flags to ViewData dictionary like</p>\n\n<pre><code>VeiwData[\"IsSomeUserSpecificLinkVisible\"] = Context.GetUser&lt;Agent&gt;().Name == \"Foo\";\n</code></pre>\n\n<p>And view should just bind those flags to appropriate attributes of controls.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-11-14T14:32:55.947", "Id": "29622", "Score": "0", "body": "So you want me to write this line for every ViewResult i return? It's like in 22 places arount the project. And what if some day i will also need that Agent Email or Id? That's not very adaptive solution, IMO." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-11-14T14:42:57.093", "Id": "29623", "Score": "1", "body": "You put behaviour like this in a filter and apply it manually to some actions/controllers or globally to all controllers." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-11-14T15:19:56.333", "Id": "29626", "Score": "0", "body": "@KristofClaes What kind of filter? Can u plz show some code sample?" } ], "meta_data": { "CommentCount": "3", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-11-14T13:56:42.400", "Id": "18609", "ParentId": "18606", "Score": "4" } }, { "body": "<p>You should try creating ViewModel classes - they're simple classes which just have a bunch of properties, and you pass them to the view instead of using <code>ViewData</code> or <code>ViewBag</code>. You can make them all inherit off of a base model which has a bunch of show/hide flags (like user1614543 suggested) or put the flags on individual models (the better choice) which get returned to the views that use those flags. Either way, you can put in sane default values so you only need to set them when you're displaying different data. You can even pass the name of the controller as a string, or use an <code>enum</code> to categorize them.</p>\n\n<p>This will make your markup more readable, and ensure type-safety of your data, which will make working with it easier.</p>\n\n<p><a href=\"http://msdn.microsoft.com/en-us/vs2010trainingcourse_aspnetmvc3fundamentals_topic7.aspx\" rel=\"noreferrer\">Here's an example</a>, although you'll have to convert it from ASPX to Razor.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-11-14T16:17:30.380", "Id": "18621", "ParentId": "18606", "Score": "5" } } ]
{ "AcceptedAnswerId": "18621", "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-11-14T13:35:24.797", "Id": "18606", "Score": "5", "Tags": [ "c#", "mvc", "http", "asp.net-mvc-3" ], "Title": "Is it ok to use HttpContext inside View?" }
18606
<p>I wrote some code in Flask for site menu:</p> <pre><code>def menu(parent_id=0, menutree=None): menutree = menutree or [] cur = g.db.execute('select id, parent, alias, title, ord from static where parent="'+ str(parent_id) +'" and ord&gt;0 order by ord') fetch = cur.fetchall() if not fetch: return None return [{'id':raw[0], 'parent':raw[1], 'alias':raw[2], 'title':raw[3], 'sub':menu(raw[0])} for raw in fetch] </code></pre> <p>The data is taken from the sqlite3 table:</p> <pre><code>create table static ( id integer primary key autoincrement, parent integer, alias string not null, title string not null, text string not null, ord integer ); </code></pre> <p>Variable (menu_list) is transmitted to template in each route:</p> <pre><code>@app.route('/') def index(): menu_list = menu() [...] return render_template('index.tpl', **locals()) </code></pre> <p>Despite the fact that the code is more or less normal (except for prepared statements in a query to the database), the template is not very good:</p> <pre><code>&lt;nav role="navigation"&gt; {% for menu in menu_list %} &lt;li&gt; &lt;a{% if page_id == menu.id %} class="active"{% endif %} href="/{{ menu.alias }}"&gt;{{ menu.title }}&lt;/a&gt; {% if menu.sub %} &lt;ul&gt; {% for sub in menu.sub %} &lt;li&gt;&lt;a href="/{{ menu.alias }}/{{ sub.alias }}"&gt;{{ sub.title }}&lt;/a&gt; {% if sub.sub %} &lt;ul&gt; {% for subsub in sub.sub %} &lt;li&gt;&lt;a href="/{{ menu.alias }}/{{ sub.alias }}/{{ subsub.alias }}"&gt;{{ subsub.title }}&lt;/a&gt; {% endfor %} &lt;/ul&gt; {% endif %} &lt;/li&gt; {% endfor %} &lt;/ul&gt; {% endif %} &lt;/li&gt; {% endfor %} &lt;/nav&gt; </code></pre> <p>Is it possible to improve the existing code / output / logic?</p>
[]
[ { "body": "<p>In this code, at first I didn't see the \"danger\" until I scrolled to the right by accident:</p>\n\n<blockquote>\n<pre><code>def menu(parent_id=0, menutree=None):\n menutree = menutree or []\n cur = g.db.execute('select id, parent, alias, title, ord from static where parent=\"'+ str(parent_id) +'\" and ord&gt;0 order by ord')\n fetch = cur.fetchall()\n\n if not fetch:\n return None\n\n return [{'id':raw[0], 'parent':raw[1], 'alias':raw[2], 'title':raw[3], 'sub':menu(raw[0])} for raw in fetch]\n</code></pre>\n</blockquote>\n\n<p>In the <code>g.db.execute</code> statement you're embedding a parameter and we cannot know where the parameter comes from and if it was properly validated to prevent SQL injection. Two things to do here:</p>\n\n<ol>\n<li>Make the line shorter, especially when it contains potentially dangerous stuff in the far right</li>\n<li>Use prepared statements with <code>?</code> placeholder</li>\n</ol>\n\n<p>It's not clear what kind of database you're using, so you might need to edit, but it should be something like this, shorter and without embedded parameters:</p>\n\n<pre><code>cur = g.db.execute('select id, parent, alias, title, ord '\n 'from static where parent = ? and ord &gt; 0 '\n 'order by ord', parent_id)\n</code></pre>\n\n<p>Another small tip here, if you reverse the checking logic of <code>if not fetch</code> to <code>if fetch</code> at the end, you don't need to <code>return None</code>, as that's the default anyway, and the method will be a bit shorter:</p>\n\n<pre><code>def menu(parent_id=0, menutree=None):\n menutree = menutree or []\n cur = g.db.execute('select id, parent, alias, title, ord '\n 'from static where parent = ? and ord &gt; 0 '\n 'order by ord', parent_id)\n fetch = cur.fetchall()\n\n if fetch:\n return [{'id': raw[0], 'parent': raw[1], 'alias': raw[2],\n 'title': raw[3], 'sub': menu(raw[0])} for raw in fetch]\n</code></pre>\n\n<p>And a tiny thing, <a href=\"http://legacy.python.org/dev/peps/pep-0008/\" rel=\"nofollow\">PEP8</a> dictates to put a space after the <code>:</code> in a <code>key:value</code> pair, like so: <code>key: value</code>.</p>\n\n<hr>\n\n<p>In this code:</p>\n\n<blockquote>\n<pre><code>@app.route('/')\ndef index():\n menu_list = menu()\n [...]\n return render_template('index.tpl', **locals())\n</code></pre>\n</blockquote>\n\n<p>I recommend to NOT include all <code>**locals()</code>, but use the list of variables you want to pass explicitly. We're all humans, one day you might accidentally expose something.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-08-19T20:04:51.980", "Id": "60509", "ParentId": "18614", "Score": "3" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-11-14T15:12:00.830", "Id": "18614", "Score": "4", "Tags": [ "python", "flask" ], "Title": "Website menu with Flask" }
18614
<p>I wonder how could I simplify the code below? Please note that it's <strong>not</strong> allowed to use instance variables here for some reason.</p> <pre><code> private bool ValidateQueryString(NameValueCollection queryString, out byte[] errorMessages) { var errorsList = new List&lt;string&gt;(); int _aId; if (!int.TryParse(queryString["a_id"], out _aId)) { errorMessageList.Add("aId invalid"); } string bName = queryString["b"]; if (string.IsNullOrWhiteSpace(bName)) { errorsList.Add("b invalid"); } else { string fullFileName = Path.Combine(MainFolder, bName); if (!File.Exists(fullFileName)) { errorsList.Add("file not exist;"); } } if (errorsList.Any()) { using (var memoryStream = new MemoryStream()) { byte[] newLineByteArray = Encoding.UTF8.GetBytes(Environment.NewLine); foreach (var item in errorsList) { byte[] currentErrorMessage = Encoding.UTF8.GetBytes(item); memoryStream.Write(currentErrorMessage, 0, currentErrorMessage.Length); memoryStream.Write(newLineByteArray, 0, newLineByteArray.Length); } errorMessages = memoryStream.ToArray(); return false; } } else { errorMessages = null; return true; } } private QueryStringData GetQueryStringData(NameValueCollection queryString) { string bName = Path.Combine(_folder, queryString["b"]); int aId = int.Parse(queryString["a_id"]); return new QueryStringData(bName, aId); } private void ProcessData() { using (Stream outputStream = context.Response.OutputStream) using (MemoryStream outputMemoryStream = new MemoryStream()) { byte[] errorMessages; long streamLength; if (ValidateQueryString(context.Request.QueryString, out errorMessages)) { QueryStringData queryStringData = GetQueryStringData(context.Request.QueryString); byte[] value = GetValueByID(); if (value != null) { context.Response.StatusCode = (int)HttpStatusCode.OK; outputMemoryStream.Write(value, 0, value.Length); streamLength = value.LongLength; } else { context.Response.StatusCode = (int)HttpStatusCode.NotFound; byte[] errorMessage = Encoding.UTF8.GetBytes(string.Format("not found", queryStringData.Var1)); outputMemoryStream.Write(errorMessage, 0, errorMessage.Length); streamLength = errorMessage.LongLength; } context.Response.ContentLength64 = streamLength; outputStream.Write(outputMemoryStream.ToArray(), 0, (int)streamLength); } else { context.Response.StatusCode = (int)HttpStatusCode.BadRequest; outputMemoryStream.Write(errorMessages, 0, errorMessages.Length); streamLength = errorMessages.LongLength; context.Response.ContentLength64 = streamLength; outputStream.Write(outputMemoryStream.ToArray(), 0, (int)streamLength); } } } </code></pre> <p>}</p>
[ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-11-14T15:45:25.337", "Id": "29632", "Score": "0", "body": "Is the method signature of `ValidateQueryString` fixed or can it be changed?" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-11-14T15:59:35.293", "Id": "29634", "Score": "0", "body": "It can be changed. The idea is to write data (byte[]) to outputStream in ProccessData()." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-11-14T20:32:12.397", "Id": "29659", "Score": "0", "body": "May I ask why it can't use instance variables? Does that include creating inner classes?" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-11-15T01:51:57.737", "Id": "29676", "Score": "0", "body": "It doesn't include. Even private variables are not allowed." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-11-15T10:59:56.650", "Id": "29688", "Score": "0", "body": "If it's not allowed to use instance variables, the methods should be made **static**." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-11-15T12:18:09.313", "Id": "29693", "Score": "0", "body": "It doesn't matter. If can be static if you like." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-11-15T16:07:14.753", "Id": "29714", "Score": "3", "body": "-1: please include relevant information in the question, instead of having odd limitations such as `please note that it's not allowed to use instance variables here for some reason` that you later accidentally clarify in comments such as `(...) it's multithreaded app and IEnumerable make local variables be shared among the other threads. Sorry, I forgot to mention it.`" } ]
[ { "body": "<p>I notice that methods should be separated.</p>\n\n<pre><code>private bool TryGetQSErrors(NameValueCollection queryString, out List&lt;string&gt; errorsList)\n{\n int aId;\n if (!int.TryParse(queryString[\"a_id\"], out aId))\n {\n errorsList.Add(\"aId invalid\");\n }\n\n string bName = queryString[\"b\"];\n if (string.IsNullOrWhiteSpace(bName))\n {\n errorsList.Add(\"b invalid\");\n }\n else\n {\n string fullFileName = Path.Combine(MainFolder, bName);\n if (!File.Exists(fullFileName))\n {\n errorsList.Add(\"file not exist;\");\n }\n }\n return errorsList.Any();\n}\n\nprivate static byte[] CreateErrorsByteArray(List&lt;string&gt; errorsList)\n{\n using (var memoryStream = new MemoryStream())\n {\n byte[] newLineByteArray = Encoding.UTF8.GetBytes(Environment.NewLine);\n foreach (var item in errorsList)\n {\n byte[] currentErrorMessage = Encoding.UTF8.GetBytes(item);\n memoryStream.Write(currentErrorMessage, 0, currentErrorMessage.Length);\n memoryStream.Write(newLineByteArray, 0, newLineByteArray.Length);\n }\n\n return memoryStream.ToArray();\n }\n}\n</code></pre>\n\n<p>ValidateQueryString is not good name for method as it creates bytes array too. I prefer to use TryGetSomething names for this kind of methods. It is more readable.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-11-15T09:01:34.797", "Id": "29683", "Score": "0", "body": "That's wrong. Where is ProcessData()? How is it going to work?" } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-11-15T07:29:47.943", "Id": "18646", "ParentId": "18616", "Score": "0" } }, { "body": "<p>First of all, your solution overuses the MemoryStream object. You can write your data directly to output stream using StreamWriter. Also, don't pass byte arrays around, it can easily cause memory pressure issues once your site hits any load. Instead of returning byte array just pass the same StreamWriter object to the method that is expected to add smth. to output.</p>\n\n<p>Also your methods have incorrect names, e.g. GetValueByID method doesn't accept any parameters (while method name suggests there should be one), and it returns a binary data rather than \"value\" (I assume it also uses MemoryStream to serialize the value into binary). </p>\n\n<p>You should rewrite GetValueByID to either return a typed object representing a \"value\" and write it to stream, or pass the StreamWriter so that method has a chance to write everything directly to the stream.</p>\n\n<p>I would provide a solution that assumes that original \"value\" type in GetValueByID is string, you can adjust it as necessary. Also I replaced ValidateQueryString with GetQueryStringValidationErrors that returns enumerable of errors, it simplifies the code of the method. The only method that takes care of data serialization and pushing it to stream is the ProcessData method.</p>\n\n<pre><code>private IEnumerable&lt;string&gt; GetQueryStringValidationErrors(NameValueCollection queryString)\n{\n int aId;\n if (!int.TryParse(queryString[\"a_id\"], out aId))\n yield return \"aId invalid\";\n\n string bName = queryString[\"b\"];\n if (string.IsNullOrWhiteSpace(bName))\n yield return \"b invalid\";\n else if (!File.Exists(Path.Combine(MainFolder, bName)))\n yield return \"file not exist;\";\n}\n\n\nprivate QueryStringData GetQueryStringData(NameValueCollection queryString)\n{\n string bName = Path.Combine(_folder, queryString[\"b\"]);\n int aId = int.Parse(queryString[\"a_id\"]);\n return new QueryStringData(bName, aId);\n}\n\nprivate void ProcessData()\n{\n using (StreamWriter writer = new StreamWriter(context.Response.OutputStream))\n {\n List&lt;string&gt; errors = GetQueryStringValidationErrors(context.Request.QueryString).ToList();\n if (errors.Count &gt; 0)\n {\n context.Response.StatusCode = (int)HttpStatusCode.BadRequest;\n errors.ForEach(writer.WriteLine);\n return;\n }\n\n string value = GetValueByID(/*you should pass the ID here*/);\n if (value != null)\n {\n context.Response.StatusCode = (int)HttpStatusCode.OK;\n writer.Write(value);\n }\n else\n {\n context.Response.StatusCode = (int)HttpStatusCode.NotFound;\n //Don't think you need QueryStringData object here\n QueryStringData queryStringData = GetQueryStringData(context.Request.QueryString);\n writer.Write(\"not found {0}\", queryStringData.Var1);\n }\n }\n}\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-11-15T15:53:50.810", "Id": "29709", "Score": "0", "body": "Why are you using IEnumerable? Also I'd rather use if (errors.Any())" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-11-15T15:57:45.177", "Id": "29710", "Score": "0", "body": "IEnumerable - to do `yield return` instead of creating and populating a list of errors. \"`if (errors.Any())`\" - agree, it would be slightly more expressive than checking count property" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-11-15T16:01:13.117", "Id": "29712", "Score": "0", "body": "What is the advantige of IEnumerable? I would not use it here because it's multithreaded app and IEnumerable make local variables be shared among the other threads. Sorry, I forgot to mention it." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-11-15T16:25:53.163", "Id": "29716", "Score": "0", "body": "IEnumerable is completely sfafe here from multithreading point of view. There is no \"sharing\" between threads happening here" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-11-15T16:40:50.120", "Id": "29717", "Score": "0", "body": "Really, there are only constants. You are wright." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-11-18T10:30:53.413", "Id": "29893", "Score": "0", "body": "Query string is parsed two times by GetQueryStringData() and by GetQueryStringValidationErrors(). Is there any way to avoid that?" } ], "meta_data": { "CommentCount": "6", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-11-15T14:09:50.807", "Id": "18661", "ParentId": "18616", "Score": "5" } } ]
{ "AcceptedAnswerId": "18661", "CommentCount": "7", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-11-14T15:39:21.770", "Id": "18616", "Score": "-1", "Tags": [ "c#" ], "Title": "Simplify the code in C#" }
18616
<p>I have written a caching wrapper method for some of my services. The actual wrapper method is written as follows:</p> <pre><code>public T GetFromCache&lt;T&gt;(string key, Func&lt;T&gt; defaultValuePredicate, object cacheLock, TimeSpan duration) { lock (cacheLock) { var result = _cache[key] is T ? (T)_cache[key] : default(T); if (Equals(default(T), result)) { result = defaultValuePredicate(); if (!Equals(default(T), result)) { _cache.Add(key, result, null, DateTime.Now.Add(duration), System.Web.Caching.Cache.NoSlidingExpiration, System.Web.Caching.CacheItemPriority.Default, (cacheKey, value, reason) =&gt; Debug.WriteLine(string.Format("{0} Dropped from cache becasue {1}", cacheKey, reason))); } } return result; } } </code></pre> <p>A typical use case is this:</p> <pre><code>public class SomeService { private static readonly object _lock = new object(); public string GetSomeValue() { return GetFromCache("SomeService_GetSomeValue", () =&gt; { //Expensive operation here }, _lock, TimeSpan.FromSeconds(600)); } } </code></pre> <p>In all the example code that I've seen floating around the web people never seem to lock around expensive, but cached operations. The reason I lock is to prevent the same operation kicking off twice, duplicating the effort.</p> <p>Is this approach reasonable and robust, or does it need serious modification to make it more reliable?</p>
[]
[ { "body": "<p>I see a minor issues with the code: you are locking every time, no matter if it's needed on not. I would implemented GetFromCache like this</p>\n\n<pre><code>public T GetFromCache&lt;T&gt;(string key, object cacheLock, Func&lt;T&gt; defaultValuePredicate, TimeSpan duration)\n{\n object result = _cache[key]; // using object as T may be value type and _cache may return null\n\n if (result == null || !(result is T))\n {\n lock (cacheLock)\n {\n result = _cache[key]; // rechecking value from cache as another thread may already initialize it\n if (result == null || !(result is T))\n {\n result = defaultValuePredicate();\n if (!Equals(default(T), result))\n {\n _cache.Add(key, result, null,\n DateTime.Now.Add(duration),\n System.Web.Caching.Cache.NoSlidingExpiration,\n System.Web.Caching.CacheItemPriority.Default,\n (cacheKey, value, reason) =&gt;\n Debug.WriteLine(string.Format(\"{0} Dropped from cache becasue {1}\", cacheKey, reason)));\n }\n }\n }\n }\n\n return (T)result;\n}\n</code></pre>\n\n<p>It's a little more code (+1 if statement) but it doesn't lock thread every time you access it.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-11-14T23:32:10.630", "Id": "18636", "ParentId": "18617", "Score": "1" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-11-14T15:43:34.233", "Id": "18617", "Score": "1", "Tags": [ "c#", ".net", "asp.net", "cache", "wrapper" ], "Title": "Wrapper for caching methods in ASP.NET" }
18617
<p>I'm writing a script that:</p> <ol> <li>fetch a list of urls from a db (about 10000 urls)</li> <li>download all the pages and insert them into the db</li> <li>parse the code</li> <li>if(some condition) do other inserts into the db</li> </ol> <p>I have a Xeon quad-core with hyper-threading, so a total of 8 thread available and I'm under Linux (64 bit).</p> <p>I'm using <code>cStringIO</code> as buffer, <code>pycurl</code> to fetch the pages, <code>BeautifulSoup</code> to parse them and <code>MySQLdb</code> to interact with the database.</p> <p>I tried to simplify the code below (removing all the try/except, parsing operation, ...).</p> <pre><code>import cStringIO, threading, MySQLdb.cursors, pycurl NUM_THREADS = 100 lock_list = threading.Lock() lock_query = threading.Lock() db = MySQLdb.connect(host = "...", user = "...", passwd = "...", db = "...", cursorclass=MySQLdb.cursors.DictCursor) cur = db.cursor() cur.execute("SELECT...") rows = cur.fetchall() rows = [x for x in rows] # convert to a list so it's editable class MyThread(threading.Thread): def run(self): """ initialize a StringIO object and a pycurl object """ while True: lock_list.acquire() # acquire the lock to extract a url if not rows: # list is empty, no more url to process lock_list.release() break row = rows.pop() lock_list.release() """ download the page with pycurl and do some check """ """ WARNING: possible bottleneck if all the pycurl connections are waiting for the timeout """ lock_query.acquire() cur.execute("INSERT INTO ...") # insert the full page into the database db.commit() lock_query.release() """do some parse with BeautifulSoup using the StringIO object""" if something is not None: lock_query.acquire() cur.execute("INSERT INTO ...") # insert the result of parsing into the database db.commit() lock_query.release() # create and start all the threads threads = [] for i in range(NUM_THREADS): t = MyThread() t.start() threads.append(t) # wait for threads to finish for t in threads: t.join() </code></pre> <p>I use <code>multithreading</code> so I don't need to wait if some requests are going to fail for timeout. That specific thread will wait but the others are free to continue with the other urls.</p> <p>Here is a screenshot while doing nothing but the script:</p> <p><a href="https://i.stack.imgur.com/Wi707.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/Wi707.png" alt="enter image description here"></a> It seems that 5 cores are busy while the other are not. So the questions are: </p> <ul> <li>should I create as many cursors as the number of threads?</li> <li>do I really need to lock the execution of a query? What happened if a thread execute a <em>cur.execute()</em> but not the <em>db.commit()</em> and another thread come in doing the <em>execution + commit</em> with another query?</li> <li>I read about the <a href="http://docs.python.org/2/library/queue.html" rel="nofollow noreferrer">Queue</a> class, but I'm not sure if I understood correctly: can I use it instead of doing <em>lock + extract a url + release</em>?</li> <li>using <code>multithreading</code> can I suffer from I/O (network) bottleneck? With 100 threads my speed doesn't exceed ~500Kb/s while my connection can go faster. If I move to <code>multiprocess</code> will I see some improvement on this side?</li> <li>the same question but with MySQL: using my code, there could be a bottleneck on this side? All those <em>lock + insert query + release</em> can be improved in some way?</li> <li><p>if the way to go is <code>multithreading</code>, is 100 an high number of threads? I mean, too many threads doing I/O requests (or DB queries) are useless because of the mutual exclusion of these operations? Or more threads means more network speed?</p> <p><a href="https://i.stack.imgur.com/Wi707.png" rel="nofollow noreferrer">1</a>: </p></li> </ul>
[]
[ { "body": "<p>Q: <em>should I create as many cursors as the number of threads?</em></p>\n\n<p>A: <del>Yes</del> Maybe. Don't share DB connection among threads, as docs say thread safety level = 1. Maybe better to have a <code>queue</code> of db connections. Once a thread popped a cursor from the queue, it's his only.</p>\n\n<p>Q: <em>do I really need to lock the execution of a query?</em></p>\n\n<p>A: No. Trust your DB to take care for its own locking. That's what DBs are for. </p>\n\n<p>Q: <em>I read about the Queue class...</em></p>\n\n<p>A: <del>You don't need any locks <em>at all</em> in this code. Just don't share anything.</del> Yap, a <code>queue</code> of db connections would be great here.</p>\n\n<p>Q: <em>using multithreading can I suffer from I/O (network) bottleneck?</em></p>\n\n<p>A: Yes, but that's not a point against threads.</p>\n\n<p>Q: <em>using my code, there could be a bottleneck...</em></p>\n\n<p>A: Though 'bottles necks' should be verified by testing, not by reading anonymous posts on forums, it's very likely that <em>downloading the files</em> will always be your bottle neck, regardless of implementation.</p>\n\n<p>Q: <em>if the way to go is multithreading, is 100 an high number of threads?</em></p>\n\n<p>A: I don't think you should explicitly use threads <em>at all</em> here. Can't you assign a callback to an async http request?</p>\n\n<hr>\n\n<p>Code sample for async http request, taken almost as-is from <a href=\"http://www.doughellmann.com/PyMOTW/asyncore/\" rel=\"nofollow\">this post</a>:</p>\n\n<p>I still owe you the db part.</p>\n\n<pre><code>import socket\nimport asyncore\nfrom cStringIO import StringIO\nfrom urlparse import urlparse\n\ndef noop(*args):\n pass\n\nclass HttpClient(asyncore.dispatcher):\n def __init__(self, url, callback = noop):\n self.url = url\n asyncore.dispatcher.__init__(self)\n self.write_buffer = 'GET %s HTTP/1.0\\r\\n\\r\\n' % self.url\n self.read_buffer = StringIO()\n self.create_socket(socket.AF_INET, socket.SOCK_STREAM)\n self.connect((urlparse(url).netloc, 80))\n self.on_close = callback\n\n def handle_read(self):\n data = self.recv(8192)\n self.read_buffer.write(data)\n\n def handle_write(self):\n sent = self.send(self.write_buffer)\n self.write_buffer = self.write_buffer[sent:]\n\n def handle_close(self):\n self.close()\n self.on_close(self.url, self.read_buffer.getvalue())\n\ndef parse(source, response):\n print source, 'got', len(response), 'bytes' \n\nif __name__ == '__main__':\n clients = [HttpClient('http://codereview.stackexchange.com/questions/18618/improve-multithreading-with-network-io-and-database-queries/18642#18642/', parse),\n HttpClient('http://www.doughellmann.com/PyMOTW/contents.html', parse)]\n\n print ('LOOP STARTING')\n asyncore.loop()\n print ('LOOP DONE')\n</code></pre>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-11-15T05:58:59.117", "Id": "18642", "ParentId": "18618", "Score": "1" } }, { "body": "<p>Take a look at the <a href=\"http://eventlet.net\" rel=\"nofollow\">eventlet</a> library. It'll let you write code that fetches all the web pages in parallel without ever explicitly implementing threads or locking. </p>\n\n<pre><code>import cStringIO, threading, MySQLdb.cursors, pycurl\n\nNUM_THREADS = 100\nlock_list = threading.Lock()\nlock_query = threading.Lock()\n</code></pre>\n\n<p>The purist that I am, I wouldn't make this locks globals. </p>\n\n<pre><code>db = MySQLdb.connect(host = \"...\", user = \"...\", passwd = \"...\", db = \"...\", cursorclass=MySQLdb.cursors.DictCursor)\ncur = db.cursor()\ncur.execute(\"SELECT...\")\nrows = cur.fetchall()\nrows = [x for x in rows] # convert to a list so it's editable\n</code></pre>\n\n<p>It would make more sense to do this sort of thing after you've define your classes. At least that would be python's convention.</p>\n\n<pre><code>class MyThread(threading.Thread):\n def run(self):\n \"\"\" initialize a StringIO object and a pycurl object \"\"\"\n</code></pre>\n\n<p>that's pretty much the most terrible description of this function I could have come up with. (You seem to be thinking of that as a comment, but by convention this should be a docstring, and describe the function)</p>\n\n<pre><code> while True:\n lock_list.acquire() # acquire the lock to extract a url\n if not rows: # list is empty, no more url to process\n lock_list.release()\n break\n row = rows.pop()\n lock_list.release()\n</code></pre>\n\n<p>It'd be a lot simpler to use a queue. It'd basically do all of that part for you.</p>\n\n<pre><code> \"\"\" download the page with pycurl and do some check \"\"\"\n\n \"\"\" WARNING: possible bottleneck if all the pycurl\n connections are waiting for the timeout \"\"\"\n\n lock_query.acquire()\n cur.execute(\"INSERT INTO ...\") # insert the full page into the database\n db.commit()\n lock_query.release()\n</code></pre>\n\n<p>It'd be better to put this data in another queue and have a database thread take care of it. This works, but I think the multi-queue approach would be cleaner.</p>\n\n<pre><code> \"\"\"do some parse with BeautifulSoup using the StringIO object\"\"\"\n\n if something is not None:\n lock_query.acquire()\n cur.execute(\"INSERT INTO ...\") # insert the result of parsing into the database\n db.commit()\n lock_query.release()\n</code></pre>\n\n<p>Same here. Note that there is no point in python of trying to split up processing using threads. The GIL means you'll get no advatange.</p>\n\n<pre><code># create and start all the threads\nthreads = []\nfor i in range(NUM_THREADS):\n t = MyThread()\n t.start()\n threads.append(t)\n\n# wait for threads to finish\nfor t in threads:\n t.join()\n</code></pre>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-11-15T19:41:01.587", "Id": "18675", "ParentId": "18618", "Score": "2" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2012-11-14T15:48:23.993", "Id": "18618", "Score": "5", "Tags": [ "python", "mysql", "multithreading", "curl" ], "Title": "Better multithreading with network IO and database queries" }
18618
<p>I have a simple text file setup as a Resource through my application's Properties as a byte[]. In order to access a "Stream.ReadLine" function, I believe I need to make it into a StreamReader. Is there a way to get the following result using only 1 Stream, or else, any tricks to make it better?</p> <pre><code>List&lt;string&gt; list = new List&lt;string&gt;(); using (Stream s = new MemoryStream(myFile)) { using (StreamReader sr = new StreamReader(s)) { while (!sr.EndOfStream) { list.Add(sr.ReadLine()); } } } </code></pre>
[ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-11-14T17:43:38.060", "Id": "29646", "Score": "2", "body": "Why would you hold your file as byte[] in the first place? That's the reason code looks clumsy - `StreamReader` is for reading text, `MemoryStream` is for raw, formatless data, where 'reading a line' has no meaning." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-11-14T22:16:26.563", "Id": "29665", "Score": "0", "body": "I use the built-in \"Properties/Resources\" to store my content. This automatically exposes my file as a byte[]. I didn't ask for this :)" } ]
[ { "body": "<p>Not without having to reinvent a lot of other things and make it more complex, no. This solution looks to be the best to me. You even use <code>using</code> correctly, which is one of my frequent nitpicks. However, if you want to simplify that bit of code, you might be able to help it with an extension method like so:</p>\n\n<pre><code> List&lt;string&gt; list;\n\n using (var s = new MemoryStream(myFile))\n {\n list = s.ReadLines().ToList();\n }\n</code></pre>\n\n<p>...</p>\n\n<pre><code> public static IEnumerable&lt;string&gt; ReadLines(this Stream s)\n {\n using (var sr = new StreamReader(s))\n {\n while (!sr.EndOfStream)\n {\n yield return sr.ReadLine();\n }\n }\n }\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-11-14T19:19:06.793", "Id": "29653", "Score": "0", "body": "Clever ! I like this one. :-)" } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-11-14T16:27:22.100", "Id": "18622", "ParentId": "18619", "Score": "7" } }, { "body": "<p><strong>EDIT</strong>: So this is the famous \"<em>how do I read my embedded resource</em>\". </p>\n\n<pre><code> using (var sr = new StreamReader(Assembly.GetExecutingAssembly().\n GetManifestResourceStream(\"MyNamespace.MyFile.Ext\"))) \n {\n return sr.ReadToEnd(); // or whatever else suits you\n }\n</code></pre>\n\n<p>You can also link instead of embedding.</p>\n\n<hr>\n\n<p>[<em>this section is now irrelevant</em>] </p>\n\n<p>I'd go with:</p>\n\n<pre><code>public static IEnumerable&lt;string&gt; ReadLines(byte[] raw)\n{\n using (var sr = new StreamReader(System.Text.ASCIIEncoding.ASCII.GetString(raw)))\n { // or whatever encoding you're actually using...\n return sr.ReadToEnd().Split(Environment.NewLine.ToCharArray());\n }\n}\n</code></pre>\n\n<p>If only to make clear that converting <code>byte[]</code> to <code>string</code> should be done using explicit encoding.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-11-15T14:11:55.853", "Id": "29698", "Score": "0", "body": "Interesting. There are so many ways to put content in an application that it's difficult to find the right approach. Some of them are really easy in code but difficult in xaml, sometime it's the opposite. I typically set my files as \"Resources\", but I wanted to try something new using the application's properties instead." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-11-15T21:47:08.267", "Id": "29735", "Score": "1", "body": "If you *link* a file, end user can edit or rename it, as it just lays in the Resources folder. On the other hand, it's an 'offline' content that you can change without rebuilding your app. If you embed it's safer in that sense, but any change requires rebuild. + your .exe becomes fatter." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-11-16T00:37:27.877", "Id": "29748", "Score": "0", "body": "If you can elaborate your answer with a quick explanation on the linking, it would be great." } ], "meta_data": { "CommentCount": "3", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-11-14T19:10:54.283", "Id": "18625", "ParentId": "18619", "Score": "2" } }, { "body": "<p>You can go with one more builtin approach.</p>\n\n<p>You can use:</p>\n\n<pre><code>string content = System.IO.File.ReadAllText(someFilePath);\n</code></pre>\n\n<p>That actually creates one SteramReader and call reader.ReadToEnd();</p>\n\n<p>Or if you need lazy one, you can use</p>\n\n<pre><code>foreach(string line in System.IO.File.ReadLines(someFilePath))\n{\n // do something with line\n}\n</code></pre>\n\n<p>Second approach creates internal StreamReader that reads one line for each iteration. It should be used in foreach because it needs to be disposed at the end.</p>\n\n<p>PS. Sorry, I missed that you are talking about data from Assembly resources</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-11-21T11:20:04.700", "Id": "18880", "ParentId": "18619", "Score": "2" } } ]
{ "AcceptedAnswerId": "18622", "CommentCount": "2", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-11-14T15:50:43.373", "Id": "18619", "Score": "5", "Tags": [ "c#", ".net" ], "Title": "Are 2 streams really needed?" }
18619
<p>I have a string, where I am only interested in getting the numbers encapsulated in single quotes. </p> <p>For instance if I have the string "hsa456456 ['1', '2', ...]</p> <p>I only want the 1 and the 2 and whatever numbers follow</p> <p>To do this, I have the following code:</p> <pre><code>import re #pattern = re.compile("dog") #l = re.findall(pattern, "dog dog dog") #valuepattern=re.compile('\'\d{1,6}\'') valuepattern = re.compile('\'\d+\'') li = [] s = "hsa04012 [[['7039', '1956', '1398', '25'], ['7039', '1956', '1399', '25']], [['1839', '1956', '1398', '25'], ['1839', '1956', '1399', '25']], [['1399', '25']], [['1398', '25']], [['727738', '1956', '1398', '25'], ['727738', '1956', '1399', '25']], [['1956', '1398', '25'], ['1956', '1399', '25']], [['1950', '1956', '1398', '25'], ['1950', '1956', '1399', '25']], [['374', '1956', '1398', '25'], ['374', '1956', '1399', '25']], [['2069', '1956', '1398', '25'], ['2069', '1956', '1399', '25']], [['685', '1956', '1398', '25'], ['685', '1956', '1399', '25']]]" #if match: # print match.group() #else: # print "no match" l = re.findall(valuepattern, s) #print l for item in l: li.append(item.strip("'")) #print item for item in li: print item </code></pre> <p>My areas of interest is to minimize the number of lists. Right now, I use two l and li. I take the item from l and append it to li after stripping. I was curious if there was a way to accomplish this operation all within one list... without the need for li and then appending.</p>
[]
[ { "body": "<h3>New regex</h3>\n\n<p>If you change your regular expression to the following you won't need to even do <code>str.strip()</code></p>\n\n<pre><code>valuepattern = re.compile(\"'(\\d+)'\")\n</code></pre>\n\n<h3>List Comprehension</h3>\n\n<p>Alternatively if you don't want to do that, you could do the following. Currently you have:</p>\n\n<pre><code>for item in l:\n li.append(item.strip(\"'\"))\n</code></pre>\n\n<p>This can be replaced with a <a href=\"http://docs.python.org/2/tutorial/datastructures.html#list-comprehensions\" rel=\"nofollow\">list comprehension</a>:</p>\n\n<pre><code>l = [x.strip(\"'\") for x in l]\n</code></pre>\n\n<h3>Final Note</h3>\n\n<p>As you compile your regular expression, you can replace</p>\n\n<pre><code>re.findall(valuepattern, s)\n</code></pre>\n\n<p>with</p>\n\n<pre><code>valuepattern.findall(s)\n</code></pre>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-11-14T20:00:59.257", "Id": "18628", "ParentId": "18626", "Score": "2" } }, { "body": "<p>Well this is not the best, but kind of 'short and works'.</p>\n\n<pre><code>def try_parse(s):\n try: return int(s)\n except: return None\n\nls = [try_parse(x) for x in your_string.split(\"'\")]\nls = filter(lambda s: s is not None, ls)\n</code></pre>\n\n<p>Alternative, given your input is representative:</p>\n\n<pre><code>ls = eval(ls[find(\"[\"):]) # now fold into recursive list flattening...\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-11-14T20:18:09.707", "Id": "29657", "Score": "0", "body": "I guess this works, but it doesn't feel like the best way to do it. It could also have problems if there are numeric values not in quotes, or if there is a stray quote somewhere. (i don't know how likely either of those scenarios are though...)" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-11-14T20:24:12.667", "Id": "29658", "Score": "0", "body": "I totally agree, but given the unknown input any method is likely to fail." } ], "meta_data": { "CommentCount": "2", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-11-14T20:13:12.663", "Id": "18630", "ParentId": "18626", "Score": "0" } }, { "body": "<p>try to avoid using regex for every problem. Many problems can be solved without regex</p>\n\n<pre><code>map(int, s.split(\"'\")[1::2])\n</code></pre>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-11-15T06:26:53.733", "Id": "18644", "ParentId": "18626", "Score": "1" } } ]
{ "AcceptedAnswerId": "18628", "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-11-14T19:39:43.483", "Id": "18626", "Score": "1", "Tags": [ "python", "regex" ], "Title": "Minimize Number of Lists" }
18626