body
stringlengths
25
86.7k
comments
list
answers
list
meta_data
dict
question_id
stringlengths
1
6
<p>I am writing an audio engine that must be multi-platform (win/linux). Basically, a <code>CSound</code> represents a sound file, and <code>CSoundInstance</code> represents <em>one playing</em> of a <code>CSound</code>. Obviously, playing sound is very different on Windows than it is on linux.</p> <p>A <code>CSoundInstance</code> needs access to some data from its corresponding <code>CSound</code>. The data is heavily implementation-dependent and cannot really be abstracted.</p> <p>Here are the API headers for the two classes. <i>I omitted <code>operator=</code> overloads / unique_ptr use etc.</i></p> <p><code>API/Sound.hpp</code></p> <pre><code>class CSound { public: CSound(...file...); ~CSound(); private: CSoundImpl *impl; }; </code></pre> <p><code>API/SoundInstance.hpp</code></p> <pre><code>class CSoundInstance { public: CSoundInstance(CSound *); // going to need access to source voice buffer ~CSoundInstance(); Play(); private: CSoundInstanceImpl *impl; }; </code></pre> <p>I guess it is clear where this is going. You would first instanciate a <code>CSound</code>, then acquire a <code>CSoundInstance</code> and <code>Play</code> it.</p> <p>I Intend to have a specific <code>XXImpl</code> class for each system and platform. Under Windows, I use XAudio2, which needs several members in <code>CSoundImpl</code> (buffer + waveform descriptor), as well as <code>CSoundInstanceImpl</code> (voice + fx + sends + callbacks).</p> <hr> <p><i>Here are the problems that I had using the pimpl idiom:</i></p> <p>To play a sound, a <code>CSoundInstanceImpl</code> ultimately needs a reference to a <code>CSoundImpl</code>, on Windows and linux, but I cannot write this constructor:</p> <pre><code>CSoundInstance::CSoundInstance(CSound *sound) : impl(sound-&gt;impl) { ... } </code></pre> <p>Not only is <code>sound-&gt;impl</code> private, but it would also mess up <code>unique_ptr</code> use.</p> <p>Another thing I tried is not using the constructor <code>CSoundInstance(CSound *)</code> at all, and adding a factory method with the signature <code>CSoundInstance CSound::CreateInstance()</code>, like this:</p> <pre><code>CSoundInstance CSound::CreateInstance() { return this-&gt;impl-&gt;CreateInstance(); } CSoundInstance CSoundImpl::CreateInstance() { // here I have access to the CSoundImpl instance, that I need: this CSoundInstance instance(this); } </code></pre> <p>But that would imply that I have this constructor:</p> <pre><code>CSoundInstance::CSoundInstance(CSoundImpl *soundImpl) : impl(new CSoundInstanceImpl(soundImpl)) { ... } </code></pre> <p>Using a pointer to an implementation in the constructor of a non-implementation API class doesn't look right to me.</p> <p>Maybe pimpl is not the right thing for this? Is there a way how I could tackle this problem better?</p>
[ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-02-03T21:41:39.977", "Id": "34115", "Score": "1", "body": "to me this sounds like a job for inheritance. You're asking for 2 different ways to do the same thing. So you would still use CSound, and CSoundImpl but those would be your parent classes. Make children classes of that, one for linux, and one for Windows. Then just have some simple logic to choose the correct child class, but use the parent class' methods to play/record your sounds." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-02-03T22:06:45.923", "Id": "34117", "Score": "0", "body": "@RobertSnyder That sounds reasonable. I've heard from a colleague about using pimpl as an alternative to interfaces in C++ (unfortunately, my area of expertise is C#, and low level C), so I just tried it and didn't really question that. You should probably make an answer from your comment though." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-02-03T22:13:50.460", "Id": "34118", "Score": "0", "body": "i can do that. Funny that you say that C# is your strength as that is my strength as well. C++ is new to me. I've not heard of pimpl so I don't want to discard it without knowing more about it, or it's principle." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2015-07-18T22:37:51.850", "Id": "178079", "Score": "0", "body": "I'm voting to close this question as off-topic because it is mostly for a design review." } ]
[ { "body": "<p>As you said, if you need something in a pimpl class from another class, then something is wrong. If you can't abstract away the differences, then you can't hide the differences and shouldn't use this idiom.</p>\n\n<p>Don't you think it would be simpler to put <code>Play()</code> in <code>CSound</code>? Each version (Linux/Windows) would have its own pimpl and there would be no need to try to find an abstraction or to try to access private data. Otherwise it gets a bit messy, since your Linux/Windows implementations of <code>CSoundInstances</code> will need to accept only the correct implementation: I don't know how easy it is to do this at compile time.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-02-05T18:32:06.043", "Id": "34249", "Score": "0", "body": "Your first sentence sums it up basically. I tried to use pimpl inappropriately. - But no, you really can't put `Play()` in `CSound`. `CSound` contains all static audio data (\"the samples\", up to several MB), and `CSoundInstance` contains playback specific parameters like effects, volume, panning, voice sends etc. Both are required for playback, and the same sound file can obviously be played multiple times simultaneously, with different parameters." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-02-06T00:55:39.723", "Id": "34268", "Score": "0", "body": "Couldn't the play() method return the playing sound?" } ], "meta_data": { "CommentCount": "2", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-02-05T16:59:56.317", "Id": "21346", "ParentId": "21257", "Score": "2" } } ]
{ "AcceptedAnswerId": "21346", "CommentCount": "4", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-02-03T21:26:09.067", "Id": "21257", "Score": "2", "Tags": [ "c++", "design-patterns" ], "Title": "Access to a pimpl's members from another pimpl" }
21257
<p>To delete a key from a trie, there are four cases:</p> <p>For the explanation of trie data structure, please check the following link: <a href="http://www.geeksforgeeks.org/trie-insert-and-search/" rel="nofollow">http://www.geeksforgeeks.org/trie-insert-and-search/</a></p> <p>(1) Key is not in the trie. </p> <p>(2) Key present in the trie as a unique key. </p> <p>(3) Key is the prefix of another longer key. </p> <p>(4) Key presents in the trie, having at least one other key as prefix key.</p> <p>The following code is my implementation of deleting a key from a trie.</p> <pre><code>struct trie_node { int mark; struct trie_node* children[ALPHABET_SIZE]; }; struct trie { struct trie_node* root; int count; }; // check if a trie node has no children bool isFreeNode(struct trie_node* p) { int i; for(i = 0; i &lt; ALPHABET_SIZE; ++i) { if(p-&gt;children[i]) return false; } return true; } bool isLeafNode(struct trie_node* p) { return p-&gt;mark == 1; } bool deleteHelper(struct trie_node* root, char* key, int level, int len) { int ind; //check if the key is in the trie. if(root!=NULL) { if(level==len) { //check if the key is in the trie. if(root-&gt;mark==1) { root-&gt;mark = 0; //Is it an unique key? if(isFreeNode(root)) { return true; } return false; } } else { ind = *(key+level) - 'a'; if(deleteHelper(root-&gt;children[ind], key, level+1, len)) { free(root-&gt;children[ind]); root-&gt;children[ind] = NULL; //check if the node is an unique key node. Case (2) and //and case (4) can both generates unique key node. if(!isLeafNode(root) &amp;&amp; isFreeNode(root)) { return true; } return false; } } } return false; } void deleteKey(struct trie* trie, char* key) { int len = strlen(key); if(len&gt;0) { //check if the key is the only one in the trie if(deleteHelper(trie-&gt;root, key, 0, len)) { free(trie-&gt;root); } } } </code></pre>
[ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-02-04T15:47:17.827", "Id": "34168", "Score": "2", "body": "What is the question?" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-02-04T18:07:15.880", "Id": "34190", "Score": "0", "body": "@tb-, I've edited the question. Please check the update. Thanks for your correction" } ]
[ { "body": "<ol>\n<li><p>Check your indentation, mostly for comments. While there are a lots of <a href=\"http://en.wikipedia.org/wiki/Indent_style\" rel=\"nofollow\">indent styles for C</a>, none of them recommends removing the spaces after <code>if</code> and <code>for</code>.</p></li>\n<li><p>Using recursive functions is not the idiomatic way of doing things in C, but that's OK.</p></li>\n<li><p>It's generally better to check for error conditions before, and handle the general case afterwards. This is a good idea because the \"error condition\" is generally smaller. For example, if you check for <code>root == NULL</code> case first, the reader doesn't have to remember that there is possibly an <code>else</code> branch. This will also force you to make <code>return false</code> cases more explicit in your if/else branches. I think it's a good thing.</p></li>\n<li><p>You can write <code>if (root-&gt;mark)</code> instead of <code>if(root-&gt;mark==1)</code>.</p></li>\n<li><p>This code is too long:</p>\n\n<pre><code>// Is it an unique key?\nif (isFreeNode(root))\n{\n return true;\n}\nreturn false;\n</code></pre>\n\n<p>Simple write <code>return isFreeNode(root);</code>. Same thing for <code>(!isLeafNode(root) &amp;&amp; isFreeNode(root))</code></p></li>\n<li><p><code>*(key+level)</code> should be written <code>key[level]</code>.</p></li>\n<li><p>You don't set <code>trie-&gt;root</code> to <code>NULL</code> after freeing it: this is not consistent with the earlier <code>free()</code>.</p></li>\n</ol>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-02-05T16:44:06.817", "Id": "21344", "ParentId": "21259", "Score": "1" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "2", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-02-04T01:29:12.343", "Id": "21259", "Score": "3", "Tags": [ "c", "trie" ], "Title": "delete a key in a trie" }
21259
<p>This is a simple program that gets a number from a user and calculates the number of primes between 3 and the user's number. I'm just curious if I'm using too many variables. I'm only asking since I'm used to not needing to initialize iterator variables before a loop.</p> <pre><code>#include &lt;iostream&gt; using namespace std; int isPrime(int); int main() { int userValue; int b; int x; char c; cout&lt;&lt; "Enter a number : "&lt;&lt; flush; cin &gt;&gt; userValue; for (x = 3; x &lt;= userValue; x= x+2){ a = isPrime(x); if (a == 1){ b +=1; } } cout &lt;&lt; "There is, " &lt;&lt; b &lt;&lt; " number of primes from 3 to "&lt;&lt; userValue &lt;&lt; endl; cout &lt;&lt; "hit enter to terminate..."&lt;&lt; flush; cin.get(); cin.get(); } int isPrime(int number){ int i; for(i=2; i&lt;number; i++){ if (number % i == 0 &amp;&amp; i != number) return 0; } return 1; } </code></pre>
[ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-02-04T02:35:02.747", "Id": "34120", "Score": "1", "body": "You didn't ask for this but you could test if an integer is a prime in a much more efficient way." } ]
[ { "body": "<p>No, I wouldn't say you're using too many variables (except for <code>c</code>, which doesn't appear to be used anywhere). Not enough functions, though. And perhaps too many spurious assignments. Specifically, I'd suggest something like:</p>\n\n<pre><code>#include &lt;iostream&gt;\nusing namespace std;\n\nbool isPrime(int);\nint countPrimes(int);\nint main() {\n int userValue;\n cout&lt;&lt; \"Enter a number : \"&lt;&lt; flush;\n cin &gt;&gt; userValue;\n\n cout &lt;&lt; \"There are, \" &lt;&lt; countPrimes(userValue) &lt;&lt; \" number of primes from 3 to \"&lt;&lt; userValue &lt;&lt; endl; \n cout &lt;&lt; \"hit enter to terminate...\"&lt;&lt; flush;\n cin.get();\n cin.get(); \n}\n\nint countPrimes(int number) {\n int result = 0;\n for (int x = 3; x &lt;= number; x += 2){\n if (isPrime(x)){ \n result++; \n }\n }\n return result;\n}\n\nbool isPrime(int number){\n for(int i=2; i&lt;number; i++){\n if (number % i == 0 &amp;&amp; i != number) return false;\n }\n return true;\n}\n</code></pre>\n\n<p>That will do the same thing as your code. Also, please consider using variable names that are not just single-letters.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-02-04T04:21:10.753", "Id": "34146", "Score": "0", "body": "Thanks for catching the unused c variable. I converted this program from C program which needed a character variable for a scanf() function." } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-02-04T02:16:37.027", "Id": "21262", "ParentId": "21261", "Score": "5" } }, { "body": "<ul>\n<li><p>Do you really need <code>std::flush</code> after each output? It does take some extra time, but fortunately it's not being used too often in this program.</p></li>\n<li><p>This does look like a C program, especially with <code>isPrime()</code> returning an <code>int</code> instead of a <code>bool</code>. You would then either return <code>true</code> or <code>false</code> instead of <code>1</code> or <code>0</code>. I see that this has already been mentioned by @aroth, but I wanted to make sure you were clear on that.</p></li>\n<li><p>Some of your indentation is consistent, particular inside the <code>for</code> loops.</p></li>\n<li><p><code>std::cin.get()</code> technically extracts a character from the screen, not waits specifically for the user to press <kbd>enter</kbd>.</p>\n\n<p>You could instead say something more accurate like this:</p>\n\n<blockquote>\n <p>\"Enter any key and press ENTER to terminate\"</p>\n</blockquote></li>\n<li><p>The <code>x= x+2</code> can be shortened to <code>x += 2</code>. This is also a bit easier to read.</p></li>\n</ul>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-12-27T04:03:27.840", "Id": "74965", "ParentId": "21261", "Score": "2" } }, { "body": "<p>Yes, you are using too many variables: the compiler should have told you that <code>c</code> was unused, and you should always compile with warnings turned on.</p>\n\n<p>However, it is hard to keep track of them when so many of them have one-letter names. It would be more pleasant if you renamed <code>b</code> → <code>primeCount</code>, <code>x</code> → <code>primeCandidate</code>.</p>\n\n<p>In addition, I would extract the loop into its own <a href=\"http://en.wikipedia.org/wiki/Prime-counting_function\" rel=\"nofollow\"><code>primeCount()</code></a> function for clarity and reusability.</p>\n\n<p>In <code>isPrime()</code>, the <code>i != number</code> condition is redundant, since the loop-terminating condition is <code>i &lt; number</code>. Actually, you could terminate earlier, at <code>ceil(sqrt(n))</code>. However, a much more efficient way for testing the primality of many numbers is to use another algorithm, such as the <a href=\"/questions/tagged/sieve-of-eratosthenes\" class=\"post-tag\" title=\"show questions tagged 'sieve-of-eratosthenes'\" rel=\"tag\">sieve-of-eratosthenes</a>.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-12-27T04:21:39.507", "Id": "74966", "ParentId": "21261", "Score": "2" } } ]
{ "AcceptedAnswerId": "21262", "CommentCount": "1", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-02-04T02:06:49.590", "Id": "21261", "Score": "2", "Tags": [ "c++", "primes" ], "Title": "Calculating the number of primes between 3 and another number" }
21261
<p>I am learning OOP using PHP5 and I wrote two simple classes for receiving data from a database using the dependency injection pattern and rendering a grid with Twig.</p> <p>Does this code have sense for OOP logic?</p> <p><strong>index.php</strong></p> <pre><code>&lt;?php /* * Remplazar con autoload */ require_once 'class/class.db.php'; require_once 'class/class.entradas.php'; require_once 'vendor/autoload.php'; Twig_Autoloader::register(); $_db = new Db('localhost', 'root', '', 'tgsm_ascm'); $entradas = new Entradas( $_db ); $arEntradas = $entradas-&gt;obtenerUltimasEntradas(); $loader = new Twig_Loader_Filesystem('tpl/'); $twig = new Twig_Environment($loader); $template = $twig-&gt;loadTemplate('ctbaGrillaActividades.twig'); echo $template-&gt;render( array( 'arEntradas' =&gt; $arEntradas ) ); </code></pre> <p><strong>class.db.php</strong></p> <pre><code>&lt;?php class Db { protected $db = NULL; private $dbServidor, $dbUsuario, $dbClave, $dbNombre; /* * Constructor * @args string $dbServidor * @args string $dbUsuario * @args string $dbClave * @args string $dbNombre * @return null */ public function __construct( $dbServidor, $dbUsuario, $dbClave, $dbNombre ) { $this-&gt;dbServidor = $dbServidor; $this-&gt;dbUsuario = $dbUsuario; $this-&gt;dbNombre = $dbNombre; $this-&gt;dbClave = $dbClave; if( is_null( $this-&gt;db ) ) { $this-&gt;conectar( $this-&gt;dbServidor, $this-&gt;dbUsuario, $this-&gt;dbClave, $this-&gt;dbNombre ); } } /* * Conecta a la BD * @args string $dbServidor * @args string $dbUsuario * @args string $dbClave * @args string $dbNombre * @return null */ public function conectar( $dbServidor="localhost", $dbUsuario="root", $dbClave="", $dbNombre="" ) { $dsn = "mysql:dbname={$dbNombre};host={$dbServidor}"; try { $this-&gt;db = new PDO( $dsn, $dbUsuario, $dbClave ); } catch ( PDOException $e ) { echo 'Falló la conexión: ' . $e-&gt;getMessage(); } } /* * Desconecta de la DB * @return null */ public function desconectar( ) { $this-&gt;db = NULL; } /* * Ejecuta una consulta directa * @args string $consulta * @args string $fetchOrFetchAll * @args string $placeHolder * @args string $retunrDataType */ public function consultaDirecta( $consulta, $fetchOrFetchAll='fetch', $placeHolder='', $returnDataType=PDO::FETCH_ASSOC ) { if( is_array( $placeHolder ) ) { $p = $this-&gt;db-&gt;prepare( $consulta ); $p-&gt;setFetchMode( $returnDataType ); if( $p-&gt;execute($placeHolder) ) { return ($fetchOrFetchAll=='fetch') ? $p-&gt;fetch() : $p-&gt;fetchAll(); } else { return false; } } else { $p = $this-&gt;db-&gt;prepare( $consulta ); $p-&gt;setFetchMode( $returnDataType ); if( $p-&gt;execute() ) { return ($fetchOrFetchAll=='fetch') ? $p-&gt;fetch() : $p-&gt;fetchAll(); } else { return false; } } } }?&gt; </code></pre> <p><strong>class.entradas.php</strong></p> <pre><code>&lt;?php class Entradas { private $db = NULL; public function __construct(Db $db) { $this-&gt;db = $db; } public function obtenerUltimasEntradas() { $_sql = "SELECT ascm_entradas.ID, ascm_entradas.autor, ascm_entradas.titulo, ascm_entradas.leyenda, ascm_entradas.img_miniatura FROM ascm_entradas WHERE ascm_entradas.`status` = '2' ORDER BY ascm_entradas.ID DESC LIMIT 0, 15"; return $this-&gt;db-&gt;consultaDirecta( $_sql, 'fetchAll', '' ); } /* * Debug * @return string */ public function debug() { return print_r( $this-&gt;db ); } } </code></pre>
[]
[ { "body": "<p>There is one major issue with your code: <strong>It's not English</strong></p>\n\n<p>You can easily guess that I'm also no native English speaker, but you can't write methods and variables in your native language. At some place, either in your company, your open source project or finally if you ask for a code review there will be people who don't understand your code because they don't understand your language.</p>\n\n<p>Beside that your questions seems totally unrelated to the template engine, or did I miss anything.</p>\n\n<p>From OOP point of view, you should think about using any of the PHP persistence frameworks and map a database row to an object and not to all objects.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-02-04T10:42:11.253", "Id": "21286", "ParentId": "21263", "Score": "1" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-02-04T02:37:45.973", "Id": "21263", "Score": "2", "Tags": [ "php", "object-oriented", "php5", "dependency-injection", "twig" ], "Title": "Receiving data from a database" }
21263
<p>My HTML has three divs, each id tagged with the logic behind my object (ma/shadow/traps) which contain 10 div each (every icons), also ID-tagged according to the object. On click, I'm gathering the ID and the parent ID to traverse the object and find the value.</p> <p>It's only possible to raise the value if the pre-requirement is not 0, or if the pre-requirement is false (no pre-req). My problem comes when there are 2 pre-requirements which need to be checked. I check the first one, and if the first meets the pre-req, I check if a second one exists, and check it.</p> <p>There has to be a better way of checking on variables than this nightmare of <code>if</code>s. It works, but I don't think it's good code at ALL. I'm not looking for a full copy/paste code here, but more for a more efficient logic on how to do what I'm already doing.</p> <pre><code>$(function () { var basemin = 0; var basemax = 20; var skill = { ma:{ //sample object }, shadow:{ clawMastery:{ base:0, preReq:false }, psychicHammer:{ base:0, preReq:false }, burstOfSpeed:{ base:0, preReq:'clawMastery' }, weaponBlock:{ base:0, preReq:'clawMastery' }, cloakOfShadows:{ base:0, preReq:'psychicHammer' }, fade:{ base:0, preReq:'burstOfSpeed' }, shadowWarrior:{ base:0, preReq:'cloakOfShadows', preReq2:'weaponBlock' }, mindBlast:{ base:0, preReq:'cloakOfShadows' }, venom:{ base:0, preReq:'fade' }, shadowMaster:{ base:0, preReq:'shadowWarrior' } }, traps:{ //sample object } }; $('#tree div').bind("contextmenu", function (e) { e.preventDefault(); }); $('#tree .tab div').mousedown(function (e) { var $this = $(this); $this.attr('unselectable', 'on').css('UserSelect', 'none').css('MozUserSelect', 'none'); var $tab = $this.parent().attr("id"); var $skill = $this.attr("id"); function checkPreReq(e) { var $preReq = skill[$tab][e]['preReq']; var $preReq2 = skill[$tab][e]['preReq2']; alert($preReq); if ($preReq === false) { alert('no pre-req'); return true; } else if ($preReq !== false) { alert('pre-req1 exists'); if(skill[$tab][$preReq]['base'] &gt; 0) { alert('pre-req1 higher than 0'); if ($preReq2 === undefined) { alert('no second pre-req, go on'); return true; } else { alert('check second pre-req value'); if (skill[$tab][$preReq2]['base'] &gt; 0) { alert('pre-req2 higher than 0'); return true; } else { alert('pre-req2 not met (0)'); return false; } } } else { alert('pre-req1 not met (0)'); return false; } } else { alert('else'); return false } } if (e.which == 1) { //leftclick if (skill[$tab][$skill]['base'] &lt; basemax &amp;&amp; checkPreReq($skill)) { skill[$tab][$skill]['base'] += 1; //$rem_skills -= 1; } } else if (e.which == 3) { //rightclick if (skill[$tab][$skill]['base'] &gt; basemin) { skill[$tab][$skill]['base'] -= 1; //$rem_skills += 1; } } $this.find(".lvl").text(skill[$tab][$skill]['base']); //$("#output").find(".rem_skills").text($rem_skills); }); }); </code></pre>
[]
[ { "body": "<p>I'm not quite sure I've followed your logic, but it sounds like you have two pre-requisites (either of which might not be present), and you want to return <code>false</code> in any case where a prerequisite is present but is not met.</p>\n\n<p>Can't you break out the testing of one prerequisite into its own function to simplify the logic? Something like this:</p>\n\n<pre><code>function checkOnePreReq(isRequired, value) {\n return !isRequired || value &gt; 0;\n}\n\nfunction checkPreReq(e) {\n var $preReq = skill[$tab][e]['preReq'];\n var $value = skill[$tab][$preReq]['base'];\n\n var $preReq2 = skill[$tab][e]['preReq2'];\n var $value2 = skill[$tab][$preReq2]['base'];\n\n return checkOnePreReq($preReq, $value) &amp;&amp;\n checkOnePreReq($preReq2, $value2);\n}\n</code></pre>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-02-03T22:42:53.737", "Id": "21265", "ParentId": "21264", "Score": "3" } }, { "body": "<p>What I would probably do is each skill has a 'prereqs' array, which contains links to the prereq skill.</p>\n\n<p>Then when you click the skill, you just loop through the prereqs and check that each one has skillpoint > 1</p>\n\n<p>This would also satisfy the first skills that have no prereqs, they will just skip the loop because their prereq array would be empty.</p>\n\n<p>This also allows if you ever need more than just 2 prereqs, since the array can have as many prereqs as you wan't and you won't have to add more 'if' checks</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-02-03T22:45:58.213", "Id": "21266", "ParentId": "21264", "Score": "4" } }, { "body": "<p>If there are zero, one, two or possible more prerequirements, generalize their storage. Do <em>not</em> use multiple properties and nested if-else-statements, but an array and a loop.</p>\n\n<p>The function should then look like this:</p>\n\n<pre><code>function checkPreReq(e) {\n var preReqs = skill[tab][e].preReqs;\n if (!preReqs)\n return true;\n for (var i=0; i&lt;preReqs.length; i++) {\n var preReq = preReqs[i];\n if (skill[tab][preReq].base &lt;= 0)\n // failed at least this preReq\n return false;\n }\n // passed all requirements\n return true;\n}\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-02-03T23:15:13.113", "Id": "34122", "Score": "1", "body": "+1 Yes, same comment as for RoneRackal's answer. Also, looping with `$.each()` would simplify the code slightly, but that's optional." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-02-03T23:41:13.707", "Id": "34123", "Score": "0", "body": "I cannot seem to extract the array, preReqs thus always returns true (being false/undefined), my array now looks like `shadowWarrior:{\n base:0,\n preReqs:{\n 1:'cloakOfShadows',\n 2:'weaponBlock'\n }\n }`" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-02-03T23:47:38.343", "Id": "34124", "Score": "0", "body": "@user1732521: That's not an [array](https://developer.mozilla.org/en-US/docs/JavaScript/Reference/Global_Objects/Array). Use `{ base:0, preReqs: ['cloakOfShadows', 'weaponBlock'] }`" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-02-03T23:48:56.593", "Id": "34125", "Score": "0", "body": "@Beetroot-Beetroot: I can't see why `$.each` would simplify anything. If at all, you might use [`.every`](https://developer.mozilla.org/en-US/docs/JavaScript/Reference/Global_Objects/Array/every)" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-02-03T23:51:38.823", "Id": "34126", "Score": "0", "body": "thanks... for some reason array and object were the same in my head" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-02-04T01:27:59.823", "Id": "34127", "Score": "0", "body": "Bergi, I like the way `$.each()` extracts array elements for you, avoiding the need for expressions like `preReqs[i];`. This can often save a line of code. I admit the code becomes a bit more involved in this case, mainly due to the need for a tracker boolean, and will be arguably less readable. I think that `array.every()` would be the same in this regard. B-B (during Superbowl half-time show)" } ], "meta_data": { "CommentCount": "6", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-02-03T22:48:33.343", "Id": "21267", "ParentId": "21264", "Score": "5" } } ]
{ "AcceptedAnswerId": "21267", "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-02-03T22:11:17.023", "Id": "21264", "Score": "1", "Tags": [ "javascript", "jquery" ], "Title": "Gathering IDs to find values from objects" }
21264
<p>I want to define a matrix of values with a very simple pattern. I've achieved it with the code below but it's ugly - very difficult to read (I find) and surely not as optimal, in terms of performance, as it could be. The former is really what I'm trying to address here. I feel this can be done much more elegantly and would love some guidance from the community.</p> <p>Here is an example of what I am hoping to achieve, from <code>x</code> and <code>y</code> I want to get <code>points</code>:</p> <pre><code>y = 10 30 50 70 x = 10 30 50 points = 10 10 30 10 50 10 10 30 30 30 50 30 10 50 30 50 50 50 10 70 30 70 50 70 </code></pre> <p><code>x</code> and <code>y</code> are, of course, no always those exact vectors. They are, however, very simply created. Something like so:</p> <pre><code>scale = 20; max_x = 85; max_y = 62; y_count = floor(max_x / scale); x_count = floor(max_y / scale); y = ((1:y_count) * scale) - scale / 2; x = ((1:x_count) * scale) - scale / 2; </code></pre> <p>Here's my brute force approach:</p> <pre><code>y = repmat(y, x_count, 1); y = reshape(y, 1, size(y, 1) * size(y, 2)); y = y'; x = repmat(x, y_count, 1); x = x'; x = reshape(x, 1, size(x, 1) * size(x, 2)); x = x'; points = [x y]; </code></pre> <p>It works, but it isn't very elegant.</p>
[]
[ { "body": "<p>It's called Cartesian product and you can do that easily:</p>\n\n<p>Here's one way:</p>\n\n<pre><code>y = [10 30 50 70]\n\nx = [10 30 50]\n\n[X,Y] = meshgrid(y,x);\nresult = [Y(:) X(:)];\n</code></pre>\n\n<p>Result:</p>\n\n<pre><code>10 10\n30 10\n50 10\n10 30\n30 30\n50 30\n10 50\n30 50\n50 50\n10 70\n30 70\n50 70\n</code></pre>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-02-01T14:43:00.407", "Id": "21273", "ParentId": "21272", "Score": "3" } } ]
{ "AcceptedAnswerId": "21273", "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-02-01T14:20:13.903", "Id": "21272", "Score": "3", "Tags": [ "matrix", "matlab" ], "Title": "Build a combinatorial matrix from two vectors" }
21272
<p>Looking for feedback on how to better improve the code below to simplify the code below.</p> <pre><code>var animateTop = $('body'); if ($('html').hasClass('lt-ie9')) { animateTop = $('html'); } $('.var').on('click', function() { animateTop.animate({ scrollTop: $('footer').offset().top }, { queue: false, duration: 1500, complete: function() { if(!$('.foo').hasClass('active')) { $('.foo').toggleClass('active'); $('.bar').slideToggle(); } } }); return false; }); </code></pre>
[]
[ { "body": "<p>Can't really tell what your code does in real life, thus the following optimization/organization might not work. However, following generic tips, here's what I got:</p>\n\n<pre><code>//we can reduce DOM fetching by fetching html first\n//caching it as well as other frequently used elements\n//assuming that they never change in the course of your page's life\nvar html = $('html')\n , footer = $('footer')\n , foo = $('.foo')\n , bar = $('.bar')\n , options = {\n queue: false,\n duration: 1500,\n complete: function () {\n if (!foo.hasClass('active')) {\n foo.toggleClass('active');\n bar.slideToggle();\n }\n }\n }\n ;\n\n//then here, we fetch body only when it's not IE9+ thus reducing operations\nhtml = html.hasClass('lt-ie9') ? html : $('body');\n\n$('.var').on('click', function (e) {\n\n //i think the properties can't be cached since it may need current values\n //however, your options can be cached since they are static values\n html.animate({\n scrollTop: footer.offset().top\n }, options);\n\n //an answer as to when to use return false vs preventDefault\n //you can use either, depending on the situation\n //http://stackoverflow.com/a/1357151/575527\n return false;\n});\n</code></pre>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-02-04T12:43:55.563", "Id": "21288", "ParentId": "21275", "Score": "1" } } ]
{ "AcceptedAnswerId": "21288", "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-02-04T05:57:13.323", "Id": "21275", "Score": "1", "Tags": [ "javascript", "jquery" ], "Title": "Simplify jQuery animation with callback" }
21275
<p>I am in two minds about function calls as parameters for other functions. The doctrine that readability is king makes me want to write like this:</p> <pre><code>br = mechanize.Browser() raw_html = br.open(__URL) soup = BeautifulSoup(raw_html) </code></pre> <p>But in the back of my mind I feel childish doing so, which makes me want to write this:</p> <pre><code>br = mechanize.Browser() soup = BeautifulSoup(br.open(__URL)) </code></pre> <p>Would it actually look unprofessional to do it the first way? Is there any serious reason to choose one method over the other?</p>
[]
[ { "body": "<p>If it's only one parameter, then sure, why not.</p>\n\n<p>I personally hate the way JQuery syntax (and recently C# and Scala) is usually written with lots of inline function calls (and even inline functions complete with bodies!).</p>\n\n<p>Readability is key. But if you can't make your code readable, then you should at least put in a comment explaining what it is you're trying to do.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-02-04T07:27:23.330", "Id": "21280", "ParentId": "21278", "Score": "1" } }, { "body": "<p>\"readable\" is a relational predicate. It does not depend on the text alone, but also on the person looking at it. So learning a language means to get familiar with statements like</p>\n\n<pre><code>soup = BeautifulSoup(mechanize.Browser().open(__URL))\n</code></pre>\n\n<p>that only use standard names to refer to often used components. The more you use this style, the more 'natural' it gets.</p>\n\n<p>Using unnecessary variables</p>\n\n<pre><code>brow = mechanize.Browser()\n...\nbr = \"&lt;br /\"\n...\nraw_html = br.open(__URL)\nsoup = BeautifulSoup(rwa_html)\n</code></pre>\n\n<p>forces you to invent non-standard (good for the specific context) names and increases the risk of typos or confusion - mistakes that happen randomly even to a pro.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-02-04T07:58:49.653", "Id": "21281", "ParentId": "21278", "Score": "3" } }, { "body": "<p>I'm typically an advocate of liberal use of space, but in this situation, I'd go with the third option:</p>\n\n<pre><code>soup = BeautifulSoup(mechanize.Browser().open(__URL))\n</code></pre>\n\n<p>(I'm not actually sure if that's valid syntax or not. I'm not very familiar with Python [I think it's Python?].)</p>\n\n<p>I find that just as readable. There are of course situations where you must separate it though. The first thing that comes to mind is error handling. I suspect that <code>open</code> throws exceptions, but if it were to return boolean <code>false</code> on failure rather than a string, then I would be a fan of option two. Option two would still be brief, but would allow for properly checking for the <code>false</code> return.</p>\n\n<hr>\n\n<p>I think this really comes down to personal taste. There's no magical rule book for this type of thing (though I'm sure there are convoluted, borderline-dogmatic metrics somewhere that support one way or the other).</p>\n\n<p>I tend to just eyeball things like this and see if they make me visually uncomfortable or not.</p>\n\n<p>For example:</p>\n\n<pre><code>superLongVariableNameHere(someParamWithLongName, someFunctionLong(param1, param2), someFunc3(param, func4(param1, param2, func5(param)))\n</code></pre>\n\n<p>Makes me cry a little whereas:</p>\n\n<pre><code>func(g(x), y(z))\n</code></pre>\n\n<p>Seems perfectly fine. I just have some weird mental barrier of what length/nesting level becomes excessive.</p>\n\n<hr>\n\n<p>While I'm at it, I'd also disagree with Juann Strauss' dislike of JavaScript's practically idiomatic use of anonymous and inline-defined functions. Yes, people go overboard sometimes with a 30 line callback, but for the most part, there's nothing wrong with a 1-10 line anonymous function as long as it's used in one and only one place and it doesn't overly clutter its context.</p>\n\n<p>In fact, to have a closure, you often have to define functions in the middle of scopes (well, by definition you do). Often in that situation you might as well inline it within another function call rather than defining it separately (once again, provided the body is brief).</p>\n\n<p>If he means this though, then yeah, I'd agree 95% of the time:</p>\n\n<pre><code>f((function(x) { return x * x; }(5))\n</code></pre>\n\n<p>That gets ugly fast.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-02-04T08:11:07.963", "Id": "34147", "Score": "1", "body": "+0.5 for pointing out that sometimes variables are necessary for error checking; +0.5 for disagreement with Juann's personal feelings." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-07-02T00:03:56.510", "Id": "98050", "Score": "0", "body": "+1 This is the reverse of Introduce Explaining Variable and IMHO a good example of when the refactoring isn't needed. The raw HTML is used just once right away, and it's pretty clear that opening a URL would produce HTML. The one-line statement is clear and concise. Introducing temporary variables in this case could mislead the reader to think there's more going on here than there is." } ], "meta_data": { "CommentCount": "2", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-02-04T07:59:01.227", "Id": "21282", "ParentId": "21278", "Score": "5" } } ]
{ "AcceptedAnswerId": "21282", "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-02-04T06:37:42.507", "Id": "21278", "Score": "3", "Tags": [ "python" ], "Title": "Function calls as parameters for other functions" }
21278
<p>I am using this static method in my class <code>IconManager</code> to read an image from jar file. <code>imagepath</code> is a relative path to the image.</p> <p>This code works perfect. But I was told it is error-prone, because does not handle Exceptions correctly.</p> <pre><code>private static BufferedImage readBufferedImage (String imagePath) { try { InputStream is = IconManager.class.getClassLoader().getResourceAsStream(imagePath); BufferedImage bimage = ImageIO.read(is); is.close(); return bimage; } catch (Exception e) { return null; } } </code></pre> <p>How would you refactor the code?</p>
[]
[ { "body": "<p>Before the <code>return null;</code> you have to had add an error message to your Logger (or print to console an error) with \n<code>e.getMessage()</code> , so you will know where is the problem.<br><br>\n Otherwise, when your code is published, nobody can know why or where your code hang.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-02-04T08:08:14.760", "Id": "21283", "ParentId": "21279", "Score": "3" } }, { "body": "<ul>\n<li>Don't catch (or throw) <code>Exception</code>.</li>\n<li><p>Try not to return null. If you cannot return a normal value you want one of the following to happen:</p>\n\n<ol>\n<li>Program quits with an error. (Your current program seems to do this)</li>\n<li>You expect calling site to take some action and try to recover and continue execution</li>\n<li>You do not want to hassle the caller of the method and try to continue execution with a sensible default value.</li>\n</ol>\n\n<p>If you want program to quit with an error. Wrap the exception in a runtime exception with a meaningful (to the developer, not user) message. That way in your logs you will see what went wrong and where. If you return a <code>null</code> what you probably get is a nondescript <code>NullPointerException</code> down the line.</p>\n\n<p>If you want the caller of the method to check if something went wrong, you want to throw a checked exception. Null checks always get ignored and your program crashes and burns in inopportune moments and users think, rightly, the program is of low quality. If you do not have and cannot create a suitable Exception, you can propagate the exception.</p>\n\n<p>Third option is usually ignored but sometimes continuing with some default value is the most logical thing to do. Think what browsers do if they cannot download an image, which basically is an <code>IOException</code>. They show a white rectangle with a red cross on it. A web page with some of the images missing is more useful than a page full of stack trace. And note that a white rectangle with a cross <strong>behaves like a normal image</strong> in terms of layout, hence do not break the page layout. This is the essence of the <a href=\"http://en.wikipedia.org/wiki/Null_Object_pattern\" rel=\"nofollow\">Null Object Pattern</a>.</p></li>\n<li><p>(Updated as per @Sulthan) You should call the <code>InputStream.close()</code> in a finally block. Because if <code>ImageIO.read</code> throws an exception you never reach the <code>close()</code> statement.</p></li>\n</ul>\n\n<p>A few notes about the example code below:</p>\n\n<ol>\n<li>Resource leaks may occur if <code>InputStream.close</code> throws. There isn't much you can do about it.</li>\n<li>Wrapping example and the <code>ImageReadException</code> do not pull their weights as they are. they are here for demonstration. </li>\n<li>Method names are shortened to fit screen. </li>\n</ol>\n\n<p>Here is the basic case:</p>\n\n<pre><code>private static BufferedImage readPropagate(String imagePath) throws IOException {\n InputStream is = null;\n try {\n is = IconManager.class.getClassLoader().getResourceAsStream(imagePath);\n // an example of how null checks can easily be forgotten \n if (is == null) {\n throw new FileNotFoundException(\"Resource not found: \" + imagePath);\n }\n return ImageIO.read(is);\n } finally {\n if (is != null) {\n is.close();\n }\n }\n}\n</code></pre>\n\n<p>Here are some examples of what can be done when the above example is not sufficient:</p>\n\n<pre><code>public static class ImageReadException extends Exception {\n private static final long serialVersionUID = 1L;\n\n public ImageReadException(String message, Throwable cause) {\n super(message, cause);\n }\n\n public ImageReadException(String message) {\n super(message);\n }\n}\n\nprivate static BufferedImage readWrap(String imagePath) throws ImageReadException {\n try {\n return readPropagate(imagePath);\n } catch (IOException e) {\n\n // log with your normal logger\n logException(e, \"An error occured while loading image \" + imagePath);\n\n // Message should be something meaningful to the calling site\n throw new ImageReadException(\"An error occured while loading image\", e);\n }\n}\n\nprivate static BufferedImage readWithDefault(String imagePath) {\n try {\n return readPropagate(imagePath);\n } catch (IOException e) {\n\n // log with your normal logger\n logException(e, \"An error occured while loading image \" + imagePath);\n\n //default image may be passed as a parameter instead\n return IconManager.DEFAULT_IMAGE;\n }\n}\n\n// YOU SHOULD NOT DO THIS IN LIBRARY CODE\n// The decision of whether to crash the program belongs to the top level application\nprivate static BufferedImage readThrowSilently(String imagePath) {\n try {\n return readPropagate(imagePath);\n } catch (IOException e) {\n // you can do this, e.g., while loading a desktop application\n // you discover a vital resource could not be loaded\n // continuing execution does not make sense\n throw new RuntimeException(\"An error occured while loading image \" + imagePath, e);\n }\n}\n\nprivate static void logException(IOException e, String message) {\n Logger.getLogger(IconManager.class.getName()).log(Level.SEVERE, message, e);\n}\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-02-04T09:52:05.437", "Id": "34151", "Score": "0", "body": "I think that wrapping `close()` into a `finally` handler should be done even when passing the exception up." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-02-04T12:01:37.627", "Id": "34152", "Score": "0", "body": "Thanks for answer, +1. I want to continue the program if some image reading fails. Can you put code edit with finally block in your answer and I would accept it." } ], "meta_data": { "CommentCount": "2", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-02-04T08:43:26.510", "Id": "21284", "ParentId": "21279", "Score": "5" } }, { "body": "<p>If you have java7:</p>\n\n<pre><code>private static final BufferedImage emptyBufferedImage = new BufferedImage(0, 0, BufferedImage.TYPE_INT_RGB);\n\nprivate static BufferedImage getBufferedImageFromInternalPath(final String imagePath) {\n BufferedImage result = null;\n try (final InputStream inputStream = IconManager.class.getClassLoader().getResourceAsStream(imagePath)) {\n result = ImageIO.read(inputStream);\n } catch (final Exception e) {\n // log exception\n }\n return result == null ? emptyBufferedImage : result;\n}\n</code></pre>\n\n<p>Some thoughts: I would avoid any return statements inside try/catch/finally. They are well defined in the JLS, but confuses most readers easily.<br>\nThe try-with-resources statement is available since java 7: <a href=\"http://docs.oracle.com/javase/tutorial/essential/exceptions/tryResourceClose.html\" rel=\"nofollow\">http://docs.oracle.com/javase/tutorial/essential/exceptions/tryResourceClose.html</a><br>\nIf you return null or a default value depends on the use case. Personally I think a default value is the more clean way, but null could be quite ok for some internal usage. KISS principle.</p>\n\n<p>For further comments, see post from abuzittin gillifirca.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-02-04T15:43:23.377", "Id": "21299", "ParentId": "21279", "Score": "4" } } ]
{ "AcceptedAnswerId": "21284", "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-02-04T07:13:14.203", "Id": "21279", "Score": "3", "Tags": [ "java", "exception-handling" ], "Title": "Reading image from jar" }
21279
<p>since in my website I have a lot of <code>&lt;HEADER&gt;</code>, <code>&lt;FOOTER&gt;</code> AND <code>&lt;SECTION&gt;</code> do you think is appropriate if i use a <code>.main</code> class for the main HEADER, main FOOTER AND main SECTION?</p> <p>In the CSS I will never style the <code>.main</code> class like this:</p> <pre><code>.main { ... } </code></pre> <p>but always like this:</p> <pre><code>header.main { ... } footer.main { ... } section.main { ... } </code></pre> <p>Of course it will be total different styling. </p>
[]
[ { "body": "<p>As a general rule, if you want your markup to be semantic, you should be using classes, IDs and document structure <strong>to describe the content as clearly as possible,</strong> to whatever level is required to achieve the styling you need. Don't just add classes and IDs with the motivation \"I need something to hook a CSS selector to\", try thinking about what it is you want to style and use your tools to describe the thing.</p>\n\n<p>Pragmatic design means you will have to be non-semantic to support particular browsers, particularly those that can't take advantage of the more advanced selectors, but you should only append these as required, if you can't achieve your desired design easily another way.</p>\n\n<hr>\n\n<p>For your scenario, I would question whether <code>main</code> is a very good class name. Classes are intended to classify something, such that several instances of that thing can appear in a document (and be styled in the same way). If you intend to have several things in the page classified as <code>main</code>, it doesn't add a great deal of semantic value - I can't understand what that element really contains, other than that it's probably more important than non-main elements.</p>\n\n<p>If you are trying to say \"this is <strong>the</strong> primary content of the page\", you should instead use an <code>id</code>. Use of an ID implies \"there is only one of these per page\", which gives you faster-performing scripts and the ability to reference the element with anchors (<code>#main</code>).</p>\n\n<p>Additionally, if the <code>header</code>, <code>footer</code> and <code>section</code> elements are being given the <code>main</code> class because they're all related, you could try representing this relationship more strongly by nesting them inside a parent element and applying an ID to that element, e.g:</p>\n\n<pre><code>&lt;article id=\"main\"&gt;\n &lt;section id=\"introduction\"&gt;\n &lt;header&gt;&lt;/header&gt;\n ...\n &lt;footer&gt;&lt;/footer&gt;\n &lt;/section&gt;\n&lt;/article&gt;\n</code></pre>\n\n<p>As an aside, the way you've listed <code>section</code> with <code>header</code> and <code>footer</code> makes me wonder if you're using it correctly.</p>\n\n<p>The <a href=\"http://www.whatwg.org/specs/web-apps/current-work/multipage/sections.html#the-section-element\" rel=\"nofollow\">HTML5 specification</a> says:</p>\n\n<blockquote>\n <p>The <code>section</code> element represents a generic section of a document or\n application. A section, in this context, is a thematic grouping of\n content, typically with a heading.</p>\n</blockquote>\n\n<p>It specifically warns:</p>\n\n<blockquote>\n <p>The <code>section</code> element is not a generic container element. When an\n element is needed for styling purposes or as a convenience for\n scripting, authors are encouraged to use the <code>div</code> element instead. A\n general rule is that the section element is appropriate only if the\n element’s contents would be listed explicitly in the document’s\n outline.</p>\n</blockquote>\n\n<p>So, the idea of a \"main\" section probably isn't right. Sections are meant to be ways partition a large article into headed-sections, in very much the way a Wikipedia article is laid out. You could easily say you have a \"main\" article, but a \"main\" section doesn't make as much sense.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-02-04T13:32:40.980", "Id": "21291", "ParentId": "21285", "Score": "1" } }, { "body": "<blockquote>\n <p>main HEADER, main FOOTER AND main SECTION</p>\n</blockquote>\n\n<p>I think you are referring to <em>page</em> header, <em>page</em> footer and <em>page</em> main content.</p>\n\n<p>Simple example:</p>\n\n<pre><code>&lt;body&gt;\n\n &lt;header&gt;…&lt;/header&gt;\n\n &lt;section&gt;\n &lt;header&gt;…&lt;/header&gt;\n &lt;section&gt;…&lt;/section&gt;\n &lt;footer&gt;…&lt;/footer&gt;\n &lt;/section&gt;\n\n &lt;footer&gt;…&lt;/footer&gt;\n\n&lt;/body&gt;\n</code></pre>\n\n<p>The definition of HTML5 makes already clear that the last <code>footer</code> <strong>applies to the whole page</strong>, while the <code>footer</code> inside the <code>section</code> applies to this section content only.</p>\n\n<p><a href=\"http://www.w3.org/TR/html5/sections.html#the-footer-element\" rel=\"nofollow\"><code>footer</code> element</a>:</p>\n\n<blockquote>\n <p>When the nearest ancestor sectioning content or sectioning root element is the <code>body</code> element, then it applies to the whole page.</p>\n</blockquote>\n\n<p>(Similar meaning can be assumed for <code>header</code>, but afaik it's not explicitly defined in the spec, probably because it may span several sectioning elements).</p>\n\n<p>Now, if you want to style the top-level <code>header</code>/<code>footer</code>/<code>section</code> differently, you could use CSS selectors like:</p>\n\n<pre><code>body &gt; header {…}\nbody &gt; section {…}\nbody &gt; footer {…}\n</code></pre>\n\n<p>These selectors only match the elements if they are <em>direct</em> childrens of <code>body</code>.</p>\n\n<p>Or you could give these elements a <code>class</code> and use the CSS class selector. <code>main</code> might be a candidate. However, I'd use <code>page</code> resp. <code>site</code>.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-02-06T00:25:58.887", "Id": "21358", "ParentId": "21285", "Score": "0" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-02-04T10:00:43.210", "Id": "21285", "Score": "1", "Tags": [ "html5" ], "Title": "HTML5 TAG using a .main class" }
21285
<p>I get a lot done with Python scripts but always feel like I'm working with a messy desk when I'm using it. I assume this is because I am not coding in Python correctly. Coming from a C# and Ruby background, I've used Python mainly as a utility language writing together things that I need quickly - never really trying to refine my work - until now.</p> <p>I want criticism as to what I'm doing that's making my Python code feel sloppy - I feel I will advance more quickly if I have such feedback, and, since I don't have a Python mentor, here I am.</p> <p>The below script scrapes new product data from an online store. I typically run this script from my console simply by typing <code>python my_scraper_script.py</code> and it will scrape the data and upload it to my rails site that I have running locally (this is a hobby project of mine).</p> <p>Some initial concerns:</p> <ul> <li>Does it make sense to declare some of the methods here in this script and some of the methods in another script (<code>scraper_tools</code>) when some of those methods are shared by similar scripts?</li> <li>My <code>websiteProduct</code> class does all of the work in the initializer part of the class, this feels dirty to me.</li> <li>I have a bunch of variables declared in what feels like an arbitrary position within the file. Is this acceptable?</li> <li>The part where this script actually gets started doing things is just hanging out in the open somewhere arbitrarily toward the end of the actual file, is this normal?</li> </ul> <p>I'm sure there's much more awry - please fix me.</p> <pre><code>import json import re import urllib2 from scraper_tools import soupify, getHtml, buildJsonPostRequest __author__ = 'ecnalyr' def getImageLinkFromDiv(div): """Expects a BeautifulSoup div from {website's} new product page""" try: fullSrc = div.find('img')['src'] return fullSrc.replace("//", "http://") # removes the unnecessary // from the beginning of the string except AttributeError: return "There is no Image Link" def getSkuFromDiv(div): """Expects a BeautifulSoup div from {website's} new product page""" try: baseUrl = div.find('a')['href'] baseSku = re.search('\productId=(\d+_\d+)', baseUrl).group(0) return baseSku.replace("productId=", "") except AttributeError: return "There is no Sku" def encodeBrandNameToUTF8(brandAndName): return str(brandAndName.encode("utf-8")) def getBrandAndNameFromDiv(div): """Expects a BeautifulSoup div from {website's} new product page""" try: brandAndName = div.find('span', {'class': 'name'}).string return str(brandAndName) except UnicodeEncodeError: return encodeBrandNameToUTF8(brandAndName) # return "unicode encode error" except AttributeError: return "There is no brand and / or name" def getPriceFromDiv(div): """Expects a BeautifulSoup div from {website's} new product page""" try: price = div.find('span', {'class': 'price'}).string return price.replace("$", "") # have to remove the dollar sign from the price except AttributeError: return "There is no price" def buildLinkFromSKU(sku): """Expects a SKU representing a product at {website}""" return productBaseUrl + sku class websiteProduct: """A product from {website's} created using a newItemDiv in a BeautifulSoup format""" def __init__(self, productDiv): self.price = str(getPriceFromDiv(productDiv)) self.brandAndName = str(getBrandAndNameFromDiv(productDiv)) self.sku = str(getSkuFromDiv(productDiv)) self.imageLink = str(getImageLinkFromDiv(productDiv)) self.link = str(buildLinkFromSKU(self.sku)) self.json = json.dumps({'store':"Website Name", 'name':self.brandAndName, 'price':self.price, 'sku':self.sku, 'link':self.link, 'imageLink':self.imageLink}) def getPrice(self): return self.price def getBrandAndName(self): return self.brandAndName def getLink(self): return self.link def getImageLink(self): return self.imageLink def getSku(self): return self.sku def getJson(self): return self.json uploadProductsUrl = "http://MySite.com/products.json" websiteNewItemLink = "http://www.website.com/newItems" newItemSoup = soupify(getHtml(websiteNewItemLink)) newItems = newItemSoup.find_all('div', {'class': 'productNew'}) productBaseUrl = "http://www.website.com/product?productId=" productList = [] for item in newItems: product = websiteProduct(item) productList.append(product) for item in productList[0:]: jsonData = item.getJson() request = buildJsonPostRequest(uploadProductsUrl) urllib2.urlopen(request, jsonData) </code></pre>
[]
[ { "body": "<pre><code>import json\nimport re\nimport urllib2\nfrom scraper_tools import soupify, getHtml, buildJsonPostRequest\n\n__author__ = 'ecnalyr'\n\n\ndef getImageLinkFromDiv(div):\n</code></pre>\n\n<p>The python style guide recommends lowercase_with_underscores for function names</p>\n\n<pre><code> \"\"\"Expects a BeautifulSoup div from {website's} new product page\"\"\"\n try:\n fullSrc = div.find('img')['src']\n</code></pre>\n\n<p>Python convention is for local variables to be lowercase_with_underscores</p>\n\n<pre><code> return fullSrc.replace(\"//\", \"http://\") # removes the unnecessary // from the beginning of the string\n</code></pre>\n\n<p>This will also make replacements throughout the entire string, not just the beginning. It's also not really removing it from the beginning. It also seems like a more generic thing and perhaps should be in a seperate <code>normalize_url</code> function.</p>\n\n<pre><code> except AttributeError:\n</code></pre>\n\n<p>It's rarely a good idea to catch an <code>AttributeError</code>, python will produce that errors for simple typos in your code so catching it here is likely to mask real bugs. I'm not sure which attribute access you are catching, but I'm guess its that <code>fullSrc</code> can be None? In that case you should really check <code>if fullSrc is None:</code></p>\n\n<pre><code> return \"There is no Image Link\"\n</code></pre>\n\n<p>That's a terrible way to report an error. Either you should <code>return None</code> or an empty string or raise an exception. But returning a string with an error message is bad because the rest of the program won't treat it as special.</p>\n\n<pre><code>def getSkuFromDiv(div):\n \"\"\"Expects a BeautifulSoup div from {website's} new product page\"\"\"\n try:\n baseUrl = div.find('a')['href']\n baseSku = re.search('\\productId=(\\d+_\\d+)', baseUrl).group(0)\n</code></pre>\n\n<p>You should use <code>.group(1)</code> as that will return the part in the parens. Then you don't need to replace trick.</p>\n\n<pre><code> return baseSku.replace(\"productId=\", \"\")\n except AttributeError:\n return \"There is no Sku\"\n\n\ndef encodeBrandNameToUTF8(brandAndName):\n return str(brandAndName.encode(\"utf-8\"))\n</code></pre>\n\n<p><code>.encode()</code> already returns a string, you don't need to stringify it again. The function also implies its specific to brand names, but its not.</p>\n\n<pre><code>def getBrandAndNameFromDiv(div):\n \"\"\"Expects a BeautifulSoup div from {website's} new product page\"\"\"\n try:\n brandAndName = div.find('span', {'class': 'name'}).string\n return str(brandAndName)\n except UnicodeEncodeError:\n return encodeBrandNameToUTF8(brandAndName)\n</code></pre>\n\n<p>Just <code>return encodeBrandNameToUTF8(brandAndName)</code> the first time. You don't gain anything by trying and failing and trying again. </p>\n\n<pre><code> # return \"unicode encode error\"\n except AttributeError:\n return \"There is no brand and / or name\"\n\ndef getPriceFromDiv(div):\n \"\"\"Expects a BeautifulSoup div from {website's} new product page\"\"\"\n try:\n price = div.find('span', {'class': 'price'}).string\n</code></pre>\n\n<p>This line is very similiar to the line in the previous function. I'd write a function to share the similiarties.</p>\n\n<pre><code> return price.replace(\"$\", \"\") # have to remove the dollar sign from the price\n</code></pre>\n\n<p>I don't like this because it implies that you are removing it from across the whole string rather then just the beginning. Instead I'd use <code>return price.lstrip('$')</code></p>\n\n<pre><code> except AttributeError:\n return \"There is no price\"\n\n\ndef buildLinkFromSKU(sku):\n \"\"\"Expects a SKU representing a product at {website}\"\"\"\n return productBaseUrl + sku\n\n\nclass websiteProduct:\n</code></pre>\n\n<p>Python style guide recomend CamelCase for class names</p>\n\n<pre><code> \"\"\"A product from {website's} created using a newItemDiv in a BeautifulSoup format\"\"\"\n def __init__(self, productDiv):\n self.price = str(getPriceFromDiv(productDiv))\n self.brandAndName = str(getBrandAndNameFromDiv(productDiv))\n</code></pre>\n\n<p>Python style guide recommends lowercase_with_underscores for object attributes.</p>\n\n<pre><code> self.sku = str(getSkuFromDiv(productDiv))\n self.imageLink = str(getImageLinkFromDiv(productDiv))\n self.link = str(buildLinkFromSKU(self.sku))\n</code></pre>\n\n<p>Stylistically, it'd make more sense for your get function to convert to strings. Especially since many of them already do.</p>\n\n<pre><code> self.json = json.dumps({'store':\"Website Name\", 'name':self.brandAndName, 'price':self.price, 'sku':self.sku,\n 'link':self.link, 'imageLink':self.imageLink})\n\n def getPrice(self):\n return self.price\n\n def getBrandAndName(self):\n return self.brandAndName\n\n def getLink(self):\n return self.link\n\n def getImageLink(self):\n return self.imageLink\n\n def getSku(self):\n return self.sku\n\n def getJson(self):\n return self.json\n</code></pre>\n\n<p>In python, we do not have get functions. Just access the attributes directly. If you need more complicated getter logic, you can use properties.</p>\n\n<pre><code>uploadProductsUrl = \"http://MySite.com/products.json\"\nwebsiteNewItemLink = \"http://www.website.com/newItems\"\nnewItemSoup = soupify(getHtml(websiteNewItemLink))\nnewItems = newItemSoup.find_all('div', {'class': 'productNew'})\nproductBaseUrl = \"http://www.website.com/product?productId=\"\n</code></pre>\n\n<p>Some of these are global constants, they should be named in ALL_CAPS, and moved to the top of the file. Other ones shouldn't really be global, and those should become local variables in a main() function.</p>\n\n<pre><code>productList = []\nfor item in newItems:\n product = websiteProduct(item)\n productList.append(product)\n</code></pre>\n\n<p>You can use <code>productList = map(websiteProduct, newItems)</code>, or <code>productList = [websiteProduct(item) for item in newItems]</code> or at least combine the last two lines.</p>\n\n<pre><code>for item in productList[0:]:\n</code></pre>\n\n<p>Why the <code>[0:]</code>? it does nothing</p>\n\n<pre><code> jsonData = item.getJson()\n request = buildJsonPostRequest(uploadProductsUrl)\n urllib2.urlopen(request, jsonData)\n</code></pre>\n\n<p>I recommend actually looking at the response to make sure it at least gave a sucesfull status.</p>\n\n<blockquote>\n <p>Does it make sense to declare some of the methods here in this script\n and some of the methods in another script (scraper_tools) when some of\n those methods are shared by similar scripts?</p>\n</blockquote>\n\n<p>Absolutely. In fact I'd move anything which looks like it could be generic into there.</p>\n\n<blockquote>\n <p>My websiteProduct class does all of the work in the initializer part\n of the class, this feels dirty to me.</p>\n</blockquote>\n\n<p>For the purpose of this script, the whole class is pointless, because all you really want is to make the json. So I'd just have a function that takes the div and returns the json. In general, having the constructor fetching attributes like that will loose flexibility.</p>\n\n<blockquote>\n <p>I have a bunch of variables declared in what feels like an arbitrary\n position within the file. Is this acceptable?</p>\n</blockquote>\n\n<p>Not really. Global constants should be at the top. Non-globals should be in functions.</p>\n\n<blockquote>\n <p>The part where this script actually gets started doing things is just\n hanging out in the open somewhere arbitrarily toward the end of the\n actual file, is this normal?</p>\n</blockquote>\n\n<p>Normal yes, correct no. You should put all that stuff in a <code>main()</code> function and add this:</p>\n\n<pre><code>if __name__ == '__main__':\n main()\n</code></pre>\n\n<p>That will only execute the main function when the script is executed directly. You can import it without executing it which may be useful. </p>\n\n<p>Now, thats a bit of a purist answer. For trivial scripts (this one is skirting on the boundary) I'll sometimes ignore that and just write it like you've done. </p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-02-04T22:47:17.033", "Id": "34204", "Score": "3", "body": "Just the type of information I was looking for. Great for the first response I've received on codereview.stackexchange." } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-02-04T15:31:21.560", "Id": "21296", "ParentId": "21290", "Score": "16" } } ]
{ "AcceptedAnswerId": "21296", "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-02-04T13:26:42.897", "Id": "21290", "Score": "8", "Tags": [ "python", "web-scraping" ], "Title": "Scraping new product data from an online store" }
21290
<p><strong>Question from Skiena's Programming Challenges.</strong> Getting WA (wrong answer) in Online Judge even though it's working for sample test cases. Can somebody find a case where it fails?</p> <p>I tried the tricky case from this link and it gave the right answer-</p> <p><a href="https://codereview.stackexchange.com/questions/18652/the-trip-problem-from-programming-challenges?rq=1">&quot;The Trip&quot; challenge from Programming Challenges</a></p> <p><strong>Input</strong></p> <p>Standard input will contain the information for several trips. Each trip consists of a line containing a positive integer n denoting the number of students on the trip. This is followed by n lines of input, each containing the amount spent by a student in dollars and cents. There are no more than 1000 students and no student spent more than $10,000.00. A single line containing 0 follows the information for the last trip.</p> <p><strong>Output</strong></p> <p>For each trip, output a line stating the total amount of money, in dollars and cents, that must be exchanged to equalize the students’ costs.</p> <pre><code>Sample Input 3 10.00 20.00 30.00 4 15.00 15.01 3.00 3.01 0 Sample Output $10.00 $11.99 #include &lt;iostream&gt; #include &lt;vector&gt; #include &lt;sstream&gt; using namespace std; int main() { vector &lt;float&gt; nums; int numStudents,loopVar1,pos; float amount,sum=0,roundAmt,ans; string strAns; stringstream ss; while(cin&gt;&gt;numStudents) { if(numStudents==0) break; ans=sum=0; nums.erase(nums.begin(),nums.end()); for(loopVar1=0;loopVar1&lt;numStudents;loopVar1++) { cin&gt;&gt;amount; nums.push_back(amount); sum+=amount; } sum/=numStudents; roundAmt=(int)(sum*100); roundAmt/=100.0f; //cout&lt;&lt;roundAmt&lt;&lt;"\n"; for(loopVar1=0;loopVar1&lt;numStudents;loopVar1++) if(nums[loopVar1]&lt;roundAmt) ans+=(roundAmt-nums[loopVar1]); strAns=""; ss.str(""); ss&lt;&lt;ans; strAns=ss.str(); pos=strAns.find('.'); if(pos==-1) strAns+=".00"; else strAns.erase(pos+3); cout&lt;&lt;'$'&lt;&lt;strAns&lt;&lt;"\n"; } return 0; } </code></pre>
[ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-02-04T16:07:34.670", "Id": "34177", "Score": "0", "body": "Code Review is for improving code that your think works, not finding errors in your code. See the [FAQ]." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-02-04T17:12:06.317", "Id": "34188", "Score": "0", "body": "@svick i had read the faq before posting and i think it comes in the \"correctness in unanticipated cases\" category.\ni just want help in finding a tricky test case." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-02-04T17:17:33.000", "Id": "34189", "Score": "0", "body": "I think that applies only when you think the code works, but want to make sure about it (see another line from the FAQ: “To the best of my knowledge, does the code work?”). But if others won't agree with me, your question won't be closed." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-02-04T19:26:29.833", "Id": "34192", "Score": "0", "body": "The other problem is not closed, which could be a hint to let it open. I think your description `improving code that your think works` fits very well to this code (without the `r`)." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-02-04T23:29:03.563", "Id": "34205", "Score": "0", "body": "Off topic (I believe), but: Use integers as much as possible. Only convert back to a float (better yet, a double) at the very last moment (to print). Money amounts are not real numbers (at least not in casual use). They are of a fixed precision. They just happen to have a decimal point in them. Just do all the calculating in cents. Also, it may help to add a small epsilon when converting to an int so things like 2.999999999997 go to 3 instead of 2: `static_cast<int>(f + 1e-6)` (or use a `const double EPS = ...;` type thing so you can change it easily in a centralized place)." } ]
[ { "body": "<p>I did not run it (and I do not like to read it, too much abbreviations, wrong variable names, too less formatting), but what about this case:</p>\n\n<blockquote>\n <p>3<br>\n 1.01<br>\n 0.99<br>\n 0.99 </p>\n</blockquote>\n\n<p><code>sum</code> will be <code>2.99 / 3 = 0.9966666...</code> \n<code>roundAmt</code> will be <code>0.99</code><br>\n<code>ans</code> will be <code>0</code><br>\nObviously, it should be <code>0.01</code> to fulfill the requirement <code>\"so that the net cost to each is the same, to within one cent\"</code></p>\n\n<p>Beside this, please consider the things I mentioned in the beginning. Some concrete examples:</p>\n\n<blockquote>\n <p>sum/=numStudents;</p>\n</blockquote>\n\n<p>This is not a sum anymore, it is the average.</p>\n\n<blockquote>\n <p>loopVar1</p>\n</blockquote>\n\n<p>Take <code>i</code>, this is expected for a loop variable</p>\n\n<blockquote>\n <p>numStudents</p>\n</blockquote>\n\n<p>Could be: <code>number_of_students</code> or <code>numberOfStudents</code></p>\n\n<pre><code>for(loopVar1=0;loopVar1&lt;numStudents;loopVar1++)\n</code></pre>\n\n<p>Could be: <code>for (i = 0; i &lt; number_of_students; ++i)</code></p>\n\n<pre><code>for(loopVar1=0;loopVar1&lt;numStudents;loopVar1++)\n if(nums[loopVar1]&lt;roundAmt)\n ans+=(roundAmt-nums[loopVar1]);\n</code></pre>\n\n<p>One could discuss if using the short form without brackets is ok for one line statements, but if it spans over multiple lines, please use brackets, even if it is syntactically ok.</p>\n\n<p>what does <code>roundAmt</code> mean?</p>\n\n<p>and so forth.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-02-05T12:21:59.103", "Id": "34224", "Score": "0", "body": "thanks, would be glad if you could also refer some resource for learning how to write cleaner code." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-02-05T13:25:26.067", "Id": "34226", "Score": "0", "body": "I do not have any references for C/C++, my personal opinion is that C/C++ is focused on hardware, not the programmer. For the basics, there are some online resources you can easily find with google and keywords like \"best practices coding\" \"clean code\" and so on. There is no whole book about the fundamentals I would explicitly recommend in C/C++. Perhaps ther users have different suggestions." } ], "meta_data": { "CommentCount": "2", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-02-04T20:18:48.863", "Id": "21312", "ParentId": "21294", "Score": "2" } } ]
{ "AcceptedAnswerId": "21312", "CommentCount": "5", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-02-04T14:54:22.727", "Id": "21294", "Score": "1", "Tags": [ "c++", "algorithm", "strings", "programming-challenge" ], "Title": "Skiena's Programming Challenge [UVa ID 10137]- Getting WA" }
21294
<p>I'm new to TDD, never used it ever. I understand the basic concepts but I'm now working on a small project which will be the first time I've ever actually used TDD.</p> <p>The code is pretty self explanatory, it's a simple user data storage class. I've written an interface, a UserData class, and then implemented the interface with SimpleUserStore which uses lists.</p> <p>I first wrote the tests, and then wrote the code so that they'd fail, and then "filled in" the code so that they would pass. When I realised I needed another method, I wrote the tests, then generated the stubs, then wrote the code so that they would pass.</p> <p>My question is basically, am I doing this right? Are there things I'm missing out? Big gaping holes that make you go <em>woah, wait a second!</em>?</p> <p>All responses appreciated.</p> <hr> <pre><code>public interface IUserStore { bool AddUser(UserData user); bool DeleteUser(UserData user); bool UpdateUser(UserData user); UserData GetUserById(int id); UserData GetUserByName(string name); } public class UserData { public UserData() { } public virtual int UserId { get; set; } public virtual string Username { get; set; } public virtual string PasswordHash { get; set; } public virtual string PasswordSalt { get; set; } } public class SimpleUserStore : IUserStore, IDisposable { private List&lt;UserData&gt; userdata; public SimpleUserStore() { userdata = new List&lt;UserData&gt;(); } public bool AddUser(UserData user) { if (user == null) throw new ArgumentNullException("user"); if (userdata.Contains(user)) return false; userdata.Add(user); return userdata.Contains(user); } public bool DeleteUser(UserData user) { if (user == null) throw new ArgumentNullException("user"); return userdata.Remove(user); } public bool UpdateUser(UserData user) { if (user == null) throw new ArgumentNullException("user"); if (!userdata.Contains(user)) return false; UserData _user = userdata.FirstOrDefault(x =&gt; x.UserId == user.UserId); _user = user; return true; } public UserData GetUserById(int id) { if (id &lt; 0) throw new ArgumentException("id"); return userdata.FirstOrDefault(x =&gt; x.UserId == id); } public UserData GetUserByName(string name) { if (name == null) throw new ArgumentNullException("name"); return userdata.FirstOrDefault(x =&gt; x.Username == name); } public void Dispose() { userdata = null; } } </code></pre> <p>I have another project for tests, and in it I have the following test helper class:</p> <pre><code>[ExcludeFromCodeCoverage] public static class TestHelper { public static void ExpectException&lt;T&gt;(Action action) where T : Exception { try { action(); Assert.Fail("Expected exception " + typeof(T).Name); } catch (T) { // Expected } } } </code></pre> <p>And the tests:</p> <pre><code>[ExcludeFromCodeCoverage] [TestClass] public class SimpleUserStoreTests { private SimpleUserStore simpleUserStore; private UserData userA, userB; [TestInitialize] public void TestInitialize() { simpleUserStore = new SimpleUserStore(); userA = new UserData { UserId = 1, Username = "UserA", PasswordHash = "", PasswordSalt = "" }; userB = new UserData { UserId = 2, Username = "UserB", PasswordHash = "", PasswordSalt = "" }; } [TestCleanup] public void TestCleanup() { userA = null; userB = null; simpleUserStore.Dispose(); } [TestMethod] public void AddUserTest() { Assert.IsTrue(simpleUserStore.AddUser(userA)); } [TestMethod] public void AddUserAlreadyExistsTest() { simpleUserStore.AddUser(userA); Assert.IsFalse(simpleUserStore.AddUser(userA)); } [TestMethod] public void AddUserNullArgumentTest() { TestHelper.ExpectException&lt;ArgumentNullException&gt;(() =&gt; simpleUserStore.AddUser(null)); } [TestMethod] public void DeleteUserTest() { simpleUserStore.AddUser(userA); Assert.IsTrue(simpleUserStore.DeleteUser(userA)); } [TestMethod] public void DeleteUserNullArgumentTest() { TestHelper.ExpectException&lt;ArgumentNullException&gt;(() =&gt; simpleUserStore.DeleteUser(null)); } [TestMethod] public void UpdateUserTest() { simpleUserStore.AddUser(userA); userA.Username = "Testing"; Assert.IsTrue(simpleUserStore.UpdateUser(userA)); } [TestMethod] public void UpdateUserNullArgumentTest() { TestHelper.ExpectException&lt;ArgumentNullException&gt;(() =&gt; simpleUserStore.UpdateUser(null)); } [TestMethod] public void UpdateUserNonExistTest() { Assert.IsFalse(simpleUserStore.UpdateUser(userA)); } [TestMethod] public void GetUserByIdTest() { simpleUserStore.AddUser(userA); Assert.AreEqual(userA.UserId, simpleUserStore.GetUserById(1).UserId); } [TestMethod] public void GetUserByIdNegativeArgumentTest() { TestHelper.ExpectException&lt;ArgumentException&gt;(() =&gt; simpleUserStore.GetUserById(-20)); } [TestMethod] public void GetUserByIdNonExistTest() { simpleUserStore.AddUser(userA); Assert.AreEqual(null, simpleUserStore.GetUserById(12)); } [TestMethod] public void GetUserByNameTest() { simpleUserStore.AddUser(userA); Assert.AreEqual(userA.UserId, simpleUserStore.GetUserByName("UserA").UserId); } [TestMethod] public void GetUserByNameNullArgumentTest() { TestHelper.ExpectException&lt;ArgumentNullException&gt;(() =&gt; simpleUserStore.GetUserByName(null)); } [TestMethod] public void GetUserByNameNonExistTest() { simpleUserStore.AddUser(userA); Assert.AreEqual(null, simpleUserStore.GetUserByName("Testing")); } } </code></pre>
[ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-02-04T15:39:38.973", "Id": "34164", "Score": "2", "body": "One thing I notice off hand is you might find it easier to use the [ExpectedExceptionAttribute](http://msdn.microsoft.com/en-us/library/microsoft.visualstudio.testtools.unittesting.expectedexceptionattribute.aspx)" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-02-04T15:43:19.950", "Id": "34165", "Score": "0", "body": "Thanks, that's exactly the kind of feedback I am looking for! :)" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-02-04T15:44:15.097", "Id": "34166", "Score": "0", "body": "Personally I'd use a single fields for password hash+salt. Then splitting, combining and generating them is an implementation details of your password hashing class." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-02-04T15:46:47.967", "Id": "34167", "Score": "2", "body": "Your test cases could be a little more robust. For example, instead of only testing that `AddUser` returns true, you should ensure that it actually added the user. Other than that, it sounds like you have the process down." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-02-04T15:53:05.373", "Id": "34173", "Score": "0", "body": "I initially had it like that, Ginosaji, but then I read one-test-one-assert and thought I had too much going on. I was calling GetUserByName to test AddUser and thought - am I doing this wrong by testing both GetUserByName *and* AddUser? Should I make the underlying UserData list publicly readable and check that?" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-02-04T16:13:33.880", "Id": "34181", "Score": "1", "body": "@AdamKDean, don't count return values that simply indicate success towards that one assert. There is a good chance they should be exceptions anyways." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-02-11T08:56:00.277", "Id": "34655", "Score": "1", "body": "I would recommend using http://code.google.com/p/moq/ for easy creating moq objects" } ]
[ { "body": "<p>imho you are using return values in the wrong way.</p>\n\n<p>For instance, the <code>AddUser</code> returns false for two different reasons which will make it harder to maintain the application. imho both cases are exceptional (the developer should make sure that the user do not exist before calling <code>AddUser</code> and the database is not likely to fail). Hence I would probably just have a <code>void</code> as return signature and use exceptions instead.</p>\n\n<p>Same goes for removal. Using a <code>bool</code> indicates that the removal may fail as often as it will succeed. And that's not the case, is it?</p>\n\n<p>As for the tests, there are some patterns which are typically used. </p>\n\n<p>First of all I usually divide my tests accoring to the arrange/act/assert pattern to make the tests more readable:</p>\n\n<pre><code>[TestMethod]\npublic void DeleteUserTest()\n{ \n // arrange \n var userA = new UserData { UserId = 1, Username = \"UserA\", PasswordHash = \"\", PasswordSalt = \"\" };\n simpleUserStore.AddUser(userA);\n\n // act \n var actual = simpleUserStore.DeleteUser(userA);\n\n //assert\n Assert.IsTrue(actual);\n}\n</code></pre>\n\n<p>Don't use method invocations in the asserts. It makes it harder to debug failing unit tests and also makes the tests harder to read.</p>\n\n<p>Many devs also name the object being tested as <code>sut</code> (subject under test) to make it easier to spot what's being tested.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-02-04T15:50:52.867", "Id": "34172", "Score": "0", "body": "Thanks for the feedback, what you say makes absolute sense. Would you say I should initialise the UserData objects in each test or in the initialization class? I felt like I was repeating myself *a lot* with that particular line." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-02-04T16:02:50.077", "Id": "34174", "Score": "0", "body": "And it also makes them … what? Did you forget to finish your sentence?" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-02-04T16:10:50.080", "Id": "34178", "Score": "0", "body": "Sorry, I meant the initialization method. Let me try and be clearer. In my code, UserData objects `userA` and `userB` are initialized in the `TestInitialize()` method. However, in the above code, they are in the //arrange section of the test. Should `userA` be made in each test that needs it (in the arrange section) or is it okay to initialize them in the `TestInitialize()` method and cut down on the number of times the line is repeated?" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-02-04T16:11:32.840", "Id": "34179", "Score": "2", "body": "Sure. You have to repeat yourself, but you also don't have to scroll like a mad man to check what the objects used have been assigned for values. Each test should be treated as an invidual unit. The class is just used to group related tests together." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-02-04T16:13:50.797", "Id": "34182", "Score": "1", "body": "I do use initialization methods too. But I try to limit the information in them to things that ALL tests use. Anything else do not belong in them. You can either use multiple classes or move the initialization code to each method. (Nothing says that there may only be one test class per class being tested)" } ], "meta_data": { "CommentCount": "5", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-02-04T15:44:13.123", "Id": "21300", "ParentId": "21297", "Score": "3" } }, { "body": "<p>Looks ok to me. I would recommend that you make your test names more descriptive of what you expect to achieve, e.g. AddUserTest -> AddUserReturnsTrueIfSuccessful.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-02-04T15:47:38.597", "Id": "34169", "Score": "0", "body": "Thanks, wasn't sure how I was supposed to name them. Your advice has been noted! :)" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-02-04T15:50:02.820", "Id": "34171", "Score": "3", "body": "Think of your tests as documentation - you are writing your requirement before you write to code, and then the code satisfies the requirement. That should help with names." } ], "meta_data": { "CommentCount": "2", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-02-04T15:46:25.590", "Id": "21302", "ParentId": "21297", "Score": "2" } }, { "body": "<p>Your tests in general suffer from trusting your code too much:</p>\n\n<pre><code>[TestMethod]\npublic void DeleteUserTest()\n{ \n simpleUserStore.AddUser(userA);\n Assert.IsTrue(simpleUserStore.DeleteUser(userA)); \n}\n</code></pre>\n\n<p>You verify the return value, but you don't verify that the user has been removed from the store. The object could very well return success without actually removing the object. You should have a call to <code>GetUser()</code> or similiar to verify that the user isn't there anymore.</p>\n\n<p>Similar with update:</p>\n\n<pre><code>[TestMethod]\npublic void UpdateUserTest()\n{ \n simpleUserStore.AddUser(userA);\n userA.Username = \"Testing\";\n Assert.IsTrue(simpleUserStore.UpdateUser(userA));\n}\n</code></pre>\n\n<p>You don't do anything to verify that update actually did the update. You trust the return value. But you shouldn't do that. Let's actually look at the implementation.</p>\n\n<pre><code>public bool UpdateUser(UserData user)\n{\n if (user == null) throw new ArgumentNullException(\"user\");\n if (!userdata.Contains(user)) return false;\n UserData _user = userdata.FirstOrDefault(x =&gt; x.UserId == user.UserId);\n</code></pre>\n\n<p>You don't verify that this works. You never pass a different object then the one you originally inserted in the Store. You need to pass another object to see if that works.</p>\n\n<pre><code> _user = user;\n</code></pre>\n\n<p>You don't verify that the user in the store gets updated, so you aren't testing this line either.\n return true;\n }</p>\n\n<p>Truth be told, I can see two bugs in this implementation. I'll leave it to you to fix your tests and actually find them yourselves. However, its bad enough that if you wrote this in an interview I probably wouldn't hire you. One of the bugs makes it look like you are very confused about the semantics of the language you are using. Maybe its just a careless error (they happen to the best of us), but it would give me grave doubts.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-02-04T16:21:27.720", "Id": "34184", "Score": "0", "body": "Thank you for your honest appraisal/review. This is exactly what I was looking for, and the exact reason why I'm writing this here now, and not in an interview. I sincerely appreciate your feedback! :)" } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-02-04T16:11:52.877", "Id": "21303", "ParentId": "21297", "Score": "5" } }, { "body": "<p>Your tests names aren't doing a good job of telling what is the test supposed to do.</p>\n\n<p><code>AddUserAlreadyExistsTest()</code> imho isn't very descriptive. </p>\n\n<p>Try <code>AddUser_GivenAlreadyExistingUser_ReturnsFalse()</code>. The first part is the <strong>function</strong> I'm testing followed by the <strong>scenario</strong> I'm testing then finally the <strong>expected output</strong>. This way you can build your test backwards (i.e. starting with the assert then moving back to the point where you create the system object).</p>\n\n<p>The point is someone else should read the name of the test and know what is being tested without actually reading inside the test. Think if it from the point of Clean Code, function names should tell what is happening while the code itself inside it should tell How it does it.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-02-04T19:32:09.213", "Id": "34194", "Score": "0", "body": "This is a good way to name tests, but may I ask how you would name something that, for example, added a user but did not get a return? Lets say it adds the user, then checks the user has been added, would you call that `AddUser_GivenNewUser_UserAdded`?" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-02-04T20:25:12.323", "Id": "34197", "Score": "2", "body": "@AdamKDean well you tell me :) How would you know if a user was added successfully? If you are adding him to a collection them maybe I'll call it `AddUser_GivenNewUser_UserAddedToCollection` that way I know my assert will check for the user in that collection and I have a way to start my test. If you are returning a `boolean` then I'll call it `AddUser_GivenNewUser_ReturnsTrue`. It all depends on how you want people to use your api." } ], "meta_data": { "CommentCount": "2", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-02-04T16:29:17.173", "Id": "21305", "ParentId": "21297", "Score": "3" } }, { "body": "<p>As indicated in other answers, the tests should definitely be named much more descriptively. \nIt is common to use the list of tests as a requirements list for the component under test. and so should indicate The method tested, the preconditions, and the expected outcome. I like Songo's suggested formatting.</p>\n\n<p>A number of the tests provided are problematic since you are only testing with one entry in your collection:\nGetUserByNameTest \nGetUserByIdTest </p>\n\n<p>This alternate (incorrect) implementation of SimpleUserStore would still pass, but only because it is lucky. (your 'not exists' tests would fail though).</p>\n\n<pre><code>public interface IUserStore\n{ \n bool AddUser(UserData user);\n bool DeleteUser(UserData user);\n bool UpdateUser(UserData user);\n\n UserData GetUserById(int id);\n UserData GetUserByName(string name);\n}\n\npublic class UserData\n{\n public UserData() { }\n\n public virtual int UserId { get; set; }\n public virtual string Username { get; set; }\n public virtual string PasswordHash { get; set; }\n public virtual string PasswordSalt { get; set; }\n}\n\npublic class SimpleUserStore : IUserStore, IDisposable\n{\n private List&lt;UserData&gt; userdata;\n\n public SimpleUserStore()\n {\n userdata = new List&lt;UserData&gt;();\n }\n\n public bool AddUser(UserData user)\n {\n if (user == null) throw new ArgumentNullException(\"user\");\n\n if (userdata.Contains(user)) return false;\n\n userdata.Add(user);\n return userdata.Contains(user);\n }\n\n public bool DeleteUser(UserData user)\n {\n //if (user == null) throw new ArgumentNullException(\"user\");\n //return userdata.Remove(user);\n return true;\n }\n\n public bool UpdateUser(UserData user)\n {\n if (user == null) throw new ArgumentNullException(\"user\");\n if (!userdata.Contains(user)) return false;\n UserData _user = userdata.FirstOrDefault();\n _user = user;\n return true;\n }\n\n public UserData GetUserById(int id)\n {\n if (id &lt; 0) throw new ArgumentException(\"id\");\n return userdata.FirstOrDefault();\n }\n\n public UserData GetUserByName(string name)\n {\n if (name == null) throw new ArgumentNullException(\"name\");\n return userdata.FirstOrDefault();\n } \n\n public void Dispose()\n {\n userdata = null;\n }\n}\n</code></pre>\n\n<p>This isn't directly related to the TDD question, but does illustrate your tests are not picking up on problems in your code:\nYour use of <code>userdata.Contains()</code> is potentially/probably problematic. Contains checks against reference. as you are using the same two objects throughout your test, the reference will be the same. what would you expect from this test?</p>\n\n<pre><code>[TestMethod]\npublic void ShouldUpdateBeIdBasedOrReferenceBased()\n{ \n simpleUserStore.AddUser(userA);\n UserData userCopy = new UserData{userA.Username, userA.UserId};\n userCopy.Username = \"Testing\";\n Assert.IsTrue(simpleUserStore.UpdateUser(userCopy));\n}\n</code></pre>\n\n<p>as you are holding the reference for A the whole time, UpdateUser doesn't do anything useful for you the object in your store and the object in your test are the same object.</p>\n\n<pre><code> simpleUserStore.AddUser(userA);\n\n userA.UserId = 7;\n UserData testResult = simpleUserStore.GetUserById(7);\n Assert.That(testResult.UserName, Is.EqualTo(userA.Username)) //victory.\n</code></pre>\n\n<p>for that matter...</p>\n\n<pre><code> ...\n simpleUserStore.AddUser(userA);\n UserData userCopy = new UserData{userA.Username, userA.UserId};\n userCopy.Username = \"Testing\";\n simplerUserStore.AddUser(userCopy);\n ...\n</code></pre>\n\n<p>You now have two users with the same id but different names.</p>\n\n<p>Testing against the boolean return values of your Add/Delete/Update methods is meaningless.\nall you test is that the method thinks it did the right thing. </p>\n\n<p>It really is ok to have more than one Assert in a test...</p>\n\n<pre><code>[TestMethod]\npublic void UpdateUserTest()\n{ \n simpleUserStore.AddUser(userA);\n userA.Username = \"Testing\";\n simpleUserStore.UpdateUser(userA); //returning true tells me nothing \n\n UserData result = simpleUserStore.GetById(userA.UserId);\n Assert.IsEqual(result.UserId, userA.UserId);\n Assert.IsEqual(result.Username, userA.Username);\n}\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-02-05T09:12:35.667", "Id": "34218", "Score": "0", "body": "Indeed, I noticed last night that there was a problem with the references, yet cloning the objects when I add/retrieve them etc causes problems, in that you can't pass the object and check it exists by reference. I wrote some new tests last night, found here: https://github.com/Imdsm/EasyAuth/blob/master/EasyAuth.Tests/UserStoreTests.cs and the new IUserStore: https://github.com/Imdsm/EasyAuth/blob/master/EasyAuth/IUserStore.cs ... going to play with these tests a bit, maybe post the results later on for another review. Thanks for your time, I appreciate it!" } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-02-05T00:34:50.127", "Id": "21322", "ParentId": "21297", "Score": "1" } } ]
{ "AcceptedAnswerId": "21303", "CommentCount": "7", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-02-04T15:32:04.480", "Id": "21297", "Score": "3", "Tags": [ "c#", ".net" ], "Title": "New to TDD, am I doing everything right? How could I improve?" }
21297
<p>Ok, so I started to build my own CMS. You can see <a href="http://cms.golubovic.info" rel="nofollow" title="Aleksandar Golubovic's Blog">Aleksandar Golubovic's Blog</a>,and I need your help. Please, look at my code, and tell me is that safe? You can download current version from <a href="http://cms.golubovic.info/tb-cms.rar" rel="nofollow">Twitter Bootstrap CMS</a>. If you want to install it, just read instructions.</p> <p>So, please, tell me if I get some errors, or some of your opinions, instructions... I really need help.</p> <p>EDIT:</p> <p>I have many functions like:</p> <pre><code>function DeletePost() { if (isset($_GET['action'])) { if ($_GET['action']==='delete-post' &amp;&amp; !isset($_GET['id'])) { $qry=mysql_query("SELECT * FROM posts ORDER BY id DESC"); while ($arr=mysql_fetch_array($qry)) { echo '&lt;div class="span8 offset1"&gt;&lt;p&gt;&lt;h3&gt;'.$arr['post_title'].'&lt;/h3&gt; &lt;a href="javascript:;" title="Delete This Post" class="delete" id="'.$arr['id'].'"&gt;Delete this post&lt;/a&gt;&lt;/p&gt;&lt;p&gt;'.$arr['post_content'].'&lt;/p&gt;&lt;/div&gt;'; } } if ($_GET['action']==='delete-post' &amp;&amp; isset($_GET['id'])) { $del=$_GET['id']; $qry=mysql_query("DELETE FROM posts WHERE id='$del'") or die ("ERROR!!!"); echo "This post has been successfull deleted."; } } } </code></pre> <p>And this function is included in some page. So my question is: Is this method safe? Note: All functions is separeted pages using .htaccess</p>
[ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-02-04T15:49:45.303", "Id": "34170", "Score": "0", "body": "This site is for code review only. IE: You post a piece of code and a question concerning the posted code and we review it and offer help on what you should do. This is not a website review board, etc. Perhaps try http://webapps.stackexchange.com/ or stack overflow?" } ]
[ { "body": "<p>Well looking at this as a code review of the code you posted i can recommend a couple of things;</p>\n\n<h2>Security</h2>\n\n<p>The major flaw at the moment is the possibility for SQL injection. You put the $_GET values directly into the query without validation or escaping. </p>\n\n<p>PHP.net has a page on SQL injection: <a href=\"http://php.net/manual/en/security.database.sql-injection.php\" rel=\"nofollow\">http://php.net/manual/en/security.database.sql-injection.php</a></p>\n\n<h2>Deprecated code</h2>\n\n<p><em>It is strongly recommend <strong>not</strong> to use the <code>mysq_*</code> functions</em>. !!!</p>\n\n<p>These functions are deprecated and will recieve no more support and will be removed in an upcoming version of PHP. See <a href=\"http://php.net/manual/en/function.mysql-connect.php\" rel=\"nofollow\">http://php.net/manual/en/function.mysql-connect.php</a> and look at the big red box. This is potentially a huge security hazzard in the future as well.</p>\n\n<h2>User Content / Access levels</h2>\n\n<p>Currently you are not demonstrating any check on access level. If i am to guess your actions i could delete the entire content of your website without logging in!</p>\n\n<h2>Database connection</h2>\n\n<p>You seem to open the sql connection somewhere else. Please verify for yourself that you also close the connection when request ends, avoiding lingering MySQL connections.</p>\n\n<h2>Misc</h2>\n\n<p>Also, look into the SOLID principles and PSR-2 codestyle, your current code does not match it. These are best practices and provide a good base strategy for your coding. Also, making it more likely the open source community would accept/adopt your code.</p>\n\n<p>Good luck in further development of your CMS! </p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-02-04T19:46:23.600", "Id": "34195", "Score": "0", "body": "Where can one find information regarding psr-2 codestyle that you speak of?" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-02-04T20:00:01.643", "Id": "34196", "Score": "0", "body": "https://github.com/php-fig/fig-standards/blob/master/accepted/PSR-2-coding-style-guide.md . Please note, PSR-2 extends PSR-1 (link in above page) which in turn extends PSR-0" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-02-04T21:10:39.880", "Id": "34199", "Score": "0", "body": "Thanks!!! This is the best answer I can get! I dont have enough points to vote for your answer, but as soon as I get some, I will vote!" } ], "meta_data": { "CommentCount": "3", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-02-04T19:38:49.963", "Id": "21310", "ParentId": "21301", "Score": "4" } } ]
{ "AcceptedAnswerId": "21310", "CommentCount": "1", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-02-04T15:44:47.760", "Id": "21301", "Score": "2", "Tags": [ "php" ], "Title": "Twitter Bootstrap CMS" }
21301
<p>I wanted to implemented an algorithm in Python 2.4 (so the odd construction for the conditional assignment) where given a list of ranges, the function returns another list with all ranges that overlap in the same entry.</p> <p>I would appreciate other options (more elegant or efficient) than the one I took. </p> <pre><code>ranges = [(1,4),(1,9),(3,7),(10,15),(1,2),(8,17),(16,20),(100,200)] def remove_overlap(rs): rs.sort() def process (rs,deviation): start = len(rs) - deviation - 1 if start &lt; 1: return rs if rs[start][0] &gt; rs[start-1][1]: return process(rs,deviation+1) else: rs[start-1] = ((rs[start][0],rs[start-1][0])[rs[start-1][0] &lt; rs[start][0]],(rs[start][1],rs[start-1][1])[rs[start-1][1] &gt; rs[start][1]]) del rs[start] return process(rs,0) return process(rs,0) print remove_overlap(ranges) </code></pre>
[]
[ { "body": "<p>Firstly, modify or return, don't do both. </p>\n\n<p>Your <code>process</code> method returns lists as well as modify them. Either you should construct a new list and return that, or modify the existing list and return nothing.</p>\n\n<p>Your <code>remove_overlap</code> function does the same thing. It should either modify the incoming list, or return a new list not both. </p>\n\n<p>You index <code>[0]</code> and <code>[1]</code> on the tuples a lot to fetch the start and end. That's best avoided because its not easy to tell whats going on. </p>\n\n<p><code>rs[start-1] = ((rs[start][0],rs[start-1][0])[rs[start-1][0] &lt; rs[start][0]],(rs[start][1],rs[start-1][1])[rs[start-1][1] &gt; rs[start][1]])</code></p>\n\n<p>Ouch! That'd be much better off broken into several lines. You shouldn't need to check which of the starts is lower because sorting the array should mean that the earlier one is always lower. I'd also use the <code>max</code> function to select the larger item, (if you don't have it in your version of python, I'd just define it)</p>\n\n<p>Your loop is backwards, working from the end. That complicates the code and makes it harder to follow. I'd suggest reworking it work from the front. </p>\n\n<pre><code>return process(rs,0)\n</code></pre>\n\n<p>You start the checking process over again whenever you merge two ranges. But that's not so great because you'll end up rechecking all the segments over and over again. Since you've already verified them you shouldn't check them again. </p>\n\n<p>Your recursion process can be easily rewritten as a while loop. All you're doing is moving an index forward, and you don't really need recursion.</p>\n\n<p>This is my implementation:</p>\n\n<pre><code>def remove_overlap(ranges):\n result = []\n current_start = -1\n current_stop = -1 \n\n for start, stop in sorted(ranges):\n if start &gt; current_stop:\n # this segment starts after the last segment stops\n # just add a new segment\n result.append( (start, stop) )\n current_start, current_stop = start, stop\n else:\n # segments overlap, replace\n result[-1] = (current_start, stop)\n # current_start already guaranteed to be lower\n current_stop = max(current_stop, stop)\n\n return result\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-02-05T11:18:12.577", "Id": "34223", "Score": "0", "body": "`remove_overlap([(-1,1)])` → `IndexError: list assignment index out of range`. Maybe start with `float('-inf')` instead of `-1`?" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-02-05T13:53:40.937", "Id": "34227", "Score": "0", "body": "@GarethRees, that'll work if you need negative ranges. I assumed the ranges were positive as typically negatives ranges are non-sensical (not always)." } ], "meta_data": { "CommentCount": "2", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-02-04T18:09:21.930", "Id": "21309", "ParentId": "21307", "Score": "8" } }, { "body": "<p>In addition to Winston Ewert's comments, I'd add:</p>\n\n<ol>\n<li><p>There's no docstring. How are users to know how what this function does and how to call it?</p></li>\n<li><p>This is an ideal function to give a couple of <a href=\"http://docs.python.org/2/library/doctest.html\" rel=\"noreferrer\">doctests</a> to show how to use it and to test that it works.</p></li>\n<li><p>The name <code>remove_overlap</code> could be improved. Remove overlap from what? And remove it how? And anyway, you don't just want to merge <em>overlapping</em> ranges (like 1–3 and 2–4), you want to merge <em>adjacent</em> ranges too (like 1–2 and 2–3). So I'd use <code>merge_ranges</code>.</p></li>\n<li><p>It's simpler and more flexible to implement the function as a generator, rather than repeatedly appending to a list. </p></li>\n<li><p>Winston's implementation doesn't work if any of the ranges are negative.</p></li>\n</ol>\n\n<p>So I would write:</p>\n\n<pre><code>def merge_ranges(ranges):\n \"\"\"\n Merge overlapping and adjacent ranges and yield the merged ranges\n in order. The argument must be an iterable of pairs (start, stop).\n\n &gt;&gt;&gt; list(merge_ranges([(5,7), (3,5), (-1,3)]))\n [(-1, 7)]\n &gt;&gt;&gt; list(merge_ranges([(5,6), (3,4), (1,2)]))\n [(1, 2), (3, 4), (5, 6)]\n &gt;&gt;&gt; list(merge_ranges([]))\n []\n \"\"\"\n ranges = iter(sorted(ranges))\n current_start, current_stop = next(ranges)\n for start, stop in ranges:\n if start &gt; current_stop:\n # Gap between segments: output current segment and start a new one.\n yield current_start, current_stop\n current_start, current_stop = start, stop\n else:\n # Segments adjacent or overlapping: merge.\n current_stop = max(current_stop, stop)\n yield current_start, current_stop\n</code></pre>\n\n<h3>Update</h3>\n\n<p>Winston Ewert notes in comments that it's not exactly obvious how this works in the case when <code>ranges</code> is the empty list: in particular, the call <code>next(ranges)</code> looks suspicious.</p>\n\n<p>The explanation is that when <code>ranges</code> is empty, <code>next(ranges)</code> raises the exception <code>StopIteration</code>. And that's exactly what we want, because we are writing a generator function and raising <code>StopIteration</code> is one of the ways that a generator can signal that it is finished.</p>\n\n<p>This is a common pattern when building one iterator from another: the outer iterator keeps reading elements from the inner iterator, relying on the inner iterator to raise <code>StopIteration</code> when it is empty. Several of the recipes in the <a href=\"http://docs.python.org/2/library/itertools.html\" rel=\"noreferrer\"><code>itertools</code> documentation</a> use this pattern, for example <a href=\"http://docs.python.org/2/library/itertools.html#itertools.imap\" rel=\"noreferrer\"><code>imap</code></a> and <a href=\"http://docs.python.org/2/library/itertools.html#itertools.islice\" rel=\"noreferrer\"><code>islice</code></a>.</p>\n\n<p>Supposing that you think this is a bit ugly, and you wanted to make the behaviour explicit, what would you write? Well, you'd end up writing something like this:</p>\n\n<pre><code>try:\n current_start, current_stop = next(ranges)\nexcept StopIteration: # ranges is empty\n raise StopIteration # and so are we\n</code></pre>\n\n<p>I hope you can see now why I didn't write it like that! I prefer to follow the maxim, \"<a href=\"http://drj11.wordpress.com/2008/10/02/c-return-and-parentheses/\" rel=\"noreferrer\">program as if you know the language</a>.\"</p>\n\n<h3>Update 2</h3>\n\n<p>The idiom of deferring from one generator to another via <code>next</code> will no longer work in Python 3.6 (see <a href=\"http://legacy.python.org/dev/peps/pep-0479/\" rel=\"noreferrer\">PEP 479</a>), so for future compatibility the code needs to read:</p>\n\n<pre><code>try:\n current_start, current_stop = next(ranges)\nexcept StopIteration:\n return\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-02-05T13:56:09.720", "Id": "34228", "Score": "0", "body": "I'm pretty sure it'll fail on `ranges = []` due to trying to fetch the next item from an empty list." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-02-05T16:29:09.573", "Id": "34241", "Score": "0", "body": "There's already a doctest for that case. (And it passes.) When `ranges` is empty, the call to `next` raises the exception `StopIteration`, which is exactly what we need." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-02-05T16:50:57.900", "Id": "34244", "Score": "0", "body": "Oh, subtle. I didn't think of the fact that `StopIteration` would trigger the end of the generator. Honestly, that feels ugly to me, but that may just be taste." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-02-05T16:58:57.690", "Id": "34245", "Score": "0", "body": "It's a natural pattern for building one iterator out of another: the outer iterator reads items from the inner iterator, relying on the inner one to raise `StopIteration` when it's empty. Many of the recipes in the [`itertools` module](http://docs.python.org/2/library/itertools.html) use this pattern. See for example `imap` and `islice`." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-02-05T17:39:02.400", "Id": "34248", "Score": "0", "body": "I reserve my right to still find it ugly. :) Maybe its just a matter of not being used to it, but I don't like the implicit way it handles the case." } ], "meta_data": { "CommentCount": "5", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-02-05T11:11:55.133", "Id": "21333", "ParentId": "21307", "Score": "8" } }, { "body": "<p>I think there is an error in the algorithm. Example:</p>\n\n<ul>\n<li>ranges = [(1,5), (2,4), (8,9)]</li>\n</ul>\n\n<p>Expected response:</p>\n\n<ul>\n<li>ranges2 = [(1,5), (8,9)]</li>\n</ul>\n\n<p>Response obtained:</p>\n\n<ul>\n<li>ranges2 = [(1,4), (8,9)]</li>\n</ul>\n\n<p>I don't know how to fix this.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-02-20T13:49:48.013", "Id": "466034", "Score": "1", "body": "This post is more suited to be a comment than an answer. Please put it in a comment." } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-02-20T12:07:03.780", "Id": "237630", "ParentId": "21307", "Score": "2" } }, { "body": "<p>I think there is an error in the algorithm. Example:</p>\n\n<ul>\n<li>ranges = [(1,5), (2,4), (8,9)]</li>\n</ul>\n\n<p>Expected response:</p>\n\n<ul>\n<li>ranges2 = [(1,5), (8,9)]</li>\n</ul>\n\n<p>Response obtained:</p>\n\n<ul>\n<li>ranges2 = [(1,4), (8,9)]</li>\n</ul>\n\n<p>A small change and the error is fixed.</p>\n\n<pre><code>def remove_overlap(ranges):\n result = []\n current_start = -1\n current_stop = -1 \n\n for start, stop in sorted(ranges):\n if start &gt; current_stop:\n # this segment starts after the last segment stops\n # just add a new segment\n current_start, current_stop = start, stop\n result.append( (start, stop) )\n else:\n # segments overlap, replace\n # current_start already guaranteed to be lower\n current_stop = max(current_stop, stop)\n result[-1] = (current_start, current_stop)\n\n return result\n</code></pre>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-02-20T13:24:47.243", "Id": "237636", "ParentId": "21307", "Score": "-1" } } ]
{ "AcceptedAnswerId": "21309", "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-02-04T17:04:46.913", "Id": "21307", "Score": "9", "Tags": [ "python", "performance", "algorithm", "python-2.x", "interval" ], "Title": "Consolidate list of ranges that overlap" }
21307
<p>As the title says, I'm looking for a better way of writing the following PHP function as it's a very very long one. It's part of a bigger class and I'm trying to keep the amount of code as little as possible. </p> <p>The reason why I needed so many cases is because the function can accept all kinds of arguments in different ways. It might not make any sense just by looking at it, but I can provide a short description of the behavior :</p> <pre><code>public function get_new_files() { $arguments = []; $args = func_get_args(); $args_count = func_num_args(); $files = []; $set = $this-&gt;methods["Public"][8]; $public_url = $this-&gt;public_url; switch ($args_count) { case 1: switch (gettype($args[0])) { case 'string': $arguments = $this-&gt;filter_arguments_recursive($args, $args_count); switch (count($arguments)) { case 0: case 1: return json_encode("[ Get Items [ New ][ Failed ] | Arguments [ Insufficient ][ 2 Required ] ]"); break; case 2: $url = preg_replace('/set/i', $set . ":" . $arguments[0] . "," . $arguments[1], $public_url); $files = [ "Marketplaces" =&gt; [ "Marketplace" =&gt; $arguments[0], "Categories" =&gt; [ $arguments[1] =&gt; $this-&gt;fetch($url, $set) ] ] ]; break; case 3: default: return json_encode("[ Get Items [ New ][ Failed ] | Arguments [ Exceeded ][ 2 Required ] ]"); break; }; break; case 'array': switch (count($args[0])) { case 0: return json_encode("[ Get Items [ New ][ Failed ] | Arguments [ Insufficient ][ 2 Required ] ]"); break; case 1: $arguments = $this-&gt;filter_arguments_recursive($args, $args_count); switch (count($arguments)) { case 0: case 1: return json_encode("[ Get Items [ New ][ Failed ] | Arguments [ Insufficient ][ 2 Required ] ]"); break; case 2: $url = preg_replace('/set/i', $set . ":" . $arguments[0] . "," . $arguments[1], $public_url); $files = [ "Marketplaces" =&gt; [ "Marketplace" =&gt; $arguments[0], "Categories" =&gt; [ $arguments[1] =&gt; $this-&gt;fetch($url, $set) ] ] ]; break; case 3: default: return json_encode("[ Get Items [ New ][ Failed ] | Arguments [ Exceeded ][ 2 Required ] ]"); break; }; break; case 2: switch (gettype($args[0][0])) { case 'string': switch (gettype($args[0][1])) { case 'string': $arguments = $this-&gt;filter_arguments_recursive([ $args[0][1] ], 1); switch (count($arguments)) { case 0: return json_encode("[ Get Items [ New ][ Failed ] | Arguments [ Category ][ Missing ][ 1 + Required ] ]"); break; case 1: $url = preg_replace('/set/i', $set . ":" . $args[0][0] . "," . $arguments[0], $public_url); $files = [ "Marketplaces" =&gt; [ "Marketplace" =&gt; $args[0][0], "Categories" =&gt; [ $arguments[0] =&gt; $this-&gt;fetch($url, $set) ] ] ]; break; case 2: default: $results = []; foreach ($arguments as $key =&gt; $argument) { $url = preg_replace('/set/i', $set . ":" . $args[0][0] . "," . $argument, $public_url); array_push($results, [ $argument =&gt; $this-&gt;fetch($url, $set) ] ); }; unset($argument); $files = [ "Marketplaces" =&gt; [ "Marketplace" =&gt; $args[0][0], "Categories" =&gt; $results ] ]; break; }; break; case 'array': $results = []; foreach ($args[0][1] as $key =&gt; $argument) { $url = preg_replace('/set/i', $set . ":" . $args[0][0] . "," . $argument, $public_url); array_push($results, [ $argument =&gt; $this-&gt;fetch($url, $set) ] ); }; unset($argument); $files = [ "Marketplaces" =&gt; [ "Marketplace" =&gt; $args[0][0], "Categories" =&gt; $results ] ]; break; default: return json_encode("[ Get Items [ New ][ Failed ] | Arguments [ Unknown Type ][ String Required ] ]"); break; }; break; default: return json_encode("[ Get Items [ New ][ Failed ] | Arguments [ Unknown Type ][ String Required ] ]"); break; }; break; default: return json_encode("[ Get Items [ New ][ Failed ] | Arguments [ Exceeded ][ 2 Required ] ]"); break; }; break; default: return json_encode("[ Get Items [ New ][ Failed ] | Arguments [ Unknown Type ][ String Required ] ]"); break; }; break; case 2: switch (gettype($args[0])) { case 'string': switch (gettype($args[1])) { case 'string': $arguments = $this-&gt;filter_arguments_recursive([ $args[1] ], 1); switch (count($arguments)) { case 0: return json_encode("[ Get Items [ New ][ Failed ] | Arguments [ Category ][ Missing ][ 1 + Required ] ]"); break; case 1: $url = preg_replace('/set/i', $set . ":" . $args[0] . "," . $arguments[0], $public_url); $files = [ "Marketplaces" =&gt; [ "Marketplace" =&gt; $args[0], "Categories" =&gt; [ $arguments[0] =&gt; $this-&gt;fetch($url, $set) ] ] ]; break; case 2: default: $results = []; foreach ($arguments as $key =&gt; $argument) { $url = preg_replace('/set/i', $set . ":" . $args[0] . "," . $argument, $public_url); array_push($results, [ $argument =&gt; $this-&gt;fetch($url, $set) ] ); }; unset($argument); $files = [ "Marketplaces" =&gt; [ "Marketplace" =&gt; $args[0], "Categories" =&gt; $results ] ]; break; }; break; case 'array': $results = []; foreach ($args[1] as $key =&gt; $argument) { $url = preg_replace('/set/i', $set . ":" . $args[0] . "," . $argument, $public_url); array_push($results, [ $argument =&gt; $this-&gt;fetch($url, $set) ] ); }; unset($argument); $files = [ "Marketplaces" =&gt; [ "Marketplace" =&gt; $args[0], "Categories" =&gt; $results ] ]; break; default: return json_encode("[ Get Items [ New ][ Failed ] | Arguments [ Unknown Type ][ String Required ] ]"); break; }; break; default: return json_encode("[ Get Items [ New ][ Failed ] | Arguments [ Unknown Type ][ String Required ] ]"); break; }; break; default: return json_encode("[ Get Items [ New ][ Failed ] | Arguments [ Exceeded ][ 2 Required ] ]"); break; }; return $this-&gt;json_encode_f_object([ "Items" =&gt; [ "New" =&gt; $files ] ]); } </code></pre> <p><strong>Description :</strong> Well, the main purpose of this function is to get the newest items published on some website ( through their API ). The function needs two arguments as a starting point : a <code>marketplace</code> and a <code>category</code> ; </p> <p>Based on those arguments, I get a JSON back with some info. What I do before doing that is filtering the arguments :</p> <ul> <li>first case would be that the user simply gives the function one string which contains the market and the category to ( only one category and market at a time is accepted ) separated by whitespace, comma, etc. So what I do is split that string and return an array with the two values and then fire the actual GET;</li> <li>another case would be that the user gives two strings, then do the above again to make sure I don't have whitespace or more arguments in each string</li> <li>then, the user can also pass an array with one string which meets the same conditions as the first case, or with two strings which again meets the same case as the first, but if the second string contains more than one word ( separated again by whitespace, comma, etc. ) then do a GET for the same market but with each category</li> </ul> <p>I could go on with the description and be more specific, but I think the above covers the bigger picture and why I have so many cases :)</p> <p>I hope someone has a better view of how I could approach this as I haven't coded PHP in some years now so I'm a bit rusty :)</p> <p><strong>Function Call Example :</strong> I think it would make sense to paste an example of how this could be called :</p> <pre><code>$test-&gt;get_new_files_from_market("themeforest", ["wordpress", "cms-themes", "psd-templates"]); $test-&gt;get_new_files_from_market("themeforest", "wordpress, cms-themes, psd-templates"); $test-&gt;get_new_files_from_market("themeforest", "wordpress"); $test-&gt;get_new_files_from_market("themeforest, wordpress"); $test-&gt;get_new_files_from_market(["themeforest", "wordpress"]); </code></pre> <p>The way of calling it could go on, as maybe you can figure out from the function's cases :)</p>
[]
[ { "body": "<p>If there's anything in this answer - concepts, words, principles, etc. - that you find confusing, please don't hesitate to ask for a clarification.</p>\n\n<blockquote>\n <p>It might not make any sense just by looking at it</p>\n</blockquote>\n\n<p>It's good that you can detect and acknowledge this, because it is an important warning sign.</p>\n\n<blockquote>\n <p>the function can accept all kinds of arguments in different ways.</p>\n</blockquote>\n\n<p>Why should it have to?</p>\n\n<p>I think this function is trying to do too much and that's the main reason you're struggling to keep it simple.</p>\n\n<p>Either way, here goes my analysis:</p>\n\n<p>First of all, having both <code>$args</code> and <code>$arguments</code> variables is confusing.\nThose two names are very similar so how is a new reader of the code supposed to initially know which is which?\nAlso, it is very easy for a person to accidentally write <code>$arguments</code> when he/she meant <code>$args</code> and vice-versa. Consider renaming one of the variables to something more obvious.</p>\n\n<p>You use <code>$args[0]</code> a lot. You should create a new variable to hold that value (and give that variable a meaningful name).</p>\n\n<p>Your function seems to (usually) only get up to <em>two</em> arguments. So is there really any reason to use varargs? Generally speaking, you shouldn't use <code>func_get_args</code> and <code>func_num_args</code> when normal function arguments will work.</p>\n\n<p>You cover lots of use cases in this function, which makes me suspect you are assigning too much responsibility to this single function. Have you considered <strong>splitting the function into three new ones</strong>? (one for each case)\nThis would, by itself, improve the quality of the code:</p>\n\n<ul>\n<li>Each function would be smaller</li>\n<li>Each function would have better cohesion</li>\n<li>Each function would be easier to understand - particularly since it should be possible to examine each of these new functions in isolation.</li>\n<li>It would reduce the maximum nesting level</li>\n</ul>\n\n<p>It is unclear what <code>filter_arguments_recursive</code> does.<br>\n<code>filter</code> seems to imply that the result will have, at most, as many elements as the argument it receives.<br>\nSo in <code>$arguments = $this-&gt;filter_arguments_recursive($args, $args_count)</code>, <code>$arguments</code> should be at most as long as <code>$args</code>.<br>\nHowever, after this piece of code:</p>\n\n<pre><code> switch ($args_count) {\n case 1:\n</code></pre>\n\n<p>we see this:</p>\n\n<pre><code> $arguments = $this-&gt;filter_arguments_recursive($args, $args_count);\n\n switch (count($arguments)) {\n case 0:\n case 1:\n return json_encode(\"[ Get Items [ New ][ Failed ] | Arguments [ Insufficient ][ 2 Required ] ]\");\n break;\n case 2:\n</code></pre>\n\n<p>So either we have some redundant code here(<code>case 2</code> shouldn't happen) or the name <code>filter_arguments_recursive</code> is misleading. (either way, the name could probably be improved: <code>filter arguments</code>? What filter is being applied here? It's not immediately obvious)</p>\n\n<p>Additionally, I see some <code>break</code> statements after <code>return</code>. These are redundant. Return immediately exits the function, therefore the loop is broken right there. In fact, those breaks are never even executed.</p>\n\n<p>Also, we see strings similar to <code>\"[ Get Items [ New ][ Failed ] | Arguments [ Unknown Type ][ String Required ] ]\"</code> very often. What are these strings used for? Perhaps you could isolate this in a function by itself? Or even just return an error code and let the caller code format it? Remember that ideally each function should have only a single responsibility.</p>\n\n<p><code>json_encode_f_object</code> What is an \"F object\"? Consider renaming this function to something more meaningful.</p>\n\n<p>What does <code>$this-&gt;methods[\"Public\"]</code> contain?</p>\n\n<p>This is the low hanging fruit I can find. After solving these issues, newer ones should be exposed. It would also be helpful to see an example of this function being called.</p>\n\n<p><strong>Short version:</strong></p>\n\n<ul>\n<li>Use semantically meaningful names when possible</li>\n<li>Avoid having multiple variables with similar names in the same function</li>\n<li>Try not to do too much in a single function. When in doubt, break down the function into multiple other ones.</li>\n</ul>\n\n<p><strong>EDIT: To address the comments</strong></p>\n\n<blockquote>\n <p>I don't find anything confusing</p>\n</blockquote>\n\n<p>But would others find it confusing?\nAnd will you still think it is obvious if you come back to this code a few months in the future, when your memory isn't as fresh?</p>\n\n<blockquote>\n <p>the user could call</p>\n</blockquote>\n\n<p>So this is just a function that somebody else will call. Then why the focus on JSON?</p>\n\n<p>Generally, we use JSON when we want to communicate with \"the outside world\". For instance, when I have PHP code and want to send data to JavaScript, JSON is a good option. However, as the return value of a function, I don't see the need for JSON. Why not just return normal PHP data and let the user convert it to JSON if he really wants/needs it?</p>\n\n<blockquote>\n <p>The main reason why I assign that much to this function is because it\n is supposed to be just one method that the user could call and get\n whatever results</p>\n</blockquote>\n\n<p>Would the user of the function be truly inconvenienced if this was split in three functions, one for each use-case you mentioned? Or would it be so bad if only one of the three formats was accepted?</p>\n\n<blockquote>\n <p>if you have a comma between the words it's going to split that</p>\n</blockquote>\n\n<p>That's not what \"filter\" usually means. \"filter\" means to \"remove unwanted stuff\" from a mix. For instance, a water filter removes the impurities from water. I'd expect an \"argument filter\" to remove unwanted arguments.</p>\n\n<p>So what your \"filter\" function does, if I understand correctly, is this:</p>\n\n<ul>\n<li>Split when a comma appears between words: Not expected in filtering</li>\n<li>Strip all the extra whitespace: This can indeed be considered filtering</li>\n<li>Strip all repeated values (making the result unique): This, too, can be considered filtering</li>\n<li>Do so recursively: This part is acceptable in a \"recursive filter\" function.</li>\n<li>Return a \"flat\" result: Not expected in filtering.</li>\n</ul>\n\n<p>Then:</p>\n\n<ul>\n<li>It is unclear what the second argument does.</li>\n<li>Indeed, I can't think of a good name for this function. Perhaps a better question would be \"why is it doing it?\" Sometimes, good names come up that way.</li>\n</ul>\n\n<p>By the way, is there a chance the data this function receives comes from an end-user? Is the following use-case possible/expected?</p>\n\n<pre><code>$test-&gt;get_new_files_from_market($_GET[\"something\"], $_GET[\"more_stuff\"]);\n</code></pre>\n\n<p>If so, then you may want to consider asking yourself \"what happens when the function is called and the arguments contain characters like '/' or '?'. You mention a GET request, so I'm just wondering if you thought about that and reviewed it under a security perspective. I'm not saying you are vulnerable, just saying you should double-check. If you are not vulnerable, add a few comments explaining <em>why</em> you are safe.</p>\n\n<p>If the user is supposed to do some sanitization himself before passing data to the function, document that too.</p>\n\n<pre><code>$test-&gt;get_new_files_from_market(\"themeforest, wordpress\");\n$test-&gt;get_new_files_from_market([\"themeforest\", \"wordpress\"]);\n$test-&gt;get_new_files_from_market(\"themeforest\", [\"wordpress\"]);\n</code></pre>\n\n<p>Are these three supposed to do the same? (Your description seems to imply so)</p>\n\n<p>If so, then I would once again consider choosing just one format for the method. I'd also try to move the <code>$this-&gt;filter_arguments_recursive($args, $args_count);</code> to right before the outer switch, but <code>$arguments = $this-&gt;filter_arguments_recursive([ $args[0][1] ], 1);</code> suggests this might not be correct.</p>\n\n<p>I just noticed this:</p>\n\n<pre><code>case 3:\ndefault:\n</code></pre>\n\n<p>This is unusual. Did you leave <code>case 3</code> there by accident? Because in this case, <code>case 3</code> will just execute the code in <code>default</code>.</p>\n\n<blockquote>\n <p><code>json_encode_f_object</code> is force encoding the array to object</p>\n</blockquote>\n\n<p>Have you considered a name like <code>json_encode_as_object</code>?</p>\n\n<blockquote>\n <p><code>$this-&gt;methods[\"Public\"]</code> is just a global array of strings. I will\n also consider placing all those message strings into a function or\n some global variable</p>\n</blockquote>\n\n<p>The reason I asked was because of the line <code>$set = $this-&gt;methods[\"Public\"][8];</code>. It is not clear in that context what <code>8</code> is supposed to be. (are you familiar with the concept of \"magic numbers\"?)</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-02-04T23:47:16.850", "Id": "34206", "Score": "1", "body": "nice one! Great job @luiscubal" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-02-05T07:50:54.953", "Id": "34210", "Score": "0", "body": "@luiscubal ~ thanks for taking the time to comment :) I don't find anything confusing ;) I do know that is a bit confusing as the class that is a part of it's pretty big, maybe if you'd see the overall of it, it would make more sense :) The main reason why I assign that much to this function is because it is supposed to be just one method that the user could call and get whatever results. I added some examples of how it could call it :)" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-02-05T08:14:00.367", "Id": "34214", "Score": "0", "body": "@luiscubal ~ the suggestion with the arguments and args, that's a good one, I couldn't notice that if anyone wouldn't point it out :) As for the `$args[0]`, I just did the replacement where I could, but the thing is that it depends on the case, so it might not have `$args[0]`" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-02-05T08:34:16.377", "Id": "34215", "Score": "0", "body": "@luiscubal ~ `filter_arguments_recursive` does exactly what is says, it filters the arguments, for instance if you have a comma between the words it's going to split that into an array containing the two words or more, and it also strips all the extra spaces and returns unique values only. By `recursive` I mean that the method is recursive, so it goes as deep as the hierarchy is and return unique values as a flat array. As for the `break` after `return`, that's a bad habit of mine :) Thanks for letting me knwo" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-02-05T09:13:40.103", "Id": "34219", "Score": "0", "body": "`json_encode_f_object` is force encoding the array to object, `$this->methods[\"Public\"]` is just a global array of strings. I will also consider placing all those message strings into a function or some global variable" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-02-05T09:55:14.753", "Id": "34221", "Score": "1", "body": "Message strings should probably be constants. That would help enforce consistent responses to input. Also try to avoid using global variables in general. If you need to group them together, you could make them class constants." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-02-05T15:13:35.980", "Id": "34230", "Score": "0", "body": "@luiscubal ~ `I don't find anything confusing`, you're totally right, I don't think that I will understand a lot from it after a year, I'll have to take some time :) `the user could call`, JSON ? Because it will be called from outside, as an API Wrapper, the user only needs JS to make an AJAX request to the methods and he shall be returned with the needed JSON data :) 'The main reason why I assign that much to this function is because it is supposed to be just one method that the user could call and get whatever results' I actually found a way of doing it recursive, I have the func call itself" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-02-05T15:21:00.050", "Id": "34232", "Score": "0", "body": "@luiscubal ~ you make a perfect point with the function name, I often find myself having a hard time finding the perfect name for a function :) In the case the user throws any special characters the result he would get would be either empty or an error with a description telling him why he didn't get anything. And `json_encode_as_object` it's a perfect name. thanks for that :)" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-02-05T15:23:46.863", "Id": "34233", "Score": "0", "body": "@luiscubal ~ the thing with the switch case it's by accident, that is why I usually like having a second pair of eyes looking over my code :) As for `magic numbers`, I'm not familiar with that :)" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-02-05T15:24:48.613", "Id": "34234", "Score": "1", "body": "@Roland \"Because it will be called from outside, as an API Wrapper, the user only needs JS to make an AJAX request to the methods and he shall be returned with the needed JSON data\" Not sure I understand what you mean here. As far as I know, only PHP can directly call PHP code, so normal PHP objects would work perfectly in that use-case. For JS to call PHP, we need an intermediate layer that receives requests (e.g. `index.php`) and sends the converted data back. I'd have the JSON be a concern of that intermediate layer." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-02-05T15:26:35.990", "Id": "34235", "Score": "0", "body": "Makes sense, I just wanted to keep it internally, and the intermediate layer between the class and JS would just take care of getting the data sent from JS and executing the method" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-02-05T15:31:57.867", "Id": "34236", "Score": "1", "body": "@Roland For a starting point about magic numbers, see http://stackoverflow.com/questions/47882/what-is-a-magic-number-and-why-is-it-bad" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-02-05T15:39:47.433", "Id": "34237", "Score": "0", "body": "Thank you for the answer, it's by far the most constructive I've had :)" } ], "meta_data": { "CommentCount": "13", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-02-04T23:33:24.767", "Id": "21320", "ParentId": "21308", "Score": "11" } }, { "body": "<p>Just my 2 cents: I would replace those switch-case blocks with the Strategy pattern and outsource those code lines to external classes implementing the same strategy.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-02-05T15:08:28.153", "Id": "34229", "Score": "0", "body": "Could you be more specific ? I found an article : http://sourcemaking.com/design_patterns/strategy/php ; But that doesn't clarify how I could implement it :)" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-02-06T08:08:58.277", "Id": "34276", "Score": "0", "body": "Sorry for the late answer. Basically the idea is that going from the innermost switch-case block the content of each case goes to separate classes, each having a function with the same name. Now replace the switch with a factory method returning the strategy implementor based on $arguments (you don't even need to know that the inner factory method will invoke count() on it).\n\nNow if you apply the same to the outer switch-case block, that will leave you with an object. Now you can call\n\n call_user_func_array(array($your_strategy_implementor, 'chosen_function_name'), array(all params));" } ], "meta_data": { "CommentCount": "2", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-02-05T08:52:45.700", "Id": "21329", "ParentId": "21308", "Score": "0" } } ]
{ "AcceptedAnswerId": "21320", "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-02-04T17:11:04.710", "Id": "21308", "Score": "1", "Tags": [ "php" ], "Title": "A better way of writing a PHP function" }
21308
<p>My task was:</p> <p>Write a function that takes three arguments: a character and two integers. The character is to be printed. The first integer specifies the number of times that the character is to be printed on a line, and the second integer specifies the number of lines that are to be printed. Write a program that makes use of this function.</p> <p>And my code is: (i know i did not add different scenarios like if the first char is number etc, but please let me know if it looks ok)</p> <pre><code>#include &lt;stdio.h&gt; void printing_char (char ch, int numberOfChars, int numberOfLines); int main (void) { char userChar; int lines,times; printf ("please enter a character, number of times in a line, and number of lines:\n"); while ((scanf ("%c%d%d", &amp;userChar, &amp;times, &amp;lines)) == 3) { printing_char (userChar, times, lines); } return 0; } void printing_char (char ch, int numberOfChars, int numberOfLines) { int x; int y = 0; while (++y &lt;= numberOfLines) { for (x = 0; x&lt;numberOfChars; x++) { printf ("%c", ch); } printf ("\n"); } } </code></pre>
[ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-02-05T05:09:29.417", "Id": "34208", "Score": "1", "body": "`printf(\"%c\", ch);` have you considered `putchar(ch);`?" } ]
[ { "body": "<p>Only a couple of things:</p>\n\n<ul>\n<li><p><code>int lines,times;</code> - one declaration per line, please!</p></li>\n<li><p><code>scanf(\"%c%d%d\", &amp;userChar, &amp;times, &amp;lines)</code> - where does one number end and the next start?. You need to include some terminating characters, such as <code>,</code></p>\n\n<pre><code>printf(\"please enter a character, number of times in a line, and number of lines, separated by a comma:\\n\");\nwhile ((scanf(\"%c,%d,%d\", &amp;userChar, &amp;times, &amp;lines)) == 3)\n</code></pre></li>\n<li><p>An expression such as <code>while (++y &lt;= numberOfLines)</code> is confusing, what value does y have at each step? It'd be better to rewrite this as a <code>for</code> loop</p>\n\n<pre><code>for ( y = 0; y &lt; numberOfLines; y++ )\n</code></pre></li>\n</ul>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-10-24T14:21:44.717", "Id": "397778", "Score": "0", "body": "One number ends and the next starts at *whitespace* - remember that numeric conversions skip leading whitespace." } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-02-04T20:47:52.703", "Id": "21313", "ParentId": "21311", "Score": "3" } }, { "body": "<p>In addition to comments by @GlennRogers, here's a bit of pedantry:</p>\n\n<ul>\n<li><p>consider putting <code>main</code> last to avoid the need for a prototype for\n<code>printing_char</code></p></li>\n<li><p><code>printing_char</code> should be <code>static</code>. Seems a bad name too.</p></li>\n<li><p>for-loops can define the loop variable in the initial loop:</p>\n\n<pre><code>for (int x = 0; x&lt;numberOfChars; x++)\n</code></pre></li>\n<li><p>nested loops are generally best avoided. Your inner for-loop would be better\nas a function:</p>\n\n<pre><code>static void print_n_times(int ch, int n)\n{\n for (int i=0; i&lt;n; ++i) {\n putchar(ch);\n }\n}\n</code></pre></li>\n<li><p>adding a blank line after the function definition is very odd. Best not\ndone.</p></li>\n<li><p><code>numberOfChars</code> and <code>numberOfLines</code> are verbose for my taste. I prefer\n<code>n_chars</code>, <code>n_lines</code> (or camel-case <code>nChars</code>, <code>nLines</code>). Also, as the variables\nin <code>main</code> have exactly the same meaning, it would be reasonable to call\n<code>lines</code> and <code>times</code> the same there, ie. <code>n_chars</code> and <code>n_lines</code></p></li>\n<li><p>you have unnecessary brackets around the <code>scanf</code> call </p></li>\n</ul>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-02-13T21:01:36.930", "Id": "21678", "ParentId": "21311", "Score": "2" } }, { "body": "<p>Expensive operations here are the nested loops and the multiple calls to the <code>printf</code> function.</p>\n\n<p>These hotspots can be corrected by using the <code>memset</code> and <code>memcpy</code> functions (but be careful, you can quickly misuse them).</p>\n\n<p>Only <strong>one <code>printf</code></strong> and <strong>one loop</strong></p>\n\n<pre><code>#include &lt;stdio.h&gt;\n#include &lt;string.h&gt;\n\nvoid printing_char (char ch, int length, int lines)\n{\n if (length &lt; 1 || lines &lt; 1) return;\n\n int size = length+1;\n char str[size*lines+1];\n\n memset(str, ch, length);\n str[length] = '\\n';\n str [size*lines] = '\\0';\n\n for (int off = size*(lines-1); off &gt; 0; off -= size) {\n memcpy(str + off, str, size); \n } \n printf (\"%s %d\", str, lines);\n}\n\nint main (void)\n{\n char ch;\n int lines;\n int times;\n\n printf(\"please enter a character, number of times in a line, and number of lines, separated by a comma:\\n\");\n while ((scanf(\"%c,%d,%d\", &amp;ch, &amp;times, &amp;lines)) == 3) {\n printing_char (ch, times, lines);\n }\n //printing_char('*', 4, 3);\n //printing_char('^', 0, 5);\n //printing_char('.', 3, -1);\n\n return 0;\n}\n</code></pre>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-10-24T18:25:39.867", "Id": "206214", "ParentId": "21311", "Score": "0" } } ]
{ "AcceptedAnswerId": "21313", "CommentCount": "1", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-02-04T19:53:28.327", "Id": "21311", "Score": "1", "Tags": [ "c" ], "Title": "A function to print a character number of times and in number of lines" }
21311
<p>I am a newcomer to design patterns. I read some articles about the <a href="https://en.wikipedia.org/wiki/Abstract_factory" rel="nofollow">abstract factory</a> pattern, and wrote the following simple example:</p> <pre><code>public interface ParserFactory { List&lt;ITransport&gt; getBusList(); List&lt;ITransport&gt; getTrainList(); List&lt;ITransport&gt; getPlaneList(); } public abstract class XMLParserFactory implements ParserFactory{ } public abstract class CSVParserFactory implements ParserFactory{ } public class DOMTransportParser extends XMLParserFactory{ public List&lt;ITransport&gt; getBusList(){ return null; } public List&lt;ITransport&gt; getTrainList(){ return null; } public List&lt;ITransport&gt; getPlaneList(){ return null; } } public class CSVTransportParser extends CSVParserFactory{ public List&lt;ITransport&gt; getBusList(){ return null; } public List&lt;ITransport&gt; getTrainList(){ return null; } public List&lt;ITransport&gt; getPlaneList(){ return null; } } } </code></pre> <p>Is anything wrong with this code? Can it be improved? Do I understand the abstract factory pattern correctly?</p>
[ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-02-05T13:19:36.140", "Id": "34225", "Score": "0", "body": "\"Abstract Factory\" is not a pattern but an abomination. I'd strongly recommend to look at Dependency Injection instead (using Guice, Spring, CDI...), which solves the same problem much more elegant and flexible." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-02-06T00:33:39.503", "Id": "34267", "Score": "0", "body": "Except an Abstract Factory is a type of Dependency Injection (manual dependency injection). You can use an Abstract Factory to implement DI. It all depends on what you want to do - DI seems like overkill for this example, anyway. Too much abstraction is just as bad as no abstraction at all." } ]
[ { "body": "<p>This isn't really an Abstract Factory. Going on the theme of what you've got above (although I'm not sure what trains, planes and buses have to do with parsing!), an Abstract Factory would look something like the following:</p>\n\n<pre><code>public interface Parser\n{\n List&lt;ITransport&gt; getBusList();\n List&lt;ITransport&gt; getTrainList();\n List&lt;ITransport&gt; getPlaneList();\n}\n\npublic interface ParserFactory \n{\n Parser getParser();\n}\n\npublic class XMLParser implements Parser\n{\n //Implementation of Constructors and Interface methods from Parser\n}\n\npublic class CSVParser implements Parser\n{\n //Implementation of Constructors and Interface methods from Parser\n}\n\npublic class XMLParserFactory implements ParserFactory\n{\n public Parser getParser()\n {\n return new XMLParser();\n }\n}\n\npublic class CSVParserFactory implements ParserFactory\n{\n public Parser getParser()\n {\n return new CSVParser(); \n }\n}\n</code></pre>\n\n<p>This is then used in some way like the following:</p>\n\n<pre><code>public class Main\n{\n //Note: Using a String is for illustrative purposes only. Ideally\n //it should be using some system or file setting. Half the point\n //of this pattern is that the caller doesn't know what kind of \n //object they are getting back (which probably doesn't make too much\n //sense for parsers, really).\n public static ParserFactory createParserFactory(String type)\n {\n if(type.equals(\"XML\") {\n return new XMLParserFactory();\n } else {\n return new CSVParserFactory();\n }\n }\n\n public Main(ParserFactory factory)\n {\n Parser parser = factory.getParser();\n List&lt;ITransport&gt; bus = parser.getBusList();\n }\n\n public static void main(String[] args)\n {\n new Main(createParserFactory(\"XML\"));\n }\n</code></pre>\n\n<p>So what's the point of all this (it's quite a lot of code, after all). Well, firstly, it insulates the caller from knowledge of the concrete type. They don't know what kind of <code>Parser</code> they're getting back, the implementation details are hidden from them. Secondly, it localizes all object creation through a single point, which means client code will need very minimal updates when things change. For example, say we want to add a new kind of <code>Parser</code> - let's say a <code>JSONParser</code> - to our code. Then we create a factory and parser like we did previously:</p>\n\n<pre><code>public class JSONParser implements Parser \n{ // Implementation details \n}\n\npublic class JSONParserFactory implements ParserFactory\n{\n public Parser getParser() { return new JSONParser(); }\n}\n</code></pre>\n\n<p>Then we simply add it to our <code>getParserFactory</code> method:</p>\n\n<pre><code> public static ParserFactory createParserFactory(String type)\n {\n if(type.equals(\"XML\") {\n return new XMLParserFactory();\n } \n else if(type.equals(\"JSON\") {\n return new JSONParserFactory();\n } else {\n return new CSVParserFactory();\n }\n }\n</code></pre>\n\n<p>Note that any client code will be calling <code>createParserFactory()</code> and then <code>getParser</code> from that - so ideally, if they want to switch in a <code>JSONParser</code>, the <strong>only</strong> thing that needs to change in their code is the call to <code>createParserFactory(\"JSON\")</code>.</p>\n\n<p>Hopefully this has cleared things up a little bit (and not confused you too much).</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-02-05T08:47:49.957", "Id": "34217", "Score": "0", "body": "I almost agree with you. But what about this. I agree in part with intefces ParserFactory and Parser. But as I understand every factory should produce own specific type of product \nXMLParser on my opinion should be interface because for it exist different implementations (DOM, SAX, StAX) in this case I couldn't create object and my abstract factory become builder. Or instead of XMLParser write DOMTransportParser, SAXTransportParser?" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-02-06T00:28:22.807", "Id": "34266", "Score": "0", "body": "So make an interface for `XMLParser` then. The idea was mainly to show you the basic structure - you can modify it as you please, either by having another layer underneath your `XMLParser` that returns a specific type (all still wrapped up in a `Parser`, however)." } ], "meta_data": { "CommentCount": "2", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-02-05T01:07:51.580", "Id": "21325", "ParentId": "21314", "Score": "2" } } ]
{ "AcceptedAnswerId": "21325", "CommentCount": "2", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-02-04T20:56:37.773", "Id": "21314", "Score": "2", "Tags": [ "java", "design-patterns" ], "Title": "Using AbstractFactory" }
21314
<p>I'm writing a WPF application and I have several <code>ReadOnlyObservableCollection</code> fields in my models.</p> <p>Suppose that I wanted to create a <code>FooViewModel</code> instance for each <code>FooModel</code> instance. <code>FooModel</code> has an observable collection of <code>BarModel</code>, and <code>FooViewModel</code> should contain a (read-only) observable collection of <code>BarViewModel</code>.</p> <p>I created an utility class to simplify this task:</p> <pre><code>using System; using System.Collections; using System.Collections.Generic; using System.Collections.ObjectModel; using System.Collections.Specialized; using System.Diagnostics.Contracts; using System.Linq; namespace NamespaceNameGoesHere { /// &lt;summary&gt; /// Creates a view of another ("inner") read-only collection, using a function to map each instance in the source collection to another instance that is viewed by users of this class. /// If the inner collection uses the CollectionChanged event correctly, then the two are kept in sync. /// Note that when there are changes to the inner collection, some transformed instances might be recreated. Any attempt to prevent this should /// This class is NOT thread-safe. /// &lt;/summary&gt; /// &lt;typeparam name="InnerType"&gt;The type of the instances in the inner collection&lt;/typeparam&gt; /// &lt;typeparam name="TargetType"&gt;The type of the instances that are exposed to users of this class&lt;/typeparam&gt; public class TransformedCollection&lt;InnerType, TargetType&gt; : INotifyCollectionChanged, IReadOnlyCollection&lt;TargetType&gt; { public event NotifyCollectionChangedEventHandler CollectionChanged; private IReadOnlyCollection&lt;InnerType&gt; innerCollection; private List&lt;TargetType&gt; transformedValues = new List&lt;TargetType&gt;(); private Func&lt;InnerType, TargetType&gt; transformationFunction; /// &lt;summary&gt; /// Creates a new transformed collection to view another collection. /// &lt;/summary&gt; /// &lt;param name="innerCollection"&gt;The collection containing the instances to transform. Must not be null.&lt;/param&gt; /// &lt;param name="transformationFunction"&gt;The function to convert an inner collection instance. Must not be null. /// This delegate must not throw any exceptions.&lt;/param&gt; public TransformedCollection(IReadOnlyCollection&lt;InnerType&gt; innerCollection, Func&lt;InnerType, TargetType&gt; transformationFunction) { Contract.Requires&lt;ArgumentNullException&gt;(innerCollection != null, "innerCollection must not be null"); Contract.Requires&lt;ArgumentNullException&gt;(transformationFunction != null, "transformationFunction must not be null"); this.innerCollection = innerCollection; this.transformationFunction = transformationFunction; CreateCollection(); //Ensure that when the inner collection is changed, the changes propagate to this one. ((INotifyCollectionChanged)innerCollection).CollectionChanged += InnerCollectionChanged; } /// &lt;summary&gt; /// Transforms and adds every element in the inner list /// &lt;/summary&gt; private void CreateCollection() { foreach (var element in CreateTransformedElements()) { transformedValues.Add(element); } } /// &lt;summary&gt; /// Transforms all elements in the inner list. /// &lt;/summary&gt; /// &lt;returns&gt;An enumerable containing all the transformed elements.&lt;/returns&gt; private IEnumerable&lt;TargetType&gt; CreateTransformedElements() { return innerCollection .Select(inner =&gt; transformationFunction(inner)); } private void InnerCollectionChanged(object sender, NotifyCollectionChangedEventArgs e) { List&lt;TargetType&gt; newItems = null; List&lt;TargetType&gt; oldItems = null; switch (e.Action) { case NotifyCollectionChangedAction.Add: newItems = new List&lt;TargetType&gt;(); for (int i = 0; i &lt; e.NewItems.Count; ++i) { //Transform all newly added items and add them to temporary "newItems" list. int index = e.NewStartingIndex + i; InnerType innerElement = (InnerType)e.NewItems[i]; TargetType transformedElement = transformationFunction(innerElement); newItems.Add(transformedElement); } transformedValues.InsertRange(e.NewStartingIndex, newItems); RaiseCollectionChanged(this, new NotifyCollectionChangedEventArgs(NotifyCollectionChangedAction.Add, newItems, e.NewStartingIndex)); break; case NotifyCollectionChangedAction.Remove: oldItems = new List&lt;TargetType&gt;(); for (int i = 0; i &lt; e.OldItems.Count; ++i) { int index = e.OldStartingIndex + i; oldItems.Add(transformedValues[index]); } transformedValues.RemoveRange(e.OldStartingIndex, e.OldItems.Count); RaiseCollectionChanged(this, new NotifyCollectionChangedEventArgs(NotifyCollectionChangedAction.Remove, oldItems, e.OldStartingIndex)); break; case NotifyCollectionChangedAction.Replace: newItems = new List&lt;TargetType&gt;(); oldItems = new List&lt;TargetType&gt;(); for (int i = 0; i &lt; e.NewItems.Count; ++i) { int index = e.NewStartingIndex + i; InnerType innerElement = (InnerType)e.NewItems[i]; TargetType transformedElement = transformationFunction(innerElement); newItems.Add(transformedElement); oldItems.Add(transformedValues[index]); transformedValues[index] = transformedElement; } RaiseCollectionChanged(this, new NotifyCollectionChangedEventArgs(NotifyCollectionChangedAction.Replace, newItems, oldItems, e.NewStartingIndex)); break; case NotifyCollectionChangedAction.Reset: transformedValues.Clear(); CreateCollection(); RaiseCollectionChanged(this, new NotifyCollectionChangedEventArgs(NotifyCollectionChangedAction.Reset)); break; case NotifyCollectionChangedAction.Move: newItems = new List&lt;TargetType&gt;(); if (e.NewItems.Count != 1) { throw new NotImplementedException("No idea how this is supposed to work"); } //The names "at old index"/"at new index" refer to the positions *before* the move method was called. TargetType valueAtOldIndex = transformedValues[e.OldStartingIndex]; TargetType valueAtNewIndex = transformedValues[e.NewStartingIndex]; //Swap positions transformedValues[e.NewStartingIndex] = valueAtOldIndex; transformedValues[e.OldStartingIndex] = valueAtNewIndex; //The value at the old index *before* the move method was called is the value that is at the new index *after* it. //We add that value to the list newItems.Add(valueAtOldIndex); RaiseCollectionChanged(this, new NotifyCollectionChangedEventArgs(NotifyCollectionChangedAction.Move, newItems, e.NewStartingIndex, e.OldStartingIndex)); break; default: throw new InvalidOperationException(); } } private void RaiseCollectionChanged(object sender, NotifyCollectionChangedEventArgs e) { if (CollectionChanged != null) { CollectionChanged(sender, e); } } public IEnumerator&lt;TargetType&gt; GetEnumerator() { return transformedValues.GetEnumerator(); } IEnumerator IEnumerable.GetEnumerator() { return GetEnumerator(); } public int Count { get { return transformedValues.Count; } } } } </code></pre> <p><code>NamespaceNameGoesHere</code> is not the real name of the namespace.</p> <p>I have created the following xUnit tests which all pass:</p> <pre><code>using System; using System.Collections; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using System.Collections.ObjectModel; using Xunit; using System.Collections.Specialized; namespace NamespaceNameGoesHere.Test { public class TransformedCollectionTest { private int Double(int x) { return x * 2; } [Fact] public void NullArgumentsTest() { var emptySourceCollection = new ObservableCollection&lt;int&gt;(); var emptyCollection = new ReadOnlyObservableCollection&lt;int&gt;(emptySourceCollection); Assert.Throws&lt;ArgumentNullException&gt;(() =&gt; new TransformedCollection&lt;int, int&gt;(null, Double)); Assert.Throws&lt;ArgumentNullException&gt;(() =&gt; new TransformedCollection&lt;int, int&gt;(emptyCollection, null)); Assert.Throws&lt;ArgumentNullException&gt;(() =&gt; new TransformedCollection&lt;int, int&gt;(null, null)); } [Fact] public void InitialStateTest() { var emptyCollection = new ObservableCollection&lt;int&gt;(); var emptyReadOnlyCollection = new ReadOnlyObservableCollection&lt;int&gt;(emptyCollection); var emptyTransformCollection = new TransformedCollection&lt;int, int&gt;(emptyReadOnlyCollection, Double); //Collection must be empty Assert.Equal(0, emptyTransformCollection.Count); //Additionally, the enumerator (from IEnumerable&lt;T&gt;) will give no result Assert.Equal(false, emptyTransformCollection.GetEnumerator().MoveNext()); //Check the same with the non-generic enumerator Assert.Equal(false, ((IEnumerable)emptyTransformCollection).GetEnumerator().MoveNext()); var simpleCollection = new ObservableCollection&lt;int&gt;(); simpleCollection.Add(1); simpleCollection.Add(2); simpleCollection.Add(3); var simpleReadOnlyCollection = new ReadOnlyObservableCollection&lt;int&gt;(simpleCollection); var simpleTransformCollection = new TransformedCollection&lt;int, int&gt;(simpleReadOnlyCollection, Double); Assert.Equal(3, simpleTransformCollection.Count); //We expect to get [2, 4, 6] int i = 2; foreach (int value in simpleTransformCollection) { Assert.Equal(i, value); i += 2; } } [Fact] public void AddElementTest() { var startIndices = new List&lt;int&gt;(); var newItems = new List&lt;IList&gt;(); var baseCollection = new ObservableCollection&lt;int&gt;(); var readOnlyCollection = new ReadOnlyObservableCollection&lt;int&gt;(baseCollection); var transformedCollection = new TransformedCollection&lt;int, int&gt;(readOnlyCollection, Double); transformedCollection.CollectionChanged += (sender, args) =&gt; { Assert.Same(transformedCollection, sender); Assert.Equal(NotifyCollectionChangedAction.Add, args.Action); //Keep track of the events startIndices.Add(args.NewStartingIndex); newItems.Add(args.NewItems); }; Assert.Equal(0, startIndices.Count); baseCollection.Add(1); Assert.Equal(1, transformedCollection.Count); Assert.Equal(2, transformedCollection.First()); //Check the events Assert.Equal(1, startIndices.Count); Assert.Equal(0, startIndices.First()); Assert.Equal(1, newItems.First().Count); Assert.Equal(2, newItems.First()[0]); baseCollection.Add(2); Assert.Equal(2, transformedCollection.Count); Assert.Equal(2, transformedCollection.First()); Assert.Equal(4, transformedCollection.ElementAt(1)); //Check the events Assert.Equal(2, startIndices.Count); Assert.Equal(1, startIndices.ElementAt(1)); Assert.Equal(1, newItems.ElementAt(1).Count); Assert.Equal(4, newItems.ElementAt(1)[0]); } [Fact] public void RemoveElementTest() { var startIndices = new List&lt;int&gt;(); var oldItems = new List&lt;IList&gt;(); var baseCollection = new ObservableCollection&lt;int&gt;(); baseCollection.Add(1); baseCollection.Add(2); baseCollection.Add(3); var readOnlyCollection = new ReadOnlyObservableCollection&lt;int&gt;(baseCollection); var transformedCollection = new TransformedCollection&lt;int, int&gt;(readOnlyCollection, Double); transformedCollection.CollectionChanged += (sender, args) =&gt; { Assert.Same(transformedCollection, sender); Assert.Equal(NotifyCollectionChangedAction.Remove, args.Action); //Keep track of the events startIndices.Add(args.OldStartingIndex); oldItems.Add(args.OldItems); }; Assert.Equal(3, transformedCollection.Count); Assert.Equal(0, startIndices.Count); Assert.Equal(2, transformedCollection.First()); Assert.Equal(4, transformedCollection.ElementAt(1)); Assert.Equal(6, transformedCollection.ElementAt(2)); baseCollection.RemoveAt(1); Assert.Equal(2, transformedCollection.Count); Assert.Equal(2, transformedCollection.First()); Assert.Equal(6, transformedCollection.ElementAt(1)); //Check the events Assert.Equal(1, startIndices.Count); Assert.Equal(1, startIndices[0]); Assert.Equal(1, oldItems.First().Count); Assert.Equal(4, oldItems.First()[0]); baseCollection.Remove(1); Assert.Equal(1, transformedCollection.Count); Assert.Equal(6, transformedCollection.First()); //Check the events Assert.Equal(2, startIndices.Count); Assert.Equal(0, startIndices[1]); Assert.Equal(1, oldItems.ElementAt(1).Count); Assert.Equal(2, oldItems.ElementAt(1)[0]); baseCollection.RemoveAt(0); Assert.Equal(0, transformedCollection.Count); //Check the events Assert.Equal(3, startIndices.Count); Assert.Equal(0, startIndices[2]); Assert.Equal(1, oldItems.ElementAt(2).Count); Assert.Equal(6, oldItems.ElementAt(2)[0]); } [Fact] public void ClearCollectionTest() { var addStartIndices = new List&lt;int&gt;(); var actions = new List&lt;NotifyCollectionChangedAction&gt;(); var baseCollection = new ObservableCollection&lt;int&gt;(); baseCollection.Add(1); baseCollection.Add(2); baseCollection.Add(3); var readOnlyCollection = new ReadOnlyObservableCollection&lt;int&gt;(baseCollection); var transformedCollection = new TransformedCollection&lt;int, int&gt;(readOnlyCollection, Double); transformedCollection.CollectionChanged += (sender, args) =&gt; { Assert.Same(transformedCollection, sender); actions.Add(args.Action); switch (args.Action) { case NotifyCollectionChangedAction.Add: addStartIndices.Add(args.NewStartingIndex); break; case NotifyCollectionChangedAction.Reset: //All we need to do is keep track that it happened, which we already do above //(outside the switch statement) break; default: Assert.True(false, "Unexpected event type: " + args.Action); break; } }; Assert.Equal(3, transformedCollection.Count); Assert.Equal(0, actions.Count); baseCollection.Clear(); Assert.Equal(0, transformedCollection.Count); //Check the events Assert.Equal(1, actions.Count); Assert.Equal(NotifyCollectionChangedAction.Reset, actions[0]); baseCollection.Add(1); Assert.Equal(1, transformedCollection.Count); Assert.Equal(2, transformedCollection.ElementAt(0)); //Check the events Assert.Equal(2, actions.Count); Assert.Equal(NotifyCollectionChangedAction.Add, actions[1]); Assert.Equal(1, addStartIndices.Count); Assert.Equal(0, addStartIndices[0]); baseCollection.Clear(); Assert.Equal(0, transformedCollection.Count); //Check the events Assert.Equal(3, actions.Count); Assert.Equal(NotifyCollectionChangedAction.Reset, actions[2]); } [Fact] public void SetItemCollectionTest() { var oldStartIndices = new List&lt;int&gt;(); var newStartIndices = new List&lt;int&gt;(); var oldItems = new List&lt;IList&gt;(); var newItems = new List&lt;IList&gt;(); var baseCollection = new ObservableCollection&lt;int&gt;(); baseCollection.Add(1); baseCollection.Add(2); baseCollection.Add(3); var readOnlyCollection = new ReadOnlyObservableCollection&lt;int&gt;(baseCollection); var transformedCollection = new TransformedCollection&lt;int, int&gt;(readOnlyCollection, Double); transformedCollection.CollectionChanged += (sender, args) =&gt; { Assert.Same(transformedCollection, sender); Assert.Equal(NotifyCollectionChangedAction.Replace, args.Action); //Keep track of the events oldStartIndices.Add(args.OldStartingIndex); newStartIndices.Add(args.NewStartingIndex); oldItems.Add(args.OldItems); newItems.Add(args.NewItems); }; Assert.Equal(0, oldStartIndices.Count); baseCollection[0] = 10; Assert.Equal(3, transformedCollection.Count); Assert.Equal(20, transformedCollection.ElementAt(0)); Assert.Equal(4, transformedCollection.ElementAt(1)); Assert.Equal(6, transformedCollection.ElementAt(2)); //Check the events Assert.Equal(1, oldStartIndices.Count); Assert.Equal(0, oldStartIndices[0]); Assert.Equal(0, newStartIndices[0]); Assert.Equal(1, oldItems[0].Count); Assert.Equal(2, oldItems[0][0]); Assert.Equal(1, newItems[0].Count); Assert.Equal(20, newItems[0][0]); baseCollection[2] = 20; Assert.Equal(3, transformedCollection.Count); Assert.Equal(20, transformedCollection.ElementAt(0)); Assert.Equal(4, transformedCollection.ElementAt(1)); Assert.Equal(40, transformedCollection.ElementAt(2)); //Check the events Assert.Equal(2, oldStartIndices.Count); Assert.Equal(2, oldStartIndices[1]); Assert.Equal(2, newStartIndices[1]); Assert.Equal(1, oldItems[1].Count); Assert.Equal(6, oldItems[1][0]); Assert.Equal(1, newItems[1].Count); Assert.Equal(40, newItems[1][0]); } [Fact] public void MoveElementTest() { var baseCollection = new ObservableCollection&lt;int&gt;(); baseCollection.Add(1); baseCollection.Add(2); baseCollection.Add(3); baseCollection.Add(4); baseCollection.Add(5); var readOnlyCollection = new ReadOnlyObservableCollection&lt;int&gt;(baseCollection); var transformedCollection = new TransformedCollection&lt;int, int&gt;(readOnlyCollection, Double); int events = 0; transformedCollection.CollectionChanged += (sender, args) =&gt; { events++; Assert.Equal(1, events); Assert.Same(transformedCollection, sender); Assert.Equal(1, args.NewItems.Count); Assert.Equal(1, args.OldItems.Count); Assert.Equal(4, args.NewItems[0]); Assert.Equal(4, args.OldItems[0]); Assert.Equal(2, args.NewStartingIndex); Assert.Equal(1, args.OldStartingIndex); }; baseCollection.Move(1, 2); Assert.Equal(5, transformedCollection.Count); Assert.Equal(2, transformedCollection.ElementAt(0)); Assert.Equal(6, transformedCollection.ElementAt(1)); Assert.Equal(4, transformedCollection.ElementAt(2)); Assert.Equal(8, transformedCollection.ElementAt(3)); Assert.Equal(10, transformedCollection.ElementAt(4)); } } } </code></pre> <p>I am using only runtime code contract verifications (that is, the static analyzer is turned off).</p> <p>I am currently satisfied with the current state of the code, but I want to see opinions from other programmers to cover any ground I may have missed. </p> <p><strong>I am looking for reviews in the following areas</strong>:</p> <ul> <li>Am I doing this right? That is: <ul> <li>Do you find this class useful?</li> <li>Is there a built-in .NET class that already does this (or something very similar)?</li> </ul></li> <li>Am I using <code>IReadOnlyCollection</code> and <code>INotifyCollectionChanged</code> right? Should I implement any other interfaces?</li> <li>Am I doing unit tests right? Are they sufficiently comprehensive?</li> <li>How is the code quality in general? Is it obvious what each part of the code does? Are the comments easy to understand?</li> <li>Is the documentation of the class and public members (that aren't already documented in implemented interfaces) correct? Is it obvious how the class and its methods should be used?</li> <li>Are the variable, method and class names appropriate?</li> <li>Pretty much anything else you might find relevant.</li> </ul>
[]
[ { "body": "<p><strong>Raising Events</strong> </p>\n\n<p>The default pattern for rasing events is to create a <code>protected void OnNameOfTheEvent(EventArguments)</code> method (without the sender parameter). Like </p>\n\n<pre><code>protected virtual void OnCollectionChanged(NotifyCollectionChangedEventArgs e)\n{\n if (CollectionChanged != null)\n {\n CollectionChanged(this, e);\n }\n} \n</code></pre>\n\n<p>in this way it can be overridden by a derived class, so the sender <code>this</code> won't be the base object. </p>\n\n<p><strong>InnerCollectionChanged()</strong> </p>\n\n<p>This eventhandler is doing a little bit too much and the code is too long (IMHO). You should split the actions to separate methods. </p>\n\n<p>which would result in </p>\n\n<pre><code>private IList&lt;TargetType&gt; GetNewItems(IList items)\n{\n IList&lt;TargetType&gt; newItems = new List&lt;TargetType&gt;();\n foreach (object item in items)\n {\n TargetType transformedElement = transformationFunction((InnerType)item);\n newItems.Add(transformedElement);\n }\n\n return newItems;\n}\nprivate IList&lt;TargetType&gt; GetItemsToBeRemoved(IList items, int startIndex)\n{\n IList&lt;TargetType&gt; itemsToBeRemoved = new List&lt;TargetType&gt;();\n int endIndex = items.Count + startIndex;\n for (int i = startIndex; i &lt; endIndex; ++i)\n {\n itemsToBeRemoved.Add(transformedValues[i]);\n }\n return itemsToBeRemoved;\n}\nprivate IList&lt;TargetType&gt; GetItemsToBeReplaced(IList items, int startIndex)\n{\n IList&lt;TargetType&gt; itemsToBeReplaced = new List&lt;TargetType&gt;();\n int endIndex = items.Count + startIndex;\n for (int i = startIndex; i &lt; endIndex; ++i)\n {\n itemsToBeReplaced.Add(transformedValues[i]);\n }\n return itemsToBeReplaced;\n}\nprivate void InternalReplace(IList&lt;TargetType&gt; replacementItems, int startIndex)\n{\n for (int i = 0; i &lt; replacementItems.Count; ++i)\n {\n transformedValues[i + startIndex] = replacementItems[i];\n }\n}\nprivate IList&lt;TargetType&gt; GetToBeReplacedItems(int startIndex, int count)\n{\n IList&lt;TargetType&gt; itemsToBeReplaced = new List&lt;TargetType&gt;();\n for (int i = startIndex; i &lt; startIndex + count; i++)\n {\n itemsToBeReplaced.Add(transformedValues[i]);\n }\n return itemsToBeReplaced;\n}\nprivate void InternalMove(int sourceIndex, int destinationIndex)\n{\n TargetType valueAtOldIndex = transformedValues[sourceIndex];\n\n transformedValues[sourceIndex] = transformedValues[destinationIndex];\n transformedValues[destinationIndex] = valueAtOldIndex;\n\n}\nprivate void InnerCollectionChanged(object sender, NotifyCollectionChangedEventArgs e)\n{\n NotifyCollectionChangedEventArgs eventArgs;\n\n switch (e.Action)\n {\n case NotifyCollectionChangedAction.Add:\n IList&lt;TargetType&gt; itemsToAdd = GetNewItems(e.NewItems);\n transformedValues.InsertRange(e.NewStartingIndex, itemsToAdd);\n eventArgs = new NotifyCollectionChangedEventArgs(NotifyCollectionChangedAction.Add, itemsToAdd, e.NewStartingIndex);\n break;\n\n case NotifyCollectionChangedAction.Remove:\n IList&lt;TargetType&gt; itemsToBeRemoved = GetItemsToBeRemoved(e.OldItems, e.OldStartingIndex);\n transformedValues.RemoveRange(e.OldStartingIndex, e.OldItems.Count);\n eventArgs = new NotifyCollectionChangedEventArgs(NotifyCollectionChangedAction.Remove, itemsToBeRemoved, e.OldStartingIndex);\n break;\n\n case NotifyCollectionChangedAction.Replace:\n\n IList&lt;TargetType&gt; replacementItems = GetNewItems(e.NewItems);\n IList&lt;TargetType&gt; toBeReplacedItems = GetToBeReplacedItems(e.NewStartingIndex, e.NewItems.Count);\n InternalReplace(replacementItems, e.NewStartingIndex);\n eventArgs = new NotifyCollectionChangedEventArgs(NotifyCollectionChangedAction.Replace, replacementItems, toBeReplacedItems, e.NewStartingIndex);\n break;\n\n case NotifyCollectionChangedAction.Reset:\n transformedValues.Clear();\n CreateCollection();\n eventArgs = new NotifyCollectionChangedEventArgs(NotifyCollectionChangedAction.Reset);\n break;\n\n case NotifyCollectionChangedAction.Move:\n if (e.NewItems.Count != 1)\n {\n throw new NotImplementedException(\"No idea how this is supposed to work\");\n }\n\n IList&lt;TargetType&gt; movedItems = new List&lt;TargetType&gt;();\n movedItems.Add(transformedValues[e.OldStartingIndex]);\n InternalMove(e.OldStartingIndex, e.NewStartingIndex);\n eventArgs = new NotifyCollectionChangedEventArgs(NotifyCollectionChangedAction.Move, movedItems, e.NewStartingIndex, e.OldStartingIndex);\n break;\n\n default:\n throw new InvalidOperationException();\n }\n OnCollectionChanged(eventArgs);\n} \n</code></pre>\n\n<p>and you now have small little methods which you can also test. </p>\n\n<p><strong>Tests</strong> </p>\n\n<p>You have a lot of <code>Asserts</code> in your tests. Usually it is seen as <code>bad practice</code> to assert to much. See: <a href=\"https://softwareengineering.stackexchange.com/q/7823/100919\">https://softwareengineering.stackexchange.com/q/7823/100919</a></p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-12-30T16:33:40.410", "Id": "75250", "ParentId": "21317", "Score": "2" } }, { "body": "<p>There is <strong><em>way</em></strong> too much going on insider of <code>InnerCollectionChanged</code>. That method is 98 lines of code. This breaks the \"Single Screen Principle\" by roughly 3 times. What's the Single Screen Principle? It's the idea that any one given method should fit neatly on the screen at once. If you have to scroll to see the rest of the code, there's too much going on and it's very likely that the Single Responsibility Principle is being broken as well.</p>\n\n<p>In fact, <code>InnerCollectionChanged</code> does exactly five different things. It handles the <code>NotifyCollectionChangedAction</code> <code>Add</code>, <code>Remove</code>, <code>Replace</code>, <code>Move</code> and <code>Reset</code> actions. All of the code in each of these cases should be extracted into their own methods. <code>InnerCollectionChanged</code> should look something like this afterward.</p>\n\n<pre><code> private void InnerCollectionChanged(object sender, NotifyCollectionChangedEventArgs e)\n {\n switch (e.Action)\n {\n case NotifyCollectionChangedAction.Add:\n HandleAddAction();\n break;\n case NotifyCollectionChangedAction.Remove:\n HandleRemoveAction();\n break;\n case NotifyCollectionChangedAction.Replace:\n HandleReplaceAction();\n break;\n case NotifyCollectionChangedAction.Reset:\n HandleResetAction();\n break;\n case NotifyCollectionChangedAction.Move:\n HandleMoveAction();\n break;\n default:\n throw new InvalidOperationException();\n }\n }\n</code></pre>\n\n<p>One screen. One job. No scrolling.\nImmediately understandable.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-12-31T12:58:13.733", "Id": "75342", "ParentId": "21317", "Score": "4" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-02-04T22:09:24.313", "Id": "21317", "Score": "6", "Tags": [ "c#" ], "Title": "Mapping ReadOnlyObservableCollection to another collection" }
21317
<p>You can see the JavaScript at the end of this post in action <a href="http://andrew-oh.com/portfolio/timeline/" rel="nofollow">here</a>.</p> <p>I've recently picked up JavaScript/jQuery and would love some feedback on how I'm implementing this functionality. As you can see, the <code>li</code> items in the navbar change based on where the user's scroll position is.</p> <p>Is this an efficient way of implementing this? Am I using best practice?</p> <p>I've already learned from posting a similar question on Reddit to cache objects in variables, that jQuery reads selectors from right to left, and that I should use <code>preventDefault()</code> instead of <code>return false</code>. Is there anything else I should do to improve my JavaScript/jQuery skills?</p> <pre><code>jQuery(function ($) { "use strict"; //don't know what this means but JSHint tells me to put this here... var $decTops = [], $decHeights = [], mobileView = 780, $i = 0, $nav = $("#navigation"), $decadeDivs = $("div.decade"), $timeline = $("#timeline"); // caching various elements in var names function coordsUpdate() { // updates where each decade starts and how long the decade's div is everytime the user scrolls/resizes the window and pushes those values to two arrays $decTops.length = 0, $decHeights.length = 0; $decadeDivs.each(function() { $decTops.push($(this).offset().top-51); $decHeights.push($(this).outerHeight(true)); }); $decTops.push($("#footer-wrapper").offset().top-21); // bugfix: push the footer's position to the array as well to avoid the disappearing navbar bug. } function decadeCounter() { // counts which decade the user is on based on scrollTop position var $currentLoc = $(window).scrollTop(); while ($currentLoc &gt; $decTops[$i] + $decHeights[$i]) { $i++; } while ($currentLoc &gt; $decTops[0] &amp;&amp; $currentLoc &lt; $decTops[$i]) { $i--; } navAdjust($i, $currentLoc); //console.log('currentHeight: ' + $(window).scrollTop() + ', decTops: ' + $decTops + ', decHeights: ' + $decHeights); //console.log('$i: ' + $i + ', $old: ' + $old); } function navAdjust($i, $currentLoc) { //fix the navbar to the top and highlight the correct decade in the navbar or fix the decade header to top if using mobile viewport. if ($(window).width() &gt;= mobileView) { $timeline.find("div.top-fix").removeClass("top-fix"); //don't want the decade headers on top if using desktop viewport if ($currentLoc &gt;= $decTops[0] &amp;&amp; $i &lt;= 6) { $nav.addClass("fixed-nav").removeClass("nav-width-fix"); $nav.find("a.active").removeClass("active"); $nav.find("a:eq(" + $i + ")").addClass("active"); } else { //unfix navbar if user is on top of page or at bottom $nav.removeClass("fixed-nav").addClass("nav-width-fix"); $nav.find("a.active").removeClass("active"); } } else { if ($currentLoc &gt;= $decTops[0]) { //don't want the navbar on top if using mobile viewport $timeline.find(".top-fix").removeClass("top-fix").removeClass("top-fix"); $timeline.find(".decade:eq(" + $i + ") .dec-banner").addClass("top-fix"); } else { $timeline.find("div.top-fix").removeClass("top-fix"); } } } $nav.on("click", "a", function() { // bring user to specific decade if clicked on in the main navbar $nav.find("a.active").removeClass("active"); var $navlink = $(this).attr("href"); $('html,body').stop().animate({scrollTop: $($navlink).offset().top},"fast"); return false; }); $timeline.find(".dec-banner").on("click", "a", function(event) { // bring user to previous or next decade if clicked on in the decade header var $navlink = $(this).attr("href"); if ($(this).parent().hasClass("decade-jump-prev")) { $("html,body").stop().animate({scrollTop: $($navlink).offset().top-41},"fast"); } if ($(this).parent().hasClass("decade-jump-next")) { $("html,body").stop().animate({scrollTop: $($navlink).offset().top+10},"fast"); } event.preventDefault(); }); // add listener $(window).on('load orientationchange resize', coordsUpdate); $(window).on('scroll load orientationchange resize', decadeCounter); }); </code></pre>
[]
[ { "body": "<blockquote>\n <p>Is there anything else I should do to improve my JS/Jquery skills?</p>\n</blockquote>\n\n<p><strong>Self-invoking Anonymous Function</strong></p>\n\n<pre><code>(function ( $, window, undefined ) {\n doStuff();\n})( jQuery, window );\n</code></pre>\n\n<p>The extra <code>()</code> at the end of the function, determines that it runs itself immediately.</p>\n\n<p>First, we are creating a self-invoking anonymous function to shield ourselves from using global variables. We pass in $, window, and undefined. </p>\n\n<p>The arguments the self invoking function is called with are jQuery and window; nothing is passed in for undefined, so that if we decide to use the undefined keyword within the plugin, “undefined” actually will be undefined. This shields from other scripts potentially assigning a malicious value to undefined, such as true! </p>\n\n<p>Now since ECMAScript 5 the \"Immutable undefined\" came along which is meant to protect you from exactly that. But as you can see from the answers to this <a href=\"https://stackoverflow.com/questions/14567055/immutable-undefined-in-self-invoking-functions/14567661#14567661\">recent question</a> I asked myself, this is not the case yet.</p>\n\n<p>$ is passed as jQuery; we do it this way to ensure that, outside of the anonymous function, $ can still refer to something else entirely, such as Prototype.</p>\n\n<p>Passing the variable for the globally accessible window object allows for more compressed code through the minification processes (which you should be doing, as well).</p>\n\n<pre><code>(function(b,a,c){doStuff()})(jQuery,window); //Same function after being compressed.\n</code></pre>\n\n<p>Thus every time you refer to <code>window</code> in your code, when compressed it can be replaced with a simple <code>a</code>(or any other letter for that matter) and depending on how much you use it, will improve your performance.</p>\n\n<p><strong>Use-Strict Mode</strong></p>\n\n<p>You should try to understand the reason why a declaration is used and not simply because someone is telling you to. JSHint isn't really a bible you should follow to the death. I'm not saying you shouldn't use it (you probably should use it), I'm saying that it's a good idea to study the \"hints\" it's giving you, and determine whether or not to use them. </p>\n\n<p>In this case I highly recomend that you <strong>do use</strong> the strict mode. It will many times force you to write better code if you understand how it works. </p>\n\n<p>As Nicholas C. Zakas puts it:</p>\n\n<p>\"Strict mode makes a lot of changes to how JavaScript runs. The intent is to allow developers to opt-in to a “better” version of JavaScript.\"</p>\n\n<p>Here is the link to his article which might help you understand.\n<a href=\"http://www.nczonline.net/blog/2012/03/13/its-time-to-start-using-javascript-strict-mode/\" rel=\"nofollow noreferrer\">http://www.nczonline.net/blog/2012/03/13/its-time-to-start-using-javascript-strict-mode/</a></p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-02-12T20:59:44.280", "Id": "34772", "Score": "0", "body": "Thank you for the detailed answers! I'll be sure to read up on the resources you linked" } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-02-07T16:26:12.203", "Id": "21433", "ParentId": "21323", "Score": "5" } } ]
{ "AcceptedAnswerId": "21433", "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-02-05T00:38:49.167", "Id": "21323", "Score": "4", "Tags": [ "javascript", "jquery", "performance", "beginner", "html" ], "Title": "Highlighting a nav list item based on the user's scroll position in that same page" }
21323
<p>I've been experimenting with the Express Node.js framework. On the face of it, the approach of passing functions to <code>app.VERB</code> methods seems unusual. In other frameworks I've used (in languages other than javascript), you create a single handler class for each url pattern, with methods representing different HTTP verbs. One advantage is the ability to bundle common functionality in methods of superclasses.</p> <p>I've tried to replicate this in node, but I'm interested in feedback on whether this seem like a good approach.</p> <p>(I realise that the naming of "as_view" doesn't make much sense - I just named it that way because I'm used to django, where the term "view" is used to refer to something akin to a controller rather than a template.)</p> <pre><code>function Controller(verbs) { for (verb in verbs) { this[verb] = verbs[verb]; } } Controller.prototype.as_view = function() { var dispatcher = function(req, res) { var verb = req.method.toLowerCase(); this[verb](req, res); }; return dispatcher.bind(this); }; var pageone = new Controller({ get: function(req, res) { res.send("Get request"); }, post: function(req, res) { res.send("Post request"); } }); .... app.all('/pageone', pageone.as_view()); .... </code></pre>
[ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-03-09T16:26:39.043", "Id": "75900", "Score": "0", "body": "You might want to take a look at express.js version 4. There is a function called `route` in the router. http://expressjs.com/4x/api.html#router.route" } ]
[ { "body": "<p>This looks good to me,</p>\n\n<ul>\n<li>As you mentioned, <code>as_view</code> stands out a bit, but I see where you are coming from</li>\n<li>I am not sure why you do not declare <code>GET</code> and <code>POST</code>, then you do not need to use <code>toLowerCase()</code>, are you worried the caller will now uppercase the verbs?</li>\n<li>You should think about error handling, you should have some framework for it</li>\n</ul>\n\n<p>All in all, I would still suggest that learning and using Express.js might be worth it.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-03-06T16:51:27.980", "Id": "43628", "ParentId": "21324", "Score": "3" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "1", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-02-05T01:02:43.160", "Id": "21324", "Score": "3", "Tags": [ "javascript", "node.js" ], "Title": "Node.js object-oriented controllers" }
21324
<p>I need to get from an array of booleans to a Flags enum.</p> <p>Here's what my enum looks like:</p> <pre><code>[Flags] public enum UserContactPreferences { None = 0, SMS = 1, Email = 2, Phone = 4 } </code></pre> <p>Here's what my parsing code looks like currently.</p> <pre><code>private UserContactPreferences GetContactPreferences(bool email, bool phone, bool sms) { var contactByEmail = email ? UserContactPreferences.Email : UserContactPreferences.None; var contactByPhone = phone ? UserContactPreferences.Phone : UserContactPreferences.None; var contactBySms = sms ? UserContactPreferences.SMS : UserContactPreferences.None; return contactByEmail | contactByPhone | contactBySms; } </code></pre> <p>That's horrible! I must be able to do better. Any ideas?</p>
[]
[ { "body": "<p>Well, you need some sort of mapping between the parameters and the <code>enum</code> values, so you can't actually avoid having three almost same pieces of code. But you can make your code shorter by using <code>if</code>s and <code>|=</code> instead of ternary operators:</p>\n\n<pre><code>private UserContactPreferences GetContactPreferences(bool email, bool phone, bool sms)\n{\n var preferences = UserContactPreferences.None;\n\n if (email)\n preferences |= UserContactPreferences.Email;\n if (phone)\n preferences |= UserContactPreferences.Phone;\n if (sms)\n preferences |= UserContactPreferences.SMS;\n\n return preferences;\n}\n</code></pre>\n\n<p>If you had more parameters (though that would be a code smell), it might be worth considering something like using a dictionary. But I'm not sure it's a good idea, it's certainly longer than the previous version:</p>\n\n<pre><code>private UserContactPreferences GetContactPreferences(bool email, bool phone, bool sms)\n{\n var dictionary = new Dictionary&lt;UserContactPreferences, bool&gt;\n {\n { UserContactPreferences.Email, email },\n { UserContactPreferences.Phone, phone },\n { UserContactPreferences.SMS, sms }\n };\n\n var preferences = UserContactPreferences.None;\n\n foreach (var kvp in dictionary)\n {\n if (kvp.Value)\n preferences |= kvp.Key;\n }\n\n return preferences;\n}\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-02-05T17:10:34.503", "Id": "34246", "Score": "0", "body": "Hmm... Of the two, I guess the |= solution works best for me. Thanks!" } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-02-05T09:43:53.617", "Id": "21332", "ParentId": "21331", "Score": "6" } } ]
{ "AcceptedAnswerId": "21332", "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-02-05T09:27:58.387", "Id": "21331", "Score": "4", "Tags": [ "c#", "enum" ], "Title": "Parse Flags enum from array of booleans" }
21331
<p>Im currently working on a system that will communicate with other systems via webservice (or some sort of communication). I have a system that stores all user data already and don't want to duplicate data in this new system so I have come up with a way of accessing the data when needed. </p> <p>In my current system I am planning to just store the user ID from the user system and fetch the data when required. My question is, is the following code considered acceptable/understood or would you suggest an alternative way of achieving this?</p> <pre class="lang-cs prettyprint-override"><code>public class Person { private string id; [Transient] private string name; [Transient] private bool isPopulated; public Person(string id){ this.id = id; } public string Id{get;set;} public string Name{ get{ init(); return this.name; } set{ this.name = value; } } private void init(){ if(!isPopulated){ TempPerson tempPerson = UserService.getPerson(this.id); this.name = tempPerson.Name; this.isPopulated = true; } } } </code></pre> <p>Is there a better way to do this and are there any problem with this way?</p>
[]
[ { "body": "<p>As a matter of opinion without knowing exactly what you would like to achieve, I can see some potential issues.</p>\n<ul>\n<li><p>Name doesn't need a set option (except if you are populating back to the source which is not shown here), otherwise it would just cause confusion.</p>\n</li>\n<li><p>You are caching name, not retrieving again from the source for the whole life of the object, that would obviously be a problem if the source change. I don't think this is a good option, retrieving every time if possible or at least keep a expiry time for the information retrieved would help.</p>\n</li>\n<li><p>Lately if you need this there are already tools that manage this and are well proved (NHibernate for instance), maybe is better take a look at them.</p>\n<p>Regards,</p>\n</li>\n</ul>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-02-05T17:13:28.900", "Id": "34247", "Score": "0", "body": "I don't think I understand your first point. With regards to the second, the life of the object isn't going to be very long and during that time the chance of the source changing is highly unlikely. I will look into NHibernate. Thank you :)" } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-02-05T14:58:12.543", "Id": "21339", "ParentId": "21334", "Score": "0" } }, { "body": "<p>What you have implemented is a sort of Active Record where the record itself knows how to communicate with the storage. </p>\n\n<p>What is bad about your design is that this kind of code will be extremely hard to unit test. Imagine that you need to write a unit test for a class that uses <code>Person</code> objects. How can you prevent it from calling <code>UserService</code>?</p>\n\n<p>The proper solution for your problem depends on use cases. </p>\n\n<ul>\n<li>Will you need to update your entities and propagate those changes back to server? </li>\n<li>Can you load several entities at once using methods other than <code>UserService.getPerson(this.id);</code>?</li>\n<li>What is the lifetime of the entities loaded?</li>\n</ul>\n\n<p>Generally the most flexible solution (as I see it) would be to implement a repository and unit-of-work pattern (similar to <code>ISession</code> in NHibernate or <code>DbContext</code> in Entity Framework). Basically it's better not to hide communication with 3rd-party but rather expose it in such a way that you have maximum control and flexibility.</p>\n\n<p>Primitive implementation may look like:</p>\n\n<pre><code>public class Person\n{\n public string Id { get; set; }\n\n public string Name { get; set; }\n}\n\npublic interface ISessionFactory\n{\n IUserServiceSession CreateSession();\n}\n\npublic interface IUserServiceSession\n{\n Person GetPerson(string id);\n}\n\npublic class SessionFactory : ISessionFactory\n{\n public IUserServiceSession CreateSession()\n {\n UserService userService = new UserService(); //better use dependency injection, or cache it once if it's thread-safe.\n return new UserServiceSession(userService);\n }\n}\n\npublic class UserServiceSession : IUserServiceSession\n{\n private readonly Dictionary&lt;string, Person&gt; _cache = new Dictionary&lt;string, Person&gt;();\n private readonly UserService _userService;\n\n public UserServiceSession(UserService userService)\n {\n _userService = userService;\n }\n\n public Person GetPerson(string id)\n {\n Person result;\n if (!_cache.TryGetValue(id, out result))\n result = _cache[id] = _userService.getPerson(id);\n\n return result;\n }\n}\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-02-06T12:56:40.800", "Id": "34311", "Score": "0", "body": "I like this approach. I've modified my code since to provide two Person classes, one is the base Person class that simply contains what needs to be persisted to the local database and another PersonFull class that acts as a view class that fetches the data from the service.\n\nWith regards to your questions: no data will be pushed back to the remote server, it is simply lookup. There are methods to load several at once and would likely need to go down this route if performance becomes an issue and finally the lifespan isnt going to be more than a few hours." } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-02-06T10:59:31.527", "Id": "21370", "ParentId": "21334", "Score": "2" } } ]
{ "AcceptedAnswerId": "21370", "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-02-05T11:37:43.597", "Id": "21334", "Score": "1", "Tags": [ "c#", "design-patterns" ], "Title": "Populating a class whose data is stored in an external application" }
21334
<p>I needed a task scheduler that could be used somehow like this:</p> <pre><code>#include &lt;iostream&gt; // To compile and run this example, include here the code listed in the second code block void Task2() { std::cout &lt;&lt; "OK2 ! now is " &lt;&lt; std::chrono::system_clock::now().time_since_epoch().count() &lt;&lt; std::endl; } void Task3() { std::cout &lt;&lt; "--3 " &lt;&lt; std::endl; } void Task1(Scheduler &amp; sch) { auto now = std::chrono::system_clock::now(); std::cout &lt;&lt; "OK1 ! now is " &lt;&lt; now.time_since_epoch().count() &lt;&lt; std::endl; sch.ScheduleAt(now + std::chrono::seconds(1), []{ Task2(); }); sch.ScheduleAt(now + std::chrono::seconds(2), []{ Task2(); }); sch.ScheduleAt(now + std::chrono::seconds(3), []{ Task2(); }); } void main() { auto now = std::chrono::system_clock::now(); Scheduler sch; sch.ScheduleAt(now + std::chrono::seconds(15), [&amp;sch]{ Task1(sch); }); sch.ScheduleAt(now + std::chrono::seconds(20), [&amp;sch]{ Task1(sch); }); sch.ScheduleAt(now + std::chrono::seconds(25), [&amp;sch]{ Task1(sch); }); sch.ScheduleAt(now + std::chrono::seconds( 2), [&amp;sch]{ Task2(); }); sch.ScheduleEvery(std::chrono::seconds(1), []{ Task3(); }); getchar(); } </code></pre> <p>It had to have tasks scheduled once and repetitive tasks, and should stop and clean itself up gracefully on destruction even while running. I did not care for parallelism: tasks that should run in their own threads should manage it. It had to accept lambdas for simplicity.</p> <p>I could not find anything similar in Boost or POCO, though I did not search very hard as I was interested in writing it myself. There are some related questions in C#, but I need C++.</p> <pre><code>#include &lt;map&gt; #include &lt;functional&gt; #include &lt;chrono&gt; #include &lt;mutex&gt; #include &lt;thread&gt; #include &lt;condition_variable&gt; #include &lt;memory&gt; #include &lt;boost/noncopyable.hpp&gt; class Scheduler : boost::noncopyable { private: std::multimap&lt;std::chrono::system_clock::time_point, std::function&lt;void()&gt;&gt; tasks; std::mutex mutex; std::unique_ptr&lt;std::thread&gt; thread; std::condition_variable blocker; bool go_on; public: Scheduler() :go_on(true) { thread.reset(new std::thread([this](){ this-&gt;ThreadLoop(); })); } ~Scheduler() { go_on = false; ScheduleAt(std::chrono::system_clock::now(), [](){}); thread-&gt;join(); } void ThreadLoop() { while(go_on) { std::function&lt;void()&gt; todo; { std::unique_lock&lt;std::mutex&gt; lock(mutex); auto now = std::chrono::system_clock::now(); if ( tasks.empty()==false &amp;&amp; tasks.begin()-&gt;first &lt;= now) { todo = tasks.begin()-&gt;second; tasks.erase(tasks.begin()); } } // Run tasks while unlocked so tasks can schedule new tasks if (todo) todo(); { std::unique_lock&lt;std::mutex&gt; lock(mutex); if (tasks.empty()) blocker.wait(lock); else blocker.wait_until(lock, tasks.begin()-&gt;first); } } } void ScheduleAt(std::chrono::system_clock::time_point &amp; time, std::function&lt;void()&gt; func) { std::unique_lock&lt;std::mutex&gt; lock(mutex); auto it = tasks.insert(std::make_pair(time, func)); if (it == tasks.begin()) blocker.notify_one(); } void ScheduleEvery(std::chrono::system_clock::duration interval, std::function&lt;void()&gt; func) { std::function&lt;void()&gt; waitFunc = [this,interval,func]() { func(); this-&gt;ScheduleEvery(interval, func); }; ScheduleAt(std::chrono::system_clock::now() + interval, waitFunc); } }; </code></pre> <p><strong>Notes:</strong></p> <p>I am not concerned with performance but I'll still take free lunches, like trading <code>std::function</code> for another faster type.</p> <p>I'm using VS2012 Express.</p> <p>If a task takes time, other tasks may run belated. Such tasks should run in their own thread or be posted in an io_service or such. In any case, the caller (of <code>ScheduleAt</code> or <code>ScheduleEvery</code>) should take care of this.</p> <p>Questions:</p> <ol> <li>What do you think?</li> <li>Are there drawbacks or pitfalls I did not see?</li> <li>Do other libs like Boost have something similar that I should use instead?</li> <li>Are there race conditions I missed?</li> <li>Is the destructor correct, especially the <code>bool</code> thing? I thought of using <code>volatile</code> here but the Wikipedia article about <code>volatile</code> had me convinced otherwise.</li> </ol>
[ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2016-05-21T19:02:27.367", "Id": "241230", "Score": "1", "body": "A few notes:\n*(1) You can use std::thread directly (no pointer), especially since your class is not copyable. *(2) std::function allows to capture context, that can potentially be heavy, you can do `todo = std::move(tasks.begin()->second)` to avoid copying the context" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2016-05-21T19:09:59.353", "Id": "241231", "Score": "1", "body": "*(3) for the same reason, you may take rvalue references for std::function and std::move() emplacing them in the multimap." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2016-05-21T19:13:37.607", "Id": "241233", "Score": "1", "body": "note: those comments assume you moved to a newer version of VS" } ]
[ { "body": "<p>So a couple of minor issues first:</p>\n<pre><code>void main()\n</code></pre>\n<p>Argh, bad. Someone who can write this should know better!</p>\n<p>There's a problem with your <code>ScheduleAt</code> function. You're passing in an rvalue reference to time, and trying to bind this to a non-const lvalue reference. Visual Studio has some (evil) extensions that let you get away with this, however, this isn't portable, and should be one of:</p>\n<pre><code>void ScheduleAt(const std::chrono::system_clock::time_point&amp; time, std::function&lt;void()&gt; func)\n\nvoid ScheduleAt(std::chrono::system_clock::time_point&amp;&amp; time, std::function&lt;void()&gt; func)\n</code></pre>\n<p>Finally, a (very) minor point: why introduce a dependency on boost simply for <code>non-copyable</code>? It's all of 2 lines in C++11:</p>\n<pre><code> Scheduler&amp; operator=(const Scheduler&amp; rhs) = delete;\n Scheduler(const Scheduler&amp; rhs) = delete;\n</code></pre>\n<p>Not only that, but it doesn't disallow move operations. Hence:</p>\n<pre><code>Scheduler&amp; operator=(Schedular&amp;&amp; rhs);\nScheduler(Schedular&amp;&amp; rhs);\n</code></pre>\n<p>are still accessible (and still generated). This may (or may not be) what you want.</p>\n<p>There may be a library that (sort of) does what you want, however, it is C, not C++: <a href=\"http://libevent.org/\" rel=\"noreferrer\">libevent</a>. I've never used it, so take this recommendation with a grain of salt.</p>\n<p>With what you have here, there won't be any race conditions, because you launch a <code>Scehduler</code> from the main thread, and this only ever creates one thread of its own. Further, this thread only performs sequential execution.</p>\n<p>Personally, this implementation has some extra pieces that don't seem to be needed; <s>the <code>mutex</code> and <code>condition_variable</code> only really there to signal when things should happen, not for any actual locking of shared mutable state. </s> Further (as you're probably aware), this likely won't work so well for any function which have a non-negligible execution time. The <code>getchar</code> at the end is a bit of a hack as well, you should probably launch this in its own thread.</p>\n<p>This implementation doesn't fix the part where long running functions will cause everything to get out of sync, but it doesn't rely on <code>mutex</code> or <code>condition_variable</code> where they aren't really needed. You could probably fix this by launching each <code>func()</code> call in its own thread if you wanted to. I've opted to use a <code>priority_queue</code> instead of a <code>multimap</code> as well:</p>\n<pre><code>#include &lt;functional&gt;\n#include &lt;chrono&gt;\n#include &lt;future&gt;\n#include &lt;queue&gt;\n#include &lt;thread&gt;\n#include &lt;memory&gt;\n\nstruct function_timer\n{\n std::function&lt;void()&gt; func;\n std::chrono::system_clock::time_point time;\n\n function_timer()\n { }\n\n function_timer(std::function&lt;void()&gt;&amp;&amp; f, std::chrono::system_clock::time_point&amp; t)\n : func(f), \n time(t)\n { }\n\n //Note: we want our priority_queue to be ordered in terms of\n //smallest time to largest, hence the &gt; in operator&lt;. This isn't good\n //practice - it should be a separate struct - but I've done this for brevity.\n bool operator&lt;(const function_timer&amp; rhs) const\n {\n return time &gt; rhs.time;\n }\n\n void get()\n {\n func();\n }\n};\n\nclass Scheduler\n{\nprivate:\n std::priority_queue&lt;function_timer&gt; tasks;\n std::unique_ptr&lt;std::thread&gt; thread;\n bool go_on;\n\n Scheduler&amp; operator=(const Scheduler&amp; rhs) = delete;\n Scheduler(const Scheduler&amp; rhs) = delete;\n\npublic:\n\n Scheduler()\n :go_on(true),\n thread(new std::thread([this]() { ThreadLoop(); }))\n { }\n\n ~Scheduler()\n {\n go_on = false;\n thread-&gt;join();\n }\n\n void ThreadLoop()\n {\n while(go_on)\n {\n auto now = std::chrono::system_clock::now();\n while(!tasks.empty() &amp;&amp; tasks.top().time &lt;= now) {\n function_timer&amp; f = tasks.top();\n f.get();\n tasks.pop();\n }\n\n if(tasks.empty()) {\n std::this_thread::sleep_for(std::chrono::milliseconds(100));\n } else {\n std::this_thread::sleep_for(tasks.top().time - std::chrono::system_clock::now());\n }\n }\n }\n\n void ScheduleAt(std::chrono::system_clock::time_point&amp; time, std::function&lt;void()&gt;&amp;&amp; func)\n {\n tasks.push(function_timer(std::move(func), time));\n }\n\n void ScheduleEvery(std::chrono::system_clock::duration interval, std::function&lt;void()&gt; func)\n {\n std::function&lt;void()&gt; waitFunc = [this,interval,func]()\n { \n func();\n this-&gt;ScheduleEvery(interval, func);\n };\n ScheduleAt(std::chrono::system_clock::now() + interval, std::move(waitFunc));\n }\n};\n</code></pre>\n<p>I imagine there's also a slightly cleaner way of doing this with <code>std::async</code>, <code>std::promise</code> and <code>std::future</code>, but perhaps someone else can figure that out.</p>\n<p>Edit: Whoops, there is shared mutable state, I'm definitely wrong about that.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-02-07T07:32:53.627", "Id": "34346", "Score": "1", "body": "Is `std::priority_queue` synchronized ? You use `tasks` in `ThreadLoop` and in the main thread (via ScheduleAt/Every). Is this really OK ? I used `condition_variable` to be able to wake up a thread when a task is posted because I did not want to peek every so often, like you did, choosing 100ms as an acceptable possible lag." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-02-07T08:40:36.477", "Id": "34348", "Score": "1", "body": "No it isn't, and yes, you're right, my apologies, it should have a `mutex` there. As for the delay, note that will only happen when the queue is empty - when it has elements in it, it will sleep for the appropriate amount of time. Given the fact that none of what's put into the queue runs in a separate thread, anything that runs for longer than 100ms will put the queue out of sync by more than that anyway - with the implementation as is, I think a condition variable is overkill. If you change it to run each function in a separate thread, though, then you'd likely need it." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-02-07T10:45:18.137", "Id": "34358", "Score": "0", "body": "I was aware of the delay generated by long-running tasks and I should have talked about it in the question. I figured that such tasks should include a thread, or a post() somewhere in an io_service or such. Thanks for the considerations !" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2016-08-03T20:52:50.190", "Id": "256405", "Score": "1", "body": "@Yuushi, I'm a bit late to the party here, but I would argue that a condition variable is far from overkill. Consider the case where the scheduler thread is sleeping for the next scheduled event, and another thread schedules a task for a time sooner than that." } ], "meta_data": { "CommentCount": "4", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-02-06T14:45:30.873", "Id": "21378", "ParentId": "21336", "Score": "9" } }, { "body": "<p>I tested the scheduler and found that in some cases, </p>\n\n<pre><code>blocker.wait_until(lock, tasks.begin()-&gt;first);\n</code></pre>\n\n<p>will wake up 1 second before the actual scheduled time. </p>\n\n<p>Then <code>tasks.begin()-&gt;first &lt;= now</code> fails.</p>\n\n<p>Then the next </p>\n\n<pre><code>blocker.wait_until(lock, tasks.begin()-&gt;first);\n</code></pre>\n\n<p>Fails because the time has already elapsed...</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2015-04-18T20:12:03.440", "Id": "157763", "Score": "0", "body": "Could you provide the full code, please?" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2015-07-07T12:59:03.467", "Id": "175430", "Score": "0", "body": "http://pastebin.com/Ju6Qh3nQ" } ], "meta_data": { "CommentCount": "2", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2015-04-17T09:50:05.233", "Id": "87164", "ParentId": "21336", "Score": "2" } }, { "body": "<p>Consider this improved version of Yuushi's code:</p>\n\n<pre><code>#include &lt;functional&gt;\n#include &lt;chrono&gt;\n#include &lt;future&gt;\n#include &lt;queue&gt;\n#include &lt;thread&gt;\n#include &lt;memory&gt;\n#include &lt;sstream&gt;\n#include &lt;assert.h&gt;\n\nstruct function_timer\n{\n std::function&lt;void()&gt; func;\n std::chrono::system_clock::time_point time;\n\n function_timer()\n // :func(nullptr),time(nullptr)\n { }\n\n function_timer(std::function&lt;void()&gt;&amp;&amp; f, const std::chrono::system_clock::time_point&amp; t)\n : func(f),\n time(t)\n { }\n\n //Note: we want our priority_queue to be ordered in terms of\n //smallest time to largest, hence the &gt; in operator&lt;. This isn't good\n //practice - it should be a separate struct - but I've done this for brevity.\n bool operator&lt;(const function_timer&amp; rhs) const\n {\n return time &gt; rhs.time;\n }\n\n void get()\n {\n //won't work correctly\n // std::thread t(func);\n // t.detach();\n func();\n }\n void operator()(){\n func();\n }\n};\n\nclass Scheduler\n{\nprivate:\n std::priority_queue&lt;function_timer&gt; tasks;\n std::unique_ptr&lt;std::thread&gt; thread;\n bool go_on;\n\n Scheduler&amp; operator=(const Scheduler&amp; rhs) = delete;\n Scheduler(const Scheduler&amp; rhs) = delete;\n\npublic:\n\n Scheduler()\n :go_on(true),\n thread(new std::thread([this]() { ThreadLoop(); }))\n { }\n\n ~Scheduler()\n {\n go_on = false;\n thread-&gt;join();\n }\n\n void ScheduleAt(const std::chrono::system_clock::time_point&amp; time, std::function&lt;void()&gt;&amp;&amp; func)\n {\n std::function&lt;void()&gt; threadFunc = [func]()\n {\n std::thread t(func);\n t.detach();\n // func();\n\n };\n tasks.push(function_timer(std::move(threadFunc), time));\n }\n\n void ScheduleEvery(std::chrono::system_clock::duration interval, std::function&lt;void()&gt; func)\n {\n std::function&lt;void()&gt; threadFunc = [func]()\n {\n std::thread t(func);\n t.detach();\n // func();\n\n };\n this-&gt;ScheduleEveryIntern(interval, threadFunc);\n }\n\n //in format \"%s %M %H %d %m %Y\" \"sec min hour date month year\"\n void ScheduleAt(const std::string &amp;time, std::function&lt;void()&gt; func)\n {\n if (time.find(\"*\") == std::string::npos &amp;&amp; time.find(\"/\") == std::string::npos)\n {\n std::tm tm = {};\n strptime(time.c_str(), \"%s %M %H %d %m %Y\", &amp;tm);\n auto tp = std::chrono::system_clock::from_time_t(std::mktime(&amp;tm));\n if(tp&gt;std::chrono::system_clock::now())\n ScheduleAtIntern(tp, std::move(func));\n }\n }\nprivate:\n void ScheduleAtIntern(const std::chrono::system_clock::time_point&amp; time, std::function&lt;void()&gt;&amp;&amp; func)\n {\n tasks.push(function_timer(std::move(func), time));\n }\n\n void ScheduleEveryIntern(std::chrono::system_clock::duration interval, std::function&lt;void()&gt; func)\n {\n std::function&lt;void()&gt; waitFunc = [this,interval,func]()\n {\n // std::thread t(func);\n // t.detach();\n func();\n this-&gt;ScheduleEveryIntern(interval, func);\n };\n ScheduleAtIntern(std::chrono::system_clock::now() + interval, std::move(waitFunc));\n }\n\n void ThreadLoop()\n {\n while(go_on)\n {\n auto now = std::chrono::system_clock::now();\n while(!tasks.empty() &amp;&amp; tasks.top().time &lt;= now) {\n function_timer f = tasks.top();\n f.get();\n tasks.pop();\n }\n\n if(tasks.empty()) {\n std::this_thread::sleep_for(std::chrono::milliseconds(100));\n } else {\n std::this_thread::sleep_for(tasks.top().time - std::chrono::system_clock::now());\n }\n }\n }\n\n};\n</code></pre>\n\n<p>Now each function is launched in a separate thread and this didn't block long time operations like this. </p>\n\n<pre><code>void Task10sec()\n{\n std::chrono::system_clock::time_point p = std::chrono::system_clock::now();\n while (std::chrono::system_clock::now()&lt;(p+std::chrono::seconds(10))){}\n}\n</code></pre>\n\n<p>so if we launch 3 tasks which should be executed in intersecting intervals each task is executed in separate thread and at the expected time.</p>\n\n<p>F1 short task is executed every second</p>\n\n<p>F2 long task is executed every minute</p>\n\n<p>F3 long task is executed once. Is started during 2 task.</p>\n\n<pre><code>sch.ScheduleEvery(std::chrono::minutes(1), []{\n std::chrono::system_clock::time_point p = std::chrono::system_clock::now();\n std::time_t t = std::chrono::system_clock::to_time_t(p);\n std::cout &lt;&lt; \"F2.1 \"&lt;&lt;std::ctime(&amp;t) &lt;&lt; std::endl;\n\n Task10sec();\n\n std::chrono::system_clock::time_point p2 = std::chrono::system_clock::now();\n std::time_t t2 = std::chrono::system_clock::to_time_t(p2);\n std::cout &lt;&lt; \"F2.2 \"&lt;&lt;std::ctime(&amp;t2) &lt;&lt; std::endl;\n\n });\nsch.ScheduleAt(now + std::chrono::seconds(65), []{\n std::chrono::system_clock::time_point p = std::chrono::system_clock::now();\n std::time_t t = std::chrono::system_clock::to_time_t(p);\n std::cout &lt;&lt; \"F3.1 \"&lt;&lt;std::ctime(&amp;t) &lt;&lt; std::endl;\n\n Task10sec();\n\n std::chrono::system_clock::time_point p2 = std::chrono::system_clock::now();\n std::time_t t2 = std::chrono::system_clock::to_time_t(p2);\n std::cout &lt;&lt; \"F3.2 \"&lt;&lt;std::ctime(&amp;t2) &lt;&lt; std::endl;\n\n });\n</code></pre>\n\n<p>can produce this result (each function is executing his code on his own thread)</p>\n\n<pre><code>F1 Thu Nov 3 15:07:41 2016\nF1 Thu Nov 3 15:07:42 2016\nF2.1 Thu Nov 3 15:07:43 2016\nF1 Thu Nov 3 15:07:43 2016\n.\n.\nF1 Thu Nov 3 15:07:47 2016\nF3.1 Thu Nov 3 15:07:48 2016\nF1 Thu Nov 3 15:07:48 2016\nF1 Thu Nov 3 15:07:49 2016\n.\n.\nF1 Thu Nov 3 15:07:52 2016\nF2.2 Thu Nov 3 15:07:53 2016\nF1 Thu Nov 3 15:07:53 2016\nF1 Thu Nov 3 15:07:54 2016\n.\n.\nF1 Thu Nov 3 15:07:57 2016\n\nF3.2 Thu Nov 3 15:07:58 2016\n\nF1 Thu Nov 3 15:07:58 2016\n</code></pre>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2016-11-03T09:15:32.873", "Id": "146007", "ParentId": "21336", "Score": "5" } } ]
{ "AcceptedAnswerId": "21378", "CommentCount": "3", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-02-05T12:39:44.577", "Id": "21336", "Score": "20", "Tags": [ "c++", "c++11", "scheduled-tasks" ], "Title": "C++ Task Scheduler" }
21336
<p>I implemented this Agent class for a project recently and was wondering if I could get some other eyes to look at it -- I'm currently the only developer where I work so I can't exactly ask someone here to do it.</p> <p>I'm pretty sure it's correct, but then I'm too close to it.</p> <pre><code>public abstract class Agent&lt;M&gt; : IDisposable { private Thread thread; private Queue&lt;M&gt; messageQueue; private bool quit; public Agent() { this.thread = new Thread(new ThreadStart(AgentThreadBody)); this.messageQueue = new Queue&lt;M&gt;(); this.quit = false; this.thread.Start(); } /// &lt;summary&gt; /// Stops the message-handling thread. /// /// Do not call this method from within the message- /// handling method, or it will result in a deadlock /// (because this method waits for the message-handling /// thread to stop). /// &lt;/summary&gt; public virtual void Dispose() { this.quit = true; this.thread.Interrupt(); this.thread.Join(); this.thread = null; // clear messageQueue before nulling? // (would do this to dispose queued items) this.messageQueue = null; } public void QueueMessage(M message) { lock (this.messageQueue) { this.messageQueue.Enqueue(message); this.thread.Interrupt(); } } private void AgentThreadBody() { while (!this.quit) { M message = default(M); bool messageAvailable = false; lock (messageQueue) { if (messageQueue.Count &gt; 0) { message = messageQueue.Dequeue(); messageAvailable = true; } } try { if (!messageAvailable) { // if the Interrupt() method was // called before we sleep or is // called while we're sleeping, // this will throw: // ThreadInterruptedException Thread.Sleep(Timeout.Infinite); } } catch (ThreadInterruptedException) { // we have a new message to handle, // so get it, or we've been told // to quit. continue; } ProcessMessage(message); } } protected abstract void ProcessMessage(M message); } </code></pre> <p>Also, are there any special considerations you can think of that should be made by a class inheriting from this base class? (I can't think of any.)</p> <p>I could add start/stop methods, but at the moment they're not needed.</p> <p>Btw, I have to use .NET 3.5.</p>
[]
[ { "body": "<p>Few minor points:</p>\n\n<ul>\n<li>Generic type parameter should be called <code>&lt;T&gt;</code> as per <a href=\"http://msdn.microsoft.com/en-us/library/aa479858.aspx#bestpractices_topic2\" rel=\"nofollow\">convention</a>.</li>\n<li><code>public</code> constructors in <code>abstract</code> classes make no sense - make it\n<code>protected</code>.</li>\n<li>Make <code>thread</code> and <code>messageQueue</code> <code>readonly</code> and don't\nset them to <code>null</code> in the <code>Dispose()</code> method.</li>\n<li>Better yet, implement the <a href=\"http://msdn.microsoft.com/en-us/library/fs2xkftw%28v=vs.90%29.aspx\" rel=\"nofollow\">Disposable Pattern</a> correctly. Though note, I do disagree with their setting of the <code>IDisposable</code> members to <code>null</code>. It's really not necessary at all; but calling <code>Dispose()</code> is. Their <code>_disposed</code> class member conveys enough information necessary.</li>\n<li>You should also lock on a dedicated locking class member when accessing your <code>quit</code> class member since it is accessed via multiple threads.</li>\n<li>Possibly wrap your call to <code>ProcessMessage(message)</code> in a <code>try..catch</code> block with appropriate error handling (or not, as the case could be). Unless, of course, you trust any subclasses from doing nasty things in their override of it.</li>\n</ul>\n\n<p>Just my initial thoughts. Hope they help.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-02-05T16:03:34.037", "Id": "34239", "Score": "1", "body": "Thanks for the tips! In response: (1) No reason not to go w/ convention on this one. (2) Good call on `protected`! (3,4) I'll have to look into proper handling of this further -- thanks for the link. (5) No need to lock `quit` since it's a `bool` and access is atomic. I did add `volatile` though. ([Related](http://stackoverflow.com/questions/59422/is-a-bool-read-write-atomic-in-c-sharp).) (6) I had considered that; I'm not sure if I want to swallow exceptions there or just let them fall through and crash. (Logging them would be difficult in this application.) Thanks again!" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-02-19T21:13:47.783", "Id": "35215", "Score": "0", "body": "I found this [article on properly implementing the dispose pattern](http://www.codeproject.com/Articles/15360/Implementing-IDisposable-and-the-Dispose-Pattern-P) a bit clearer than the article to which you linked, in case you need a good link for someone in the future." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-02-27T22:28:38.450", "Id": "35838", "Score": "0", "body": "@Jesse, concerning \"don't set fields to null\". Obviously null'ing fields will not free the memory immediately, and it will not help GC in case when the code *is written correctly*. But it will help in reducing memory leaks if some references to main (owner) object will remain after disposition thus preventing it from being garbage-collected. In this case null'ing the references allows nested objects to be garbage-collected even though parent object will stay in memory." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-02-27T22:35:17.010", "Id": "35839", "Score": "0", "body": "@almaz I disagree completely. Your object which is being `Dispose`'d, as the owner of those fields, will be unused by your program and eligible for garbage collection directly post-`Dispose()`. Those fields will then also be GC'd if they have no other references (they shouldn't)." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-02-27T22:54:03.333", "Id": "35841", "Score": "0", "body": "I'd rather use `TMessage` than the meaningless `T`. Just `T` is mostly applicable in situations where the parameter has no real meaning, such as collections." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-02-27T22:56:45.497", "Id": "35842", "Score": "0", "body": "I disagree about the dispose pattern: It's almost never the right choice. If you don't own the unmanaged resourced *directly*, you should just forward `Dispose` to the actual owners, no reason to implement a finalizer. If you directly own them, you should implement a `SafeHandle` with a critical finalizer, not a normal finalizer." } ], "meta_data": { "CommentCount": "6", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-02-05T15:14:41.637", "Id": "21340", "ParentId": "21337", "Score": "4" } }, { "body": "<p>No, this implementation <strong>is <em>not</em> issue free!</strong></p>\n\n<p>The <code>Thread.Interrupt()</code> method apparently causes a <code>ThreadInterruptedException</code> to be thrown <em>whenever the thread is blocked</em>. <a href=\"http://msdn.microsoft.com/en-us/library/system.threading.thread.interrupt%28v=vs.90%29.aspx\" rel=\"nofollow noreferrer\">The documentation</a> led me to believe that it was only thrown under certain circumstances:</p>\n\n<blockquote>\n <p>If this thread is not currently blocked in a <em>wait, sleep, or join state, [emph mine]</em> it will be interrupted when it next begins to block.</p>\n</blockquote>\n\n<p>However, a lot more can block a thread than you'd think! I first started seeing what I thought were rogue instances of this exception in a derived agent instance when accessing <code>DateTime.Now</code>! (This is apparently due to <a href=\"https://stackoverflow.com/questions/10899709/datetime-now-causes-io-blocking\">the <code>Now</code> property requiring blocking IO to obtain a value</a>.)</p>\n\n<p><em>Locking</em> can also cause a thread to block, as <a href=\"https://stackoverflow.com/a/6029829/225292\"><code>lock</code> gets translated into <code>Monitor</code>s</a> (which block).</p>\n\n<p>Looks like I'll have to go with a solution that just <code>Sleep()</code>s for short periods of time instead of waiting indefinitely until new input became available :-/</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-02-27T21:19:02.313", "Id": "23240", "ParentId": "21337", "Score": "0" } }, { "body": "<p>Instead of sleeping for short periods or using <code>Thread.Interrupt()</code> it's better to use waithandles, <code>ManualResetEvent</code> in your case. I don't have Visual Studio at hand, but the following example should give you the basic idea (most of the complexity will be gone if you start using .NET 4 or 4.5, in particular <code>BlockingCollection&lt;T&gt;</code>):</p>\n\n<pre><code>public abstract class Agent&lt;TMessage&gt; : IDisposable\n{\n private readonly Thread _thread = new Thread(AgentThreadBody);\n private readonly Queue&lt;TMessage&gt; _messageQueue = new Queue&lt;TMessage&gt;();\n private readonly ManualResetEvent _waitHandle = new ManualResetEvent(false);\n private volatile bool _quit;\n private bool _disposed;\n\n protected Agent()\n {\n _thread.Start();\n }\n\n public void QueueMessage(M message)\n {\n lock (_messageQueue)\n {\n _messageQueue.Enqueue(message);\n _waitHandle.Set();\n }\n }\n\n private void AgentThreadBody()\n {\n while (!_quit)\n {\n _waitHandle.WaitOne();\n TMessage message;\n\n lock (messageQueue)\n {\n if (messageQueue.Count == 0)\n {\n _waitHandle.Reset();\n continue;\n }\n\n message = messageQueue.Dequeue();\n }\n\n ProcessMessage(message);\n }\n }\n\n protected abstract void ProcessMessage(M message);\n\n /// &lt;summary&gt;\n /// Stops the message-handling thread.\n /// \n /// Do not call this method from within the message-\n /// handling method, or it will result in a deadlock\n /// (because this method waits for the message-handling\n /// thread to stop).\n /// &lt;/summary&gt;\n public void Dispose()\n {\n Dispose(true);\n GC.SupressFinalize(this);\n }\n\n protected virtual void Dispose(bool disposing)\n {\n if (_disposed || !disposing)\n return;\n\n _quit = true;\n _waitHandle.Set();\n _thread.Join();\n _waitHandle.Dispose();\n _disposed = true;\n }\n}\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-03-01T21:25:36.320", "Id": "35962", "Score": "0", "body": "Thanks, this method is working well! I'm not that familiar with all of .NET's thread synchronization methods, and I was in a bit of a rush, so I probably wouldn't have come up with using this any time soon. If I _were_ using .NET _4_, I would have been doing this in F# and used a `MailboxProcessor` (or `Agent` from the FSharpx library) instead of rolling my own. (I _think_ I read somewhere that F# has been backported to .NET 2 but I haven't had time to investigate using it.) Thanks again!" } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-02-27T22:13:20.523", "Id": "23243", "ParentId": "21337", "Score": "2" } } ]
{ "AcceptedAnswerId": "23243", "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-02-05T14:25:09.737", "Id": "21337", "Score": "4", "Tags": [ "c#", "thread-safety", "actor" ], "Title": "Is this Agent/Actor implementation issue free?" }
21337
<p>Posted my question <a href="https://stackoverflow.com/questions/14710039/vbscript-poker-game-what-hand-do-i-have">here</a>.</p> <p>Here is the full code:</p> <pre><code>'buy a blank deck of cards 'declare variables dim defaultDeck(51) dim trueDeck(51) dim isUsed(51) numPlayers = 1 numCards = 12 intMyHand = 0 '0 through numPlayers-1... highest number is dealer Set objStdOut = WScript.StdOut 'put values on the blank cards: i=0 for suit=0 to 3 for faceValue=0 to 12 select case suit Case 0 strSuit = chr(3) case 1 strSuit = chr(4) case 2 strSuit = chr(5) case 3 strSuit = chr(6) case else strSuit = "SuitNotFound" end Select face = faceValue+1 select case face case 11 face = "J" case 12 face = "Q" case 13 face = "K" case 1 face = "A" case default face=face end select defaultDeck(i) = face &amp; strSuit i = i+1 next Next function translateCard(number) translateCard = defaultDeck(number) end function 'shuffle the deck function randNum() max = 51 min = 0 Randomize randNum = Int((max-min+1)*Rnd+min) end Function function shuffleDeck() 'reset from last shuffle y=0 for i=0 to 51 isUsed(i) ="n" next 'draw a card and put it in the deck do while y&lt;52 card = randNum() if isUsed(card) &lt;&gt; "Y" then isUsed(card) = "Y" trueDeck(y) = card y = y+1 end if loop ' objStdOut.Write "Shuffling." ' jsleep(1) ' objStdOut.Write "." ' jsleep(1) ' objStdOut.Write "." ' jsleep(1) ' objStdOut.Write "." ' jsleep(1) ' objStdOut.Write "Shuffled." objStdOut.WriteBlankLines(1) jsleep(1) end Function function showDeck() for i=0 to 50 'wscript.echo i &amp; ". " &amp; truedeck(i) strDeck = strDeck &amp; translateCard(truedeck(i)) &amp; "," next strDeck = strDeck &amp; translateCard(trueDeck(51)) 'to get rid of last comma wscript.echo "" wscript.echo "Shuffled Deck" wscript.echo "-------------" wscript.echo strDeck end Function function showdefDeck() for i=0 to 51 wscript.echo i &amp; ". " &amp; defaultdeck(i) ' strDeck = strDeck &amp; truedeck(i) &amp; ", " next 'strDeck = strDeck &amp; trueDeck(51) 'to get rid of last comma ' wscript.echo strDeck end Function playa = numPlayers-1 carda = numCards-1 Dim hands() ReDim Hands(playa,carda) dim myHand() reDim myHand(carda) function Dealcards() totalNumCards = (numPlayers * numCards) tnc =0 i = 0 do while tnc &lt; totalnumCards for c=0 to (numCards - 1) for p=0 to (numPlayers -1) Hands(p,c) = trueDeck(i) 'debug line 'wscript.echo truedeck(i) &amp; " dealt to player " &amp; p+1 &amp; "." i=i+1 tnc = tnc+1 next next loop ' objStdOut.Write "Dealing." ' jsleep(1) ' objStdOut.Write "." ' jsleep(1) ' objStdOut.Write "." ' jsleep(1) ' objStdOut.Write "Dealt." objStdOut.WriteBlankLines(2) jsleep(1) End function function showHand(h) if (h = intMyHand) then specialString = "*(You)* " else specialString = "" end if wscript.echo specialString &amp; "Player " &amp; h+1 &amp; "'s hand:" for i=0 to (numCards - 1) theCard = translatecard(Hands(h, i)) wscript.echo theCard next wscript.echo "" end Function function showSortedHand(t) if (t = intMyHand) then specialString = "*(You)* " else specialString = "" end if wscript.echo specialString &amp; "Player " &amp; t+1 &amp; "'s hand:" theSortedHand = getHand(t) for each card in theSortedHand transCard = translateCard(card) wscript.echo transCard next end Function function showMyHand() showHand(intMyHand) end Function function showAllHands() for q=0 to playa showHand(q) next end Function function jsleep (seconds) wscript.sleep seconds*1000 end function 'sort method function SortArray(arrShort) dim i, j, temp for i = UBound(arrShort) - 1 To 0 Step -1 for j= 0 to i if arrShort(j)&gt;arrShort(j+1) then temp=arrShort(j+1) arrShort(j+1)=arrShort(j) arrShort(j)=temp end if next next SortArray = arrShort end function function getHand(x) purple = numCards-1 dim a() redim a(purple) for i=0 to (numCards-1) a(i) = Hands(x, i) next sortArray a getHand = a end function objstdOUt.Write "Welcome to PokerGame1.0" objStdOut.WriteBlankLines(1) objStdOut.Write "-----------------------" objStdOut.WriteBlankLines(2) 'showdefdeck shuffleDeck showdeck dealCards 'showMyHand showAllHands showSortedHand(0) </code></pre>
[ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-02-07T14:29:12.700", "Id": "34396", "Score": "0", "body": "As fun as this was, I'm switching to Python." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-11-18T22:20:49.717", "Id": "57873", "Score": "0", "body": "please post the Python code here when you have it working. I will take a look at this and maybe add a tag or two to get some more attention" } ]
[ { "body": "<p>You're creating your cards with a nested <code>For</code> loop; one over <code>suit</code>, another over <code>faceValue</code> - I'd do the same (or quite similar). However I'm not buying the <code>Select Case</code> part:</p>\n\n<pre><code>for suit=0 to 3\n for faceValue=0 to 12\n select case suit\n Case 0\n strSuit = chr(3)\n case 1\n strSuit = chr(4)\n case 2\n strSuit = chr(5)\n case 3\n strSuit = chr(6)\n case else\n strSuit = \"SuitNotFound\"\n end Select\n ...\n</code></pre>\n\n<p>This whole <code>select case suit</code> could be replaced with <code>strSuit = chr(suit + 3)</code> with a comment that says something like <code>'chr(3)-chr(6): ♥ ♦ ♣ ♠</code>. The <code>\"SuitNotFound\"</code> case is a WTF for me.</p>\n\n<p>Naming-wise, I don't understand how you can name a variable <code>suit</code> (good), another <code>faceValue</code> (good) and then have horrible Hungarian notation with <code>strSuit</code> - call it <code>currentSuit</code> or <code>cardSuit</code> or whatever, but <strong>please</strong> don't prefix with an abbreviation of type's name! [and that's valid for <a href=\"/questions/tagged/python\" class=\"post-tag\" title=\"show questions tagged &#39;python&#39;\" rel=\"tag\">python</a> as well I guess!]</p>\n\n<p>Your Ace is worth 1; if you're playing Poker the Ace can be either 1 or 14, depending on the hand.</p>\n\n<p>Lastly, in VBScript/VBA/VB6, you should always use the zero-footprint <code>vbNullString</code> language constant instead of <code>\"\"</code> which takes up unnecessary memory (not that memory would be an issue though).</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-12-12T16:53:31.460", "Id": "61404", "Score": "2", "body": "True, the OP seems to have no particular naming convention for variables. I particularly like `purple` which temporarily stores a number." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2015-02-05T13:51:24.447", "Id": "144298", "Score": "0", "body": "If you could think of a better color to store numbers, I'm all ears." } ], "meta_data": { "CommentCount": "2", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-12-12T00:03:20.293", "Id": "37185", "ParentId": "21338", "Score": "3" } }, { "body": "<p>In addition to <a href=\"https://codereview.stackexchange.com/a/37185/14909\">@retailcoder's</a> good feedback, here are a few points:</p>\n\n<ol>\n<li><p><a href=\"http://msdn.microsoft.com/en-us/library/bw9t3484(v=vs.84).aspx\" rel=\"nofollow noreferrer\">Option Explicit</a> as your first line is considered a best practice for VBScript. It will require you to declare all of your variables, which will assure you don't accidentally use <code>purpel</code> when you meant <code>purple</code></p></li>\n<li><p>In general your names are inconsistent or simply odd. <code>playa</code> = <code>numPlayers - 1</code> - weird, <code>jsleep</code> What's the <code>j</code>?, and <code>purple</code> - fun but meaningless.</p></li>\n<li><p>Your shuffledeck method is a potential issue. In the extremely unlikely case your do loop would seemlingly hang due to repeatedly returning the same random number as <code>isUsed(card) &lt;&gt; \"Y\"</code> would keep being false.\nSomething like populating trueDeck the same as defaultDeck then looping through swaping indexes might suit. Here's an example of what I mean:</p>\n\n<pre><code>'set up trueDeck prior to this\nfor i= 0 to 51\n card = randNum()\n temp = trueDeck(card)\n trueDeck(card) = i\n trueDeck(i) = temp\nloop\n</code></pre></li>\n</ol>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-12-12T17:35:15.683", "Id": "37233", "ParentId": "21338", "Score": "3" } } ]
{ "AcceptedAnswerId": "37185", "CommentCount": "2", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-02-05T14:39:41.030", "Id": "21338", "Score": "5", "Tags": [ "playing-cards", "vbscript" ], "Title": "How to tell the NPC what hand it has?" }
21338
<p>I my class hierarchy looks like this:</p> <ul> <li><code>P</code></li> <li><code>I : P</code></li> <li><code>O : P</code></li> </ul> <p>I have this method. The goal of this method is to return a new object of type <code>I</code> or <code>O</code> depending on a certain condition. </p> <pre><code> public P GetP() { this.Session.Begin(); var pDetail = GetPDetail(); if (pDetail == null) { this.Session.Close(); return null; } switch (pDetail.Code) { case "1": var i = new I(); i.PDetail = pDetail; FillBaseP(i); FillI(i); this.Session.Close(); return i; case "3": var o = new O(); o.PDetail = pDetail; FillBaseP(o); FillO(o); this.Session.Close(); return o; default: throw new Exception("Code is invalid"); } } </code></pre> <p>I'm looking to rewrite this in a more logical way. Both <code>case "1"</code> and <code>case "3"</code> are doing some of the same work.</p> <p>If I'm constantly checking type like <code>If(var is O)</code> or <code>If(var is I)</code> I feel as though I'm doing something wrong. Is this the case?</p>
[ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-02-05T16:12:16.963", "Id": "34240", "Score": "1", "body": "Is this something that could fall under a [factory pattern](http://en.wikipedia.org/wiki/Factory_method_pattern)? Change the factory based on the value of `pDetail.Code`, then call a standard \"create\" method? (I'm not sure how extensible you need this to be)." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-02-05T16:40:02.523", "Id": "34243", "Score": "0", "body": "Additionally you may want to consider dealing in terms of an interface, especially since much of the code under the case \"1\" and \"3\" look very similar." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-02-05T20:44:09.530", "Id": "34257", "Score": "0", "body": "@RyanGates I think that's the question Chance is asking: How to do that?" } ]
[ { "body": "<ol>\n<li><p>I think it would be better if <code>Session.Begin()</code> returned an <code>IDisposable</code>, which would call <code>Session.Close()</code> in its <code>Dispose()</code>. That way, you can enclose the whole method inside <code>using</code> and you don't have to worry about calling it properly. (For example, it's not called in your code if the code is invalid.)</p></li>\n<li><p>You can extract the creation of <code>I</code> or <code>O</code> into a generic method. It will also have a delegate parameter that represents the type-specific fill method.</p></li>\n<li><p>It's better if you throw a specific exception (maybe something like <code>InvalidCodeException</code>), not <code>Exception</code>.</p></li>\n</ol>\n\n<p>With these changes, the code would look like this:</p>\n\n<pre><code>private P CreateP&lt;T&gt;(PDetail pDetail, Action&lt;T&gt; fillT) where T : P, new()\n{\n var p = new T { PDetail = pDetail };\n FillBaseP(p);\n fillT(p);\n return p;\n}\n\npublic P GetP()\n{\n using (this.Session.Begin())\n {\n var pDetail = GetPDetail();\n\n if (pDetail == null)\n return null;\n\n switch (pDetail.Code)\n {\n case \"1\":\n return CreateP&lt;I&gt;(pDetail, FillI);\n case \"3\":\n return CreateP&lt;O&gt;(pDetail, FillO);\n default:\n throw new InvalidCodeException(\"Code is invalid\");\n }\n }\n}\n</code></pre>\n\n<blockquote>\n <p>If I'm constantly checking type like <code>If(var is O)</code> or <code>If(var is I)</code> I feel as though I'm doing something wrong. Is this the case?</p>\n</blockquote>\n\n<p>Yeah, probably. But it's hard to tell (and advise a better approach) without seeing the code.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-02-05T20:43:26.270", "Id": "21351", "ParentId": "21342", "Score": "5" } }, { "body": "<blockquote>\n <p>If I'm constantly checking type like If(var is O) or If(var is I) I feel as though I'm doing something wrong. Is this the case?</p>\n</blockquote>\n\n<p>Well, your code does not fully utilize the OOP paradigm, which is why you keep checking types manually instead of delegating that to the framework/language.</p>\n\n<p>Consider the following code:</p>\n\n<pre><code>class P\n{\n protected P(PDetail detail)\n {\n this.Fill(detail);\n }\n\n protected virtual void Fill(PDetail detail)\n {\n // FillBaseP() imp.\n }\n}\n\nclass I : P\n{\n public I(PDetail detail)\n : base(detail) \n {\n // some imp.\n }\n\n protected override void Fill(PDetail detail)\n {\n base.Fill(detail);\n // FillI() imp.\n }\n}\n\nclass O : P\n{\n public O(PDetail detail)\n : base(detail) { }\n\n protected override void Fill(PDetail detail)\n {\n base.Fill(detail);\n // FillO() imp.\n }\n}\n\n public P GetP()\n {\n using (this.Session.Begin())\n {\n var pDetail = GetPDetail();\n\n if (pDetail == null)\n return null;\n\n switch (pDetail.Code)\n {\n case \"1\":\n return new I(pDetail);\n case \"3\":\n return new O(pDetail);\n default:\n throw new InvalidCodeException(\"Code is invalid\");\n }\n }\n }\n</code></pre>\n\n<p>Now each subclass contains its own implementation details, and when the base contractor calls <code>Fill()</code>, the most recent implementation is called (for <code>O</code>, <code>O.Fill</code>, for <code>I</code>, <code>I.Fill</code>). Then, the implementation calls the base Fill (your old <code>FillBaseP</code>), and than performs it's own magic.</p>\n\n<p><code>new I(d)</code> call chain:</p>\n\n<pre><code>I(d)\n P(d)\n I.Fill(d)\n P.Fill(d)\n back to I.Fill(d) (to // FillI() imp.)\n back to P(d) \nback to I(d) (to // some imp.)\n</code></pre>\n\n<p>Note that aside from the construction part, the code <strong>never</strong> checks the type or the details variable. It just assumes that each subclass override <code>Fill()</code> correctly.</p>\n\n<p>Hope that helps!</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-02-09T15:00:27.667", "Id": "34562", "Score": "0", "body": "My issue is `I` and `O` have properties and methods that are not common, so they are not in `P` and need to be accessed in the code. This leaves me having to downcast `P` to the correct concrete type. I'm not certain any way to get around the downcasting. Should I not be using base type `P` then?" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-02-09T22:54:25.480", "Id": "34577", "Score": "0", "body": "You should decide what is the 'interface' of I&O (i.e, what they have in common, like 'Fill') and define it in P, and what is specific to each of them (i.e, the underlying properties). I would then try to move as much of the type-dependent code **into** the classes. For example, say you need to `Print()` them, and I is a circle and O is square. You need I's `Radius` and O's `SideLength`, but both can provide the print interface." } ], "meta_data": { "CommentCount": "2", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-02-09T09:19:24.117", "Id": "21504", "ParentId": "21342", "Score": "1" } }, { "body": "<p>I'd use a combination of the abstract factory, template method and null object patterns.\nIn order to satisfy the single responsibility principle, you would need to use the abstract factory pattern to create a specialized factory to fill the object.</p>\n\n<p>I have made some assumptions because very little detail has been provided.</p>\n\n<pre><code>internal class Program\n{\n private static void Main(string[] args) {\n //Example usage\n var detail = new PDetail();\n var instanceFactory = new PFactory();\n var instance = instanceFactory.CreateFrom(detail);\n }\n}\n\npublic abstract class P {}\n\npublic class NullP : P {}\n\npublic class I : P {}\n\npublic class O : P {}\n\npublic class PDetail\n{\n public int Code { get; set; }\n}\n\npublic class PFactory\n{\n private static readonly IDictionary&lt;int, Func&lt;IPFactory&gt;&gt; factories;\n\n static PFactory() {\n //factories is a map between the code and a method that returns an IPFactory\n factories = new Dictionary&lt;int, Func&lt;IPFactory&gt;&gt; {\n { 1, () =&gt; new IFactory() }, \n { 3, () =&gt; new OFactory() }\n };\n }\n\n private static IPFactory CreateFactory(int code) {\n //This abstract factory creates a specific instance factory that will create and fill an instance of P\n if (!factories.ContainsKey(code)) {\n return new NullPFactory();\n }\n\n var createFactory = factories[code];\n return createFactory();\n }\n\n public P CreateFrom(PDetail detail) {\n //1. Create the specific factory required to produce the specific instance based on a discriminator (detail.Code)\n var factory = CreateFactory(detail.Code);\n //2. Create and fill the instance and return it\n return factory.CreateAndFill(detail);\n }\n}\n\npublic interface IPFactory\n{\n P CreateAndFill(PDetail detail);\n}\n\npublic abstract class PFactoryBase&lt;T&gt; : IPFactory\n where T : P\n{\n public P CreateAndFill(PDetail detail) {\n //Template method pattern -&gt; Fill is implemented by concrete factories ex. IFactory, OFactory\n var instance = CreateInstance();\n FillBase(instance, detail);\n Fill(instance, detail);\n return instance;\n }\n\n private void FillBase(P instance, PDetail detail) {\n //Fill base\n }\n\n protected abstract T CreateInstance();\n\n protected abstract void Fill(T instance, PDetail detail);\n}\n\npublic class NullPFactory : PFactoryBase&lt;NullP&gt;\n{\n protected override NullP CreateInstance() {\n return new NullP();\n }\n\n protected override void Fill(NullP instance, PDetail detail) {\n //Do nothing?\n }\n}\n\npublic class OFactory : PFactoryBase&lt;O&gt;\n{\n protected override O CreateInstance() {\n return new O();\n }\n\n protected override void Fill(O instance, PDetail detail) {\n //Fill the instance\n }\n}\n\npublic class IFactory : PFactoryBase&lt;I&gt;\n{\n protected override I CreateInstance() {\n return new I();\n }\n\n protected override void Fill(I instance, PDetail detail) {\n //Fill the instance\n }\n}\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-02-10T18:42:51.100", "Id": "34621", "Score": "1", "body": "I really don't think the null object pattern is appropriate here. If you can't create the proper object, throw an exception, don't create something that looks like it's what you wanted, but actually isn't." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-02-10T19:29:38.897", "Id": "34623", "Score": "0", "body": "I agree with you in the case that P and O are anemic domain models or data objects. For components I would stick to a null object pattern (ex. pricing strategy) to ensure consistent usage. Unfortunately the question posed is vague in these matters - it simply attains that different objects are created based on a 'Code' discriminator - no usage examples are given. I tend to use exceptions only in exceptional circumstances (when the fault lays with the developer or external libraries) and never for control flow unless no other options are available (ex. Amazon SDK sending e-mail via SES)." } ], "meta_data": { "CommentCount": "2", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-02-10T16:48:27.193", "Id": "21545", "ParentId": "21342", "Score": "1" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "3", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-02-05T15:55:35.897", "Id": "21342", "Score": "6", "Tags": [ "c#" ], "Title": "Need help with my code using a base class?" }
21342
<p>I'm trying to make a sprite cache for SFML sprites. The basic idea I got was to use a map of an <code>enum</code> and a sprite pointer. Then when I would ask for a certain sprite I'd have a manager that would check if the pointer for that sprite is null. If it is, then it would create a new sprite object and clip it to fit what it's supposed to be. If it isn't null, then it means that the sprite object for this particular <code>enum</code> already exists, and I get that.</p> <p>So far I've made this and it works, but I'm not sure I did it quite right.</p> <p>This is my example code. It contains a small class called <code>SpriteManager</code> which holds the sprite map. It does the before mentioned pointer checking and creating, as well as assigning a texture to, and clipping the sprite.</p> <p>Here's the example code:</p> <pre><code>#include &lt;SFML/Graphics.hpp&gt; #include &lt;algorithm&gt; #include &lt;map&gt; enum Sprites { ITEM1, ITEM2, ITEM3, ITEM4, ITEM5 }; const int WIDTH = 100; const int HEIGHT = 100; typedef std::map&lt; Sprites, sf::Sprite* &gt; SpriteMap; typedef std::map&lt; Sprites, sf::Sprite* &gt;::iterator iter; class SpriteManager { private: SpriteMap spriteMap; sf::Texture&amp; m_texture; void clipSprite(Sprites name) { spriteMap.at(name)-&gt;setTexture(m_texture); switch(name) { case ITEM1: spriteMap.at(name)-&gt;setTextureRect(sf::IntRect(0,0,WIDTH,HEIGHT));break; case ITEM2: spriteMap.at(name)-&gt;setTextureRect(sf::IntRect((1*WIDTH),0,WIDTH,HEIGHT));break; case ITEM3: spriteMap.at(name)-&gt;setTextureRect(sf::IntRect((2*WIDTH),0,WIDTH,HEIGHT));break; case ITEM4: spriteMap.at(name)-&gt;setTextureRect(sf::IntRect((3*WIDTH),0,WIDTH,HEIGHT));break; case ITEM5: spriteMap.at(name)-&gt;setTextureRect(sf::IntRect((4*WIDTH),0,WIDTH,HEIGHT));break; } } public: SpriteManager(sf::Texture&amp; texture) : m_texture(texture) {} sf::Sprite* getSprite(Sprites name) { if(!spriteMap[name]) { spriteMap[name] = new sf::Sprite(); clipSprite(name); return spriteMap[name]; } else return spriteMap[name]; } ~SpriteManager() { for(iter i = spriteMap.begin(); i != spriteMap.end(); ++i ) { delete i-&gt;second; } } }; int main() { sf::RenderWindow window(sf::VideoMode(800,600), "Test", sf::Style::Titlebar | sf::Style::Close); sf::RectangleShape background(sf::Vector2f(800.0f,600.0f)); window.setFramerateLimit(30); sf::Texture spriteSheet; if(!spriteSheet.loadFromFile("TestSprites.png")) { return 1; } SpriteManager sprites(spriteSheet); sf::Sprite *sprite = sprites.getSprite(ITEM1); sf::Sprite *sprite2 = sprites.getSprite(ITEM3); sprite-&gt;setPosition(100,100); sprite2-&gt;setPosition(200,100); while(window.isOpen()) { sf::Event event; while( window.pollEvent(event)) { if(event.type == sf::Event::Closed) { window.close(); } } window.clear(); window.draw(background); window.draw(*sprite); window.draw(*sprite2); window.display(); } return 0; } </code></pre> <p>So far my biggest concerns are:</p> <ol> <li><p>Is the destructor ok? I figured that since I'm allocating sprites that I should delete them all upon the manager going out of scope, though the more I think about it the more uneasy I feel. </p></li> <li><p>What would I do if I have to have two of the same sprites on the screen at the same time? Basically what happens now is, if I have two calls for a sprite with the same name:</p> <pre><code>sf::Sprite *sprite1 = sprites.getSprite(ITEM1); sprite1-&gt;setPosition(100,100); sf::Sprite *sprite2 = sprites.getSprite(ITEM1); sprite2-&gt;setPosition(100,200); </code></pre></li> </ol> <p>I won't actually have two sprites on the screen but only one at the position 100x, 200y, since when I called the first <code>getSprite</code> I created a sprite under <code>ITEM1</code> key and then when I call the <code>getSprite</code> method the second time I get that first sprite again. Now this is great for memory conservation, however a lot of the times I'll need to have multiple instances of the same sprite on screen. For that I have an idea to add some sort of a counter or something, but nothing concrete yet. Any suggestions?</p>
[]
[ { "body": "<p>The code looks good, and your question is well written: thanks.</p>\n\n<ol>\n<li><p>I would call the <code>Sprites</code> enum <code>SpriteId</code> since at any given point it only store one sprite id.</p></li>\n<li><p>Returning a pointer could be quite problematic here: as you say, if SpriteManager goes out of scope then any reference to those sprites will cause issues. The simplest thing to do is to use a <code>shared_ptr</code>: it won't be deleted until no one references it.</p></li>\n<li><p>There is no default case in your switch and your names are not descriptive.</p></li>\n<li><p>The number and position of sprites is hardcoded and isn't easy to change. Did you consider using a string as a key, and storing the sprite coordinates in a file elsewhere?</p></li>\n</ol>\n\n<p><strong>EDIT answer</strong>:</p>\n\n<ol>\n<li>When the enum is not found, you certainly don't want to fail silently, and the way you fail depends on your objectives. You can have a production mode where you don't fail, but otherwise you want this error to be as visible as possible: throwing an exception/ending the program is a good idea.</li>\n<li>You no longer need a destructor indeed, but you still need to think about potential child classes: if you want to allow inheritance, then add an empty virtual constructor. Another thing to consider is that you'll need this code when you'll be hunting for memory leaks: a tool like valgrind will tell you that there are still references to those pointers only if they get reset in <code>SpriteManager</code>.</li>\n<li>I think you need to use <a href=\"https://stackoverflow.com/questions/642229/why-do-i-need-to-use-typedef-typename-in-g-but-not-vs\">typedef typename</a> instead of just <code>typedef</code>.</li>\n</ol>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-02-06T13:30:44.987", "Id": "34313", "Score": "0", "body": "Whoops, pressed enter by accident. This is what i meant to write:\n\n\nThanks for the answer.\n\n1. True, I'll change it.\n\n\n2. Thanks, I'm not that experience when it comes to smart pointers so i wasn't sure if I could and should use one, and which one.\n\n\n3. As far as the names go, these are just names for a test case, if I'd use this code in an actual application I'd use more descriptive enums. I'm not quite sure as to what should i make my default do. \n\n\n4. True, i probably should use a string as a key. Storing the sprite coordinates in a file? Similar to `Properties` in Java?" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-02-06T14:28:30.173", "Id": "34317", "Score": "0", "body": "I don't know about `Properties`. That's up to you: if you think it's fine in a C++ file, then it can work too. It mostly depends on the size and complexity of the game." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-02-07T23:01:02.773", "Id": "34436", "Score": "0", "body": "I updated the OP with an improved version and I'd really appreciate any comments on it. Also I thought about using std::strings as keys but wouldn't that allow \"duplicates\"(spelling/uppercase/lowercase mistakes), and make clipping the sprites quite a bit harder? Unless I first set them to all uppercase or all lowercase. Of course i could use files to load sprite info like you said." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-02-08T08:24:56.477", "Id": "34445", "Score": "0", "body": "You're right, strings aren't such a good idea because the typos won't be caught at compile time. I edited my answer for the other issues. (if you liked it, feel free to upvote it :)" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-02-09T00:24:29.393", "Id": "34529", "Score": "0", "body": "Thanks for the input. \n1. Indeed i shall tackle exceptions. This semester I had a Java class so i got used to Java exceptions, will take me a bit to get back to C++ style exceptions, though wouldn't there be a compiler error if something that is not a part of the enum was entered? \n2. My biggest issue right now is that if my thinking is correct, at the start the map is empty, but after i add an entry, even if the pointer gets auto deleted when it's not referenced anymore, the key itself stays, and that takes up space doesn't it?" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-02-09T00:28:10.817", "Id": "34530", "Score": "0", "body": "3. Where exactly and why? For my iterator? From the link you provided i figured that that is something I'd have to do only if I'm making a function/method with a template. I don't really understand." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-02-11T13:11:52.607", "Id": "34667", "Score": "0", "body": "1. enums are not strongly typed in C++03, so if you pass an int, it's not going to fail IIRC. ([C++11 has strongly typed enums](http://en.wikipedia.org/wiki/C%2B%2B11#Strongly_typed_enumerations). 2. Indeed, but as long as it's still in the map, the pointer had better be valid when doing loops over the maps and so on. If you remove it explicitly in the map and elsewhere in the code, then the space will be freed. 3. Yeah, I'm probably wrong for this one, sorry." } ], "meta_data": { "CommentCount": "7", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-02-06T09:54:14.740", "Id": "21366", "ParentId": "21345", "Score": "2" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-02-05T16:52:22.540", "Id": "21345", "Score": "3", "Tags": [ "c++", "cache", "sfml" ], "Title": "Sprite cache for SFML sprites" }
21345
<p>Checklist from FAQ for proper posting.</p> <pre><code>Does my question contain code? - YES Did I write that code? - YES Is it actual code from a project rather than pseudo-code or example code? - Strait from actual code, minus a few functions that do not apply to the Q To the best of my knowledge, does the code work? - To the best of my knowledge it works most of the time, other times it fails to do what I ask of it but produces no runtime errors. Do I want feedback about any or all facets of the code? - Just about how to reliably wait for the clipboard to be set and reliably set it while I am waiting. </code></pre> <p>I am trying to reliably set the system clipboard text in my program but keep coming back with confusing results. Those results being it sometimes setting the text and sometimes not setting it. Here is where I create a thread of type ClipSetThread and tell it to set the system clipboard and also set a global variable called waitForMe in the main Application.</p> <pre><code>public void setClip(String arg) // Starts a clip setting thread { CLUtilCompact.waitForMe = true; ClipSetThread set = new ClipSetThread(theApp); set.arg = arg; set.start(); while(CLUtilCompact.waitForMe){} } </code></pre> <p>And here is the class ClipSetThread</p> <pre><code>import java.awt.Toolkit; import java.awt.datatransfer.Clipboard; import java.awt.datatransfer.DataFlavor; import java.awt.datatransfer.StringSelection; import java.awt.datatransfer.Transferable; public class ClipSetThread extends Thread { String arg = ""; Clipboard sysClip = null; CLUtilCompact theApp = null; public ClipSetThread(CLUtilCompact app) { theApp = app; theApp.updateOutput("Set Clip ID:" + this.getId() + "|CREATED"); sysClip = Toolkit.getDefaultToolkit().getSystemClipboard(); } public void run() { setClip2(arg); CLUtilCompact.waitForMe = false; return; } public void setClip2(String arg) { while(true) { try { sysClip.setContents(new StringSelection(arg), null); } catch(Exception e) { try {Thread.sleep(20);} catch (InterruptedException e1) {} continue; } break; } return; } } </code></pre> <p>It seems that even with the while loop to wait for the waitForMe flag the setClip function will return and allow the application to try and continue what it is doing even though the clipboard is not set. </p> <p>After the clipboard is set I almost always try to paste what is there; I usually call Thread.sleep(1000) between a call to setClip and my call to paste(). (Paste simply simulates ctrl+V with the java Robot class)</p>
[ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-02-05T22:40:12.710", "Id": "34262", "Score": "0", "body": "Please define 'reliably set', as it's probably setting the copied value _eventually_. Your first major problem is that you're limited by the fact that you're using a global variable. What is it you're actually trying to accomplish - why are you attempting to transfer data this way? You should be implementing `Runnable`, not extending `Thread`, and submitting it with the swing worker thread. There's also a Swing class which should help out, [DefaultEditorKit.CopyAction](http://docs.oracle.com/javase/6/docs/api/javax/swing/text/DefaultEditorKit.CopyAction.html)" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-02-05T23:16:00.890", "Id": "34263", "Score": "0", "body": "Hmm, you might solve all my problems with this CopyAction. It looks like it has to be in a menu item to work though as per this link (http://www.java2s.com/Code/Java/Swing-JFC/SimpleEditorDemo.htm). If you have worked with it do you know how I could submit a string to \"the action\"? I feel it is ingrained in swing, and would be up to swing to find which Object we wish to copy, namely the object on the screen with focus? (Could that be a clue to submit a string to the action I need to give it a StringSelection object?)" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-02-06T00:12:45.907", "Id": "34265", "Score": "0", "body": "I have a feeling that you're supposed to pass a serializable object in the `ActionEvent` (as the `source` parameter). But other than that, I don't know off hand. To _get_ that object, you're going to have to have some sort of 'picking', regardless of using Swing or the AWT version." } ]
[ { "body": "<p>This code is quite confusing. Do you know about parallel threads mechanisms?</p>\n\n<pre><code>CLUtilCompact.waitForMe = true;\nset.start();\n</code></pre>\n\n<p>A new thread is started now and executes the run method from the interface. It is not defined when the thread is run, how fast and when he will execute any statements (and can not, the OS is responsible for this, not the JVM)</p>\n\n<p>So, sometimes, this lines is called first:</p>\n\n<pre><code>while(CLUtilCompact.waitForMe){}\n</code></pre>\n\n<p>Sometimes this line is called first:</p>\n\n<pre><code>CLUtilCompact.waitForMe = false;\n</code></pre>\n\n<p>Even if the second line is called first, nobody knows when the field update will propagate to the other thread.</p>\n\n<p>What we can do about this? In general, nothing. This is the (desired) behavior of threads.<br>\nFor your problem, you can either block the application until the job is done, or hope that it is done fast enough asynchronously. You could implement some logic, which will display some error message after a given time. But this is quite a bad solution for slow system or systems under heavy load.</p>\n\n<p>If you want to do something after the run method has finished, try <code>SwingWorker</code> (read the java documentation).</p>\n\n<hr>\n\n<p>Some more things:</p>\n\n<pre><code>ClipSetThread set = new ClipSetThread(theApp);\nset.arg = arg;\n</code></pre>\n\n<p>Use the constructor, add a second argument.</p>\n\n<hr>\n\n<pre><code>while(true) \n{\n try\n {\n sysClip.setContents(new StringSelection(arg), null);\n }\n catch(Exception e)\n {\n try {Thread.sleep(20);} catch (InterruptedException e1) {}\n continue;\n }\n break;\n}\nreturn;\n</code></pre>\n\n<p>Without discussing the pattern, this could be more readable:</p>\n\n<pre><code>boolean isSuccessful = false;\nwhile(!isSuccessful) {\n try {\n sysClip.setContents(new StringSelection(arg), null);\n isSuccessful = true;\n }\n catch(Exception e) {\n try {Thread.sleep(20);} catch (InterruptedException e1) {} //you could use a method wait(seconds) for this\n }\n}\nreturn;\n</code></pre>\n\n<p>And you should, if possible, document inside the catch block why you are doing nothing there.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-02-05T22:07:38.830", "Id": "21355", "ParentId": "21348", "Score": "1" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "3", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-02-05T19:43:53.737", "Id": "21348", "Score": "1", "Tags": [ "java" ], "Title": "Reliably setting the system clipboard in a spawned thread and having the spawner wait" }
21348
<p>I did this program and I need to make sure I did it right. The answers come out to be right but I want to make sure nothing is wrong with the coding.</p> <pre><code>class RecursiveMethods { RecursiveMethods() //default constructor { } public int fOf(int x) { if (x &lt;= 10) //the base case { System.out.println(x + " &lt;= 10, therefore ... f(" + x + ") = -5"); return -5; } else { System.out.println(x + " &gt; 10, therefore ... f(" + x + ") = f(" + x + " - 3) + 2 = f(" + (x -3) + ") + 2"); return fOf(x-3) + 2; } } } public class RecursionMethodTester { public static void main(String[] args) { int x; RecursiveMethods rMethods = new RecursiveMethods(); System.out.println("---------------------------------"); System.out.println(" f(x - 3) + 2 if x &gt; 10"); System.out.println("f(x) = "); System.out.println(" -5 if x &lt;= 10"); System.out.println("---------------------------------"); System.out.println(); x = 20; System.out.println("Example 1: x = " + x); System.out.println("f(" + x + ") = " + rMethods.fOf(x)); System.out.println(); x = 19; System.out.println("Example 2: x = " + x); System.out.println("f(" + x + ") = " + rMethods.fOf(x)); System.out.println(); x = 18; System.out.println("Example 3: x = " + x); System.out.println("f(" + x + ") = " + rMethods.fOf(x)); System.out.println(); } } </code></pre>
[ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-02-05T20:18:03.650", "Id": "34256", "Score": "2", "body": "Could you add an explanation of what is the code supposed to do?" } ]
[ { "body": "<p>It is fine. The code could use the following improvements:</p>\n\n<ul>\n<li>some additional comments, to describe in particular what the recursive function does. Recursive functions are by nature harder to read.</li>\n<li>\"fOf\" is not a particularly good method name. Try to use longer, explicit names.</li>\n</ul>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-02-05T20:43:32.983", "Id": "21352", "ParentId": "21349", "Score": "-1" } }, { "body": "<p>As mentioned by @Cyrille fOf is not a good method name.</p>\n\n<p>I disagree with the use of more comments, if you name your function well enough, you shouldn't need comments. Comments should be used to explain hard to understand or confusing code, not describe what is going on.</p>\n\n<p>In java the opening <code>{</code> is usually placed at the end of the line where the code block starts. i.e.</p>\n\n<pre><code>if (somethingIsTrue) {\n</code></pre>\n\n<p>You can get rid of the else in your fOf function. It is implied with the return in the if.</p>\n\n<p>You don't need to specify the default constructor. It does nothing, so it is just clutter.</p>\n\n<p>I'm also not happy with having the <code>System.out.println</code> in your class. Off of the top of my head, I would create an reporting structure, which would include an interface and at least one class. Something like</p>\n\n<pre><code>interface Reporter {\n\n void reportLine(string message);\n}\n</code></pre>\n\n<p>Then you could implement it like</p>\n\n<pre><code>public class ConsoleReporter implements Reporter {\n\n void reportLine(string message) {\n System.out.println(message);\n }\n\n}\n</code></pre>\n\n<p>and your implementation. Notice the constructor now does something, so my point about removing it is not valid in this case.</p>\n\n<pre><code>class RecursiveMethods {\n\n private Reporter reporter;\n\n RecursiveMethods(Reporter reporter) //default constructor\n {\n this.reporter = reporter;\n }\n\n public int fOf(int x)\n {\n if (x &lt;= 10) //the base case\n {\n reporter.reportLine(x + \" &lt;= 10, therefore ... f(\" + x + \") = -5\");\n return -5;\n }\n\n reporter.reportLine(x + \" &gt; 10, therefore ... f(\" + x + \") = f(\" + x + \" - 3) + 2 = f(\" + (x -3) + \") + 2\");\n\n return fOf(x-3) + 2;\n } \n}\n\npublic static void main(String[] args)\n{\n Reporter reporter = new ConsoleReporter();\n int x;\n RecursiveMethods rMethods = new RecursiveMethods(reporter);\n\n // Change all System.out.writeLn to reporter.reportLine\n}\n</code></pre>\n\n<p>Doing this will allow you to output to different mediums, for instance, you could create FileReporter, which would output to a file, or StreamingReporter, which would output to a stream of some sort. It just makes your code more versatile. You could also add a method like reportString, which would write an entire formatted string.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-02-05T21:21:32.357", "Id": "21354", "ParentId": "21349", "Score": "5" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "1", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-02-05T19:48:48.197", "Id": "21349", "Score": "1", "Tags": [ "java", "recursion" ], "Title": "Recursively printing equations" }
21349
<p>I just started Java programming yesterday (so don't expect too much), and I've written some code. My code works the way I want it to work, but there are obviously things wrong with it.</p> <p>I was wondering how it could be improved. I think I've added unnecessary things. I'm practicing using classes and other stuff.</p> <p><strong>testing.java</strong></p> <pre><code>import java.util.Scanner; class testing { private static Scanner input_sn; private static Scanner input_fn; private static Scanner input_mem; public static void main(String[] args){ String First_Name; String Second_Name; int members; int count; System.out.println("Members: "); input_mem = new Scanner(System.in); members = input_mem.nextInt(); funcs funcsObj = new funcs(); for (count = 0; count &lt; members; count++) { System.out.println("What is the first name? "); input_fn = new Scanner(System.in); First_Name = input_fn.nextLine(); System.out.println("What is the second name? "); input_sn = new Scanner(System.in); Second_Name = input_sn.nextLine(); funcsObj.names( funcsObj.setFn(First_Name), funcsObj.setSn(Second_Name)); } } } </code></pre> <p><strong>funcs.java</strong></p> <pre><code>public class funcs { private String firstName; private String secondName; private static int members = 0; public String setFn(String fn) { firstName = fn; return fn; } public String setSn(String sn) { secondName = sn; return sn; } public void names(String fn, String sn) { firstName = fn; secondName = sn; members++; System.out.printf("%d\t%s\t%s\n", members, fn, sn); } } </code></pre> <p>(I think most of the problems can be found in the <strong>funcs.java</strong> file.)</p>
[ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-02-05T20:54:08.560", "Id": "34258", "Score": "0", "body": "You've added a \"Performance\" tag. Is the program too slow for you? Just how fast do you need it to be?" } ]
[ { "body": "<h3>Styling:</h3>\n\n<p>You have to fix the case of your identifiers to be more idiomatic. It means:</p>\n\n<ul>\n<li>Class names should be Capitalized (\"Testing\", \"Funcs\", ...)</li>\n<li>Class members and variables should use camel case (\"firstName\", \"inputSn\", ...)</li>\n</ul>\n\n<p>Also:</p>\n\n<ul>\n<li>The method <code>names</code> of class <code>funcs</code> behaves like a \"setter\", so it should have a name like <code>setNames</code>. In general, try to use action verbs in your method names.</li>\n<li><strong>Edit</strong>: the <code>setXX()</code> methods of <code>funcs</code> should not return anything, as they are \"setters\", they are there to \"set\".</li>\n</ul>\n\n<h3>Code quality:</h3>\n\n<ul>\n<li>Variables like \"String First_Name\" should not all be declared at the beginning of the method, but instead next to the place where they are first used. This way you limit their scope (which makes programming errors more clear) and the code is easier to read.</li>\n<li>Similarily, if you don't have a compelling reason to have all the Scanner instances as class members, declare them in your main method where they are used.</li>\n<li>Why do you use different Scanner objects for every input? You can simply use one Scanner and use its <code>nextLine()</code> method 3 times. That's the only \"performance\" tips that you can get, I think (not that you would have any performance problem with such a short program anyway).</li>\n<li><strong>Edit</strong>: In the line <code>funcsObj.names( funcsObj.setFn(First_Name), funcsObj.setSn(Second_Name));</code> you are actually setting the members of your <code>funcs</code> objects twice. First in the <code>setFn</code> and <code>setSn</code> methods and then in the <code>names</code> method. You don't need to. Just call your <code>setXX</code> methods. If you want to have the <code>members</code> thing incremented and the data displayed, you can rename <code>names</code> into <code>incrementMembers</code> and remove all setting code from there.</li>\n</ul>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-02-05T21:23:07.873", "Id": "34259", "Score": "2", "body": "`the setXX() methods of funcs should not return anything, as they are \"setters\"` well, unless they return `this`, allowing for method-chaining. but that's probably outside the scope of this issue." } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-02-05T20:56:00.990", "Id": "21353", "ParentId": "21350", "Score": "3" } }, { "body": "<p>Given that Cyrille has already given some good advice, here's a more 'learned' solution, showing some patterns and possibilities to watch out for:</p>\n\n<pre><code>public class App {\n public static void main(String[] args) {\n\n new Thread(new Runnable() {\n public void run() {\n Testing.collectAndReport(System.out, System.in);\n }\n }).start();\n }\n}\n</code></pre>\n\n<p>The first thing that you should know is that it's always best to isolate pretty much everything from your <code>main(...)</code> method. Among other things, this means that it can be easy to include your actual application in some other framework, simply by saying \"instantiate this class\". Parsing <code>args</code> as needed should be fine.<br>\nFor the same reason, it's best for the main method to not 'run' your actual application, either. This is more for when dealing with <code>Swing</code>, where you're supposed to use the 'event-dispatch' thread, but here results in (directly) creating a thread to start.<br>\n<code>Thread</code> should not be sub-classed, so an anonymous inner sub-class of <code>Runnable</code> (an interface) is used. The one required method, <code>run()</code>, contains the actual 'startup' code of the application.<br>\nIt's always best to 'inject' dependencies, such as input/output streams (<code>System.in</code> and <code>System.out</code>). For one thing, this allows other implementations to be swapped out as necessary; in our 'application framework' example, this means I could use a fancy text editor, instead of requiring use of the console.</p>\n\n<p>public final class Member {</p>\n\n<pre><code>private final String firstName;\nprivate final String lastName;\n\npublic Member(String firstName, String lastName) {\n this.firstName = firstName;\n this.lastName = lastName;\n}\n\npublic String getFirstName() {\n return firstName;\n}\n\npublic String getLastName() {\n return lastName;\n}\n\n@Override\npublic String toString() {\n return String.format(\"%s\\t%s\", firstName, lastName);\n}\n</code></pre>\n\n<p>}</p>\n\n<p>Learn how to make good use of 'value' types - small classes, comprising no more than a few primitives. Unless there are very good reasons, these should be 'Immutable' (although you're allowed to 'cheat', sortof) - among other things, doing so makes multi-threaded code <strong>much</strong> simpler. Use things like an overrideable <code>toString()</code> method to be able to get an 'understandable' output.</p>\n\n<pre><code>import java.io.InputStream;\nimport java.io.PrintStream;\nimport java.util.Iterator;\nimport java.util.Scanner;\n\npublic class Testing {\n\n public static void collectAndReport(PrintStream out, InputStream in) {\n final Scanner input = new Scanner(in);\n\n // This count is because you want to print out the index.\n int count = 1;\n for (Member member : getMembers(out, input)) {\n out.printf(\"%d\\t%s\\t\\n\", count++, member);\n }\n\n }\n\n private static Iterable&lt;Member&gt; getMembers(final PrintStream out, final Scanner input) {\n return new Iterable&lt;Member&gt;() {\n\n public Iterator&lt;Member&gt; iterator() {\n\n out.println(\"Number of Members:\");\n final int numberOfMembers = input.nextInt();\n\n return new Iterator&lt;Member&gt;() {\n\n int member = 0;\n\n public void remove() {\n throw new UnsupportedOperationException(\"Not Implemented\");\n }\n\n public Member next() {\n out.println(\"What is the first name?\");\n final String firstName = input.next();\n\n out.println(\"What is the second name?\");\n final String lastName = input.next();\n\n return new Member(firstName, lastName);\n }\n\n public boolean hasNext() {\n return member++ &lt; numberOfMembers;\n }\n };\n }\n };\n }\n}\n</code></pre>\n\n<p>... Learn how to cheat. Computer programming is largely about being able to think in abstractions. Learn what abstractions your language supports, and how to use them. Also learn the standard libraries (and the more commonly used public ones), and what they enable.<br>\nFor instance, by implementing <code>Iterable&lt;Member&gt;</code> like this, I can work with the results as a collections much easier. By implementing <code>Iterator&lt;Member&gt;</code>, I can trivially modify this code to accept 'early exit' from the member creation, or even allow 'infinite' entries (by changing how <code>hasNext()</code> works).</p>\n\n<p>All code compiles and runs on my local JVM/eclipse instance.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-02-05T23:57:01.790", "Id": "21357", "ParentId": "21350", "Score": "1" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "1", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-02-05T20:38:56.993", "Id": "21350", "Score": "5", "Tags": [ "java", "beginner" ], "Title": "Beginner's exercise to ask for first names and surnames" }
21350
<p>As a fairly new C# programmer I am a unsure about when and how to best make use of LINQ (and also when to choose the expression method syntax vs. the query syntax). This question often comes up for me at work, because I heavily lean toward making full use of new language features and a functional style, while my colleagues seem to prefer a more conservative style. This means I have to think a lot about when using LINQ is actually worth it.</p> <p>Now here is where the review part comes in. This is an anonymized piece of code that this question came up for, once coded in a LINQ style and once in imperative style. Which version do you believe is preferable from a readability / maintainability viewpoint?</p> <pre><code>void updateItems() { Items.Clear(); Items.AddRange(Widget.GetDetectedWidgets() .Intersect(GetRelevantWidgets()) .Select(widget =&gt; readSerialNr(widget)) .Where(serial =&gt; serial != null) .DefaultIfEmpty("No relevant widgets found.") .ToArray()); } void updateItems() { Items.Clear(); List&lt;string&gt; relevantWidgets = GetRelevantWidgets().ToList(); foreach(string widget in Widget.GetDetectedWidgets()) { if(relevantWidgets.Contains(widget)) { string serial = readSerialNr(widget); if(serial != null) Items.Add(serial); } } if(Items.Count == 0) Items.Add("No relevant widgets found."); } </code></pre>
[ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-02-06T01:09:24.610", "Id": "34270", "Score": "0", "body": "Tomato solution #1 (s1) - tomatoes solution #2 (s2). S1 results in cleaner code and easier to spot logical errors in since it contains less \"manual code\". However, say that any of the functions you call (GetDetectedWidgets, GetRelevantWidgets, readSerialNr) contains some logic errors, then I would be much happier with debugging that in s2. Also s1 requires LINQ knowledge whereas s2 could be read by anyone not familiar with LINQ. If LINQ is important to your company and for everyone who is or ever will be employed, then go for s1, otherwise stick with s2 :)" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-02-06T01:14:55.310", "Id": "34271", "Score": "0", "body": "Go for S1, and use unit-tests to make sure that those functions you are calling do not themselves contain logic errors. And for what it's worth, I have no knowledge of LINQ and for me the first example is just about as readable as the second." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-02-06T01:23:44.113", "Id": "34272", "Score": "1", "body": "BTW, are you really calling 6 years old features “new”? :-)" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-02-06T16:30:30.720", "Id": "34325", "Score": "0", "body": "@svick you'd be surprised how many people are resistant to LINQ for whatever reason. It's goofy, sure, but there are some people who are just happy with iterative patterns." } ]
[ { "body": "<p>Some notes:</p>\n\n<ol>\n<li><p>I think the LINQ version would be more readable if you extracted a variable for the collection. Something like:</p>\n\n<pre><code>var serials = /* the whole LINQ query here */\n\nItems.Clear();\nItems.AddRange(serials);\n</code></pre></li>\n<li><p>The LINQ version might be more efficient if there were lots of widgets, because <code>Intersect()</code> uses hashing to achieve O(n+m) time complexity, while your imperative code is O(n·m).</p></li>\n<li>You don't need <code>ToArray()</code> in your LINQ version. (Assuming <code>Items</code> is <code>List&lt;string&gt;</code>.)</li>\n<li>I really don't think the string <code>\"No relevant widgets found.\"</code> should be the default value if the list is empty. List of widget serial numbers should contain widget serial numbers, nothing else. And you should separate your business logic and presentation.</li>\n</ol>\n\n<p>With the mentioned changes, I think the LINQ version will be more readable, primarily because <code>Intersect()</code> explains what you want to do better.</p>\n\n<p>Also don't forget that you don't have to use only LINQ or only imperative code, you can combine the two in a single method (e.g. improve the imperative approach by using <code>Intersect()</code>).</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-02-06T02:13:23.570", "Id": "34273", "Score": "0", "body": "Point 1 is the only one I'm not sure what you mean: Assign the intersection to a new variable? On 2: Efficiency is a non-issue here. 3: I do need `ToArray()` in this particular case, since `Items` is a `ComboBox.ObjectCollection` and takes an `object[]` as parameter to AddRange. 4: I agree that the actual logic of getting the port list should have been a separate method, but adding the default text here is consistent with the old behaviour of this UI component." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-02-06T08:16:34.903", "Id": "34277", "Score": "0", "body": "@Medo42 Re 1.: I clarified that." } ], "meta_data": { "CommentCount": "2", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-02-06T01:35:35.603", "Id": "21361", "ParentId": "21359", "Score": "7" } }, { "body": "<p>The greater issue here is not to LINQ or not to LINQ, but rather that of code smells - specifically with the lack of specialized classes and responsibility.</p>\n\n<p>I would assume that the relevant widgets would already be a subset of the detected widgets, hence it would not be necessary to do an intersection at all. </p>\n\n<p>I would definitely use a class instead than just a string to represent a widget. The responsibility of deriving the serial number should lay with the widget class and not with an external method. I would also abstract the responsibility of determining the relevant widgets to an external class and perhaps even the method to return the serial numbers of the relevant widgets.</p>\n\n<p>I believe once you got your basic OOP down, it won't really matter what you use. As long as the code is simple and readable.</p>\n\n<pre><code>internal class Program\n{\n private static void Main(string[] args) {\n var items = new List&lt;string&gt;();\n var widgetStore = new WidgetStore();\n\n var relevantWidgetSerialNumbers = widgetStore.GetRelevantWidgetSerialNumbers()\n .ToArray();\n\n if (relevantWidgetSerialNumbers.Length == 0) {\n items.Add(\"No relevant widgets found.\");\n } else {\n items.AddRange(relevantWidgetSerialNumbers);\n }\n }\n}\n\npublic class Widget\n{\n public string SerialNo {\n get {\n //Implement the logic here to derive the serial number or implement get; set; instead if it's predefined\n return null;\n }\n }\n}\n\npublic class WidgetStore\n{\n public IEnumerable&lt;Widget&gt; GetRelevantWidgets() {\n yield break;\n }\n\n public IEnumerable&lt;string&gt; GetRelevantWidgetSerialNumbers() {\n return GetRelevantWidgets().Select(widget =&gt; widget.SerialNo);\n }\n}\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-02-10T22:37:45.657", "Id": "34633", "Score": "2", "body": "Thank you for taking the time to respond, but this does not relate to my question. Besides, your advice might apply in some cases, but the question simply doesn't contain the details you would need to decide what a good object structure would be in my case, or whether a certain operation is necessary or not." } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-02-10T17:57:32.360", "Id": "21550", "ParentId": "21359", "Score": "0" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "4", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-02-06T00:42:12.450", "Id": "21359", "Score": "3", "Tags": [ "c#", "linq" ], "Title": "To LINQ or not to LINQ" }
21359
<p>I have some code that uses a multidimensional look-up table (LUT) to do interpolation. The typical application is a color space conversion, where 3D inputs (RGB) are converted to 4D (CMYK), but the code is rather general. The look-up table is a numpy array, which will generally have a shape like <code>(4, 17, 17, 17)</code>. Here, <code>4</code> is the number of output dimensions, <code>o</code>, 17 is the number of grid points along each axis, <code>g</code>, which must be the same for all, and 3 (the number of 17s in the shape tuple) is the number of input dimensions, <code>i</code>. There is also <code>lut_axis</code>, 0 in this case, that indicates the position of <code>o</code> in the shape tuple. There is an additional requirement for <code>g</code> to be either a power of two (1, 2, 4, 8, 16...) or a power of two plus one (2, 3, 5, 9, 17...).</p> <p>I am currently checking that the <code>lut</code> and <code>lut_axis</code> I receive as inputs are compatible with the above requirements. But in most cases there is only one value of <code>lut_axis</code> that would yield a correct result, so I think I could improve the code by only using <code>lut_axis</code> when the shape of the LUT doesn't give away what it should be, and else ignoring it.</p> <p>My first attempt was this logical spaghetti code, that gets things done, but which I will be unable to figure out a month from today :</p> <p><strong>OPTION 1</strong></p> <pre><code>from operator import and_ def process_lut_shape(lut_shape, default_axis=0) : i = len(lut_shape) - 1 values = sorted(set(lut_shape)) counts = [lut_shape.count(j) for j in values] count_of_values = len(values) figured_lut_out = False if count_of_values &gt; 2 or i &lt; 1 : figured_lut_out = -1 elif count_of_values == 2 : is_pow_of_two = [j - 2**(j.bit_length() - 1) in (0, 1) for j in values] other_is_one = [counts[(j + 1) % 2] for j in xrange(2)] could_be_g = map(and_, is_pow_of_two, other_is_one) candidates = could_be_g.count(True) if candidates == 0 : figured_lut_out = -1 elif candidates == 1 : idx = could_be_g.index(True) g = values[idx] o = values[(idx + 1) % 2] lut_axis = lut_shape.index(o) figured_out_lut = True if figured_lut_out == False : o = lut_shape[default_axis] g = (o if count_of_values == 1 else values[(values.index(o) + 1) % 2]) lut_axis = default_axis elif figured_out_lut == -1 : msg = 'Array of shape {0} cannot be a lut.' msg = msg.format(str(lut_shape)) raise ValueError(msg) return lut_axis, i, o, g lut_axis, i, o, g = process_lut_shape(lut_shape, default_axis) </code></pre> <p>I think that, since the LUTs that are reasonable to expect will never have more than few dimensions, typically 4 or 5, it may be much clearer to brute-force my way through this:</p> <p><strong>OPTION 2</strong></p> <pre><code>def check_lut_shape(lut_shape, lut_axis) : i = len(lut_shape) - 1 if i &lt; 1 : return False, None o = lut_shape[lut_axis] g = lut_shape[(lut_axis + 1) % (i + 1)] if g - 2**(g.bit_length() - 1) not in (0, 1) : return False, None shape = (g,) * lut_axis + (o,) + (g,) * (i - lut_axis) if any(lut_shape[j] != shape[j] for j in xrange(i + 1)) : return False, None return True, (i, o, g) def find_lut_axis(lut_shape, default_lut_axis=0) : func = lambda j : check_lut_shape(lut_shape, j)[0] could_be_lut_axis = map(func, xrange(len(lut_shape))) candidates = could_be_lut_axis.count(True) if candidates == 0 : msg = 'Array of shape {0} cannot be a lut.' msg = msg.format(str(lut_shape)) raise ValueError(msg) elif candidates == 1 : return could_be_lut_axis.index(True) # I don't think the following can ever happen... elif could_be_lut_axis[default_lut_axis] != True : msg = 'Cannot determine lut_axis for array of shape {0}.' msg = msg.format(str(lut_shape)) raise ValueError(msg) return default_lut_axis lut_axis = find_lut_axis(lut_shape, default_lut_axis) i, o, g = check_lut_shape(lut_shape, lut_axis)[1] </code></pre> <p>There's one call too many to <code>check_lut_shape</code> to fetch the values of <code>i</code>, <code>o</code> and <code>g</code>, but since the code is already not an example of efficiency, the focus should be on readability, and I find it is easier to understand like this.</p> <p>I would feel more comfortable if I could put together a more elegant version of <strong>option 1</strong>, but since I don't see how to go about that, I am more and more leaning to something along the lines of <strong>option 2</strong>. Any comments on which way to go, or improvements over the code above are more than welcome.</p>
[]
[ { "body": "<p>Firstly, you could use some tests. Here are a few I cooked up:</p>\n\n<pre><code>assert_equals( process_lut_shape( (4, 17, 17, 17) ) , (0, 3, 4, 17) )\nassert_equals( process_lut_shape( (14, 16, 16) ) , (0, 2, 14, 16) )\nassert_raises( ValueError, process_lut_shape, (14, 15, 15) )\nassert_equals( process_lut_shape( (1, 16, 16) ) , (0, 2, 1, 16) )\nassert_equals( process_lut_shape( (16, 16, 3) ) , (2, 2, 3, 16) )\nassert_raises( ValueError, process_lut_shape, (14,) )\nassert_raises( ValueError, process_lut_shape, () )\n</code></pre>\n\n<p>If you try these tests, you'll find your function doesn't actually work. It uses <code>figured_lut_out</code> and <code>figured_out_lut</code> interchangeably. </p>\n\n<pre><code>def process_lut_shape(lut_shape, default_axis=0) :\n i = len(lut_shape) - 1\n values = sorted(set(lut_shape))\n</code></pre>\n\n<p>Why sort it? </p>\n\n<pre><code> counts = [lut_shape.count(j) for j in values]\n count_of_values = len(values)\n figured_lut_out = False\n</code></pre>\n\n<p>Flag variables are delayed gotos. They make code hard to read. Instead of setting a flag to do something later, just do it.</p>\n\n<pre><code> if count_of_values &gt; 2 or i &lt; 1 :\n</code></pre>\n\n<p>Using <code>i</code> here is confusing, I'd use <code>len(lut_shape)</code> </p>\n\n<pre><code> figured_lut_out = -1\n</code></pre>\n\n<p>Using -1 to create a trinary value is just confusing.</p>\n\n<pre><code> elif count_of_values == 2 :\n is_pow_of_two = [j - 2**(j.bit_length() - 1) in (0, 1) for j in values]\n</code></pre>\n\n<p>Somewhat confusingly named because its not really just checking for a power of 2</p>\n\n<pre><code> other_is_one = [counts[(j + 1) % 2] for j in xrange(2)]\n could_be_g = map(and_, is_pow_of_two, other_is_one)\n</code></pre>\n\n<p>I think this is too clever, simply writing it out without using loops would probably be clearer</p>\n\n<pre><code> candidates = could_be_g.count(True)\n if candidates == 0 :\n figured_lut_out = -1\n elif candidates == 1 :\n idx = could_be_g.index(True)\n g = values[idx]\n o = values[(idx + 1) % 2]\n lut_axis = lut_shape.index(o)\n figured_out_lut = True\n</code></pre>\n\n<p>You already have all the data here, just return it.</p>\n\n<pre><code> if figured_lut_out == False :\n o = lut_shape[default_axis]\n g = (o if count_of_values == 1 else\n values[(values.index(o) + 1) % 2])\n</code></pre>\n\n<p>That feels very awkward.</p>\n\n<pre><code> lut_axis = default_axis\n elif figured_out_lut == -1 :\n msg = 'Array of shape {0} cannot be a lut.'\n msg = msg.format(str(lut.shape))\n</code></pre>\n\n<p>There is no reason to use <code>str</code> when doing format.\n raise ValueError(msg)</p>\n\n<pre><code>def check_lut_shape(lut_shape, lut_axis) :\n i = len(lut_shape) - 1\n if i &lt; 1 :\n</code></pre>\n\n<p>Why check <code>i</code>? Isn't <code>len(lut_shape)</code> more clear?\n return False, None</p>\n\n<p>You don't need to return two values, just return None.</p>\n\n<pre><code> o = lut_shape[lut_axis]\n g = lut_shape[(lut_axis + 1) % (i + 1)]\n</code></pre>\n\n<p>Again use <code>len</code> not <code>i</code></p>\n\n<pre><code> if g - 2**(g.bit_length() - 1) not in (0, 1) :\n return False, None\n shape = (g,) * lut_axis + (o,) + (g,) * (i - lut_axis)\n if any(lut_shape[j] != shape[j] for j in xrange(i + 1)) :\n</code></pre>\n\n<p>just use <code>if lut_shape != shape</code>. However, reconstructing the shape to compare it feels a little awkward.</p>\n\n<pre><code> return False, None\n return True, (i, o, g)\n\ndef find_lut_axis(lut_shape, default_lut_axis=0) :\n func = lambda j : check_lut_shape(lut_shape, j)[0]\n could_be_lut_axis = map(func, xrange(len(lut_shape)))\n</code></pre>\n\n<p>Use <code>could_be_lut_axis = [check_lut_shape(lut_shape, j)[0] for j in xrange(len(lut_shape))]</code></p>\n\n<pre><code> candidates = could_be_lut_axis.count(True)\n if candidates == 0 :\n msg = 'Array of shape {0} cannot be a lut.'\n msg = msg.format(str(lut_shape))\n raise ValueError(msg)\n elif candidates == 1 :\n return could_be_lut_axis.index(True)\n # I don't think the following can ever happen...\n elif could_be_lut_axis[default_lut_axis] != True :\n msg = 'Cannot determine lut_axis for array of shape {0}.'\n msg = msg.format(str(lut_shape))\n raise ValueError(msg)\n return default_lut_axis\n</code></pre>\n\n<p>Here's my approach:</p>\n\n<pre><code>def process_lut_shape(lut_shape, default_axis=0):\n\n if len(lut_shape) &lt; 2:\n # anything less then two long cannot be a shape\n raise NoneLutShapeError(lut_shape)\n elif len(lut_shape) == 2:\n # given two, either could be the lut_axis\n # try the default if it can work\n # otherwise try the other one\n if is_almost_power_of_two(lut_shape[default_axis]):\n lut_axis = default_axis\n else:\n lut_axis = 1 - default_axis\n else: # len(lut_shape) &gt;= 3\n counts = Counter(lut_shape)\n if len(counts) == 1:\n # since all axis are the same, we can't distinguish between them\n lut_axis = default_axis\n elif len(counts) &gt; 2:\n # can't have more then 2 distinct values in the shape\n raise NoneLutShapeError(lut_shape)\n else:\n # the least common count, with three elements should be the one\n lut_value, count = counts.most_common()[-1]\n if count != 1:\n raise NoneLutShapeError(lut_shape)\n lut_axis = lut_shape.index(lut_value)\n\n g = lut_shape[(lut_axis + 1) % len(lut_shape)]\n if not is_almost_power_of_two(g):\n raise NoneLutShapeError(g)\n return lut_axis, len(lut_shape) - 1, lut_shape[lut_axis], g\n</code></pre>\n\n<p>However, I'd really recommend you not write this function at all. This function is guessing. As the zen of python says:</p>\n\n<blockquote>\n <p>In the face of ambiguity, refuse the temptation to guess.</p>\n</blockquote>\n\n<p>Given <code>(16, 16, 16)</code> you have no way of knowing which axis was intended to be the lut_axis. So I really really recommend not trying to guess. You'll just do the wrong thing oddly in certain circumstances. Even trying to figure it out when its not ambigious is problematic because it'll still become ambigious at times and your code will work differently. As the Zen of Python also says:</p>\n\n<blockquote>\n <p>Explicit is better than implicit.</p>\n</blockquote>\n\n<p>Make your users explicitly pass the lut_axis. You can't do the correct thing for all inputs, so don't create false expectations by doing the correct thing for some inputs. </p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-02-06T07:42:10.743", "Id": "34274", "Score": "0", "body": "Nice use of `Counter`, I need to get more acquainted with `collections`. And lose my fear of calling `len` more than once on the same sequence, it is an O(1) operation in Python. Good point also on the Zen of Python, but I'm leaning towards still writing this function, but call it only if `lut_axis` is not explicitly provided, and raise an error if the result cannot be unambiguously determined. Ambiguous shapes are a rare corner case, and most users don't know (and don't have to know) what `lut_axis` is." } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-02-06T02:32:28.107", "Id": "21363", "ParentId": "21360", "Score": "4" } } ]
{ "AcceptedAnswerId": "21363", "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-02-06T01:20:00.097", "Id": "21360", "Score": "1", "Tags": [ "python", "numpy" ], "Title": "Figuring out the structure of a shape tuple" }
21360
<p>I am looking for a memory efficient python script for the following script. The following script works well for smaller dimension but the dimension of the matrix is 5000X5000 in my actual calculation. Therefore, it takes very long time to finish it. Can anyone help me how can I do that?</p> <pre><code>def check(v1,v2): if len(v1)!=len(v2): raise ValueError,"the lenght of both arrays must be the same" pass def d0(v1, v2): check(v1, v2) return dot(v1, v2) import numpy as np from pylab import * vector=[[0.1, .32, .2, 0.4, 0.8], [.23, .18, .56, .61, .12], [.9, .3, .6, .5, .3], [.34, .75, .91, .19, .21]] rav= np.mean(vector,axis=0) #print rav #print vector m= vector-rav corr_matrix=[] for i in range(0,len(vector)): tmp=[] x=sqrt(d0(m[i],m[i])) for j in range(0,len(vector)): y=sqrt(d0(m[j],m[j])) z=d0(m[i],m[j]) w=z/(x*y) tmp.append(w) corr_matrix.append(tmp) print corr_matrix </code></pre>
[ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-02-06T12:27:08.100", "Id": "34309", "Score": "0", "body": "\"... memory efficient ... very long time ...\" Do you want to optimize memory usage or runtime?" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-02-06T18:24:46.373", "Id": "34329", "Score": "0", "body": "I am looking for both." } ]
[ { "body": "<p>I noticed one of your issues is that you are calculating the same thing over and over again when it is possible to pre-calculate the values before looping. First of all:</p>\n<pre><code>x = sqrt(d0(m[i], m[i]))\n</code></pre>\n<p>and:</p>\n<pre><code>y = sqrt(d0(m[j], m[j]))\n</code></pre>\n<p>are doing the exact same thing. You are calculating the sqrt() of dot product of the entire length of the vector length^2 times! For your 5000 element vector list, that's 25,000,000 times.</p>\n<p>When it comes to iterating over giant mounds of data, try to pre-calculate as much as possible. Try this:</p>\n<pre><code>pre_sqrt = [sqrt(d0(elem, elem)) for elem in m]\npre_d0 = [d0(i, j) for i in m for j in m]\n</code></pre>\n<p>Then, to reduce the amount of repetitive calls to <code>len()</code> and <code>range()</code>:</p>\n<pre><code>vectorLength = len(vector)\niterRange = range(vectorLength)\n</code></pre>\n<p>Finally, this is how your for loops should look:</p>\n<pre><code>for i in iterRange:\n\n tmp = [] \n x = pre_sqrt[i]\n \n for j in iterRange:\n\n y = pre_sqrt[j]\n z = pre_d0[i*vectorLength + j]\n \n w = z / (x * y)\n\n tmp.append(w)\n\n corr_matrix.append(tmp)\n</code></pre>\n<p>When I timed your implementation vs mine these were the average speeds over 10000 repetitions:</p>\n<blockquote>\n<p><strong>Old:</strong> .150 ms</p>\n<p><strong>Mine:</strong> .021 ms</p>\n</blockquote>\n<p>That's about a 7 fold increase over your small sample vector. I imagine the speed increase will be even better when you enter the 5000 element vector.</p>\n<p>You should also be aware that there could be some Python specific improvements to be made. For example, using lists vs numpy arrays to store large amounts of data. Perhaps someone else can elaborate further on those types of speed increases.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-02-06T05:01:49.013", "Id": "21364", "ParentId": "21362", "Score": "4" } }, { "body": "<p>Use a profiler to know your hot spots: <a href=\"http://docs.python.org/2/library/profile.html\" rel=\"nofollow\">http://docs.python.org/2/library/profile.html</a></p>\n\n<hr>\n\n<p>Follow the advices from TerryTate.</p>\n\n<hr>\n\n<p>Describe your algorithm. It is not directly clear what should happen in this loop. If you abstract the algorithm inside a specification, you can perhaps simplify the abstract specification to get a better algorithm.</p>\n\n<hr>\n\n<p>Correlates to the previous one: Use meaningful names.<br>\nFor example:</p>\n\n<pre><code>vector=[[0.1, .32, .2, 0.4, 0.8], [.23, .18, .56, .61, .12], [.9, .3, .6, .5, .3], [.34, .75, .91, .19, .21]]\n</code></pre>\n\n<p>Sure, this is a vector for a vector space over a R^5 field, but you could call it a matrix and everyone can follow it.</p>\n\n<pre><code>def check(v1,v2):\n if len(v1)!=len(v2):\n raise ValueError,\"the lenght of both arrays must be the same\"\n</code></pre>\n\n<p>What does it check? (And i think, you do not need it. Because dot from numpy will already raise an error for illegal arguments)</p>\n\n<pre><code>def d0(v1, v2):\n check(v1, v2)\n return dot(v1, v2)\n</code></pre>\n\n<p>What is d0? Call it get_inner_product or something like this (I even do not like the numpy name, but well)</p>\n\n<p>and some more</p>\n\n<hr>\n\n<p>from pylab import *</p>\n\n<p>Try to avoid import everything. This will lead to problems, sometimes hard to read code and namespace problems.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-02-06T14:41:55.697", "Id": "21377", "ParentId": "21362", "Score": "0" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "2", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-02-06T02:19:53.197", "Id": "21362", "Score": "1", "Tags": [ "python" ], "Title": "Looking for efficient python program for this following python script" }
21362
<p>Here's my attempt at Project Euler Problem #5, which is looking quite clumsy when seen the first time. Is there any better way to solve this? Or any built-in library that already does some part of the problem?</p> <pre><code>''' Problem 5: 2520 is the smallest number that can be divided by each of the numbers from 1 to 10 What is the smallest number, that is evenly divisible by each of the numbers from 1 to 20? ''' from collections import defaultdict def smallest_number_divisible(start, end): ''' Function that calculates LCM of all the numbers from start to end It breaks each number into it's prime factorization, simultaneously keeping track of highest power of each prime number ''' # Dictionary to store highest power of each prime number. prime_power = defaultdict(int) for num in xrange(start, end + 1): # Prime number generator to generate all primes till num prime_gen = (each_num for each_num in range(2, num + 1) if is_prime(each_num)) # Iterate over all the prime numbers for prime in prime_gen: # initially quotient should be 0 for this prime numbers # Will be increased, if the num is divisible by the current prime quotient = 0 # Iterate until num is still divisible by current prime while num % prime == 0: num = num / prime quotient += 1 # If quotient of this priime in dictionary is less than new quotient, # update dictionary with new quotient if prime_power[prime] &lt; quotient: prime_power[prime] = quotient # Time to get product of each prime raised to corresponding power product = 1 # Get each prime number with power for prime, power in prime_power.iteritems(): product *= prime ** power return product def is_prime(num): ''' Function that takes a `number` and checks whether it's prime or not Returns False if not prime Returns True if prime ''' for i in xrange(2, int(num ** 0.5) + 1): if num % i == 0: return False return True if __name__ == '__main__': print smallest_number_divisible(1, 20) import timeit t = timeit.timeit print t('smallest_number_divisible(1, 20)', setup = 'from __main__ import smallest_number_divisible', number = 100) </code></pre> <p>While I timed the code, and it came out with a somewhat ok result. The output came out to be:</p> <pre><code>0.0295362259729 # average 0.03 </code></pre> <p>Any inputs?</p>
[ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-02-06T12:07:04.760", "Id": "34279", "Score": "0", "body": "I think you can adapt [Erathosthenes' prime sieve](http://en.wikipedia.org/wiki/Sieve_of_Eratosthenes) to compute is_prime plus the amount of factors in one go." } ]
[ { "body": "<p>You are recomputing the list of prime numbers for each iteration. Do it just once and reuse it. There are also better ways of computing them other than trial division, the <a href=\"http://en.wikipedia.org/wiki/Sieve_of_Eratosthenes\" rel=\"nofollow\">sieve of Eratosthenes</a> is very simple yet effective, and will get you a long way in Project Euler. Also, the factors of <code>n</code> are all smaller than <code>n**0.5</code>, so you can break out earlier from your checks.</p>\n\n<p>So add this before the <code>num</code> for loop:</p>\n\n<pre><code>prime_numbers = list_of_primes(int(end**0.5))\n</code></pre>\n\n<p>And replace <code>prime_gen</code> with :</p>\n\n<pre><code>prime_gen =(each_prime for each_prime in prime_numbers if each_prime &lt;= int(num**0.5))\n</code></pre>\n\n<p>The <code>list_of_primes</code> function could be like this using trial division :</p>\n\n<pre><code>def list_of_primes(n)\n \"\"\"Returns a list of all the primes below n\"\"\"\n ret = []\n for j in xrange(2, n + 1) :\n for k in xrange(2, int(j**0.5) + 1) :\n if j % k == 0 :\n break\n else :\n ret.append(j)\n return ret\n</code></pre>\n\n<p>But you are better off with a very basic <a href=\"http://numericalrecipes.wordpress.com/2009/03/16/prime-numbers-2-the-sieve-of-erathostenes/\" rel=\"nofollow\">sieve of Erathostenes</a>:</p>\n\n<pre><code>def list_of_primes(n) :\n sieve = [True for j in xrange(2, n + 1)]\n for j in xrange(2, int(sqrt(n)) + 1) :\n i = j - 2\n if sieve[j - 2]:\n for k in range(j * j, n + 1, j) :\n sieve[k - 2] = False\n return [j for j in xrange(2, n + 1) if sieve[j - 2]]\n</code></pre>\n\n<hr>\n\n<p>There is an alternative, better for most cases, definitely for Project Euler #5, way of going about calculating the least common multiple, using the greatest common divisor and <a href=\"http://en.wikipedia.org/wiki/Euclidean_algorithm\" rel=\"nofollow\">Euclid's algorithm</a>:</p>\n\n<pre><code>def gcd(a, b) :\n while b != 0 :\n a, b = b, a % b\n return a\n\ndef lcm(a, b) :\n return a // gcd(a, b) * b\n\nreduce(lcm, xrange(start, end + 1))\n</code></pre>\n\n<p>On my netbook this gets Project Euler's correct result lightning fast:</p>\n\n<pre><code>In [2]: %timeit reduce(lcm, xrange(1, 21))\n10000 loops, best of 3: 69.4 us per loop\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-02-06T14:46:49.650", "Id": "34318", "Score": "0", "body": "I agree, using gcd is the easiest way here. I am quite sure it had to be written before or anywhere else anyway. (For very large numbers, this approach has some problems, but well, 20 is not a very large number)" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-02-07T03:27:25.840", "Id": "34344", "Score": "0", "body": "Hello @Jaime. Thanks for your response. I tried to use your `list_of_prime` method, but the problem is: - `end ** 0.5` range generates just `[2, 3]` as prime numbers below `20`. So, it's not considering `5`, which is a valid prime diviser. Same in the case of `10`. It's not considering `5`. And hence I'm loosing some factors. Also, for numbers like `5`, or `7`, again it is not considering `5` and `7` respectively, which we should consider right? So, does that mean that `range(2, int(end**0.5))` is not working well?" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-02-07T03:30:09.453", "Id": "34345", "Score": "0", "body": "However, if I replace the range with `range(2, end)`, and in list comprehension also: - `each_prime <= num`, it's giving me correct result." } ], "meta_data": { "CommentCount": "3", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-02-06T14:24:13.717", "Id": "21375", "ParentId": "21367", "Score": "7" } }, { "body": "<p>You can use the Sieve of Erathosthenes just once AND count the factors while you filter the primes:</p>\n\n<pre><code>def computeMultiplicity(currentPrime, n):\n result = 0\n while n % currentPrime == 0:\n n = n / currentPrime\n result = result + 1\n return result\n\ndef euler5(n):\n result = 1\n isPrime = [True for _ in range(n + 1)]\n\n for currentPrime in range(2, n + 1):\n if isPrime[currentPrime]:\n multiplicity = 1 \n for multiple in range(2 * currentPrime, n + 1, currentPrime):\n isPrime[multiple] = False\n multiplicity = max(multiplicity, computeMultiplicity(currentPrime, multiple))\n result *= currentPrime ** multiplicity\n\n return result\n\nif __name__ == '__main__':\n print(euler5(20))\n\n from timeit import timeit\n print(timeit('euler5(20)', setup='from __main__ import euler5', number=100))\n</code></pre>\n\n<p>Prints:</p>\n\n<pre><code>0.00373393183391\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-11-02T15:12:53.207", "Id": "53972", "Score": "0", "body": "This code does not appear to be in Python." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-11-02T15:46:15.350", "Id": "53974", "Score": "0", "body": "@GarethRees You are most observant ;) It is a Java implementation of a (way) more efficient algorithm. Shouldn't be too hard to port to python since it's all simple arithmetic computations." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-11-02T16:42:24.750", "Id": "53977", "Score": "0", "body": "@GarethRees Ported to Python. Better? :)" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-11-02T18:10:39.683", "Id": "53981", "Score": "0", "body": "Yes, that's better." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-01-04T20:07:07.307", "Id": "64367", "Score": "0", "body": "`isPrime = [True for _ in range(n + 1)]` can be written as `isPrime = [True] * (n + 1)`. I would also add a comment that `isPrime[0]` and `isPrime[1]` are erroneous but inconsequential." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-01-04T20:08:22.140", "Id": "64368", "Score": "0", "body": "Write `n = n / currentPrime` as `n = n // currentPrime` (explicit integer division) for compatibility with Python 3. Or, `n //= currentPrime`." } ], "meta_data": { "CommentCount": "6", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-02-06T14:31:03.190", "Id": "21376", "ParentId": "21367", "Score": "3" } }, { "body": "<p>For a \"small\" problem like this, performance is a non-issue, and clarity should be the primary consideration. I would decompose the problem into well recognized and testable primitives.</p>\n\n<p>Furthermore, you can eliminate the <code>is_prime()</code> test, as it is just unnecessary extra work. (Why?)</p>\n\n<pre><code>def prime_factors(n):\n '''\n Returns the prime factorization of n as a dict-like object whose keys\n are prime factors and whose values are their powers.\n\n &gt;&gt;&gt; [(k, v) for k, v in prime_factors(360).iteritems()]\n [(2, 3), (3, 2), (5, 1)]\n '''\n # This is a simplistic, non-optimized implementation. For better\n # performance with larger inputs, you could terminate the loop earlier, use\n # memoization, or implement the Sieve of Eratosthenes.\n factors_and_powers = defaultdict(int)\n for i in range(2, n+1):\n while n % i == 0:\n factors_and_powers[i] += 1\n n //= i\n return factors_and_powers\n\ndef product(factors_and_powers):\n '''\n Given a dict-like object whose keys are factors and whose values\n are their powers, returns the product.\n\n &gt;&gt;&gt; product({})\n 1\n &gt;&gt;&gt; product({3: 1})\n 3\n &gt;&gt;&gt; product({2: 3, 3: 2, 5: 1})\n 360\n '''\n return reduce(lambda mult, (factor, power): mult * (factor ** power),\n factors_and_powers.iteritems(),\n 1)\n\ndef least_common_multiple(numbers):\n '''\n Returns the least common multiple of numbers, which is an iterable\n that yields integers.\n\n &gt;&gt;&gt; least_common_multiple([1])\n 1\n &gt;&gt;&gt; least_common_multiple([2])\n 2\n &gt;&gt;&gt; least_common_multiple([6])\n 6\n &gt;&gt;&gt; least_common_multiple([4, 6])\n 12\n '''\n lcm_factors = defaultdict(int)\n for n in numbers:\n for factor, power in prime_factors(n).iteritems():\n lcm_factors[factor] = max(lcm_factors[factor], power)\n return product(lcm_factors)\n\ndef smallest_number_divisible(start, end):\n '''\n Calculates the LCM of all the numbers from start to end, inclusive. It\n breaks each number into its prime factorization, keeping track of highest\n power of each prime factor.\n\n &gt;&gt;&gt; smallest_number_divisible(1, 10)\n 2520\n '''\n return least_common_multiple(xrange(start, end + 1))\n\nif __name__ == '__main__':\n import doctest\n doctest.testmod()\n print smallest_number_divisible(1, 20)\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-11-03T19:04:21.950", "Id": "54040", "Score": "0", "body": "By the way, this version completes in about 1/3 of the time of the original code." } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-11-03T19:00:51.827", "Id": "33752", "ParentId": "21367", "Score": "0" } }, { "body": "<p>There is no least common multiple function in the built-in library. However, there is a greatest common divisor function. You can take advantage of the fact that LCM(<em>a</em>, <em>b</em>) × GCD(<em>a</em>, <em>b</em>) = <em>a b</em>.</p>\n\n<pre><code>from fractions import gcd\n\ndef lcm(a, b):\n return (a * b) // gcd(a, b)\n\nreduce(lcm, range(1, 20 + 1))\n</code></pre>\n\n<p><a href=\"http://docs.python.org/2/library/functions.html#reduce\" rel=\"nofollow\"><code>reduce()</code></a> calls <code>lcm()</code> repeatedly, as in <code>lcm(… lcm(lcm(lcm(1, 2), 3), 4), … 20)</code>.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-01-03T08:28:32.220", "Id": "38486", "ParentId": "21367", "Score": "0" } } ]
{ "AcceptedAnswerId": "21375", "CommentCount": "1", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-02-06T10:09:49.247", "Id": "21367", "Score": "5", "Tags": [ "python", "project-euler", "primes" ], "Title": "Any better way to solve Project Euler Problem #5?" }
21367
<p>I am having a few issues about a session class that I found after reading it a lots of times,</p> <p><strong>Here is the class :</strong></p> <pre><code>class SessionManager{ static function sessionStart($name, $limit = 0, $path = '/', $domain = null, $secure = null) { $https = isset($secure) ? $secure : isset($_SERVER['HTTPS']); session_set_cookie_params($limit, $path, $domain, $https, true); session_start(); if(self::validateSession()) { if(!self::preventHijacking()) { $_SESSION = array(); $_SESSION['IPaddress'] = $_SERVER['REMOTE_ADDR']; $_SESSION['userAgent'] = $_SERVER['HTTP_USER_AGENT']; self::regenerateSession(); }elseif(rand(1, 100) &lt;= 5){ self::regenerateSession(); } }else{ $_SESSION = array(); session_destroy(); session_start(); } } static protected function preventHijacking() { if(!isset($_SESSION['IPaddress']) || !isset($_SESSION['userAgent'])) return false; if ($_SESSION['IPaddress'] != $_SERVER['REMOTE_ADDR']) return false; if( $_SESSION['userAgent'] != $_SERVER['HTTP_USER_AGENT']) return false; return true; } static function regenerateSession() { if(isset($_SESSION['OBSOLETE']) || $_SESSION['OBSOLETE'] == true) return; $_SESSION['OBSOLETE'] = true; $_SESSION['EXPIRES'] = time() + 10; session_regenerate_id(false); $newSession = session_id(); session_write_close(); session_id($newSession); session_start(); unset($_SESSION['OBSOLETE']); unset($_SESSION['EXPIRES']); } static protected function validateSession() { if( isset($_SESSION['OBSOLETE']) &amp;&amp; !isset($_SESSION['EXPIRES']) ) return false; if(isset($_SESSION['EXPIRES']) &amp;&amp; $_SESSION['EXPIRES'] &lt; time()) return false; return true; } } </code></pre> <p>My concerns are:</p> <ol> <li><p><strong>Security</strong> [Fixation,Hijacking] , is the above a bulletproof ?</p></li> <li><p><strong>Usability</strong> I am unable to understand how to use the above code in terms of providing the user an authorized access as long not logging out was performed i.e after secure logging should I just keep calling <code>session_start(parameters);</code> and when logging out call <code>session_destroy()</code> [In addition to make the class functions public/protected .. ]; ?</p></li> <li><p>I am unable to convince myself that this will not cause problems when redirecting between pages such as after submitting a form(like when pressing the back button [I am not attending to rely on JavaScript]),disconnecting and reconnecting </p></li> <li><p>How do I integrate secure cookies mechanism with above code while maintaining a complete secure environment and compatibility with SECTION 3</p></li> <li><p>Will the above code be compatible with these settings:</p> <pre><code>session.cookie_httponly = 1 session.session.use_only_cookies = 1 session.entropy_file = "/dev/urandom" session.cookie_lifetime = 0 session.cookie_secure = 1 </code></pre></li> <li><p>Should I integrate DB functionality to provide more security?,</p></li> <li><p>As for AJAX,the above code is built to response to multiple Sessions requests,are there any related security issues about this ?</p></li> </ol> <p>Original source <a href="http://blog.teamtreehouse.com/how-to-create-bulletproof-sessions" rel="nofollow">http://blog.teamtreehouse.com/how-to-create-bulletproof-sessions</a></p> <p>I will be very happy if you could let me know your own thoughts,improvements,concerns about the above code to drive it into maximum security.</p>
[ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-02-06T12:13:14.833", "Id": "34280", "Score": "0", "body": "Someone please?" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-02-06T12:21:44.943", "Id": "34308", "Score": "0", "body": "Please add a link to the source. I guess there is an article about it, or did you copy it from an other project?" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-02-06T12:55:18.570", "Id": "34310", "Score": "0", "body": "Your correct,I should have put the source link:\nhttp://blog.teamtreehouse.com/how-to-create-bulletproof-sessions" } ]
[]
{ "AcceptedAnswerId": null, "CommentCount": "3", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-02-06T10:21:00.670", "Id": "21368", "Score": "1", "Tags": [ "php", "security", "session" ], "Title": "Few concerns about specific session class" }
21368
<p>OK, I've been playing with D for a while (and been <em>in love</em> with its expressive power and simplicity, to be honest). However, since I'm still new to D, I'm facing a few issues.</p> <p>Let's take the following example. All the following program does is to take numbers in the 0..10000000 (fairly big one, for benchmarking purposes) and for each one of them return a vector/array with the positions of bits set (in binary).</p> <p><strong>E.g.</strong></p> <pre><code>4 = 100(2) =&gt; [ 2 ] 5 = 101(2) =&gt; [ 0, 2 ] 6 = 110(2) =&gt; [ 1, 2 ] 7 = 111(2) =&gt; [ 0, 1, 2] And so on... </code></pre> <hr> <p>Now here's my <strong>C++ code</strong> (no vector <code>reserve</code> etc being used) :</p> <pre><code>// bits.cpp #include &lt;vector&gt; #include &lt;iostream&gt; #include "math.h" using namespace std; vector&lt;unsigned int&gt; bitsSet(unsigned long long bitboard) { unsigned int n; vector&lt;unsigned int&gt; res; for (n = 0; bitboard != 0; n++, bitboard &amp;= (bitboard - 1)) { res.push_back(log2(bitboard &amp; ~(bitboard-1))); } return res; } int main() { for (int k=0; k&lt;10000000; k++) { vector&lt;unsigned int&gt; res = bitsSet(k); } return 0; } </code></pre> <p>And here's my <strong>D code</strong> :</p> <pre><code>// bits.d import std.stdio; import std.math; int[] bitsSet(ulong bitboard) { int[] res; for (int n=0; bitboard!=0; n++, bitboard&amp;=(bitboard-1)) res ~= cast(int)log2(bitboard &amp; ~(bitboard-1)); return res; } void main(string[] args) { for (ulong k=0; k&lt;10000000; k++) { int[] bits = bitsSet(k); } } </code></pre> <hr> <p>Now, given that the 2 pieces of code are compiled with <code>g++ bits.cpp -o cbits</code> (or <code>clang++ bits.cpp -o cbits</code>) and <code>dmd bits.d -ofdbits</code>, respectively, these are my benchmark results, using <code>time</code> (on Mac OS X 10.8.2) :</p> <p><strong>For C++ :</strong></p> <pre><code>time ./cbits real 0m19.742s user 0m19.722s sys 0m0.012s </code></pre> <p><strong>For D :</strong></p> <pre><code>time ./dbits real 0m14.914s user 0m14.891s sys 0m0.017s </code></pre> <hr> <p>This looks OK. (with D being - for me - noticeably faster).</p> <p><strong>NOTE :</strong> </p> <p>Now, if I try to use something like <code>res.reserve(64);</code> in my C++ <code>bitsSet</code> function, though, time drops to around 7s.... which <em>IS</em> significantly faster. Tried something like <code>res.length = 64;</code> (in my D code), time dropped to around 11s (though slower than C++), but I'm not sure if the result is the same...</p> <hr> <p><strong>What further optimizations would you suggest for my D code, so that it's <em>at least</em> as fast as my C++ code?</strong></p> <hr> <h3>Results with Compiler Optimization flags :</h3> <p>With <code>clang++ bits.cpp -O3 -o cbits</code></p> <pre><code>time ./cbits real 0m8.994s user 0m8.986s sys 0m0.006s </code></pre> <p>With <code>dmd bits.d -O -release -inline -m64 -ofdbits</code></p> <pre><code>time ./bitsd real 0m14.083s user 0m14.034s sys 0m0.014s </code></pre> <p>Which looks pretty amazing (or bizarre). Clang managed to go from 19 to 8 seconds, while D optimization did nothing???</p> <p><strong>EDIT :</strong> So, is there no hope that my D code will run as fast as it's C++ counterpart?</p>
[ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-02-06T08:34:06.507", "Id": "34281", "Score": "3", "body": "What further optimisations? What about... `-O3`?" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-02-06T08:34:45.197", "Id": "34282", "Score": "3", "body": "I could suggest compiling with optimizations on (`-O2` or `-Os`) for the C++ code." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-02-06T08:35:51.063", "Id": "34283", "Score": "0", "body": "@R.MartinhoFernandes Well, I was basically talking about optimizations in the code. (I'll post my results with `-O3` - and their D analogues - right now)" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-02-06T08:36:30.310", "Id": "34284", "Score": "9", "body": "@Dr.Kameleon optimisations in the code are a pointless exercise if you request of the compiler to make a slow program." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-02-06T08:39:17.520", "Id": "34285", "Score": "0", "body": "@R.MartinhoFernandes Have a look at my posted results. Any additional advice (on the D code/compilation) would be more than welcome." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-02-06T08:40:35.360", "Id": "34286", "Score": "0", "body": "@R.MartinhoFernandes Is this actually true? For example the Linux kernel is rarely built with -O3. From my C++ experience the compiler will often emit 2 version, one that is optimized and one that is not optimized when it should only omit the optimized version, this is a problem because it may be too strict when choosing when to use the optimized version." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-02-06T08:40:53.373", "Id": "34287", "Score": "4", "body": "I would be more than happy to know why *this* question has received 3 downvotes and 2 close votes. I'm really curious... (I know D may sound obscure to most people, but that's definitely not a reason to downvote... without any explanation)..." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-02-06T08:46:29.457", "Id": "34288", "Score": "1", "body": "If you're looking for ways to improve the D code, a better place is codereview IMO. If you're asking to compare the results, it's not really constructive." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-02-06T08:47:44.143", "Id": "34289", "Score": "0", "body": "@Dr.Kameleon sorry, I only know C++ :) I would probably get rid of log2, but from there I have no idea." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-02-06T08:49:33.533", "Id": "34290", "Score": "0", "body": "*\"`cast(int)log2`\"* - Looks like you're using some floating point log2 in *D* (don't now about *C++*, since you seem to be using your own `\"math.h\"`, probably with an int log2?). If that's the case then better luck next time." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-02-06T08:49:50.990", "Id": "34291", "Score": "0", "body": "The `n` variable seems to be completely unused in both examples, also, shouldn't `6` be `110(2) => [ 1, 2 ]`?" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-02-06T08:50:20.093", "Id": "34292", "Score": "0", "body": "@R.MartinhoFernandes It's OK! :-) As far as the `log2` in the `bitsSet` function, I've ran *countless* of test for this specific function and this is by far the fastest implementation (at least in C++). I'm using it in a Chess engine project of mine (which I'm currently rewriting in D), so speed is crucial..." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-02-06T08:51:45.250", "Id": "34293", "Score": "0", "body": "*\"Here is a code in one language and a similar code in another, why is one faster than the other? By the way I left out any compiler optimizations to make all time measurements obsolete\"* - Better luck next time with this, too." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-02-06T08:54:37.057", "Id": "34294", "Score": "0", "body": "@Dr.Kameleon But you're sure this standard library `log2` in *D* also works on integers? I'm asking because of the cast (and I'm not sure *D* even has an integer log2). For a simple yet fast integer implementation see [here](http://graphics.stanford.edu/~seander/bithacks.html). But then again I might be wrong and *D* really provides and optimized integer log2." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-02-06T08:54:47.473", "Id": "34295", "Score": "0", "body": "@Mankarse Your observation about `n` is correct (just a leftover from previous implementations) and so is your observation about the `110(2)` example (just a typo; which I fixed)" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-02-06T08:55:00.967", "Id": "34296", "Score": "0", "body": "The reason this has so many down and close votes is because it is a bad question that does not belong here. There is no set problem to which a correction can be provided, you simply have an open ended X is better then Y. You have ignorantly attempted to compare languages as if they equal, despite the fact they have different was of working." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-02-06T08:56:50.890", "Id": "34297", "Score": "0", "body": "@ChristianRau This *may* be a great catch. I'm quite new to D, so this could actually be an issue (I'm currently looking into that, and I'll let you know). As for compiler optimizations, I just decided to put them aside, just in order to compare the different version (as they are) and then with different flags, etc. (You may currently see the results *with* the appropriate optimization flags at the end of the original post)." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-02-06T08:59:32.137", "Id": "34298", "Score": "0", "body": "@thecoshman The question is as clear as that : is there anything wrong in the D counterpart? (or phrased this way : \"am I missing something, or is it just that we're dealing with a compiler generating slower binaries?\"). Maybe it's just me, but I still can't see what's so debateable about it. (I suppose if I was asking for advice for conversion to Java code, the downvotes would be quite fewer...)" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-02-06T09:02:36.563", "Id": "34299", "Score": "0", "body": "@Dr.Kameleon a better question would then be - here's my D code, how do I make it faster? And, even so, a better place would be codereview. The relevant SO part would be, I guess, \"why is the log function so slow in D?\". I see absolutely no reason for dragging C++ into this." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-02-06T09:11:28.110", "Id": "34300", "Score": "0", "body": "@ChristianRau Just tried \"eliminating\" the `cast(int)` part as well as D's `log2` (by replacing it with an `extern (C)` call to `log2`). There *is* some speed gain. But it still runs like 4 seconds slower - quite disappointing..." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-02-06T09:28:01.813", "Id": "34301", "Score": "0", "body": "I am pretty sure that C++ program is that fast because it throw away whole loop. I'm even thinking why it take it 3s to execute. You should display the result of the function." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-02-06T09:32:31.487", "Id": "34302", "Score": "0", "body": "@Dr.Kameleon *\"by replacing it with an `extern (C)` call to `log2`\"* - But I hope not the `log2` of the C standard library, sicne that works on floats, too. What function do you use in C++, if that is also the builtin `log2`, then Ok, both versions would at least be equal (even if using a float log2 for integer computation was rubbish in the first place)." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-02-06T09:34:40.830", "Id": "34303", "Score": "0", "body": "@ŁukaszNiemier *\"pretty sure\"* - Wouldn't that make the C++ program run in nearly no time, instead of just double the speed of the D version (and still 9 seconds)?" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-02-06T13:44:40.837", "Id": "34314", "Score": "1", "body": "Not sure about difference, but try using `gdc` for better performance. By the way you can use `res.reserve(64)` in D too." } ]
[ { "body": "<p>How about: using <code>res.length = 64;</code> and then in your loop replace </p>\n\n<pre><code>res ~= cast(int)log2(bitboard &amp; ~(bitboard-1));\n</code></pre>\n\n<p>by:</p>\n\n<pre><code>res[n] = cast(int)log2(bitboard &amp; ~(bitboard-1));\n</code></pre>\n\n<p>But to be honest this type of code will be completely dominated by allocations, which is not entirely interesting as a language benchmark. Try to reuse the same array instead.</p>\n\n<p>And there is much faster ways of locating bits (see <code>core.bitop</code>).</p>\n\n<p>tl;dr you're optimizing a slow program.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-02-06T09:27:30.263", "Id": "34304", "Score": "0", "body": "Thanks for the suggestions, I'm currently looking into it. (Actually I've tried what you suggest with `res.length` but without any great difference). One question : I knew about `std.intrinsic`. However, I'm a bit perplexed : Is it working with `ulong`s (64-bit unsigned ints)? (this *has* to be able to work with 64-bit ints, otherwise it's not of much use to me...)" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-02-06T09:36:33.793", "Id": "34305", "Score": "0", "body": "*\"you're optimizing a slow program\"* - Better than optimizing a fast one, isn't it? No, really +1 ;)" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-02-06T09:39:59.590", "Id": "34306", "Score": "0", "body": "@ponce Just trying to figure out what's going on : is `std.intrinsic` still supported? (`dmd` and `ldmd2` both give me errors, and I definitely cannot find the `std/intrinsic.d` file in D's current release. (Perhaps it's been deprecated since D v1.0?)" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-02-06T10:25:16.790", "Id": "34307", "Score": "0", "body": "My bad, `std.intrinsic` is now called `core.bitop`. bsf makes you avoid a call to log2." } ], "meta_data": { "CommentCount": "4", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-02-06T09:21:06.013", "Id": "21372", "ParentId": "21371", "Score": "8" } } ]
{ "AcceptedAnswerId": "21372", "CommentCount": "24", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-02-06T08:30:01.563", "Id": "21371", "Score": "10", "Tags": [ "c++", "optimization", "d" ], "Title": "C++ vs D - Algorithm Optimization/Conversion (Using vectors/arrays)" }
21371
<p>I've written a program that calculates the best rational approximation for e with a 1, 2, 3, 4, 5, and 6 digit denominator respectively (on Matlab). For a 5-digit denominator it takes about a minute. For a 6-digit denominator it takes 2 hours. I've tried to improve the code, but I am a beginner. Suggestions are kindly appreciated.</p> <pre><code>tic clear p=1; q=1; e=exp(1); digits=1; trial=1; while numel(num2str(q))&lt;=6 while numel(num2str(q))==digits p=p+1; if p/q&gt;e q=q+1; end A(trial)=p/q; B(trial,1:2)=[p,q]; trial=trial+1; end for i=1:trial-1 error(i)=abs(A(i)-e); end [b,r]=min(error); p_q(digits,1:2)=B(r,1:2); digits=digits+1; end p_q toc </code></pre> <p>This is the output:</p> <pre><code>p_q = 19 7 106 39 1264 465 25946 9545 271801 99990 1084483 398959 Elapsed time is 7232.153581 seconds. </code></pre> <p>Edit: Thanks to all who answered. Dennis and Jonas were right. It was the strings and growing matrices that slowed everything down. Besides I got two wrong values for p and q. The new code is this:</p> <pre><code>tic p_best=1; q_best=1; e=exp(1); for i=1:6 for q=10^(i-1):10^i-1 p=round(q*e); if abs(p/q-e)&lt;abs(p_best/q_best-e) p_best=p; q_best=q; end end disp([p_best,q_best]) end toc </code></pre> <p>The output is:</p> <pre><code> 19 7 193 71 1457 536 25946 9545 271801 99990 1084483 398959 </code></pre> <p>Elapsed time is 0.054986 seconds.</p> <p>It's faster and actually correct. I assumed I knew e like Dennis said. To Joni and hardmath: I can't use continued fractions because the teacher wanted us to use brute force, but thanks. </p>
[ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-02-05T16:39:51.360", "Id": "34321", "Score": "1", "body": "I think this question may be better off at codereview or math. Two pointers: working with strings is usually quite slow, and it can be a lot faster if you think more about the properties of e." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-02-05T17:13:31.920", "Id": "34322", "Score": "1", "body": "What really slows you down is that you grow all your arrays (A, B, etc) inside the loop. Preassign them to a sufficiently large array, and you'll get decent speed-ups" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-02-05T18:19:37.777", "Id": "34323", "Score": "2", "body": "Indeed there's [a nice characterization of the best rational approximations for real numbers](http://math.stackexchange.com/questions/2321/a-nicer-proof-of-lagranges-best-approximations-law) in terms of the convergents of their continued fraction expansions. Obviously trial and error works, but if you are aiming for much faster answers as the digits allowed in the denominator increase, some theory can really speed things up. I'm pretty sure I remember Knuth covering this in vol. 2 of AofCP (Seminumerical Algorithms)." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-02-05T18:24:22.667", "Id": "34324", "Score": "0", "body": "It's even more tempting to go the continued fraction route if you know that e (unlike pi) has [a regular continued fraction expansion](http://en.wikipedia.org/wiki/Continued_fraction#Regular_patterns_in_continued_fractions)." } ]
[ { "body": "<p>In the evening I thought a bit about the question, and though it is a bit more radical than giving pointers on the code, I have created an example on how to approach this problem the matlab way.</p>\n\n<p>Judging from your code the value of <code>e</code> can be considered known. With this I have created a small fragment to make over and under estimations and see which is the best one.</p>\n\n<pre><code>x=1e6:1e7-1; %To guarantee that the denominator has 6 digits \ne = exp(1);\nylow = floor(x*e); %Candidates for over estimation\nyhigh = ceil(x*e); %Candidates for under estimation\nlowerr = e - ylow./x ;\nhigherr = yhigh./x - e;\nlowfind = find(lowerr == min(lowerr));\nhighfind = find(higherr == min(higherr));\ngoodfractions = [ylow(lowfind),yhigh(highfind)\n x(lowfind),x(highfind)]\nerrors = [lowerr(lowfind) higherr(highfind)] \n</code></pre>\n\n<p>Note that the runtime is quite fast but that the errors are or order 10^-14 which indicates that unless some measures are taken rounding errors may become relevant when you try to upscale this solution one or two digits.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-02-06T10:17:15.767", "Id": "21380", "ParentId": "21379", "Score": "1" } }, { "body": "<p><a href=\"http://en.wikipedia.org/wiki/Continued%20Fraction\" rel=\"nofollow\">Continued fractions</a> are an easy way to calculate good rational approximations to real numbers. You can find a disussion of an algorithm to <a href=\"http://jonisalonen.com/2012/converting-decimal-numbers-to-ratios/\" rel=\"nofollow\">convert a floating point number into a fraction</a> in my blog, with code in JavaScript which should be easy to convert to matlab:</p>\n\n<pre><code>function float2rat(x) {\n var tolerance = 1.0E-6;\n var h1=1; var h2=0;\n var k1=0; var k2=1;\n var b = x;\n do {\n var a = Math.floor(b);\n var aux = h1; h1 = a*h1+h2; h2 = aux;\n aux = k1; k1 = a*k1+k2; k2 = aux;\n b = 1/(b-a);\n } while (Math.abs(x-h1/k1) &gt; x*tolerance);\n return h1+\"/\"+k1;\n}\n</code></pre>\n\n<p>If you're specifically interested in <em>e</em> you can take a shortcut and use the regularities in its continued fraction representation to produce rational approximations that are far more accurate than the machine epsilon. This method is <a href=\"http://www.johndcook.com/blog/2013/01/30/rational-approximations-to-e/\" rel=\"nofollow\">described here</a>.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-02-07T07:18:34.883", "Id": "21410", "ParentId": "21379", "Score": "2" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "4", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-02-05T16:30:36.957", "Id": "21379", "Score": "3", "Tags": [ "matlab" ], "Title": "Rational Approximation for e with Matlab" }
21379
<p>I have a situation where I would like to use a single <code>QThread</code> to run two (or more) separate methods at different times. For example, I would like the <code>QThread</code>to run <code>play()</code> sometimes, and when I am done playing, I want to disconnect the <code>QThread.started()</code> signal from this method so that I may connect it somewhere else. In essence I would like the <code>QThread</code> to act as a container for anything I would like to run in parallel with the main process.</p> <p>I have run into the problem where starting the <code>QThread</code> and then immediately disconnecting the started() signal it causes strange behavior at runtime. Before I discovered what 'race condition' meant (or really understanding much about multithreading), I had the sneaking suspicion that the thread wasn't fully started before being disconnected. To overcome this, I added a 5 ms sleep in between the <code>start()</code> and <code>disconnect()</code> calls and it works like a charm. It works like a charm but it isn't The Right Way. </p> <p>How can I implement this functionality with one <code>QThread</code> without making the call to <code>sleep()</code>?</p> <pre><code>def play(self): self.stateLabel.setText("Status: Playback initated ...") self.myThread.started.connect(self.mouseRecorder.play) self.myThread.start() time.sleep(.005) #This is the line I'd like to eliminate self.myThread.started.disconnect() def record(self): self.stateLabel.setText("Status: Recording ...") self.myThread.started.connect(self.mouseRecorder.record) self.myThread.start() time.sleep(.005) #This is the line I'd like to eliminate self.myThread.started.disconnect() </code></pre>
[]
[ { "body": "<p>Use a Queue, python has a threadsafe Queue class.</p>\n\n<p>Push the function you want to run on the background thread onto the queue.</p>\n\n<p>Have the thread wait on the queue executing functions as they are put into it.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-02-06T16:21:05.960", "Id": "21385", "ParentId": "21382", "Score": "3" } } ]
{ "AcceptedAnswerId": "21385", "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-02-06T15:51:06.187", "Id": "21382", "Score": "1", "Tags": [ "python", "multithreading", "pyqt" ], "Title": "Alternative to using sleep() to avoid a race condition in PyQt" }
21382
<p>I'm writing a program which takes individual int inputs from the user and then outputs some details on the numbers (average, min, max and how many). <code>Input.readInt()</code> is a method I made which simply reads an integer from the command line and returns it.</p> <p>There are a few things I'd like to improve - for the average the float does not seem to work, it only holds prints out value to nearest integer. I'd also like to format this to always display 2 decimal places. Is there any way to dynamically assign the size of the array? So I could enter more than 10 values?</p> <p>I'm looking for advice on more efficient methods (both speed and code length), and any other general advice which could help me learn.</p> <pre><code>public class NumberStats { public static void main(String[] args) { int[] input = new int[10]; int i; int total = 0; int min = 0; int max = 0; double average = 0; int count = 0; while (true) { // READ INPUTS System.out.print("Please enter a number: "); input[count] = Input.readInt(); if (input[count] == 0) { break; } else if (input[count] &lt; 0) { System.err.println("Error: " + input[count] + " is not valid, exiting.\n"); break; } else if (input[count] &gt; 100) { System.out .println("Warning: " + input[count] + " is not valid and will be excluded from final statistics."); } if (input[count] &lt;= 100) { // IF INPUT VALID if (count == 0) { min = input[count]; max = input[count]; } else if (input[count] &lt; min) { min = input[count]; } else if (input[count] &gt; max) { max = input[count]; } count++; System.out.println("#" + count + ": " + input[count - 1]); } } if (count != 0) { for (i = 0; i &lt; input.length; i++) { // CALCULATE SUM total += input[i]; } average = total / count; // CALCULATE AVERAGE System.out.println("Total: " + total); System.out.println("Count: " + count); System.out.println("Min: " + min); System.out.println("Max: " + max); System.out.println("Average: " + average); } else { System.out.println("No valid input"); } } } </code></pre>
[]
[ { "body": "<p>Please tell me this is for your personal benefit and that you aren't asking me to do your homework!</p>\n\n<pre><code>average = total / count;\n</code></pre>\n\n<p><code>total</code> and <code>count</code> are both integers, so <code>/</code> performs integer division. The result is then converted to a double. This should fix your problem:</p>\n\n<pre><code>average = ((double) total) / ((double) count);\n</code></pre>\n\n<blockquote>\n <p>Is there any way to dynamically assign the size of the array? so i\n could if i wish enter more than 10 values?</p>\n</blockquote>\n\n<p>Use a <a href=\"http://docs.oracle.com/javase/7/docs/api/java/util/ArrayList.html\" rel=\"nofollow\">java.util.ArrayList</a>:</p>\n\n<pre><code>// old:\n// int[] input = new int[10];\n// new:\nList&lt;Integer&gt; input = new ArrayList&lt;Integer&gt;();\n</code></pre>\n\n<blockquote>\n <p>I'd also like to format this to always display 2 decimal places</p>\n</blockquote>\n\n<p>Look at <a href=\"http://docs.oracle.com/javase/7/docs/api/java/text/DecimalFormat.html\" rel=\"nofollow\">java.text.DecimalFormat</a>.</p>\n\n<h1>General Advice</h1>\n\n<p>You do an awful lot of typing and a lot of dereferencing (and typing!). Declare a local <code>inVal</code> parameter:</p>\n\n<pre><code>int inVal = 0;\n...\n\ninVal = Input.readInt();\nif (inVal &lt; 0) {\n ...\n}\n// Finally, after all your checks and calculations, add inVal to your array (or List):\ninput[count] = inVal;\n</code></pre>\n\n<p>The point of most loop syntax is to make the exit conditions for the loop obvious. Instead of <code>while (true)</code> I'd like to see something like:</p>\n\n<pre><code>do {\n ...\n} while (inVal &gt;= 0)\n</code></pre>\n\n<p>I like that you calculate your max and min in the input loop. You could count your total in that loop as well instead of taking a second loop through your data. Hmm... If you do that, you don't need to use an array or a List, just <code>inVal</code>.</p>\n\n<p>You have \"magic numbers\" 0 and 100. Years from now when three other programmers have worked on this code, they may add a percentage calculation as <code>x / 100</code> so that when you decide to increase your number of inputs to 200, you search-and-replace <code>100</code> with <code>200</code> you have broken your percentage calculation. You should factor these out of your code:</p>\n\n<pre><code>public final int MAX_NUM_INPUTS = 100;\npublic final int INPUT_TOO_LOW_VALUE = 0;\n</code></pre>\n\n<p>This clarifies what you are comparing in a way that Magic Numbers could not:</p>\n\n<pre><code>if (count &gt; MAX_NUM_INPUTS) ...\n\nif (inVal &lt;= INPUT_TOO_LOW_VALUE) ...\n</code></pre>\n\n<p>Hopefully no-one would ever calculate percent as <code>x / MAX_NUM_INPUTS</code>. Now you can change these limits in one place without doing any search-and-replace.</p>\n\n<p><strong>UPDATE:</strong></p>\n\n<p><code>System.out.println</code>...</p>\n\n<p>Yeah, Java is funny about string concatenation. If you have a non-final variable as part of a String, it can cause a bunch of nasty overhead. For a little program like yours, it really doesn't matter what you do. If it were going to print out a String in a loop, then I'd suggest the following change. Note that <code>System.err.println()</code> uses an OS-specific line separator - not necessarily <code>\\n</code>.</p>\n\n<pre><code>// This is fine for your program..\nSystem.err.println(\"Error: \" + input[count]\n + \" is not valid, exiting.\\n\");\n\n// Option 1: Use multiple print stmts to avoid String concatenation:\nSystem.err.print(\"Error: \");\nSystem.err.print(inVal);\nSystem.err.println(\" is not valid; exiting.\");\nSystem.err.println();\n\n// Option 2: Use a StringBuilder (also uses \"method chaining\" idiom):\nSystem.err.println(new StringBuilder().append(\"Error: \")\n .append(inVal)\n .append(\" is not valid; exiting.\")\n .toString());\nSystem.err.println();\n</code></pre>\n\n<p>This really isn't important in your specific example because it's so small. In a bigger program or a production situation String concatenation can be a real performance problem. People often make mistakes in logging code that really slows a system down. I think later versions of Java have tamed this issue. I know IntelliJ IDEA reports various times when it's better to use the + signs vs. a StringBuilder. I've checked the compiled code a few times when I thought it was wrong, and it turned out to be right, so now I just trust it to tell me.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-02-06T19:26:18.127", "Id": "34333", "Score": "0", "body": "Haha no this is a personal learning exercise i'm doing. thanks for the detailed advice and explanations, it helps alot!" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-02-06T19:37:45.670", "Id": "34334", "Score": "0", "body": "Is it more acceptable to use system.out.println() repeatedly for the final out put or should I be using system.out.print and then format the string?" } ], "meta_data": { "CommentCount": "2", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-02-06T18:33:58.060", "Id": "21388", "ParentId": "21383", "Score": "5" } }, { "body": "<p>Glen Peterson's advice is good, but there's something I'd like to add:</p>\n\n<p>You're programming in Java, an <strong>object-oriented</strong> language. When first learning to program, it's often hard to imagine the practical value of using objects. Therefore, as a beginner one often ends up with a style similar to yours: all code is in a single class, and indeed within a single method in that class. </p>\n\n<p>This style is called <em>monolithic</em> and although it has the benefit of being very concise, it leads to unmaintainable, hard-to-debug and unreadable code. As the requirements evolve in complexity, these problems become worse. </p>\n\n<p>To <em>solve</em> them, first analyse the <strong>responsibilities</strong> of your code:</p>\n\n<ul>\n<li>Input/Output</li>\n<li>Validation</li>\n<li>Tracking statistics</li>\n</ul>\n\n<p>These <strong>concerns</strong> should be handled by <strong>collaborating objects</strong>. For instance, to track statistics, you could create a <code>StatisticsTracker</code>:</p>\n\n<pre><code>public class StatisticsTracker {\n private int count;\n private int total;\n private int minimum;\n private int maximum;\n\n public void addNumber(int number) {\n count++;\n total += number;\n adjustMinimumAndMaximum(number);\n }\n\n private void adjustMinimumAndMaximum(int number) {\n if (containsSingleNumber()) {\n minimum = number;\n maximum = number;\n } else if (number &lt; minimum) {\n minimum = number;\n } else if (number &gt; maximum) {\n maximum = number;\n }\n }\n\n private boolean containsSingleNumber() {\n return count == 1;\n }\n\n public int getCount() {\n return count;\n }\n\n public int getTotal() {\n return total;\n }\n\n public int getMinimum() {\n return minimum;\n }\n\n public int getMaximum() {\n return maximum;\n }\n\n public double getAverage() {\n return (double) total / count;\n }\n}\n</code></pre>\n\n<p>Notice that you don't need to hang on to an array or list of numbers; you can track the statistics as you add numbers. Please also note that all this code knows <em>nothing</em> about validation or input/output: all it cares about is tracking statistics.</p>\n\n<p>Next, we'll need a collaborator that validates our input. Because I'm assuming your validation requirements are likely to change, it makes sense to define an <em>interface</em> (<code>T</code> means there can be validators for any type of data, such as strings, integers or floating-point numbers):</p>\n\n<pre><code>public interface Validator&lt;T&gt; {\n public ValidationResult validate(T input);\n}\n</code></pre>\n\n<p>Our validator needs to check if the input is between two bounds, so let's implement the interface:</p>\n\n<pre><code>public class IntegerBoundsValidator implements Validator&lt;Integer&gt; {\n private int lower;\n private int upper;\n\n public IntegerBoundsValidator(int lowerBound, int upperBound) {\n lower = lowerBound;\n upper = upperBound;\n }\n\n @Override\n public ValidationResult validate(Integer input) {\n if (input &lt; lower) {\n return ValidationResult.invalid(\"input must be greater than \" + lower);\n }\n if (input &gt; upper) {\n return ValidationResult.invalid(\"input must be smaller than \" + upper);\n }\n return ValidationResult.valid();\n }\n}\n</code></pre>\n\n<p>You'll notice the use of a class called <code>ValidationResult</code>. This is a <strong>Value Type</strong>. It has no significant behaviour; it just contains data and some static convenience methods to create instances of it, as seen below. Some OOP purists disagree with my use of <code>public final</code> fields; feel free to make them <code>private</code> and add getters if you so desire.</p>\n\n<pre><code>public class ValidationResult {\n public final boolean isValid;\n public final String message;\n\n private static final ValidationResult VALID = new ValidationResult(true, \"\");\n\n public static ValidationResult valid() {\n return VALID;\n }\n\n public static ValidationResult invalid(String message) {\n return new ValidationResult(false, message);\n }\n\n private ValidationResult(boolean isValid, String message) {\n this.isValid = isValid;\n this.message = message;\n }\n}\n</code></pre>\n\n<p>To connect all these parts together, we'll use a class called <code>Main</code> - for the lack of a better name.</p>\n\n<pre><code>public class Main {\n private static final Scanner input = new Scanner(System.in);\n private static final Validator&lt;Integer&gt; validator = new IntegerBoundsValidator(0, 100);\n private static final StatisticsTracker statistics = new StatisticsTracker();\n\n public static void main(String[] args) {\n while (input.hasNextInt()) {\n int next = input.nextInt();\n handleInput(next);\n }\n printStatistics();\n }\n\n public static void handleInput(int input) {\n ValidationResult result = validator.validate(input);\n if (result.isValid) {\n statistics.addNumber(input);\n } else {\n printLine(result.message);\n }\n }\n\n private static void printStatistics() {\n if (statistics.getCount() == 0){\n printLine(\"No valid input.\");\n return;\n }\n printLine(\"Total: %d\", statistics.getTotal());\n printLine(\"Count: %d\", statistics.getCount());\n printLine(\"Min: %d\", statistics.getMinimum());\n printLine(\"Max: %d\", statistics.getMaximum());\n printLine(\"Average: %.2f\", statistics.getAverage());\n }\n\n private static void printLine(String format, Object... args) {\n System.out.println(String.format(format, args));\n }\n}\n</code></pre>\n\n<h1>Conclusion</h1>\n\n<p>Why go to all this effort of <strong>refactoring</strong>? Well, the benefits are apparent:</p>\n\n<ul>\n<li>Each class now fulfils a clearly-defined <strong>responsibility</strong>. Changes in one of those classes will not affect the other responsibilities.</li>\n<li>Each method within these classes is short and has a readable name. These methods can and should be tested separately with <strong>unit tests</strong>, which is close to impossible with monolithic code.</li>\n<li>The system is <strong>extensible</strong>: It's easy to change your validation requirements by simply plugging in a different <code>Validator</code> instance. You could create a <code>CompositeValidator</code> that combines several validators into a single validator chain.</li>\n</ul>\n\n<p>Of course, you may disagree with some of the implementation details — but this review isn't really about those. It's more of a demonstration of which questions you should be asking in order to end up with <strong>clean code</strong>. </p>\n\n<p>Good luck with your learning, and thanks for sharing your code.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-02-06T21:56:07.137", "Id": "21397", "ParentId": "21383", "Score": "4" } } ]
{ "AcceptedAnswerId": "21388", "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-02-06T15:59:43.003", "Id": "21383", "Score": "4", "Tags": [ "java", "array", "statistics" ], "Title": "Calculating and displaying number statistics" }
21383
<p>I do a single select in one radgrid, and based upon that selection I want to select multiple rows in a different radgrid:</p> <pre><code>&lt;telerik:RadGrid ID="rgPaymentLines"&gt; &lt;ClientEvents OnRowSelected="RowPaymentSelected"/&gt; ... &lt;/telerik:RadGrid&gt; &lt;telerik:RadCodeBlock ID="RadCodeBlock1" runat="server"&gt; &lt;script type="text/javascript"&gt; function RowPaymentSelected(sender, eventArgs) { var grid = $find("&lt;%=rgPaymentLines.ClientID %&gt;"); var MasterTablePayment = grid.get_masterTableView(); var paymentRow = MasterTablePayment.get_selectedItems()[0]; var paymentCell = MasterTablePayment.getCellByColumnUniqueName(paymentRow, "DossierID") selectDossierRow(paymentCell.innerHTML); } function selectDossierRow(dossierID) { var gridDossier = $find("&lt;%=rgDossiersAdmin.ClientID %&gt;"); var MasterTableDossier = gridDossier.get_masterTableView(); var rows = MasterTableDossier.get_dataItems(); MasterTableDossier.clearSelectedItems(); for (var i = 0; i &lt; rows.length; i++) { if (MasterTableDossier.getCellByColumnUniqueName(rows[i], "columnDossierID").innerHTML == dossierID) { MasterTableDossier.selectItem(i); } } } </code></pre>
[]
[ { "body": "<p>welcome to Code Review and thank you for your question. You need to profile the code to see for yourself where it is slow. Firebug and Chrome can do this. Only then will you be able to optimize your code.</p>\n\n<p>Side note: Be careful about variable names, some of them seem to be in French (dossier).</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-02-16T19:59:45.377", "Id": "22787", "ParentId": "21384", "Score": "3" } } ]
{ "AcceptedAnswerId": "22787", "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-02-06T16:16:51.907", "Id": "21384", "Score": "4", "Tags": [ "javascript", "jquery", "optimization" ], "Title": "Looping through Radgrid in JS is slow, can this be faster?" }
21384
<p>I am working on a way to quickly build JSON strings in Java. To this end, I have created the following two files. Assuming that I do not need to parse JSON strings for Java, is this an efficient implementation? Furthermore, are there any cases where it would output an invalid JSON string?</p> <p><strong>JSONList.java:</strong></p> <pre><code>public class JSONList { private ArrayList&lt;JSON&gt; items = null; public JSONList() { this.items = new ArrayList&lt;JSON&gt;(); } public JSONList add(JSON value) { if(value != null) { this.items.add(value); } else { throw new IllegalArgumentException("Value must be JSON, was " + (value == null ? "null" : value.getClass())); } return this; } @Override public String toString() { StringBuilder sb = new StringBuilder(); boolean first = true; for(JSON j : this.items) { if(first) { first = false; } else { sb.append(","); } sb.append(j.toString()); } return "[" + sb.toString() + "]"; } </code></pre> <p><strong>JSON.java:</strong></p> <pre><code>public class JSON { private HashMap&lt;String, Object&gt; parts = null; public JSON() { this.parts = new HashMap&lt;String, Object&gt;(); } public JSON add(String key, Object value) { if(value != null &amp;&amp; (value instanceof String || value instanceof Boolean || value instanceof Integer || value instanceof Float || value instanceof JSONList)) { this.parts.put(key, value); } else if(value == null) { this.parts.put(key, "null"); } else { throw new IllegalArgumentException("Value must be either String, Boolean, Integer or Float, was " + (value == null ? "null" : value.getClass())); } return this; } @Override public String toString() { StringBuilder sb = new StringBuilder(); boolean first = true; for(Entry&lt;String, Object&gt; entry : this.parts.entrySet()) { Object v = entry.getValue(); if(first) { first = false; } else { sb.append(","); } if(v instanceof String) { sb.append("\"").append(entry.getKey()).append("\":\"").append(v).append("\""); } else if(v instanceof Boolean || v instanceof Integer || v instanceof Float) { sb.append("\"").append(entry.getKey()).append("\":").append(v); } else if(v instanceof JSONList) { sb.append("\"").append(entry.getKey()).append("\":").append(((JSONList) v).toString()); } } return "{" + sb.toString() + "}"; } } </code></pre>
[ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-02-06T18:02:49.483", "Id": "34327", "Score": "1", "body": "Is there a reason you are not using an existing library to do this? For instance [Gson](http://code.google.com/p/google-gson/)." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-02-06T18:10:19.813", "Id": "34328", "Score": "0", "body": "@JeffVanzella - Partially to learn how to do it on my own, partially for size (my two files are around 3K in total as opposed to GSON's 185K)." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-02-06T19:41:01.513", "Id": "34335", "Score": "0", "body": "Do you want to support all JSON? If so, how would you produce a valid JSON string such as `[\"GML\", \"XML\"]` with this code?" } ]
[ { "body": "<p>First of all, <code>this.items</code> is redundant in most cases - just <code>items</code> would be enough.</p>\n\n<hr>\n\n<pre><code>if(value != null)\n{\n this.items.add(value);\n}\nelse\n{\n throw new IllegalArgumentException(\"Value must be JSON, was \" + (value == null ? \"null\" : value.getClass()));\n}\nreturn this;\n</code></pre>\n\n<p>This format is not what I'd expect. Usually, I'd use a guard clause.</p>\n\n<pre><code>if(value == null) {\n throw new IllegalArgumentException(\"Value must be JSON, was \" + (value == null ? \"null\" : value.getClass()));\n}\n\nitems.add(value);\nreturn this;\n</code></pre>\n\n<hr>\n\n<p>Java <a href=\"http://www.oracle.com/technetwork/java/javase/documentation/codeconvtoc-136057.html\">coding conventions</a> show that there should be a space between an <code>if</code> and the parenthesis:</p>\n\n<pre><code>if(value == null) //Doesn't follow the convention\nif (value == null) //Follows the convention\n</code></pre>\n\n<hr>\n\n<pre><code>return \"[\" + sb.toString() + \"]\";\n</code></pre>\n\n<p>If you are using a <code>StringBuilder</code> why don't you directly append '[' and ']' to the builder? Same in the other class.</p>\n\n<hr>\n\n<p>If I understand correctly, <code>JSONList</code> is a JSON array and <code>JSON</code> is a JSON object, is this correct?\nHave you considered renaming them to JSONArray and JSONObject?\nAlso, if you reuse the <code>String</code>, <code>Boolean</code>, integer, etc. classes, why don't you also reuse Java's <code>List</code>?</p>\n\n<p>Your arrays also seem overly restrictive. You allow arrays of objects but not anything else. How would I output <code>[\"Hello\", \"World\"]</code> with your classes?</p>\n\n<p>And what if I want an object inside another object? <code>{\"foo\":{}}</code></p>\n\n<hr>\n\n<pre><code>this.parts.put(key, \"null\");\n</code></pre>\n\n<p>This is problematic. You later use <code>Object v = entry.getValue();</code> and check for the type of <code>v</code>, which will be reported as <code>String</code>. This is incorrect. JSON supports null values, but your class will replace them by <code>\"null\"</code>.</p>\n\n<hr>\n\n<pre><code>sb.append(\"\\\"\").append(entry.getKey())\n</code></pre>\n\n<p>You repeat this <em>a lot</em>. Consider moving this to <em>before</em> the type checks.</p>\n\n<hr>\n\n<p>As a precaution, after the last <code>else if(v instanceof JSONList)</code>, consider adding:</p>\n\n<pre><code>else {\n assert false : \"This should never happen\";\n}\n</code></pre>\n\n<p>as defensive programming.</p>\n\n<hr>\n\n<p>If I pass a NaN float to your JSON class, it'll generate a JSON like <code>{foo: NaN}</code> which is invalid. NaN is not supported in JSON.</p>\n\n<p>Some Strings will be incorrectly output to the JSON file. Consider Strings using the <code>\\</code> or <code>\"</code> character, for instance. And also \"control characters\". You should properly escape them. Same applies to object keys.</p>\n\n<p>For more information about the JSON format, see <a href=\"http://www.json.org/\">http://www.json.org/</a>.</p>\n\n<hr>\n\n<p>In <code>JSON.add</code>, you never check if the key is null.</p>\n\n<hr>\n\n<p>You offer <code>add</code> methods but not <code>remove</code>. Is this intentional?</p>\n\n<hr>\n\n<p>You support <code>Integer</code> and <code>Float</code>, but not <code>Byte</code>, <code>Short</code>, <code>Long</code> and <code>Double</code>. This might cause some unpleasant surprises to users of your application.</p>\n\n<hr>\n\n<p><code>.append(((JSONList) v).toString())</code> is redundant. <code>.append(v)</code> would work (see documentation for <a href=\"http://docs.oracle.com/javase/1.5.0/docs/api/java/lang/StringBuilder.html#append%28java.lang.Object%29\"><code>StringBuilder</code></a> and <a href=\"http://docs.oracle.com/javase/1.5.0/docs/api/java/lang/String.html#valueOf%28java.lang.Object%29\"><code>valueOf</code></a>.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-02-06T20:19:43.640", "Id": "34341", "Score": "1", "body": "Thank you for your feedback luiscubal! I'm still learning JSON formatting, and I've taken many of your ideas into consideration (and fixed some of the immediate problems you've highlighted)." } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-02-06T19:45:33.287", "Id": "21393", "ParentId": "21387", "Score": "6" } }, { "body": "<ol>\n<li><p>The <code>= null</code> is unnecessary here, since it's the default:</p>\n\n<pre><code>private HashMap&lt;String, Object&gt; parts = null;\n</code></pre></li>\n<li><p><code>HashMap&lt;...&gt;</code> reference types should be simply <code>Map&lt;...&gt;</code>. See: <em>Effective Java, 2nd edition</em>, <em>Item 52: Refer to objects by their interfaces</em></p>\n\n<pre><code>private Map&lt;String, Object&gt; parts;\n</code></pre></li>\n<li><p><code>\"null\"</code> is never used in the following snippet, since <code>value</code> can't be <code>null</code> in the last <code>else</code> block:</p>\n\n<pre><code>...\nelse if(value == null) {\n this.parts.put(key, \"null\");\n} else {\n throw new IllegalArgumentException(\"Value must be either String, Boolean\" +\n \", Integer or Float, was \" + (value == null ? \"null\" : value.getClass()));\n}\n</code></pre></li>\n<li><p>A reference for Jeff's comment: <em>Effective Java, 2nd edition</em>, <em>Item 47: Know and use the libraries</em> (The author mentions only the JDK's built-in libraries but I think the reasoning could be true for other libraries too.)</p></li>\n</ol>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-02-07T00:27:58.820", "Id": "21404", "ParentId": "21387", "Score": "1" } }, { "body": "<p>To Keep the existing content and append the new content to the end of JSON file, please use below code:</p>\n\n<pre><code>new FileWriter(file,true);\n</code></pre>\n\n<p>or you can try as below</p>\n\n<pre><code>FileWriter file= new FileWriter(JSONLPATH,true)\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-09-04T07:59:32.287", "Id": "391381", "Score": "1", "body": "Welcome to Code Review! You have presented an alternative solution, but haven't reviewed the code. Please [edit] to show what aspects of the question code prompted you to write this version, and in what ways it's an improvement over the original." } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-09-04T04:00:46.637", "Id": "203072", "ParentId": "21387", "Score": "0" } } ]
{ "AcceptedAnswerId": "21393", "CommentCount": "3", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-02-06T17:57:21.790", "Id": "21387", "Score": "1", "Tags": [ "java", "json" ], "Title": "Simple JSON writer" }
21387
<p>I have the following code, but it somehow looks a bit redundant. As I am new to ColdFusion, I am not sure how to optimize it. Can someone suggest an alternative?</p> <pre><code>&lt;cfparam name="url.idInfopage" default="0"&gt; &lt;cfif not isNumeric(url.idInfopage)&gt;&lt;cfset url.idInfopage= 0&gt;&lt;/cfif&gt; &lt;cfif isDefined("stElement.idInfopage") and isNumeric(stElement.idInfopage)&gt; &lt;cfset idInfopage= stElement.idInfopage&gt; &lt;cfif idInfopage is ""&gt;&lt;cfset idInfopage= 0&gt;&lt;/cfif&gt; &lt;cfelse&gt; &lt;cfset idInfopage= url.idInfopage&gt; &lt;/cfif&gt; </code></pre>
[ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-02-04T16:20:37.063", "Id": "34331", "Score": "1", "body": "What version of CF are you running?" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-02-04T16:21:31.027", "Id": "34332", "Score": "0", "body": "I am using MX7 at the moment." } ]
[ { "body": "<p>You could re-write it something like this:</p>\n\n<pre><code>&lt;cfif StructKeyExists(stElement,'idInfoPage') AND isNumeric(stElement.idInfopage)&gt;\n &lt;cfset idInfopage = stElement.idInfopage /&gt;\n\n&lt;cfelseif StructKeyExists(Url,'idInfoPage') AND isNumeric(Url.idInfopage)&gt;\n &lt;cfset idInfopage = Url.idInfopage /&gt;\n\n&lt;cfelse&gt;\n &lt;cfset idInfopage = 0 /&gt;\n\n&lt;/cfif&gt;\n</code></pre>\n\n<p>Notes on the changes:</p>\n\n<ul>\n<li><a href=\"http://cfdocs.org/StructKeyExists\">StructKeyExists</a> is generally recommended over <a href=\"http://cfdocs.org/isDefined\">isDefined</a>.</li>\n<li><a href=\"http://cfdocs.org/isNumeric\">isNumeric</a> wont return true for empty string.</li>\n</ul>\n\n<p><br/>\nIf you have a lot of code like this, it might make sense to create a function, something like:</p>\n\n<pre><code>&lt;cfset idInfopage = getNumberOrZero('idInfopage',stElement,Url) /&gt;\n</code></pre>\n\n<p>Then implemented as:</p>\n\n<pre><code>&lt;cffunction name=\"getNumberOrZero\" returntype=\"numeric\" output=false\n hint=\"Loops through structs (args 2..n) looking for number; else return 0\"&gt;\n &lt;cfargument name=\"Key\" type=\"String\" required /&gt;\n &lt;cfset var i = 0 /&gt;\n\n &lt;cfloop index=\"i\" from=2 to=#ArrayLen(Arguments)#&gt;\n &lt;cfif StructKeyExists(Arguments[i],Arguments.Key)\n AND isNumeric(Arguments[i][Arguments.Key])\n &gt;\n &lt;cfreturn Arguments[i][Arguments.Key] /&gt;\n &lt;/cfif&gt;\n &lt;/cfloop&gt;\n\n &lt;cfreturn 0 /&gt;\n&lt;/cffunction&gt;\n</code></pre>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-02-04T16:24:48.600", "Id": "21390", "ParentId": "21389", "Score": "12" } } ]
{ "AcceptedAnswerId": "21390", "CommentCount": "2", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-02-04T16:13:07.703", "Id": "21389", "Score": "3", "Tags": [ "performance", "beginner", "url", "coldfusion", "cfml" ], "Title": "Setting a page number from the URL, with fallbacks" }
21389
<p>I have created this simple code:</p> <blockquote> <p>For the size of an array with 2 values (<code>n</code> and <code>m</code>), verify if <code>n</code> and <code>m</code> are >= 1. <code>m</code> = width and <code>n</code> = height.</p> </blockquote> <p>The code works but I'm sure it isn't optimized.</p> <pre><code>printf("Number of ligns."); scanf("%d",n); printf("Number of columns."); scanf("%d",m); if(*n &gt;= 1) { if(*m &gt;= 1) { printf("Number of ligns : %x, Number of columns : %x \n", *n, *m); } else { while(*m &lt; 1) { printf("Error, number of colums/ligns &lt; 1. \n"); scanf("%d",m); } printf("Number of ligns : %x, Number of columns : %x \n", *n, *m); } } else { while(*n &lt; 1) { printf("Error, number of colums/ligns &lt; 1. \n"); scanf("%d",n); } if(*m &gt;= 1) { printf("Number of ligns : %x, Number of columns : %x \n", *n, *m); } else { while(*m &lt; 1) { printf("Error, number of colums/ligns &lt; 1. \n"); scanf("%d",m); } printf("Number of ligns : %x, Number of columns : %x \n", *n, *m); } } </code></pre>
[ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-02-06T19:51:47.750", "Id": "34336", "Score": "0", "body": "The big question is not whether it is optimized. The big question is \"Does it matter\"? Do you find it too slow? How fast would you like it to be?" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-02-06T19:56:02.547", "Id": "34337", "Score": "0", "body": "@luiscubal I think this is a learning exercise - and if so, its more about learning how to do it the right way than optimizing for performance. At first glance, I see they are violating the DRY principle." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-02-06T19:59:01.620", "Id": "34338", "Score": "0", "body": "Also, this doesn't seem to be the whole function." } ]
[ { "body": "<p>You should provide a compiling code. I'll assume that <code>n</code> and <code>m</code> are <code>int</code>, but you should have added their declaration.</p>\n\n<ul>\n<li>You should use explicit names for variables. <code>n</code> is a line count, so call it <code>line_count</code>. <code>m</code> is <code>column_count</code>.</li>\n<li>You should check the return values of <code>scanf</code> to be sure you handle gracefully EOF and bad input.</li>\n<li>You print \"Error, number of colums/ligns &lt; 1. \\n\" every time, so the user can't know if it's the lines or the columns or both that are &lt; 1.</li>\n<li>The english word is \"lines\", not \"ligns\".</li>\n<li><p>Your checks are too complicated and redundants. The entire if/else block can be replaced by this:</p>\n\n<pre><code>while(*line_count &lt; 1)\n{\n printf(\"Error, number of lines &lt; 1. \\n\");\n scanf(\"%d\", line_count);\n}\n\n\nwhile(*column_count &lt; 1)\n{\n printf(\"Error, number of colums &lt; 1. \\n\");\n scanf(\"%d\", column_count);\n}\n\nprintf(\"Number of lines : %x, Number of columns : %x \\n\", *line_count, *column_count);\n</code></pre></li>\n</ul>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-02-06T20:07:17.033", "Id": "34339", "Score": "1", "body": "Note that `n` and `m` don't seem to be the line/col count variables, they are *pointers* to the count variables." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-02-06T20:17:43.420", "Id": "34340", "Score": "0", "body": "Indeed. But I am often reluctant to put some \"ptr\" prefix or suffix in the names. I had an overdose of hungarian notation several years ago, I try to avoid anything that looks like it." } ], "meta_data": { "CommentCount": "2", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-02-06T19:59:04.847", "Id": "21395", "ParentId": "21392", "Score": "5" } } ]
{ "AcceptedAnswerId": "21395", "CommentCount": "3", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-02-06T19:38:47.037", "Id": "21392", "Score": "1", "Tags": [ "c", "validation", "io" ], "Title": "Verifying column and line counts" }
21392
<p>This is the first time I've written JavaScript in this way (previously all I've done mostly is DOM manipulation and form validation in vanilla and jQuery).</p> <p>I've begun working on a basic Pong game. It's currently unfinished, but before I continue, I'd like to get some feedback from experienced JS developers:</p> <p>Full codebase is available <a href="https://github.com/bencoder/jspong/" rel="nofollow">here</a>.</p> <p>The main pong.js file is as so:</p> <pre><code>var PaddleObj = function() { }; PaddleObj.prototype.init = function(game_object, side) { this.game = game_object; this.width = 15; this.height = 100; if (side == 'left') this.position = {x:40, y:this.game.height/2}; else this.position = {x:this.game.width-40, y:this.game.height/2}; } PaddleObj.prototype.render = function(ctx) { ctx.fillStyle = "white"; ctx.fillRect (this.position.x-this.width/2, this.position.y-this.height/2, this.width, this.height); } PaddleObj.prototype.setYPosition = function(y_pos) { this.position.y = y_pos; if ((this.position.y - this.height/2) &lt; 0) this.position.y = this.height/2; if ((this.position.y + this.height/2) &gt; this.game.height) this.position.y = this.game.height - this.height/2; } PaddleObj.prototype.update = function(delta_time) { //don't do anything on update by default } PaddleObj.prototype.isBallColliding = function(ball) { return (ball.position.x &lt; (this.position.x + this.width/2)) &amp;&amp; (ball.position.x &gt; (this.position.x - this.width/2)) &amp;&amp; (ball.position.y &lt; (this.position.y + this.height/2)) &amp;&amp; (ball.position.y &gt; (this.position.y - this.height/2)); } AIPaddleObj = function() { this.speed = 100; }; AIPaddleObj.prototype = PaddleObj.prototype; AIPaddleObj.constructor = AIPaddleObj; AIPaddleObj.prototype.update = function(delta_time) { if (this.game.ball.position.y &lt; this.position.y) { this.setYPosition(this.position.y -= this.speed * delta_time); } if (this.game.ball.position.y &gt; this.position.y) { this.setYPosition(this.position.y += this.speed * delta_time); } } var BallObj = function() { }; BallObj.prototype.init = function(game_object, initial_speed, pos_x, pos_y) { this.game = game_object; this.position = {x:pos_x, y:pos_y}; this.vector = {x:initial_speed, y:initial_speed}; } BallObj.prototype.update = function(frame_time) { var previous_position = this.position; this.position.x += this.vector.x*frame_time; this.position.y += this.vector.y*frame_time; if (this.position.x &gt; this.game.width) { this.position.x = this.game.width; this.vector.x *= -1; } if (this.position.x &lt; 0) { this.position.x = 0; this.vector.x *= -1; } if (this.position.y &lt; 0) { this.position.y = 0; this.vector.y *= -1; } if (this.position.y &gt; this.game.height) { this.position.y = this.game.height; this.vector.y *= -1; } if (this.game.aiPaddle.isBallColliding(this) || this.game.playerPaddle.isBallColliding(this)) { this.position = previous_position; this.vector.x *= -1; } } BallObj.prototype.render = function(ctx) { ctx.beginPath(); ctx.fillStyle="white"; ctx.arc(this.position.x, this.position.y, 10, 0 , 2 * Math.PI, false); ctx.fill(); //ctx.stroke(); } var GameObj = function() { this.gameCanvas = document.createElement('canvas'); } GameObj.prototype.setCanvasSize = function(width, height) { this.width = width; this.height = height; this.gameCanvas.width = width; this.gameCanvas.height = height; } GameObj.prototype.init = function(parent, width, height) { this.setCanvasSize(width, height); parent.appendChild(this.gameCanvas); this.ball = new BallObj(); this.ball.init(this, 100, width/2, height/2); this.playerPaddle = new PaddleObj(); this.playerPaddle.init(this, 'left'); this.gameCanvas.onmousemove = function(playerPaddle) { return function(e) { playerPaddle.setYPosition(e.offsetY || e.layerY); } }(this.playerPaddle); this.aiPaddle = new AIPaddleObj(); this.aiPaddle.init(this,'right'); } GameObj.prototype.update = function(delta_time) { this.ball.update(delta_time); this.aiPaddle.update(delta_time); } GameObj.prototype.drawFrame = function() { var ctx = this.gameCanvas.getContext("2d"); ctx.fillStyle="black"; ctx.fillRect(0,0,this.gameCanvas.width,this.gameCanvas.height); this.ball.render(ctx); this.playerPaddle.render(ctx); this.aiPaddle.render(ctx); } GameObj.prototype.run = function(delta_time) { this.update(delta_time); this.drawFrame(); } var setup = function() { var div = document.getElementById('pongDiv'); var game = new GameObj(); game.init(div, 640, 480); var previous_time = 0; var frameCallback = function(timestamp) { if (previous_time == 0) { previous_time = timestamp; } //convert to seconds delta_time = (timestamp - previous_time)/1000; //fix the delta time to a max of 0.1 seconds, so that even if frame rate is really slow, the jumps don't get too big if (delta_time &gt; 0.1) delta_time = 0.1; previous_time = timestamp; game.run(delta_time); window.requestAnimationFrame(frameCallback); } window.requestAnimationFrame(frameCallback); /* window.onresize = function() { game.setCanvasSize(window.innerWidth, window.innerHeight); } */ } </code></pre> <p>I would really appreciate any comments on general structure or techniques that I've used here from experienced devs.</p>
[]
[ { "body": "<p>I don't see anything wrong with your code as it stands but there are at least two things you may need to think about as it develops:</p>\n\n<ol>\n<li><p>can objects drawn on the canvas interfere with each other, and if so, how can the programme deal with that?</p></li>\n<li><p>are you likely to want a library of drawing functions, and if so, how will the individual rendering functions access those?</p></li>\n</ol>\n\n<p>I would deal with these concerns by setting up an object called Canvas or View which handles all of the drawing and can contain generic drawing functions, e.g. circle, to avoid repetition within the methods rendering individual objects.</p>\n\n<p>Then I would actually move the rendering methods to within this object, and have a single method <code>canvas.draw</code> that draws everything you want on the canvas. This is in some ways less elegant, but separates the main game logic from the drawing logic (analogous to separating content from style in web design), and helps to deal with the possibility of objects interacting in the display; for instance, what happens if they overlap? The order or way they are drawn may need to vary depending on the other objects. (Though this is not an issue in your game currently). Canvas can keep a register of which objects need to be drawn and contain consistent logic to draw them in the right way.</p>\n\n<p>The ball and paddle objects don't need to be passed the entire game object; they could be passed a more limited object, say <code>frame</code>, that only contains what they 'need to know' (in this case, the width and height of the playing area).</p>\n\n<p>As GameObj and Canvas are only likely to have a single instance each and their methods unlikely to be rewritten in other parts of the code, I would tend to write each within a single constructor function so that variables can be shared among their methods without having to make everything a public property of the object.</p>\n\n<p>Finally, it would seem natural to merge <code>setup</code> with the code initiating <code>GameObj</code>.</p>\n\n<pre><code>// ...\nfunction Canvas(width, height) {\n var el = document.createElement('canvas'),\n objects = [],\n ctx = el.getContext(\"2d\");\n this.setSize = function(width, height) {\n el.width = width;\n el.height = height;\n };\n this.setSize(width, height);\n this.appendTo = function (div) {\n div.appendChild(el);\n };\n this.register = function (type, object) {\n objects.push({\n type: type,\n object: object\n });\n };\n this.draw = function () {\n for (var i = 0; i &lt; objects.length; i++) {\n render[objects[i].type](objects[i].object);\n }\n };\n var render = {\n ball: function (obj) {\n circle(obj.position.x, obj.position.y, 10, 'white');\n },\n paddle: function (obj) {\n ctx.fillStyle = \"white\";\n ctx.fillRect(obj.position.x - obj.width / 2, obj.position.y - obj.height / 2, obj.width, obj.height);\n }\n };\n\n function circle(x, y, radius, colour) {\n ctx.beginPath();\n ctx.fillStyle = colour;\n ctx.arc(x, y, radius, 0, 2 * Math.PI, false);\n ctx.fill();\n }\n // can add extra generic drawing functions here \n}\n\nfunction GameObj() {\n var canvas,\n frame,\n ball,\n playerPaddle;\n init(document.getElementById('pongDiv'), 640, 480);\n\n function init(div, width, height) {\n ballObj.init(frame, 100, width / 2, height / 2);\n playerPaddle.init(frame, left);\n canvas = new Canvas(width, height);\n canvas.appendTo(div);\n frame = {\n width: width,\n height: height\n };\n ball = new BallObj();\n playerPaddle = new PlayerPaddle();\n canvas.register({type: 'ball', object: ball});\n canvas.register({type: 'paddle', object: playerPaddle});\n // ...\n }\n var previous_time = 0;\n var frameCallback = function (timestamp) {\n if (previous_time == 0) {\n previous_time = timestamp;\n }\n //convert to seconds\n delta_time = (timestamp - previous_time) / 1000;\n //fix the delta time to a max of 0.1 seconds, so that even if frame rate is really slow, the jumps don't get too big\n if (delta_time &gt; 0.1) delta_time = 0.1;\n\n previous_time = timestamp;\n update(delta_time);\n canvas.draw(); // draws all of the objects registered earlier\n window.requestAnimationFrame(frameCallback);\n }\n window.requestAnimationFrame(frameCallback);\n\n //...\n}\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-02-11T19:20:45.380", "Id": "34687", "Score": "0", "body": "This is a really great answer. Thank you so much!" } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-02-09T16:41:40.253", "Id": "21518", "ParentId": "21398", "Score": "3" } } ]
{ "AcceptedAnswerId": "21518", "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-02-06T22:25:52.217", "Id": "21398", "Score": "5", "Tags": [ "javascript", "game", "html5", "canvas" ], "Title": "JavaScript/Canvas Pong game" }
21398
<p>This is my first attempt at reading the contents of a file consisting of strings separated by a null character.</p> <pre><code>vector&lt;string&gt; CReadFileTest::ReadFile( const char * filename ) { ifstream ifs(filename, ifstream::in); if (ifs) { vector&lt;string&gt; list ; while (ifs.good()) { string s; std::getline(ifs, s,'\0'); list.push_back(s); } ifs.close(); return list; } return vector&lt;string&gt;(); } </code></pre> <ol> <li>Does this code snippet follows good coding practices?</li> <li>Is it correct to return a vector type and an empty vector in case of errors?</li> </ol>
[]
[ { "body": "<p>A couple of issues:</p>\n\n<pre><code>while (ifs.good())\n</code></pre>\n\n<p>Don't loop on <code>good()</code> (or <code>eof()</code>). This is one of the more annoying parts of the C++ <code>iostream</code> library. This should be:</p>\n\n<pre><code>while(std::getline(ifs, s, '\\0'))\n</code></pre>\n\n<p><code>std::getline</code> returns a reference to its input stream (<code>std::basic_istream&amp;</code>). How this actually checks the stream state and continues looping is pretty complicated* - suffice to say this is the canonical way of doing it. If you're really being good about your error checking, you'd then call <code>ifs.readstate()</code> after your <code>while</code> loop and check the <code>fail</code> and <code>error</code> flags aren't set.</p>\n\n<p>Secondly, this creates a new <code>string</code> every time around the while loop. Instead, you probably want:</p>\n\n<pre><code>//Note you probably shouldn't call it list, because of the std::list&lt;T&gt; type\nvector&lt;string&gt; v; \nstring s;\n\nwhile(std::getline(ifs, s, '\\0')) {\n v.push_back(s);\n}\n</code></pre>\n\n<p>There are a few ways of signalling that an error has occurred - throwing an exception is one possibility. Returning a <code>pair&lt;vector&lt;string&gt;, bool&gt;</code> or <code>pair&lt;vector&lt;string&gt;, int&gt;</code> indicating either success (for <code>bool</code>) or number of characters read (for <code>int</code>) is another possibility - this is basically an \"error code\" way of dealing with the problem. Error handling is always tricky, unfortunately.</p>\n\n<p>Either way, currently you return a vector whatever happens, so you might as well construct it outside the <code>if</code> test:</p>\n\n<pre><code>ifstream ifs(filename, ifstream::in);\nvector&lt;string&gt; v;\n\nif(ifs) { ... }\n\nreturn v;\n</code></pre>\n\n<ul>\n<li><sub>What happens that it calls the ifstream's <code>operator void*()</code> which tests all error flags and <code>eof</code>, returning a nullptr if any of them are set, otherwise a non-zero pointer. See also <a href=\"https://stackoverflow.com/questions/259269/stdgetline-returns\">std::getline returns</a>.</sub></li>\n</ul>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-02-07T12:55:45.970", "Id": "34390", "Score": "0", "body": "Thank you, one thing however, can you explain why std::getline(ifs, s,'\\0') return value only works when inside the while() statement ? When I try to check its value with something like auto i = std::getline(ifs, s,'\\0'); it tells me that it is inaccessible. None of the docs I've looked at do mention that it returns the numbers of characters read but rather the input stream. (Msdn, Cppreference.com, Cplusplus.com)" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-02-07T12:59:47.373", "Id": "34391", "Score": "1", "body": "Sorry, I've updated my post - it doesn't return how many characters it reads, it returns a reference to the stream as you've said." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-02-07T13:08:49.953", "Id": "34393", "Score": "0", "body": "Okay great, thanks a lot for your explanations !" } ], "meta_data": { "CommentCount": "3", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-02-07T00:23:47.387", "Id": "21403", "ParentId": "21400", "Score": "3" } } ]
{ "AcceptedAnswerId": "21403", "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-02-06T23:34:47.330", "Id": "21400", "Score": "4", "Tags": [ "c++", "file", "stream", "vectors" ], "Title": "Reading contents of a file consisting of strings separated by a null character" }
21400
<p>I started taking a look at a programming challenge I had read about earlier today on <a href="http://webcache.googleusercontent.com/search?q=cache%3aAb2gQz9h2zMJ%3ablog.8thlight.com/eric-koslow/archive.html%20&amp;cd=5&amp;hl=en&amp;ct=clnk&amp;gl=us" rel="nofollow">8thlight</a>. Unfortunately, it seems to have been taken down and all I could remember about it was the problem posed: Given an array of integers, find the maximum sum of contiguous values (a sub-array). </p> <p>I wanted to tackle the problem from a TDD standpoint rather than diving right in, as the poster had recommended. I didn't see his solution, but what I ended up with was remarkably like <a href="http://en.wikipedia.org/wiki/Maximum_subarray_problem" rel="nofollow">Kadane's algorithm</a>, despite having never seen or heard of it until after writing my code and attempting to make this post.</p> <p>My question is as follows: Is there some extraneous logic in here that could be refactored away? Or perhaps more critically, can you provide any test cases that break this? Some solutions I've seen now that I am searching have special restrictions, such as not being able to work with arrays full of negative numbers, while mine will solve them correctly.</p> <pre><code>public static int HighestContiguousSum(int[] inputArray) { int currentSum = inputArray[0]; int bestSum = inputArray[0]; for (int i = 1; i &lt; inputArray.Length; i++) { int value = inputArray[i]; if (bestSum &lt; 0 &amp;&amp; bestSum &lt; value) { bestSum = value; currentSum = value; } else if (value &gt; 0 || (value &lt; 0 &amp;&amp; value &gt; -1 * currentSum)) { currentSum += value; bestSum = Math.Max(currentSum, bestSum); } else if (value &lt;= -1 * currentSum) { currentSum = 0; } } return bestSum; } </code></pre> <p>I ended up with ~11 tests, although not all of them are probably required (some were me just trying to break things after the fact to prove to myself it was working).</p>
[ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-02-07T11:18:01.963", "Id": "34363", "Score": "3", "body": "If you want us to review the tests, you should include those too." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-02-07T15:01:43.407", "Id": "34402", "Score": "0", "body": "I will do so as soon as possible, I don't have them available at the moment." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-02-07T15:01:49.103", "Id": "34403", "Score": "0", "body": "In addition to the two cases @jesse-c-slicer pointed out, it also misbehaves if `int.MaxValue` is an element and there are any positive numbers anywhere before it or immediately following it." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-02-07T15:04:31.427", "Id": "34405", "Score": "0", "body": "@Bobson - see my comment to @jesse-c-slicer. I did strip out the vaidation code, although it seems I shouldn't have! I had the two he mentioned, and I assumed I was done. I missed the `int.MaxValue` case entirely. I'll adjust this when I'm able." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-02-07T15:08:58.947", "Id": "34407", "Score": "0", "body": "@jtheis - I'm not sure there's much you *can* do about `int.MaxValue`, unless you accept `int`s but do all the math in `long` variables and return a `long`. Don't forget about `(int.MaxValue - 1)` too - you can't *just* handle the one case." } ]
[ { "body": "<p>A couple of very simple tests that would fail would be to call your method with a parameter of <code>null</code> or <code>new int[0]</code>. Also, I'm not a big fan of using arrays so I did a tiny bit of rework on it to use a simple enumerable as well as guard against those edge cases.</p>\n\n<p><strong>EDIT:</strong> re-did with LINQ for the <code>Enumerator</code> haters :)</p>\n\n<pre><code> if (inputSequence == null)\n {\n throw new ArgumentNullException(\"inputSequence\");\n }\n\n if (!inputSequence.Any())\n {\n throw new ArgumentException(\"input should not be an empty sequence.\");\n }\n\n var currentSum = inputSequence.First();\n var bestSum = currentSum;\n\n foreach (var value in inputSequence.Skip(1))\n {\n if (bestSum &lt; 0 &amp;&amp; bestSum &lt; value)\n {\n bestSum = value;\n currentSum = value;\n }\n else if (value &gt; 0 || (value &lt; 0 &amp;&amp; value &gt; -1 * currentSum))\n {\n currentSum += value;\n bestSum = Math.Max(currentSum, bestSum);\n }\n else if (value &lt;= -1 * currentSum)\n {\n currentSum = 0;\n }\n }\n\n return bestSum;\n }\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-02-07T09:22:10.217", "Id": "34349", "Score": "3", "body": "Not sure using IEnumerator cleaned things up, as for me it just added more clutter. Cases when you need to iterate manually without `foreach` are quite rare..." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-02-07T11:20:59.963", "Id": "34364", "Score": "1", "body": "I also think that using `IEnumerator` directly just to verify that the input is not empty is an overkill. I think it would be simpler to use `foreach` together with a flag and check that flag after the `foreach`." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-02-07T11:43:03.700", "Id": "34369", "Score": "0", "body": "Accepting an `IEnumerable<T>` is good design. I would +1 if it were not for the clutter of accessing the enumerator directly. `foreach` is the way to go - in combination with LINQ `.Any()` if you want to guard against empty sequences." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-02-07T12:40:39.510", "Id": "34372", "Score": "1", "body": "I think it would be interesting to explain a bit what changes you did and why you did them instead of only providing a new version." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-02-07T14:59:25.857", "Id": "34401", "Score": "1", "body": "Actually, the original did include the input validation. Those were my first tests actually. :) It also included some comments. I stripped it all down to its bare essence to hopefully focus on the logic and whether it was too verbose or repetitive, rather than precipitate a commenting style argument." } ], "meta_data": { "CommentCount": "5", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-02-07T04:17:16.920", "Id": "21406", "ParentId": "21405", "Score": "1" } }, { "body": "<blockquote>\n <p>I wanted to tackle the problem from a TDD standpoint</p>\n</blockquote>\n\n<p>and</p>\n\n<blockquote>\n <p>I ended up with ~11 tests, although not all of them are probably required (some were me just trying to break things after the fact to prove to myself it was working).</p>\n</blockquote>\n\n<p>You should look at other options for example QuickCheck (Haskell), but there apparently is a F# port [fscheck][1]. \nBasic idea is the quickcheck asserts some invariant of the output value of a function.</p>\n\n<p>Or in the same vein but more simply, why not test the following cases:\nFor each array with a length between 1 and 5 and whose each element is one of {-2, -1, 0, 1, 2}. \nIt gives you tests in 10s of thousands tests, not several; \nand exhaustively searches the most interesting, albeit small, portion of the problem domain. \nYou can generate and store the answers or can generate them on the fly.</p>\n\n<p>This is the black box part.</p>\n\n<p>For white box part you can check the internal invariants of the algorithm.\nYou can use Debug.Assert or whatever else your compiler gives you.</p>\n\n<pre><code> if (bestSum &lt; 0 &amp;&amp; bestSum &lt; value)\n {\n bestSum = value;\n currentSum = value;\n }\n\n...........\n\nbestSum = Math.Max(currentSum, bestSum);\n</code></pre>\n\n<p>snippets are repetitive</p>\n\n<p>So is <code>value &gt; -1 * currentSum</code> and <code>value &lt;= -1 * currentSum</code>.</p>\n\n<p>Moreover, <code>(currentSum + value) &gt; 0</code> is more readable than <code>value &gt; -1 * currentSum</code>.\nSimilarly <code>(currentSum + value) &lt;= 0</code> is more readable than <code>value &lt;= -1 * currentSum</code>.\nAlso note there is another <code>currentSum + value</code> hidden in <code>currentSum += value</code>.</p>\n\n<p>Compare </p>\n\n<pre><code>if (value &lt; 0 &amp;&amp; value &gt; -1 * currentSum)\n currentSum += value;\n</code></pre>\n\n<p>and </p>\n\n<pre><code>if (value &lt; 0 &amp;&amp; (currentSum + value) &gt; 0)\n currentSum = currentSum + value;\n</code></pre>\n\n<p><code>currentSum</code> is called <code>currentSum</code> but most of the time holds the <code>previousSum</code>.\nThis isn't semantic nitpicking. Correct naming is valuable in itself, \nbut this also prevents you from <code>bestSum = Math.Max(currentSum, bestSum);</code> \nright at the end of the for loop. Which is an important loop invariant.\nThat is expressed succinctly in a single site. \nAs it is, this is provided by the two <code>bestSum=</code> assignments mentioned above.\nBut it requires the reader to reason (rightly or wrongly) third clause and the conspicuously missing 4th (else) clause in the conditional analysis of the code does not break the invariant (that is <code>bestSum</code> remains the maximal sub-array sum).</p>\n\n<p><code>if (bestSum &lt; 0 &amp;&amp;</code> means we only encountered negative numbers and this is a special case and should be handled lower than the main cases. Or better yet do not handle this case separately.</p>\n\n<blockquote>\n <p>Is there some extraneous logic in here that could be refactored away?</p>\n</blockquote>\n\n<p>I think your algorithm is not fundamentally different <code>Kadane's algorithm</code>, unless there is a missed case in the confusing conditional.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-02-07T15:02:22.550", "Id": "34404", "Score": "0", "body": "This is awesome and exactly what I was looking for. I will have to take a look at this and see if I can refactor away some of the cruft." } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-02-07T14:48:43.517", "Id": "21429", "ParentId": "21405", "Score": "2" } }, { "body": "<p>You can avoid using <code>if</code> statements entirely if you don't mind making assignments each iteration (untested): </p>\n\n<pre><code>public static int HighestContiguousSum(IEnumerable&lt;int&gt; inputSequence)\n{\n int bestSum = inputSequence.First();\n int currentSum = Math.Max(bestSum, 0);\n\n foreach (var value in inputSequence.Skip(1))\n {\n int newSum = value + currentSum;\n bestSum = Math.Max(bestSum, newSum);\n currentSum = Math.Max(newSum, 0);\n }\n return bestSum;\n}\n</code></pre>\n\n<p>It's pretty simple if you recognize a few key properties:</p>\n\n<ol>\n<li>The currentSum is always non-negative.</li>\n<li>The newSum is always the current value plus the currentSum.</li>\n<li>The bestSum is always the maximum of the previous bestSum and the newSum.</li>\n</ol>\n\n<p>In general, I favor using expressions over statements (see <a href=\"http://fsharpforfunandprofit.com/posts/expressions-vs-statements/\" rel=\"nofollow\">Expressions vs. statements</a>). It generally leads to safer, more readable code. If you want to avoid statements altogether, you could replace the <code>foreach</code> loop with a call to <code>IEnumerable.Aggregate</code>:</p>\n\n<pre><code>public static int HighestContiguousSum(IEnumerable&lt;int&gt; inputSequence)\n{\n int initialBestSum = inputSequence.First();\n int currentSum = Math.Max(initialBestSum, 0);\n int bestSum = inputSequence\n .Skip(1)\n .Aggregate(Tuple.Create(initialBestSum, currentSum), GetNext, x =&gt; x.Item1);\n return bestSum;\n}\n\nprivate static Tuple&lt;int, int&gt; GetNext(Tuple&lt;int, int&gt; bestAndCurrentSum, int value)\n{\n int newSum = value + bestAndCurrentSum.Item2;\n return Tuple.Create(Math.Max(bestAndCurrentSum.Item1, newSum), Math.Max(newSum, 0));\n}\n</code></pre>\n\n<p>But as you can see, working with aggregates in C# can be clunky.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-02-08T00:19:44.257", "Id": "34437", "Score": "0", "body": "Also helpful. I'll be taking a look at this as well." } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-02-07T22:56:50.333", "Id": "21446", "ParentId": "21405", "Score": "1" } }, { "body": "<p>I think it can compress a lot more</p>\n\n<pre><code>public static int HighestContiguousSum(int[] inputArray)\n{\n int currentSum = 0;\n int bestSum = 0;\n foreach (int i in inputArray.Length)\n {\n currentSum = Math.Max(0, currentSum + i);\n bestSum = MathMax(bestSum, currentSum);\n }\n return bestSum;\n}\n</code></pre>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2017-02-23T02:26:57.613", "Id": "156065", "ParentId": "21405", "Score": "0" } } ]
{ "AcceptedAnswerId": "21429", "CommentCount": "5", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-02-07T03:17:14.557", "Id": "21405", "Score": "5", "Tags": [ "c#", "algorithm", "unit-testing", "tdd" ], "Title": "Maximum Sub-array Problem" }
21405
<p>I'm looking for a general review of a generalized linear interpolation table. Design decisions, anything that's missing, anything that could be clearer or simplified, any style considerations. Keep in mind that I've tried to keep this C++03 compatible, so no recommendations for using C++11 features please.</p> <p><strong>linear_table.hpp:</strong></p> <pre><code>#ifndef LOOKUP_LINEAR_TABLE_HPP_ #define LOOKUP_LINEAR_TABLE_HPP_ #include &lt;functional&gt; #include &lt;utility&gt; #include &lt;memory&gt; #include "lookup_detail.hpp" namespace lookup { template &lt;typename Key, typename Value, typename Compare = std::less&lt;Key&gt;, typename Allocator = std::allocator&lt;std::pair&lt;const Key, Value&gt; &gt; &gt; class unbounded_linear_table : public detail::basic_lookup_table&lt;Key, Value, Compare, Allocator&gt; { private: typedef detail::basic_lookup_table&lt;Key, Value, Compare, Allocator&gt; base; public: typedef typename base::iterator iterator; typedef typename base::const_iterator const_iterator; typedef typename base::size_type size_type; typedef typename base::allocator allocator; typedef typename base::key_type key_type; typedef typename base::mapped_type mapped_type; typedef typename base::value_type value_type; typedef typename base::key_compare key_compare; typedef typename base::reference reference; typedef typename base::const_reference const_reference; typedef typename base::pointer pointer; typedef typename base::const_pointer const_pointer; //Returns an unbounded linear interpolation based on key. //Unbounded -&gt; if the key is less than the minimum key in //the map, it will return the minimum value, if it is greater //than the maximum, it will return the maximum. mapped_type linear_interp(const Key&amp; k) const { //First, test to see if the exact key //is actually in the table. const_iterator find = base::find(k); if(find != base::end()) { return find-&gt;second; } const_iterator higher = base::upper_bound(k); //Lower constraint; upper_bound is less than the //min table value if(higher == base::begin()) { return higher-&gt;second; } //Higher constraint check; upper bound (may) //be greater than max table value. if(higher == base::end()) { const_iterator end_iter = base::end(); --end_iter; if(base::cmp_(end_iter-&gt;first, k)) return end_iter-&gt;second; } const_iterator lower = higher; --lower; key_type diff_low = k - lower-&gt;first; key_type total = higher-&gt;first - lower-&gt;first; //Linearlly interpolate between lower and higher values return lower-&gt;second + (diff_low / total) * (higher-&gt;second - lower-&gt;second); } }; //end class unbounded_linear_table typedef unbounded_linear_table&lt;double, double&gt; unbounded_lookup1d; } //end namespace lookup #endif //LOOKUP_LINEAR_TABLE_HPP </code></pre> <p><strong>lookup_detail.hpp:</strong></p> <pre><code>//Internal Header: Not to be directly imported #ifndef LOOKUP_DETAIL_HPP_ #define LOOKUP_DETAIL_HPP_ #include &lt;map&gt; namespace lookup { namespace detail { template &lt;typename Key, typename Value, typename Compare, typename Allocator&gt; class basic_lookup_table { private: typedef std::map&lt;Key, Value, Compare, Allocator&gt; container; container table_; public: typedef typename container::iterator iterator; typedef typename container::const_iterator const_iterator; typedef typename container::size_type size_type; typedef typename container::reference reference; typedef typename container::const_reference const_reference; typedef typename container::pointer pointer; typedef typename container::const_pointer const_pointer; typedef typename container::value_type value_type; typedef Allocator allocator; typedef Key key_type; typedef Value mapped_type; typedef Compare key_compare; protected: key_compare cmp_; //Disallow polymorphic usage through derived pointer ~basic_lookup_table() { } iterator upper_bound(const Key&amp; k) { return table_.upper_bound(k); } const_iterator upper_bound(const Key&amp; k) const { return table_.upper_bound(k); } iterator lower_bound(const Key&amp; k) { return table_.lower_bound(k); } const_iterator lower_bound(const Key&amp; k) const { return table_.lower_bound(k); } iterator find(const Key&amp; k) { return table_.find(k); } const_iterator find(const Key&amp; k) const { return table_.find(k); } public: void insert(const key_type&amp; key, const mapped_type&amp; value) { table_.insert(std::make_pair(key, value)); } #if __cplusplus &gt;= 201103L void insert(key_type&amp;&amp; key, mapped_type&amp;&amp; value) { table_.insert(std::make_pair(key, value)); } #endif bool erase_key(const key_type&amp; k) { size_type s = table_.erase(k); return s != 0; } void erase_greater(const key_type&amp; k) { iterator bound = table_.upper_bound(k); table_.erase(bound, table_.end()); } void erase_less(const key_type&amp; k) { iterator bound = table_.lower_bound(k); table_.erase(table_.begin(), bound); } void clear() { table_.clear(); } iterator begin() { return table_.begin(); } const_iterator begin() const { return table_.begin(); } iterator end() { return table_.end(); } const_iterator end() const { return table_.end(); } }; } //end namespace detail } //end namespace lookup #endif //LOOKUP_DETAIL_HPP_ </code></pre> <p><strong>(Basic) example usage:</strong></p> <pre><code>#include &lt;iostream&gt; #include "linear_table.hpp" int main() { using namespace lookup; unbounded_lookup1d lut; lut.insert(1.0, 2); lut.insert(1.5, 3); lut.insert(2.0, 7); lut.insert(2.5, 10); lut.insert(3.0, 15); std::cout &lt;&lt; lut.linear_interp(2.4) &lt;&lt; "\n"; lut.erase_greater(2.0); std::cout &lt;&lt; lut.linear_interp(2.4) &lt;&lt; "\n"; return 0; } </code></pre>
[]
[ { "body": "<pre><code>//Lower constraint; upper_bound is less than the\n//min table value\n</code></pre>\n\n<p>You probably mean \"upper_bound is the min table value\". This also applies to the next comment.</p>\n\n<pre><code> //Higher constraint check; upper bound (may)\n //be greater than max table value.\n if(higher == base::end()) {\n const_iterator end_iter = base::end();\n --end_iter;\n if(base::cmp_(end_iter-&gt;first, k))\n return end_iter-&gt;second;\n }\n</code></pre>\n\n<p>I may be wrong but this case seems to be covered by the first test. Maybe <code>if (base::cmp_(end_iter-&gt;first, k) &gt; 0</code>?</p>\n\n<p>No comments on <code>basic_lookup_table</code> which is simply a <code>map</code> wrapper anyway. Your code is very good C++. Oh, and since you asked about style: I prefer <code>if (test)</code> to <code>if(test)</code> and you could be careful about trailing white spaces.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-02-07T11:21:43.690", "Id": "34365", "Score": "0", "body": "Ah, yes, that's poor wording on my part. It should be \"upper bound is the min table value, hence the key is less than the min table value\", likewise for max. Good catch. For the test, I need to decrement `end_iter` first, since it points to one past the end of the map. I don't *think* it's covered by any other test." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-02-07T12:38:08.707", "Id": "34371", "Score": "1", "body": "I was wrong for the test, but let me ask another question: in what case would you enter in `higher == base::end()` but not in `base::cmp_(end_iter->first, k)`?" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-02-07T12:45:26.700", "Id": "34374", "Score": "0", "body": "I see your point - it can't happen. Another nice catch." } ], "meta_data": { "CommentCount": "3", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-02-07T10:31:42.030", "Id": "21418", "ParentId": "21407", "Score": "1" } } ]
{ "AcceptedAnswerId": "21418", "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-02-07T05:26:01.383", "Id": "21407", "Score": "2", "Tags": [ "c++", "lookup", "c++03" ], "Title": "Standard library-like linear interpolation table" }
21407
<p>I am writing a program which calculates the scores for participants of a small "Football Score Prediction" game.</p> <p>Rules are:</p> <ol> <li>if the match result(win/loss/draw) is predicted correctly: 1 point</li> <li>if the match score is predicted correctly(exact score): 3 points (and +1 point because 1st rule is automatically satisfied)</li> </ol> <p>Score is calculated after every round of matches (10 matches in a round).</p> <p>The program I've written is as follows:</p> <pre><code>import numpy as np import re players = {0:'Alex',1:'Charlton',2:'Vineet'} results = np.array(range(40),dtype='a20').reshape(4,10) eachPrediction = np.array(range(20),dtype='a2').reshape(2,10) score = np.zeros(3) correctScore=3 correctResult=1 allPredictions = [] done = False def takeFixtures(): filename='bplinput.txt' file = open(filename) text = file.readlines() fixtures = [line.strip() for line in text] file.close() i=0 for eachMatch in fixtures: x=re.match("(.*) ([0-9]+) ?- ?([0-9]+) (.*)", eachMatch) results[0,i]=x.group(1) results[1,i]=x.group(2) results[2,i]=x.group(3) results[3,i]=x.group(4) i+=1 def takePredictions(noOfParticipants): for i in range(0,noOfParticipants): print("Enter predictions by "+players[i]+" in x-y format") for i in range(0,10): eachFixturePrediction = raw_input("Enter prediction for "+results[0,i]+" vs "+results[3,i]+": ") x=eachFixturePrediction.split('-') eachPrediction[0,i]=str(x[0]) eachPrediction[1,i]=str(x[1]) allPredictions.append(eachPrediction) def scoreEngine(): for i in range(0,len(players)): for j in range(0,10): resultH=int(results[1,j]) resultA=int(results[2,j]) result=resultH-resultA predictionH=int(allPredictions[i][0][j]) predictionA=int(allPredictions[i][1][j]) pResult = predictionH-predictionA if result == pResult or (result&lt;0 and pResult&lt;0) or (result&gt;0 and pResult&gt;0): score[i]+=correctResult if resultH==predictionH and resultA==predictionA: score[i]+=correctScore noOfParticipants=len(players) takeFixtures() takePredictions(noOfParticipants) scoreEngine() print("Scores are:") print(score) for player in players: print(players[player]+" has scored "+ str(score[player])+" points" ) </code></pre> <p>The file used to take list of fixtures looks like this:</p> <pre><code>West Bromwich Albion 0-1 Tottenham Hotspur Manchester City 2-2 Liverpool Queens Park Rangers 0-0 Norwich City Arsenal 1-0 Stoke City Everton 3-3 Aston Villa Newcastle United 3-2 Chelsea Reading 2-1 Sunderland West Ham United 1-0 Swansea City Wigan Athletic 2-2 Southampton Fulham 0-1 Manchester United </code></pre> <p>I want advice on how this program can be improved in any way (decreasing the code/ making it efficient).</p>
[]
[ { "body": "<p>I'd change something in the style of your application in order to decrease the coupling.</p>\n\n<p>Why do you use global variables?\nI'd change the design to have the following functions:</p>\n\n<ul>\n<li><code>takeFixtures(fileName)</code> returning the fixtures;</li>\n<li><code>takePredictions(numberOfParticipants, fixtures)</code> returning the predictions for each player. This should be decomposed in a function that takes the predictions of a player and another that takes the prediction for a single game;</li>\n<li><code>computeScores(fixtures, predictions)</code> that returns a list of pair <code>(player, score)</code>. That function should be decomposed to other functions computing the score for a player and the score for a single game.</li>\n</ul>\n\n<p>In addition to that, why do you limit your code to work only if you have 10 games?\nWouldn't it be better if you replace the <code>10</code> in <code>for j in range(0,10):</code> with <code>len(games)</code> or something similar? That would also benefit from the functional point of view as your code would support out of the box any league regardless of the number of games played each turn.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-02-07T15:23:59.583", "Id": "34408", "Score": "0", "body": "the reason I limited to 10 games because its for Barclays premier league which has 20 teams. but its a good suggestion, i'll take it :) thanks" } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-02-07T09:25:34.407", "Id": "21411", "ParentId": "21408", "Score": "4" } }, { "body": "<p>First thing, let's talk about the <code>players</code> array : </p>\n\n<ul>\n<li>you define it with <code>players = {0:'Alex',1:'Charlton',2:'Vineet'}</code>.</li>\n<li><p>you iterate on it using :</p>\n\n<pre><code>for i in range(0,noOfParticipants):\n # Something about : players[i]\n</code></pre>\n\n<p>or</p>\n\n<pre><code>for player in players:\n # Something about : players[player] and str(score[player])\n</code></pre></li>\n</ul>\n\n<p>First passing the length of an array without passing the array is a bit awkward (not to say useless). Then, the way you loop is not very pythonic. If what you want is a list of names, define it as a list of names: <code>players = ['Alex','Charlton','Vineet']</code> (if you define the index yourself and you iterate using only the size of the loop, you might get troubles). Then, if you want to iterate over the names, it's pretty straightforward: <code>for player in players:</code>. You want the index as well ? Enumerate is what you want: <code>for i,name in enumerate(players)</code>. How cool is this ?</p>\n\n<p>However, it might be a good idea to make this array a little bit more complicated and use it to store not only the players' names but also their prediction and their score. Then, a dictionary would be a good solution.</p>\n\n<p>Then, a few details :</p>\n\n<ul>\n<li><p>I think you should get rid of the magic numbers: I have no idea what the different numbers are for.</p></li>\n<li><p>I think <code>correctScore</code> and <code>correctResult</code> are not very good names to express number of points (<code>pointCorrectScore</code> and <code>pointCorrectResult</code> are my suggestions) but storing this in variable is a pretty good idea. Also, I would advise you to create a function returning the score from an estimation and an actual score. Your variables <code>correctScore</code> and <code>correctResult</code> could then be local to your function.</p></li>\n</ul>\n\n<p>I have no time to go further in the code I didn't quite understand at first glance but I'll try to do it eventually.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-02-07T09:29:36.267", "Id": "21412", "ParentId": "21408", "Score": "5" } }, { "body": "<h2>Style</h2>\n\n<p>The first thing to do is to follow PEP 8: it's a style guide that says how you should indent your code, name your variables, and so on. For example, prefer <code>results[0, i] = x.group(1)</code> to <code>results[0,i]=x.group(1)</code>.</p>\n\n<h2>Files</h2>\n\n<p>Opening files in Python should be done using the <a href=\"http://www.python.org/dev/peps/pep-0343/\" rel=\"nofollow\"><code>with</code> idiom</a>: your file is then guaranteed to be close correctly. <code>takeFixtures</code> now becomes:</p>\n\n<pre><code>def takeFixtures():\n with open('bplinput.txt') as file:\n for eachMath in file:\n x=re.match(\"(.*) ([0-9]+) ?- ?([0-9]+) (.*)\", eachMatch.strip)\n results[0,i]=x.group(1)\n results[1,i]=x.group(2)\n results[2,i]=x.group(3)\n results[3,i]=x.group(4)\n i+=1\n</code></pre>\n\n<h2>Data structures</h2>\n\n<p>I you didn't use numpy, you could have written <code>results[i] = x.groups()</code>, and then used <code>zip(*results)</code> to transpose the resulting matrix. More generally, as pointed out by Josay, you should use Python data structures, and only switch to numpy if you find out that this is where the inefficiency lies.</p>\n\n<h2>Formatting</h2>\n\n<p>The last thing that the other reviewers didn't mention is that concatenating strings is poor style, and <code>format()</code> should be preferred since it's more readable and more efficient:</p>\n\n<pre><code>for player in players:\n print(\"{} has scored {} points\".format(players[player], score[player]))\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-02-07T15:29:14.560", "Id": "34409", "Score": "0", "body": "thanks,Can you give me suggestion on a better way to take input from all the players? right now I have to manually input the score predictions by all players, and if there is some mistake i have to do it all over again. ie. one mistake and i have to input 30 predictions all over again" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-02-07T16:14:28.623", "Id": "34413", "Score": "1", "body": "You need to catch the [exception](http://docs.python.org/2/tutorial/errors.html) that comes out and ask the input to be made again. You would need some kind of loop to make the input until it worked correctly. This would be a good question on StackOverflow unless it has alread been asked." } ], "meta_data": { "CommentCount": "2", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-02-07T10:11:11.890", "Id": "21416", "ParentId": "21408", "Score": "6" } } ]
{ "AcceptedAnswerId": "21416", "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-02-07T05:51:57.967", "Id": "21408", "Score": "4", "Tags": [ "python", "optimization", "game" ], "Title": "Calculating scores for predictions of football scores" }
21408
<p>I need some advice off the back of a question I posted on StackOverflow. I'm a procedural PHP programmer and I'm looking to make the move into object oriented PHP. I have started a small project that basically acts as a small CMS that allows me to separate my website content from the actual structure of the page. The code I am using to achieve this is:</p> <pre><code>&lt;?php class Connection extends Mysqli{ public function __construct($mysqli_host,$mysqli_user,$mysqli_pass, $mysqli_db) { parent::__construct($mysqli_host,$mysqli_user,$mysqli_pass,$mysqli_db); $this-&gt;throwConnectionExceptionOnConnectionError(); } private function throwConnectionExceptionOnConnectionError(){ if(!$this-&gt;connect_error){ echo "Database connection established&lt;br/&gt;"; }else{ //$message = sprintf('(%s) %s', $this-&gt;connect_errno, $this-&gt;connect_error); echo "Error connecting to the database."; throw new DatabaseException($message); } } } class DatabaseException extends Exception { } class Page{ private $con; public function __construct(Connection $con) { $this-&gt;con = $con; if(isset($_GET['id'])){ $id = $_GET['id']; }else{ $id = 1; } $this-&gt;get_headers($id); $this-&gt;get_content($id); $this-&gt;get_footer($id); } private function get_headers($pageId){ $retrieveHead = $this-&gt;con-&gt;prepare("SELECT headers FROM pages WHERE page_id=?"); $retrieveHead-&gt;bind_param('i',$pageId); $retrieveHead-&gt;execute(); $retrieveHead-&gt;bind_result($header); $retrieveHead-&gt;fetch(); $retrieveHead-&gt;close(); echo $header; } private function get_footer($pageId){ $retrieveFooter = $this-&gt;con-&gt;prepare("SELECT footer FROM pages WHERE page_id=?"); $retrieveFooter-&gt;bind_param('i',$pageId); $retrieveFooter-&gt;execute(); $retrieveFooter-&gt;bind_result($footer); $retrieveFooter-&gt;fetch(); $retrieveFooter-&gt;close(); echo $footer; } private function get_content($pageId){ $retreiveContent = $this-&gt;con-&gt;prepare("SELECT template_id, section_title, i1, i2 FROM content WHERE page_id=? ORDER BY sequence DESC"); $retreiveContent-&gt;bind_param('i',$pageId); $retreiveContent-&gt;execute(); $retreiveContent-&gt;bind_result($template_id, $section_title, $i1, $i2); $retreiveContent-&gt;store_result(); while ($retreiveContent-&gt;fetch()) { //Variables will be populated for this row. //Update the tags in the template. $template = $this-&gt;get_template($template_id); $template = str_replace('[i1]',$i1,$template); $template = str_replace('[i2]',$i2,$template); //$theTemplate is populated with content. Probably want to echo here echo $template; } $retreiveContent-&gt;free_result(); $retreiveContent-&gt;close(); } private function get_template($template_id){ $retreiveTemplate = $this-&gt;con-&gt;prepare("SELECT code FROM templates WHERE template_id=?"); $retreiveTemplate-&gt;bind_param('i',$template_id); $retreiveTemplate-&gt;execute(); $retreiveTemplate-&gt;bind_result($template); $retreiveTemplate-&gt;fetch(); $retreiveTemplate-&gt;close(); return $template; } } ?&gt; </code></pre> <p>I create a page object in my <code>index.php</code> file which is used to output the page by running the functions below in the order listed in the Page constructor. The comments I received on StackOverflow were along the lines of:</p> <blockquote> <p>This code violates numerous OOP principles. As a result of that, I hope that no newbies attempt to use this as a means of learning OOP, as they will be learning an invalid programming paradigm if they use what you have here as an example. Read up on the single responsibility principle and the other components of SOLID, and perhaps get a book on design patterns.</p> </blockquote> <p>I've read up on these subjects and I remember a lot of the principals from Java in my first year of Uni (about 6 years ago now) but as far as I can see in my code I am separating concerns as much as possible. It doesn't make sense to me to have the database connection as part of the page as it isn't really a property of the page whereas the headers and footers and content are. However, the page requires a database connection to function so I therefore have to pass a Connection object into the Page class to acheive the connectivity.</p> <p>I've asked the authors of the comments numerous times to explain their reasoning behind such comments but all the keep doing is making statements saying this is bad code without providing examples as to why or what I might do to change it therefore I thought I'd ask this question here as I'll never learn if I'm not given a helping hand along the way.</p>
[ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-02-07T09:47:13.243", "Id": "34351", "Score": "0", "body": "possible duplicate of [Object Orientated PHP, what's wrong with this setup?](http://codereview.stackexchange.com/questions/21413/object-orientated-php-whats-wrong-with-this-setup)" } ]
[ { "body": "<p>What I see at first glance.</p>\n\n<p><code>Page</code> and <code>Connection</code> are extending <code>Mysqli</code></p>\n\n<p>Why is a Page a special Mysqli? (Page extends Mysqli)</p>\n\n<p>Why is a Connection a special Mysqli? (Connection extends Mysqli)</p>\n\n<p>A page can use a Mysqli to save stuff, but it <em>is not</em> a Mysqli.\nAlso the word Connection suggests it's a base-class of Mysqli (since a Connection can be a connection to a OracleDB, a TCP-Server etc.) but in your case Mysqli is the base for Connection.</p>\n\n<p>The whole code implies you have no idea of OOP at all. Which is Okay, you can read some stuff about it, there is many outter there :)</p>\n\n<p>Probably the most OOP programmers just see the code and don't know <em>where</em> to start improving it, because it just eludes them completly.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-02-07T10:09:50.753", "Id": "34354", "Score": "0", "body": "Sorry, that's actually old code from before I was passing the Connection object. Page shouldn't actually extend mysqli as you rightly suggest but once again I'm told I have no idea of OOP when most of this setup has been achieved using books and tutorials on the subject. Could you please elaborate.." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-02-07T10:22:01.737", "Id": "34355", "Score": "0", "body": "Could you elaborate please. My implementation takes into account separation of concerns (e.g. the database object [Connection] is in charge of the connection to the database. The Page object [Page] is responsible for everything to do with the pages. I use inheritance correctly to ensure I am not duplicating code (My Connection class is a version of MySQLi with specified error handling)." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-02-07T10:33:21.877", "Id": "34356", "Score": "2", "body": "Your `Connection` class adds nothing the `Mysqli` class did not already have. So why extend it? To add an extended exception, which also don't adds something new?" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-02-07T10:43:01.507", "Id": "34357", "Score": "0", "body": "Okay so in your view I shouldn't have a Connection class. That's fine. This was suggested elsewhere to implement it in this way but instead of passing the Connection class in here I would pass in the base Mysqli class using the built in exception handling. Any other pointers (I really appreciate this) there is an absence of real world examples anywhere that explain these principles with useable code. All examples refer to animals or people but this isn't useful in understanding classes would come together to form a login system for example.." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-02-07T10:52:07.967", "Id": "34359", "Score": "0", "body": "Yes, I know your problem very well :\\ I've been there a few years ago, even studying computer science didn't help that much, since all examples in university where with animals or cars. Once I read a nice tutorial about MVC with PHP, which helped me alot. But I don't find it anymore." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-02-07T10:53:26.220", "Id": "34360", "Score": "0", "body": "probably something like this would help: http://r.je/mvc-in-php.html" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-02-07T11:08:36.373", "Id": "34362", "Score": "1", "body": "Thanks @..K I'll take a look at this. I did OOP in Java years ago at Uni but as I am an expert in HTML and CSS I moved away from Java and learned procedural PHP instead. In my job I don't really code in PHP but I want to put a portfolio together and most comments online suggest that PHP should now be coded using OOP hence why I'm trying to learn it. However, I am still a fan of the procedural approach and don't understand why people call it inefficient. If functions are well commented and documented the a procedural application can be very easy to maintain so I may just stick to procedural.." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-02-07T11:25:31.117", "Id": "34366", "Score": "0", "body": "as far as I know there is no empirical evidence that OOP is in any way better than procedural programming." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-02-07T11:43:51.170", "Id": "34370", "Score": "0", "body": "Exactly. However when applying for jobs (particularly in the UK) everyone seems to want OOPHP which is a shame because I'm a good programmer procedurally." } ], "meta_data": { "CommentCount": "9", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-02-07T10:06:25.023", "Id": "21415", "ParentId": "21414", "Score": "5" } } ]
{ "AcceptedAnswerId": "21415", "CommentCount": "1", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-02-07T09:24:45.540", "Id": "21414", "Score": "0", "Tags": [ "php", "object-oriented" ], "Title": "Object Orientated PHP, what's wrong with this implementation of OOPHP and how might it be improved?" }
21414
<p>I am creating an application which will be testable(unit + integration). In this application I have a FileHelper static class,</p> <pre><code>public static class FileHelper { public static void ExtractZipFile(Stream zipStream, string location) { .................................. } public static void CreatePageFolderIfNotExist(string directory) { ................................................. } ....................................................... ....................................................... } </code></pre> <p>But due to static I think it is not testable. How to make this class testable?</p>
[ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-02-07T11:40:39.180", "Id": "34368", "Score": "1", "body": "Why would you want this class to be static at all? If you want testable code, avoid them. I'd change the API slightly. so you use Zip = new Zip('file.zip'); Zip.extractTo('/path/); Combining these seemingly unrelated functions is poor separation of concerns." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-02-07T19:53:12.117", "Id": "34427", "Score": "0", "body": "@Tom B, \"if you want testable code, then avoid static classes \"... Really? Seriously? So, if I have a function `public static double sqrt(double x)`, then I just cannot test it? I cannot pass a few parameters in and make sure that I get the expected result or exception? If I have a more complicated function/method that affects the file system or creates some other side effect, is it suddenly that much different?" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-02-08T09:28:12.203", "Id": "34448", "Score": "3", "body": "@Leonid see: http://misko.hevery.com/2008/12/15/static-methods-are-death-to-testability/ It's not the static methods which are hard to test, it's the code which uses them. It becomes difficult to test because it's impossible to substitute them for mocks. You *must* test the client code and the static method during the test. This means it's impossible to know whether a bug is in the method you're actually testing or the static method it calls, which defeats the purpose of unit testing-- it's impossible to isolate the exact code you're trying to test." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-02-19T15:32:23.610", "Id": "35200", "Score": "0", "body": "I'm a big fan of static methods, but these should not be static since they access external state." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-09-06T17:16:23.117", "Id": "49155", "Score": "1", "body": "The tldr of static methods is that they should generally be stateless. Stateless methods are usually pretty easy to test, because you have a well-defined set of inputs and well-defined outputs. When testing a piece of code which uses *stateless* static methods, you simply treat them as part of the unit you are testing, no different than if the code is in-lined." } ]
[ { "body": "<p>If you want to write tests for this helper class only - they would be <em>integration tests</em> since they touch the file system. </p>\n\n<p>In order to make the code <em>unit testable</em> you need to make it independent from hardware and physical interaction with network or disk.</p>\n\n<p>If you want to unit test the business logic that uses this <code>FileHelper</code>, then you should introduce <a href=\"http://en.wikipedia.org/wiki/Inversion_of_control\">Inversion of Control</a> to separate business logic from file activities. You'll have to create an interface that describes all operations you can do with files, transform this static helper class into class implementing that interface, and reference file operations from business logic via interface only. Example of file helper:</p>\n\n<pre><code>public interface IFileOperations\n{\n void ExtractZipFile(Stream zipStream, string location);\n void CreatePageFolderIfNotExist(string directory);\n}\n\npublic class FileOperations : IFileOperations\n{\n public void ExtractZipFile(Stream zipStream, string location)\n {\n ..................................\n } \n\n public void CreatePageFolderIfNotExist(string directory)\n {\n .................................................\n }\n}\n</code></pre>\n\n<p>Then, in order to properly cover you code with tests, you would need to write <em>unit tests</em> for business logic and add <em>integration tests</em> for the implementation of <code>FileOperations</code>.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-02-07T10:57:23.837", "Id": "21419", "ParentId": "21417", "Score": "8" } } ]
{ "AcceptedAnswerId": "21419", "CommentCount": "5", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-02-07T10:28:08.167", "Id": "21417", "Score": "5", "Tags": [ "c#", "unit-testing", "static" ], "Title": "How to make static methods testable?" }
21417
<p>I was hoping someone could give me some feedback on my code. I am still new to php and I'm sure I have messed up somewhere. The code pasted is for a registration page where users will submit their information which will then be posted to the database.</p> <pre><code>&lt;?php&gt; include 'PasswordHash.php'; $sql = new mysqli('localhost', '#######', '#####', '######'); // Create an array to catch any errors in the registration form. $errors = array(); /** * Make sure the form has been submitted before trying to process it. This is * single most common cause of 'undefined index' notices. */ if (!empty($_POST)) { // First check that required fields have been filled in. if (empty($_POST['username'])) { $errors['username'] = "Username cannot be empty."; } // Restrict usernames to alphanumeric plus space, dot, dash, and underscore. /* if (preg_match('/[^a-zA-Z0-9 .-_]/', $_POST['username'])) { $errors['username'] = "Username contains illegal characters."; } */ if (empty($_POST['firstname'])) { $errors['firstname'] = "First Name cannot be empty."; } if (empty($_POST['surname'])) { $errors['surname'] = "Surname cannot be empty."; } if (empty($_POST['password'])) { $errors['password'] = "Password cannot be empty."; } if (strlen($_POST['password']) &lt; 8) { $errors['password'] = "Password must be at least 8 charcaters."; } // Force passwords to contain at least one number and one special character. /* if (!preg_match('/[0-9]/', $_POST['password'])) { $errors['password'] = "Password must contain at least one number."; } if (!preg_match('/[\W]/', $_POST['password'])) { $errors['password'] = "Password must contain at least one special character."; } */ if (empty($_POST['password_confirm'])) { $errors['password_confirm'] = "Please confirm password."; } if ($_POST['password'] != $_POST['password_confirm']) { $errors['password'] = "Passwords do not match."; } $email = filter_var($_POST['email'], FILTER_VALIDATE_EMAIL); if (!$email) { $errors['email'] = "Not a valid email address."; } /** * Escape the data we're going to use in our query. Never trust user input. */ $username = $sql-&gt;real_escape_string($_POST['username']); $email = $sql-&gt;real_escape_string($email); $firstname = $sql-&gt;real_escape_string($_POST['firstname']); $surname = $sql-&gt;real_escape_string($_POST['surname']); $addressline1 = $sql-&gt;real_escape_string($_POST['addressline1']); $addressline2 = $sql-&gt;real_escape_string($_POST['addressline2']); $city = $sql-&gt;real_escape_string($_POST['city']); $county = $sql-&gt;real_escape_string($_POST['county']); $postcode = $sql-&gt;real_escape_string($_POST['postcode']); /** * Check that the username and email aren't already in our database. * * Note also the absence of SELECT * */ $query = "SELECT username, email FROM users WHERE username = '{$username}' OR email = '{$email}'"; $result = $sql-&gt;query($query); /** * There may well be more than one point of failure, but all we really need * is the first one. */ $existing = $result-&gt;fetch_object(); if ($existing) { if ($existing-&gt;username == $_POST['username']) { $errors['username'] = "That username is already in use."; } if ($existing-&gt;email == $email) { $errors['email'] = "That email address is already in use."; } } } if (!empty($_POST) &amp;&amp; empty($errors)) { /** * Hash password before storing in database */ $hasher = new PasswordHash(8, FALSE); $password = $hasher-&gt;HashPassword($_POST['password']); $query = "INSERT INTO users (firstname, surname, username,email, password, addressline1, addressline2, city, county, postcode, created) VALUES ('{$firstname}','{$surname}','{$username}','{$email}', '{$password}','{$addressline1}','{$addressline2}','{$city}','{$county}','{$postcode}', NOW())"; $success = $sql-&gt;query($query); if ($success) { $message = "Account created."; } else { $errors['registration'] = "Account could not be created. Please try again later."; } } ?&gt; </code></pre>
[ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-02-07T14:00:27.243", "Id": "34394", "Score": "0", "body": "`<?php>` is wrong. It should be just `<?php`." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-02-07T14:31:32.673", "Id": "34397", "Score": "0", "body": "You check if $_POST is not empty twice. Just nest your check for errors inside the first !empty clause." } ]
[ { "body": "<p>Well, here are my notes from looking through the code:</p>\n\n<ol>\n<li><p>You create a connection to the database, and include <code>PasswordHash.php</code>, when it is not yet needed. Database connections are not \"free of charge\" and should be used conservatively.</p></li>\n<li><p>You use two <code>if</code> blocks where you could use just one.</p></li>\n<li><p>There is no real checking/validation/sanitation of the incoming data. Sure, you escape it before you <code>INSERT</code> it, but you never check if it is valid. For example, the <code>$county</code> variable is just assumed to be a county... it could be anything.</p></li>\n<li><p>The first <code>SELECT</code> query may not be entirely necessary. If your database schema is set up properly (i.e. using <code>UNIQUE</code> on the <code>username</code> and <code>email</code> fields), then you will be told that the user already exists. You can then take it from there. If is always a good deal if you can eliminate database calls.</p></li>\n<li><p>The <code>$errors</code> array is never used. You probably know this, so I will not use any time on it.</p></li>\n</ol>\n\n<p>The main problem (if you want to call it that) is that you need to be a little more systematic. You need to think about the whole process in steps, or more as an algorithm:</p>\n\n<ol>\n<li>Sanitize the input</li>\n<li>Validate the input\n<ol>\n<li>If the input does not validate, stop, let the user correct it</li>\n<li>If the input is valid, go to #3</li>\n</ol></li>\n<li>Set up database connection</li>\n<li>Insert data\n<ol>\n<li>If there is a duplicate record error, stop, the user already exists!</li>\n<li>If there is no error, go to #5</li>\n</ol></li>\n<li>Success, user was created. DONE.</li>\n</ol>\n\n<p>That is about it.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-02-08T22:41:29.050", "Id": "21488", "ParentId": "21420", "Score": "1" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "2", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-02-07T12:51:56.853", "Id": "21420", "Score": "2", "Tags": [ "php", "mysql", "mysqli" ], "Title": "Could really use some feedback on this registration code in php" }
21420
<p>I am trying to create a multiway tree with the following code in C++. As of now, it is more like a sample piece of code.</p> <p>I wish to do the following with this piece of code(and I am able to get the desired result):</p> <ol> <li>Create a struct Node of two members : value(of the node) and array of children of the node.</li> <li>Make 'root's value = 5</li> <li>Make the children's values equal to 10,20,30 &amp; 40</li> <li>Make the children of children's values equal to null(=0);</li> </ol> <p>I am getting the desired output , but <strong>what I want to know is if I am doing it the right way.</strong></p> <p>Thanks, in advance.</p> <pre><code>//multinode tree #include&lt;iostream&gt; #define null 0 struct Node { int value; Node *child[4]; }; void display(Node *root){ if(root==null) return; else{ std::cout&lt;&lt;root-&gt;value&lt;&lt;" "; if(root-&gt;child[0]!=null) for (int i=0;i&lt;4;i++) { if(root-&gt;child[i]!=null) display(root-&gt;child[i]); } } } int main() { Node *root=new Node; Node *test=null; root-&gt;value=5; int values[]={10,20,30,40}; int i=0; for (i=0;i&lt;4;i++) { Node *temp=new Node; temp-&gt;value=values[i]; root-&gt;child[i]=temp; for (int j=0;j&lt;4;j++) { root-&gt;child[i]-&gt;child[j]=null; } std::cout&lt;&lt;"Root value "&lt;&lt;root-&gt;child[i]-&gt;value&lt;&lt;"\n\n "; } std::cout&lt;&lt;"\n\n\n\n\n"; display(root); } </code></pre>
[ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-02-07T01:22:48.550", "Id": "34375", "Score": "0", "body": "I've fixed the indentation on this code. There was some non-standard indentation that could confuse readers." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-02-07T08:21:08.257", "Id": "34377", "Score": "0", "body": "Also, \"`#define null 0`\"? What's wrong with `NULL`?" } ]
[ { "body": "<p>This is correct enough. </p>\n\n<p>You could improve it in a couple of ways,</p>\n\n<ul>\n<li>if you do <code>new Node()</code>, note the additional <code>()</code>, <a href=\"https://stackoverflow.com/a/620402/1520364\">its members will be zero initialized</a>, so you can skip the <code>null</code>ing of the children.</li>\n<li>you can add a constructor which initializes among other things the arrays to <code>null</code>, so that you don't need to remember to do it every time, Recommended for readability and future proof as commenters suggest?</li>\n</ul>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-02-07T01:28:36.173", "Id": "34378", "Score": "1", "body": "The standard does not require default initialisation of members, so your first advice is dangerous." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-02-07T01:31:32.057", "Id": "34379", "Score": "1", "body": "@CongXu I am going based on [Do the parentheses after the type name make a difference with new?](http://stackoverflow.com/a/620402)" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-02-07T01:40:12.373", "Id": "34380", "Score": "0", "body": "@KarthikT: I think it's dangerous to rely on that behavior. What happens if someone unwittingly adds a new member to the `Node` class which makes it non-POD?" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-02-07T01:45:51.490", "Id": "34381", "Score": "0", "body": "@NikBougalis correct me if I am wrong, but it looks to me like the link promises 0 initialization as long as there is no user defined constructor. Regardless, I would go the explicit route (#2) myself." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-02-07T03:54:12.363", "Id": "34382", "Score": "0", "body": "Thank you for your reply. I was specifically wondering if **root->child[i]->child[j]=null;** was a prudent way to initialize the grand-children of root to null." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-02-07T04:48:23.733", "Id": "34383", "Score": "1", "body": "@RahulRajaram imo, the right way is that they be `null` by default instead of having to do it manually, safer that way, you cant forget." } ], "meta_data": { "CommentCount": "6", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-02-07T01:16:11.093", "Id": "21422", "ParentId": "21421", "Score": "0" } }, { "body": "<p>This is a very C like approach and you are using C++ so take advantage of that fact.</p>\n\n<ol>\n<li><p>Get rid of the <code>#define</code> and use <code>nullptr</code> keyword instead.</p></li>\n<li><p>Name member variables something special such as <code>m_</code> so <code>Node *m_children[4]</code>; </p></li>\n<li><p>Try use C++ data structures instead of arrays and <code>char*</code> so <code>vector&lt;Node*&gt;</code> children.</p></li>\n<li><p>Make the <code>Node</code> struct into a class and write getters and setters to encapsulate the new vector structure you should use.</p></li>\n<li><p>Encapsulate the <code>void display(Node *root)</code> function into a class such:</p>\n\n<pre><code>class Tree\n{\n Tree(int depth);// create a tree with x depth\n etc...\n void display();\npublic:\n Node* m_root;\n};\n</code></pre>\n\n<p>You could create some functionality to able to initialise the tree with some custom data structure.</p></li>\n<li><p>Add the following code in main into the tree class</p>\n\n<pre><code>for (i=0;i&lt;4;i++)\n{\n Node *temp=new Node;\n temp-&gt;value=values[i];\n root-&gt;child[i]=temp;\n for (int j=0;j&lt;4;j++)\n {\n root-&gt;child[i]-&gt;child[j]=null;\n }\n std::cout&lt;&lt;\"Root value \"&lt;&lt;root-&gt;child[i]-&gt;value&lt;&lt;\"\\n\\n \";\n}\n</code></pre></li>\n</ol>\n\n<p>PS. Sorry if the code doesn't work; I'm at work and have no way to check it!</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-02-07T01:46:37.467", "Id": "34384", "Score": "0", "body": "Additionally you might want to add into the Node struct another Node* to its parent so you can reverse navigate the tree also." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-02-07T01:49:00.477", "Id": "34385", "Score": "3", "body": "#2 is a style choice, not necessarily C++ mandated.." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-02-07T02:53:22.980", "Id": "34386", "Score": "0", "body": "#2 http://www.devx.com/cplus/10MinuteSolution/35167\nhttp://www.open-std.org/jtc1/sc22/wg21/docs/papers/2003/n1488.pdf\n\nIts a bad approach if you are using C++ instead of C.\nThere is a keyword for very good reasons." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-02-07T03:07:43.377", "Id": "34387", "Score": "0", "body": "I was talking about the `m_` prefix, I have nothing against `nullptr`" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-02-07T03:10:24.300", "Id": "34388", "Score": "0", "body": "Sorry, my mistake yes your right it is a style choice. But any similar style choice is good. I'm just highly recommending for the same reason we dont call everything \"a\", \"b\", \"c\" or writing our code on 1 line or just having 1 file with everything." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-02-07T03:53:30.477", "Id": "34389", "Score": "0", "body": "Thanks you. Yes, I realize that the style of the program is very much C-like, but I want to better my ability to manipulate the more fundamental aspects , first. At this point, I am unable to adapt to the genuine C++ style of programming, but I will adopt C++ fully, once I find adequate time." } ], "meta_data": { "CommentCount": "6", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-02-07T01:45:11.537", "Id": "21423", "ParentId": "21421", "Score": "1" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "2", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-02-07T01:11:04.943", "Id": "21421", "Score": "2", "Tags": [ "c++" ], "Title": "Making grandchild of root null , the right way in C++" }
21421
<p>I have made a function which calculates the index of a point to which an arbitrary point on a polygon made of XY points belong.</p> <p>This is a visual representation:</p> <p><img src="https://i.stack.imgur.com/d13dZ.png" alt="enter image description here"></p> <p>And this is the function I made:</p> <pre><code>stock GetNodeIndexFromPolygonIndex(polygonid,Polygon_Size) { new polid = (polygonid - (polygonid % 2)); new mid = Polygon_Size/2; if(polid &gt; mid) { polid /= 2; return (mid - (++polid)); } else { polid /= 2; if(polid == 0) { return 0; } return --polid; } } </code></pre> <p>Is there anything I can optimize here? This function is going to be called ~2000 times in the worst case in one run on a single threaded application. I would like this to be as optimal as possible. Is it already?</p>
[ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-02-07T14:32:47.727", "Id": "34398", "Score": "2", "body": "I personally don't understand the explanation. Why 3 in the first red circle for example?" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-02-07T16:15:52.103", "Id": "34414", "Score": "0", "body": "The basic thing is thhat the red circles are a PATH which is created from XYZ points and have indexes from 0 to up. yet, there is a polygon around it which has to be closed so one polygon point has 4 indexes (XY, XY, first and last polygon point). The black points are thus the polygon around the red path with a specific width. Just like here: http://i.stack.imgur.com/x865n.png" } ]
[ { "body": "<p>First, I do not know anything about PAWN.</p>\n\n<p>Does it have a profiler? Can any profiler be used? If yes, probably use it.<br>\nIf no, write at least some test units to measure execution time.</p>\n\n<p>I will assume typical language elements. I will assume <code>polygonid &gt; 0</code> and <code>Polygon_Size &gt; 0</code>, because I do not know (and did not find in short time) the behavior of <code>/</code> and <code>%</code> for negative numbers.</p>\n\n<p>As far as I understood, there is a virtual machine between compiler and execution. This makes things a little bit more complex, but well, we will assume that nothing special happens there.</p>\n\n<p>Some of the optimizations could change nothing, because the compiler already does it. I can not predict or test it.</p>\n\n<p>That said, I will choose line after line. I do not know if you can change the algorithm, because like Cygal I do not understand the exact purpose.</p>\n\n<hr>\n\n<pre><code>new polid = (polygonid - (polygonid % 2));\n</code></pre>\n\n<p>This makes polid the next smallest even number? <code>%</code> is rather costly, you could either do a <code>polygonid &amp; 1</code> instead of <code>polygonid % 2</code> or <code>new polid = polygonid &amp; (max_value - 1)</code> which will set all bits, but the last one to zero. max_value - 1 should be precalculated.</p>\n\n<hr>\n\n<pre><code>new mid = Polygon_Size/2;\n</code></pre>\n\n<p>Change to: <code>new mid = Polygon_Size &gt;&gt; 1</code> This will be done most probably by the compiler anyway, but we do not know, so lets try it.</p>\n\n<hr>\n\n<pre><code>polid /= 2;\n</code></pre>\n\n<p>This is calculated in both branches. It could help to do it before the branching:</p>\n\n<pre><code>new polid_half = polid &gt;&gt; 1;\n...\n</code></pre>\n\n<hr>\n\n<pre><code>return (mid - (++polid));\n</code></pre>\n\n<p>This depends on the language details. It could be that <code>++polid</code> as preincrement operator will load polid, update it by one, and store polid back. We do not plan to use the modified polid, so we could try <code>return (mid - polid + 1)</code> assuming that <code>++polid</code> is not some magic fast special instruction compared to the normal <code>+</code>.</p>\n\n<hr>\n\n<pre><code> if(polid == 0)\n {\n return 0;\n }\n</code></pre>\n\n<p>This does only happen if polygonid is 0 or 1. If this happens a lot, you should return immediately at the beginning, saving all the rest:</p>\n\n<pre><code>if (polygonid &lt; 2 ) //assuming polygonid &gt; 0\n return 0;\n</code></pre>\n\n<p>And remove the check inside the else branch.</p>\n\n<hr>\n\n<pre><code> return --polid;\n</code></pre>\n\n<p>Same as before, it could be better to <code>return polid - 1</code></p>\n\n<hr>\n\n<p>Depending on the branch prediction handling, it could be better to have only one return point, not one in every branch. You could introduce a return value and set it according to the current logic.</p>\n\n<hr>\n\n<p>I would try one change after the next and profile every step. All together, it could be:</p>\n\n<pre><code>stock GetNodeIndexFromPolygonIndex(polygonid,Polygon_Size)\n{\n if (polygonid &lt; 2 ) //assuming polygonid &gt; 0\n return 0;\n new result = 0;\n new polid = polygonid &amp; (max_value - 1); //polid is a bad name\n new polid_half = polid &gt;&gt; 1;\n new mid = Polygon_Size &gt;&gt; 1;\n if(polid &gt; mid)\n result = mid - polid_half + 1;\n else\n result = polid_half - 1;\n return result;\n}\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-02-08T08:28:29.747", "Id": "34446", "Score": "0", "body": "Another caveat: those micro-optimizations make the code way less readable, but since it's probably the only thing to do, here's an upvote for you. :)" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-02-08T13:55:46.377", "Id": "34463", "Score": "0", "body": "@Cygal Well, the `>> 1` are probably too much and some `if-else` braces would also increase readability." } ], "meta_data": { "CommentCount": "2", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-02-08T04:07:23.873", "Id": "21449", "ParentId": "21424", "Score": "1" } } ]
{ "AcceptedAnswerId": "21449", "CommentCount": "2", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-02-07T13:03:24.067", "Id": "21424", "Score": "1", "Tags": [ "optimization", "computational-geometry", "pawn" ], "Title": "Optimizing mathematical index calculation function" }
21424
<p>My overall challenge and why this code was written was to compare two strings. One string being a description of a item in inventory and one string being a description of a item, but possibly truncated/missing some characters. I am trying to match up the items I have posted on Craigslist and the items I think I have posted. </p> <p>So I go to Craigslist and copy the table showing each active item, parse the text, and come up with the item descriptions from craigslist. When they are initially put on craigslist they could have been truncated or possibly I might have missed a few chars when pasting. So I cannot try to find an exact match for each item. </p> <p>After search for some time I found the Levenshtein edit distance algorithm, which helps. It can reduce the search space by a good amount but it still gives me many false positives (low edit distance, but not the same item string) before I come to the true answer. </p> <p>It also does not do well when trying to match strings that have been severely truncated (their description is 1.75x bigger than allowed text in craigslist description) because their edit distance is huge. </p> <p><strong>About the code</strong></p> <p>After the text is parsed I have a linked list of strings which are from craigslist, I then create a dummy item for each and have a list of possible items to set to active. So for each possible <code>clItem</code> I go through every item in the inventory until I find a match, then break. (I have multiple of the same inventory items, I only want to set one to true if one of them is posted).</p> <p>For each comparison between a <code>clItem</code> and a Item in my inventory I call <code>sameItemDesc()</code> which uses the Levenshtein distance to determine if two strings are the same. </p> <p>In this function is where my issues lies, if I allow Levenshtein distance to be looked at that are too large I will have to answer the <code>JOptionPane</code> numerous times for items that have numerous low Levenshtein distance. If it is too low I will not set enough and have to go through manually to set the rest (painstaking). </p> <p>Are there any good ideas as to how to improve the code, or trim my search space so I might come to a faster solution?</p> <pre><code> public boolean updateItems2(LinkedList&lt;String&gt; arg) { // Create a list of items with the CL descriptions LinkedList&lt;Item&gt; clItems = new LinkedList&lt;Item&gt;(); for(String a : arg) { Item newCL = new Item(); newCL.setDesc(a); clItems.add(newCL); } System.out.println("Update Items got " + clItems.size() + " items"); // Try to set one item in the inventory to active for each clItem int setNum = 1; for(Item cl : clItems) for(Item cur : theApp.TheMasterList.Inventory) if(cur.getActv() != "YES" &amp;&amp; sameItemDesc(cl.getDesc(), cur.getDesc())) { System.out.println("Set#:" + setNum + "\nInvItem:" + cur.getDesc() + "\nCLItem:" + cl.getDesc()); cl.setActv("YES"); cur.setActv("YES"); setNum++; break; } // Print out the items that were not set int notSet = 0; for(Item cl : clItems) if(cl.getActv() != "YES") {System.out.println("Not Set:" + cl.getDesc());notSet++;} // See how many we set int actv = 0; for(Item a : theApp.TheMasterList.Inventory) if(a.getActv() == "YES") actv++; System.out.println("UpdateItems set:" + actv + " notset:" + notSet); showUserDif(clItems); return true; } public boolean sameItemDesc(String cl, String mark) { // We did this to each read in CLItem so do it to each real item desc too mark = mark.replace(" -", "").trim(); String msg = "Are these the same\n" + cl + "\n" + mark; int levD = LD(cl, mark); if(levD == 0) return true; else if(levD &lt; 7) { int reply = JOptionPane.showConfirmDialog(null, msg, null, JOptionPane.YES_NO_OPTION); if (reply == JOptionPane.YES_OPTION) return true; else return false; } else if(levD &lt; 15) { if(mark.contains(cl.substring(0, 6))) { int reply = JOptionPane.showConfirmDialog(null, msg, null, JOptionPane.YES_NO_OPTION); if (reply == JOptionPane.YES_OPTION) return true; else return false; } else return false; } else return false; } </code></pre>
[]
[ { "body": "<p>It sounds from your problem description that the strings can only differ if one is a substring of the other. Maybe even the one will only be truncated at the end? When I look at your code I see that CraigsList may add hyphens and spaces. I think this is a much simpler problem than the more general case of lexical similarity. Would something like the following work for you?</p>\n\n<pre><code>public boolean isSimilar(String orig, String test) {\n // Remove every character that's not relevant to your comparison.\n // (assumes you are writing in ASCII English)\n // The regular expression should be read as: \"replace each character that\n // is not a capital or lower-case letter or number with... nothing\"\n // Since this will remove all whitespace, you don't need to trim.\n orig = orig.replaceAll(\"[^A-Za-z0-9]\", \"\");\n test = test.replaceAll(\"[^A-Za-z0-9]\", \"\");\n\n return (test.length &lt; orig.length) &amp;&amp;\n orig.substring(0, test.length).equalsIgnoreCase(test);\n}\n</code></pre>\n\n<p>I didn't compile this, so it might be Java-ish pseudo-code, but I hope that gives you an idea.</p>\n\n<p>Also using == or != with Strings in Java is very dangerous. It will not work if your code is ever serialized, or used on separate machines. I would make one or more of the following changes:</p>\n\n<pre><code>// Original\nif(cur.getActv() != \"YES\" &amp;&amp; sameItemDesc(cl.getDesc(), cur.getDesc()))\n\n// Better - parenthesis and indentation makes clear two separate comparisons\n// Also, makes clear that the != \"YES\" gets evaluated before the &amp;&amp;\nif( (cur.getActv() != \"YES\") &amp;&amp;\n sameItemDesc(cl.getDesc(), cur.getDesc()) )\n\n// Better: compares the *contents* of the string \"YES\" with\n// the contents of whatever string getActv() returns. You were comparing\n// the *address* of \"YES\" with the *address* of whatever string cur.getActv()\n// returns.\nif( !\"YES\".equals(cur.getActv()) &amp;&amp;\n sameItemDesc(cl.getDesc(), cur.getDesc()) )\n\n// Better still to make getActv return a boolean! Now you don't\n// have to worry about what kind of comparison you use, or even\n// typos!\nif( !cur.getActv() &amp;&amp;\n sameItemDesc(cl.getDesc(), cur.getDesc()) )\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-02-07T14:39:24.687", "Id": "34400", "Score": "0", "body": "I like to watch the world burn when I code, so I use things like != and use YES and NO instead of booleans. --- Why am I paying for college.....Why did I use YES/NO....Excuse me I'll be slapping my wrists all day for that." } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-02-07T14:14:56.660", "Id": "21427", "ParentId": "21425", "Score": "3" } }, { "body": "<h2>Style</h2>\n\n<p>Please use braces everywhere, removing them hurts readability and makes it easier to produces bugs.</p>\n\n<pre><code> if (reply == JOptionPane.YES_OPTION) \n return true;\n else \n return false;\n</code></pre>\n\n<p>This can be written as <code>return reply == JOptionPane.YES_OPTION</code>.</p>\n\n<h2>A simple Levenshtein distance trick</h2>\n\n<p>Instead of using absolute distances for the Levenshtein distance, you can define a ratio. That is, if string1 is within 30% of edit distance of string2, then it can considered egal. I've used this trick in the past and accuracy increased a bit.</p>\n\n<h2>BumSkeeter-aware distance</h2>\n\n<p>You're saying that the errors come from paste errors where a few chars are missing at the end. If this is the only possible error, then you don't need the full power of the Levenshtein Distance, and might want to use a distance which only counts the number of added characters, and use Levenshtein distance * 10 otherwise.</p>\n\n<h2>Searching intelligently</h2>\n\n<p>(This is the most important point.)</p>\n\n<p>The best way to get good results is to stop pairing two strings when the distance is short enough, but to always assign the best string. That is, you still do your outer loop <code>for(Item cl : clItems)</code>, but for the second loop, store the score for every possibility, and assign only the best score. The time complexity is the same, it could possibly be a bit longer, but unless you have thousands or millions of items it's going to produce much better results.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-02-07T14:34:53.640", "Id": "34399", "Score": "0", "body": "I had been creating a list of the lowest edit distances and then choosing from that, I abandoned it last night after I got to frustrated trying to get it to work properly. I think I might try again, I guess it is the only good way to do this." } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-02-07T14:24:10.440", "Id": "21428", "ParentId": "21425", "Score": "3" } }, { "body": "<p>The overall question could be better for stackoverflow. This is more about reviewing code, where one would expect to see the code. There is no source for the Levenshtein distance.</p>\n\n<p>But well, let me separate my answer in two parts.</p>\n\n<h2>First, the overall question</h2>\n\n<blockquote>\n <p>Are there any good ideas as to how to improve the code, or trim my search space so I might come to a faster solution?</p>\n</blockquote>\n\n<p>According to the given preconditions:</p>\n\n<blockquote>\n <p>One string being a description of a item in inventory and one string being a description of a item, but possibly truncated/missing some characters</p>\n</blockquote>\n\n<p>One string is correct, the other one has flaws in a way, that characters are missing.<br>\nIf we rephrase this, we have a string <code>correct</code> and a string <code>flawed</code> with this properties:<br>\nFor all characters <code>char</code> in <code>flawed</code></p>\n\n<ul>\n<li><code>char</code> is included in <code>correct</code> and <code>count(char)</code> in <code>flawed</code> is smaller or equal to <code>count(char)</code> in <code>correct</code> (\"contained\").</li>\n<li><code>index(char)</code> in <code>flawed</code> is smaller or equal to <code>index(char)</code> in <code>correct</code> (\"ordered\").</li>\n</ul>\n\n<p>We use this properties to base our algorithm. </p>\n\n<p>Trivial version:<br>\nFor every flawed string, take every char, look if it is inside any correct string, if yes, remove char from correct string and continue with next char. If we found a correct string, which includes all chars from flawed string, we have a good candidate.<br>\nAn implementation could be:</p>\n\n<pre><code>public static boolean isCharArrayIncludedInString(final char[] arrayChar, final String string) {\n final char[] targetArray = string.toCharArray();\n for (final char arrayCharItem : arrayChar) {\n boolean isFound = false;\n for (int i = 0; i &lt; targetArray.length; ++i) { //if we have large targetArrays, we could improve this by a linkedlist and removing the entries\n if (arrayCharItem == targetArray[i]) {\n targetArray[i] = 0;\n isFound = true;\n break;\n }\n }\n if (!isFound)\n return false;\n }\n return true;\n}\n\n//if we use the ordered property, too:\n\npublic static boolean isCharArrayIncludedInString(final char[] arrayChar, final String string) {\n final char[] targetArray = string.toCharArray();\n int innerIndex = 0;\n for (final char arrayCharItem : arrayChar) {\n boolean isFound = false;\n while (innerIndex &lt; targetArray.length) {\n if (arrayCharItem == targetArray[innerIndex++]) { // here we use the \"ordered\" property\n isFound = true;\n break;\n }\n }\n if (!isFound)\n return false;\n }\n return true;\n}\n// hint: i choosed isCharArrayIncludedInString instad of isStringIncludedInString, because the second typically assumes contiguous appearance\n</code></pre>\n\n<p>We can improve this, if you know that at least x of the first characters must be the same. Then do a startsWith for the substring.<br>\nThe algorithm has a worst time complexity of (n<em>m</em>len(longest string))</p>\n\n<p>The not trivial solution: </p>\n\n<p>Create a modified trie data structure. If we did not found a character for a node, look for all subnodes. The complexity is hard to guess, but in the average case should be better than the trivial version.</p>\n\n<hr>\n\n<h2>Second part, Code quality</h2>\n\n<p>Some parts are already pointed out, I try to avoid them.</p>\n\n<pre><code>public boolean updateItems2(LinkedList&lt;String&gt; arg)\n</code></pre>\n\n<p>Bad name for method (what is the meaning of the 2? What is the difference between 1 and 2?), expected result from a update method with return boolean is the success state, which is not the case(?). Rename it perhaps to printAllMatchingDescriptions or something like that. getAllMatchingDescriptions if you want to return it later.</p>\n\n<pre><code>public boolean updateItems2(LinkedList&lt;String&gt; arg)\n</code></pre>\n\n<p>Bad name for argument. Clearly, this is an argument, and arg could be an abbreviation for this. listDescriptions could be a better name. And use <code>List</code> if there is no specific need for LinkedList:</p>\n\n<pre><code>public boolean printAllMatchingDescriptions(List&lt;String&gt; listDescriptions)\n</code></pre>\n\n<hr>\n\n<pre><code> // Create a list of items with the CL descriptions\nLinkedList&lt;Item&gt; clItems = new LinkedList&lt;Item&gt;();\n</code></pre>\n\n<p>Yes, the comment describes the next line. But it has no additional value as already written by the source code. You should avoid such comments.</p>\n\n<hr>\n\n<pre><code>LinkedList&lt;Item&gt; clItems = new LinkedList&lt;Item&gt;();\n</code></pre>\n\n<p>Again, i would avoid abbreviations and would name it listItems.</p>\n\n<pre><code>for(String a : arg)\n{\n Item newCL = new Item();\n newCL.setDesc(a);\n clItems.add(newCL);\n}\n</code></pre>\n\n<p>It looks like the description is a good candidate for the constructor.<br>\nAnd again, try to avoid abbreviations.<br>\nIt could be:</p>\n\n<pre><code> for (final String listDescriptionsItem : listDescriptions)\n listItems.add(new Item(listDescriptionsItem));\n</code></pre>\n\n<hr>\n\n<pre><code>System.out.println(\"Update Items got \" + clItems.size() + \" items\");\n</code></pre>\n\n<p>A logger could be nice. But ok, for quick &amp; dirty debugging in small programs, println could be fine.</p>\n\n<hr>\n\n<pre><code>// Try to set one item in the inventory to active for each clItem\nint setNum = 1;\nfor(Item cl : clItems)\n for(Item cur : theApp.TheMasterList.Inventory)\n if(cur.getActv() != \"YES\" &amp;&amp; sameItemDesc(cl.getDesc(), cur.getDesc()))\n {\n System.out.println(\"Set#:\" + setNum + \"\\nInvItem:\" + cur.getDesc() + \"\\nCLItem:\" + cl.getDesc());\n cl.setActv(\"YES\");\n cur.setActv(\"YES\");\n setNum++;\n break;\n }\n</code></pre>\n\n<p><code>int setNum = 1;</code>why does it start with 1? From the code, it looks like you are counting the number of activated items. At least, this is what is happening. From the println it looks like this should be a index. If the second is the case, you should modify the code.<br>\nUse brackets for statements with more than one line. This is confusing.<br>\nAgain, abbreviations.<br>\n<code>theApp.TheMasterList.Inventory</code> this does not look good. But I can not make any suggestions, because code is unknown. Try to avoid static access for dynamic parts.<br>\nThe string \"YES\"/\"NO\" thing was already mentioned. Names for better method names could be <code>isActivated()</code> and <code>activate()</code>.<br>\nYou could call the <code>sameItemDesc</code> with two items, rather than the description.<br>\n<code>cur.setActv(\"YES\");</code> this does not make sense. You are only inside the statement, if this is already true. \nIt could be:</p>\n\n<pre><code> for (final Item listItemsItem : listItems) {\n for (final Item inventoryItem : Inventory) {\n if (inventoryItem.isActivated())\n continue;\n if (!isFirstItemSameAsSecondItem(listItemsItem, inventoryItem))\n continue;\n System.out.println(\"Set#:\" + numberOfActivatedItems + \"\\nInvItem:\" + inventoryItem.getDescription() + \"\\nCLItem:\"\n + listItemsItem.getDescription());\n listItemsItem.activate();\n numberOfActivatedItems++;\n break;\n }\n }\n</code></pre>\n\n<hr>\n\n<pre><code>// Print out the items that were not set\nint notSet = 0;\nfor(Item cl : clItems)\n if(cl.getActv() != \"YES\")\n {System.out.println(\"Not Set:\" + cl.getDesc());notSet++;}\n</code></pre>\n\n<p>You know it already, abbreviations. And unexpected brackets. And this method is perhaps not necessary.\nBecause the number of deactivated items is size of the list (all items) minus activated:</p>\n\n<pre><code>final int numberOfDeactivatedItems = listItems.size() - numberOfActivatedItems;\n</code></pre>\n\n<hr>\n\n<pre><code>// See how many we set\nint actv = 0;\nfor(Item a : theApp.TheMasterList.Inventory)\n if(a.getActv() == \"YES\")\n actv++;\nSystem.out.println(\"UpdateItems set:\" + actv + \" notset:\" + notSet);\n</code></pre>\n\n<p>Why do you calculate this a second time?</p>\n\n<hr>\n\n<p>The <code>sameItemDesc</code> could be changed too, but I will spare this part because I do not know if it is necessary.</p>\n\n<hr>\n\n<p>Overall, we could have something like this:</p>\n\n<pre><code>public void printAllMatchingDescriptions(final List&lt;String&gt; listDescriptions) {\n final List&lt;Item&gt; listItems = new LinkedList&lt;Item&gt;();\n for (final String listDescriptionsItem : listDescriptions)\n listItems.add(new Item(listDescriptionsItem));\n System.out.println(\"Update Items got \" + listItems.size() + \" items\");\n\n // Plan: Check if any of the listDescriptions is contained in any state in the overall list\n int numberOfActivatedItems = 0;\n for (final Item listItemsItem : listItems) {\n for (final Item inventoryItem : Inventory) {\n if (inventoryItem.isActivated()) // if you have a lot of activated ones, it could be better to create a new list with only deactivated entries\n continue;\n if (!isFirstItemSameAsSecondItem(listItemsItem, inventoryItem))\n continue;\n System.out.println(\"Set#:\" + numberOfActivatedItems + \"\\nInvItem:\" + inventoryItem.getDescription() + \"\\nCLItem:\"\n + listItemsItem.getDescription());\n listItemsItem.activate();\n numberOfActivatedItems++;\n break;\n }\n }\n\n final int numberOfDeactivatedItems = listItems.size() - numberOfActivatedItems;\n\n System.out.println(\"Items activated:\" + numberOfActivatedItems + \", deactivated:\" + numberOfDeactivatedItems);\n\n showUserDif(listItems); // I do not know what is happening here. At least abbreviations again\n}\n\npublic static boolean isFirstItemSameAsSecondItem(final Item item, final Item other) {\n return isCharArrayIncludedInString(item.getDescription().toCharArray(), other.getDescription());\n}\n\npublic static boolean isCharArrayIncludedInString(final char[] arrayChar, final String string) {\n final char[] targetArray = string.toCharArray();\n int innerIndex = 0;\n for (final char arrayCharItem : arrayChar) {\n boolean isFound = false;\n while (innerIndex &lt; targetArray.length) {\n if (arrayCharItem == targetArray[innerIndex++]) { // here we use the \"ordered\" property\n isFound = true;\n break;\n }\n }\n if (!isFound)\n return false;\n }\n return true;\n}\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-02-07T19:19:40.307", "Id": "34425", "Score": "0", "body": "I apologize for the poor coding practices (naming, logical errors, bad syntax). When I initially started on this I never thought I might use it more than once. I then got caught trying to write the code as I was using it, thus the piss poor coding. --- Thank you for the extended response, This seems that it will work much better than my current implementation. I will try it later today when i get back home. Thanks tb-!!!!" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-02-07T19:27:49.660", "Id": "34426", "Score": "0", "body": "Do not use harsh words, at least you got some other thoughts, which is always fine. If you experiment with the algorithm, you should create some unit tests. I did some trivial cases for me, too. But you have some real data which makes an advantage." } ], "meta_data": { "CommentCount": "2", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2013-02-07T18:58:18.707", "Id": "21439", "ParentId": "21425", "Score": "5" } } ]
{ "AcceptedAnswerId": "21439", "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2013-02-07T13:39:23.613", "Id": "21425", "Score": "3", "Tags": [ "java", "performance", "edit-distance" ], "Title": "Using Levenshtein distance to compare strings" }
21425
<p>I'm new to Lisp and I'm yet to wrap my head around the lisp way of writing programs. Any comments regarding approach, style, missed opportunities appreciated:</p> <p><em>In particular</em>, please advice if I build results list correctly (<code>(setf merged-list (append merged-list (list a)))</code>).</p> <pre><code>;;;; Count inversions (defun small-list (list) (or (null list) (null (rest list)))) (defun split-in-half (list) (let ((mid (ceiling (length list) 2))) (values (subseq list 0 mid) (subseq list mid)))) (defun count-inversions (list) (if (small-list list) (list list 0) (multiple-value-bind (lower upper) (split-in-half list) (merge-inversions (count-inversions lower) (count-inversions upper))))) (defun merge-inversions (lower-pair upper-pair) (let ((lower (first lower-pair)) (upper (first upper-pair)) (merged-list '()) (num-inversions 0)) (loop while (not (and (null lower) (null upper))) do (cond ((null lower) (let ((a (first upper))) (setf merged-list (append merged-list (list a))) (setf upper (rest upper)))) ((null upper) (let ((a (first lower))) (setf merged-list (append merged-list (list a))) (setf lower (rest lower)))) ((&lt; (first lower) (first upper)) (let ((a (first lower))) (setf merged-list (append merged-list (list a))) (setf lower (rest lower))) ) (t (let ((a (first upper))) (setf merged-list (append merged-list (list a))) (setf upper (rest upper)) (incf num-inversions (length lower)))))) (list merged-list (+ (second lower-pair) (second upper-pair) num-inversions))) </code></pre>
[ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-02-07T16:26:39.737", "Id": "34416", "Score": "0", "body": "@RTOSkit, As I said, I need advice on how to make my lisp better. The program does what it needs to do, however there is certainly ways to make it more concise, efficient, elegant. I would like to learn them." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-02-08T21:06:01.180", "Id": "34506", "Score": "1", "body": "No docstrings!!" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-03-03T18:22:44.940", "Id": "36057", "Score": "1", "body": "An explanation of what this code is doing would be appreciated. Also, I see you don't declare any types." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-03-03T21:14:15.823", "Id": "36070", "Score": "0", "body": "@FaheemMitha, the code is aimed at counting inversions on a list, that is each situation when an element lower in the list is greater than an element higher in the list. Regarding types, could you please elaborate, as I mentioned I'm new to Lisp, and might easily be missing something obvious." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-03-04T10:08:26.717", "Id": "36089", "Score": "0", "body": "@zzandy: I think adding type declarations is used when you want to improve performance and/or when you want to add some typing to improve error checking of your code. (Specifically, for many operations, simple vectors are faster than linked lists.) However, performance considerations may not apply in your case. Most lisp books have sections on this topic. It is in the Common Lisp standard. Could you add a usage example for your code that the reader could run?" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-03-04T14:42:45.087", "Id": "36122", "Score": "0", "body": "@FaheemMitha: The code is used simply as `(count-inversions list-of-like-100000-integers)`. I've read about type declarations, though I think it's a bit too advanced for me. Any advice appreciated though." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-03-04T17:34:57.233", "Id": "36162", "Score": "0", "body": "@zzandy: No, type declarations are nothing special. You can read about them in [Practical Common Lisp: Subsection Make It Work, Make It Right, Make It Fast](http://www.gigamonkeys.com/book/conclusion-whats-next.html). This is not detailed enough to use as a reference, but I think he explains the basic ideas well enough. There is of course much other information about this available on the net and in other books." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-03-04T17:53:03.380", "Id": "36163", "Score": "0", "body": "@FaheemMitha: thanks, I'll definitely read that. I'm currently oscillating between \"Make It Work\" and \"Make It Right\"" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2016-11-01T22:16:31.003", "Id": "273935", "Score": "0", "body": "I have rolled back Rev 7 → 2. Please see *[What to do when someone answers](http://codereview.stackexchange.com/help/someone-answers)*." } ]
[ { "body": "<ol>\n<li><p>Use <a href=\"http://www.lispworks.com/documentation/HyperSpec/Body/f_nconc.htm\" rel=\"nofollow\"><code>nconc</code></a> instead of <code>append</code> for speed in</p>\n\n<p>(setf merged-list (append merged-list (list a)))</p>\n\n<p>Note that you need <code>setf</code> with <code>nconc</code> only if <code>merged-list</code> is nil.</p></li>\n<li><p>Use <a href=\"http://www.lispworks.com/documentation/HyperSpec/Body/m_pop.htm\" rel=\"nofollow\"><code>pop</code></a>: instead of</p>\n\n<p>(let ((a (first lower)))\n (setf merged-list (append merged-list (list a)))\n (setf lower (rest lower))))</p>\n\n<p>you can write</p>\n\n<p>(setf merged-list (nconc merged-list (list (pop lower))))</p></li>\n<li><p>The combination of <code>let</code> and <code>loop</code> creates extra indentation for no good reason. You can use <code>with</code> clause in <code>loop</code> to create bindings instead, or use the <a href=\"http://www.lispworks.com/documentation/HyperSpec/Body/m_do_do.htm\" rel=\"nofollow\"><code>do</code></a> macro.</p></li>\n<li><p>Usually <em>predicates</em> are named with a <em>-p</em> suffix, so I suggest that you rename your <code>small-list</code> to <code>small-list-p</code>.</p></li>\n<li><p>Please fix line breaks and indentation in the third <code>cond</code> clause.</p></li>\n</ol>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-02-08T09:09:13.083", "Id": "34447", "Score": "0", "body": "Thanks, that's a reply I was hoping for. I've changed indentation in third clause, I that what you meant?" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-02-08T13:51:40.040", "Id": "34461", "Score": "0", "body": "@zzandy: looks good now (I added another small thing, see #3)" } ], "meta_data": { "CommentCount": "2", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-02-07T18:42:52.030", "Id": "21438", "ParentId": "21431", "Score": "4" } }, { "body": "<ul>\n<li>using <em>multiple values</em> instead of lists for return values</li>\n<li>merge-inversions has four parameters</li>\n<li>using multiple-value-call</li>\n<li>using LOOP functionality to <em>collect</em> items and to <em>sum</em> values</li>\n<li>much less traversal of lists</li>\n</ul>\n\n<p>Try this:</p>\n\n<pre><code>(defun small-list-p (list)\n (not (and list (rest list))))\n\n(defun split-in-half (list)\n (values (loop repeat (ceiling (length list) 2) collect (pop list))\n list))\n\n(defun merge-inversions (lower lower-n upper upper-n &amp;aux (num-inversions 0))\n (values (loop while (or lower upper)\n collect (cond ((null lower) (pop upper))\n ((null upper) (pop lower))\n ((&lt; (first lower) (first upper)) (pop lower))\n (t (incf num-inversions (length lower)) (pop upper))))\n (+ lower-n upper-n num-inversions)))\n\n(defun count-inversions (list)\n (if (small-list-p list)\n (values list 0)\n (multiple-value-bind (lower upper)\n (split-in-half list)\n (multiple-value-call #'merge-inversions\n (count-inversions lower)\n (count-inversions upper)))))\n</code></pre>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2016-11-01T21:37:45.797", "Id": "145879", "ParentId": "21431", "Score": "0" } }, { "body": "<p>Revised version using @sds's suggestions:</p>\n\n<pre><code>(defun small-list-p (list)\n (or (null list) (null (rest list))))\n\n(defun split-in-half (list)\n (let ((mid (ceiling (length list) 2)))\n (values (subseq list 0 mid)\n (subseq list mid))))\n\n(defun count-inversions (list)\n (if (small-list-p list) (list list 0)\n (multiple-value-bind (lower upper) (split-in-half list)\n (merge-inversions\n (count-inversions lower)\n (count-inversions upper)))))\n\n(defmacro move-last (source target)\n `(setf ,target (nconc ,target (list (pop ,source)))))\n</code></pre>\n\n<p>Function <code>MERGE-INVERSIONS</code>:</p>\n\n<pre><code>(defun merge-inversions (lower-pair upper-pair )\n (loop \n with lower = (first lower-pair)\n with upper = (first upper-pair)\n with merged-list = '()\n with num-inversions = 0\n while (not (and (null lower) (null upper)))\n do (cond\n ((null lower) (move-last upper merged-list))\n ((null upper) (move-last lower merged-list))\n ((&lt; (first lower) (first upper)) (move-last lower merged-list))\n (t\n (move-last upper merged-list)\n (incf num-inversions (length lower)) ))\n finally (return (list merged-list\n (+ (second lower-pair)\n (second upper-pair)\n num-inversions)))))\n</code></pre>\n\n<p>Performance went from this</p>\n\n<pre><code>139.740 seconds of real time\n80,080,445,136 bytes consed\n</code></pre>\n\n<p>to this:</p>\n\n<pre><code>26.411 seconds of real time\n87,009,536 bytes consed\n</code></pre>\n\n<hr>\n\n<p><sub>This \"answer\" was extracted from Rev 7 of the question.</sub></p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2016-11-01T22:49:48.283", "Id": "145888", "ParentId": "21431", "Score": "0" } } ]
{ "AcceptedAnswerId": "21438", "CommentCount": "9", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-02-07T15:16:37.903", "Id": "21431", "Score": "4", "Tags": [ "beginner", "mergesort", "lisp", "common-lisp" ], "Title": "Mergesort with an inversion counter" }
21431
<p>I have a simple form validation script. Could you tell me how I can improve this script (mainly regarding security)?</p> <p><strong>HTML page</strong></p> <pre><code>&lt;form name="input_form" action="process_form.php" method="post"&gt; &lt;p&gt; &lt;label for="name"&gt;Name&lt;/label&gt; &lt;input type="text" name="name" id="name" maxlength="25" /&gt; &lt;/p&gt; &lt;p&gt; &lt;label for="password"&gt;Password&lt;/label&gt; &lt;input type="password" name="password" id="password" maxlength="25" /&gt; &lt;/p&gt; &lt;p&gt; &lt;label for="email"&gt;Email&lt;/label&gt; &lt;input type="text" name="email" id="email" maxlength="100" /&gt; &lt;/p&gt; &lt;p&gt; &lt;label for="website"&gt;Website&lt;/label&gt; &lt;input type="text" name="website" id="website" maxlength="100" /&gt; &lt;/p&gt; &lt;p&gt; &lt;label for="feedback"&gt;Feedback&lt;/label&gt; &lt;textarea name="feedback"&gt;&lt;/textarea&gt; &lt;/p&gt; &lt;p&gt; &lt;label for="sex"&gt;Sex&lt;/label&gt; &lt;input type="radio" name="sex" value="male" /&gt;Male &lt;input type="radio" name="sex" value="female" /&gt;Female &lt;/p&gt; &lt;p&gt; &lt;label for="hobbies"&gt;Hobbies&lt;/label&gt; &lt;input type="checkbox" name="hobbies[]" value="reading" /&gt;Reading &lt;input type="checkbox" name="hobbies[]" value="basketball" /&gt;Basketball &lt;input type="checkbox" name="hobbies[]" value="football" /&gt;Football &lt;/p&gt; &lt;p&gt; &lt;label for="country"&gt;Country&lt;/label&gt; &lt;select name="country"&gt; &lt;option value="0"&gt;Select&lt;/option&gt; &lt;option value="india"&gt;India&lt;/option&gt; &lt;option value="england"&gt;England&lt;/option&gt; &lt;option value="usa"&gt;USA&lt;/option&gt; &lt;/select&gt; &lt;/p&gt; &lt;p&gt; &lt;label for="education"&gt;Education&lt;/label&gt; &lt;select multiple="multiple" name="education[]"&gt; &lt;option value="high_school"&gt;High School&lt;/option&gt; &lt;option value="degree"&gt;Degree&lt;/option&gt; &lt;option value="phd"&gt;Phd&lt;/option&gt; &lt;/select&gt; &lt;/p&gt; &lt;p&gt; &lt;input type="submit" name="submit" id="submit" value="Submit" /&gt; &lt;input type="reset" name="reset" id="reset" value="Reset" /&gt; &lt;/p&gt; &lt;/form&gt; </code></pre> <p><strong>process_form.php</strong></p> <pre><code>&lt;?php if(isset($_POST['submit'])) { // white list $expected_elements = array('name','password','email','website','feedback','country'); // create dynamic variables with same name as the form elements foreach ($expected_elements as $key) { ${$key} = $_POST[$key]; } $error = ""; /* * This array will store the names of those form elements whose value shouldn't be empty */ $check_empty_vars = array('name','password','email','website'); /* * This array will store the names the form elements and the corresponding max length allowed */ $max_allowed_length = array( "name" =&gt; 25, "password" =&gt; 25, "email" =&gt; 100 ); foreach($check_empty_vars as $var_name) { if(${$var_name} == "") { $error .= ucfirst($var_name) . " cannot be empty &lt;br /&gt;"; } } foreach ($max_allowed_length as $key =&gt; $value) { if(strlen(${$key}) &gt; $value) { $error .= ucfirst($key) . " cannot be greater than $value characters &lt;br /&gt;"; } } // letters and spaces only if( ! preg_match('/^[A-Za-z\s ]+$/', $name)) { $error .= "Name should contain only letters and spaces &lt;br /&gt;"; } if($email != "") { if( ! filter_var($email, FILTER_VALIDATE_EMAIL)) { $error .= "Enter a valid email &lt;br /&gt;"; } } if($website != "") { if( ! filter_var($website, FILTER_VALIDATE_URL)) { $error .= "Enter a valid website address &lt;br /&gt;"; } } if( ! isset($_POST['sex'])) { $error .= "Select Sex &lt;br /&gt;"; } else { switch($_POST['sex']) { case 'male': case 'female': $sex = $_POST['sex']; break; } } if( ! isset($_POST['hobbies'])) { $error .= "Select Hobbies &lt;br /&gt;"; } else { switch($_POST['hobbies']) { case 'reading': case 'basketball': case 'football': $hobbies = $_POST['hobbies']; break; } } if($country == "0") { $error .= "Select country &lt;br /&gt;"; } if( ! isset($_POST['education'])) { $error .= "Select education &lt;br /&gt;"; } else { switch($_POST['education']) { case 'high_school': case 'degree': case 'phd': $education = $_POST['education']; break; } } echo $error. "&lt;br /&gt;"; } ?&gt; </code></pre>
[]
[ { "body": "<pre><code>${$key}\n</code></pre>\n\n<p>This makes me somewhat nervous, but I guess it's acceptable in this context since it's whitelisted.</p>\n\n<hr>\n\n<pre><code>foreach($check_empty_vars as $var_name)\n{\n if(${$var_name} == \"\") \n {\n $error .= ucfirst($var_name) . \" cannot be empty &lt;br /&gt;\";\n }\n}\n</code></pre>\n\n<p>I'd recommend moving this right after the <code>$check_empty_vars</code> to reduce the variable live time. This would have the pleasant side-effect of also moving the <code>$max_allowed_length</code> declaration close to its <code>foreach</code> loop.</p>\n\n<hr>\n\n<pre><code>foreach ($expected_elements as $key) \n{\n ${$key} = $_POST[$key];\n}\n</code></pre>\n\n<p>What happens if the user submits a form without a value of <code>$key</code>? Depending on your warning level, you may get a <code>Notice: Undefined index</code>. You may want to add <code>isset</code> or <code>array_key_exists</code> to that loop.</p>\n\n<hr>\n\n<p>In <code>[A-Za-z\\s ]</code>, <code>\\s</code> already includes whitespace. Also, your name filtering choices are incomplete. What if my name includes other characters?</p>\n\n<p>Some people may report their names as having a <code>'</code>, or <code>á</code>, <code>í</code>, etc.</p>\n\n<hr>\n\n<p>You have your validating logic and your display logic in a single script. This might be problematic in terms of maintenance. See <a href=\"http://en.wikipedia.org/wiki/Separation_of_concerns\" rel=\"nofollow\">separation of concerns</a>.</p>\n\n<p>A comment in the official PHP documentation page for <a href=\"http://php.net/manual/en/function.filter-var.php\" rel=\"nofollow\">filter_var</a> claim that <code>http://example.com/\"&gt;&lt;script&gt;alert(document.cookie)&lt;/script&gt;</code> is accepted as a valid URL. Beware.</p>\n\n<hr>\n\n<pre><code>switch($_POST['sex'])\n{\n case 'male':\n case 'female':\n $sex = $_POST['sex']; \n break;\n}\n</code></pre>\n\n<p>What if I send a POST request with a sex of <code>robot</code>? Add an appropriate error message.</p>\n\n<hr>\n\n<pre><code>switch($_POST['hobbies'])\n{\n case 'reading':\n case 'basketball':\n case 'football':\n $hobbies = $_POST['hobbies']; \n break;\n}\n</code></pre>\n\n<p>Isn't hobbies supposed to be an array? (Not a single variable)\nWhat I said about invalid input in <code>$_POST['sex']</code> also applies here.</p>\n\n<hr>\n\n<p>Education has the same array-related problem.</p>\n\n<hr>\n\n<p>You should validate country too. I send a bogus POST request saying I'm from \"The Moon\" and your code won't complain.</p>\n\n<hr>\n\n<p>Is there a particular reason to giving the <code>form</code> and <code>input reset</code> elements a name?</p>\n\n<hr>\n\n<p>I can't tell if it's safe without seeing the PHP code that is executed later in that same page. The usual PHP security recommendations apply, though:</p>\n\n<ul>\n<li>Use prepared statements for database queries (and preferably isolate it in its own layer) to prevent SQL injections</li>\n<li>Properly escape your fields before <code>echo</code>ing them to prevent XSS injections.</li>\n<li>If this is a registration form, you might want to add some protection against bots (such as displaying a CAPTCHA if too many requests are submitted).</li>\n<li>If this is a form that's displayed after the user has logged in, make sure you're protected against CSRF attacks.</li>\n</ul>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-02-07T21:40:33.043", "Id": "34434", "Score": "0", "body": "I dont have the minimum rep required to vote your answer up. So +1 and thanks a lot." } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-02-07T18:42:07.023", "Id": "21437", "ParentId": "21434", "Score": "1" } } ]
{ "AcceptedAnswerId": "21437", "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-02-07T17:17:00.597", "Id": "21434", "Score": "1", "Tags": [ "php", "validation", "form" ], "Title": "Form validation script" }
21434
<p>I have this piece of code to replace current text inside an array of html divs with values coming from a JSON file:</p> <pre><code> $.each($('.something'), function(){ if($(this).text()=="1"){ $(this).html(jsondata.CameraTypeLabel1); }else if($(this).text()=="2"){ $(this).html(jsondata.CameraTypeLabel2); } }); </code></pre> <p>I'd like to make it "dynamic": if I'd have 100 values, I don't want to copy/paste it 100 times. </p> <p>Maybe it would be better creating an array "CameraTypeLabel" in the JSON string ?</p> <p>EDIT: Fixed the selector, it was a typo.</p> <p>Thanks!</p>
[]
[ { "body": "<p>jQuery's <a href=\"http://api.jquery.com/html/\" rel=\"nofollow\"><code>.html()</code></a> method can take a callback function - it'll be called for every element in the collection - and will use the returned value to set the element's html.</p>\n\n<p>You can use bracket notation to access the key in your <code>jsondata</code>, so that you can dynamically get to the key you want with the string in the brackets:</p>\n\n<pre><code>$('.something').html(function () {\n return jsondata[ 'CameraTypeLabel' + $.text(this) ];\n});\n</code></pre>\n\n<p><strong>Note:</strong> <code>$.text(this)</code> is the same as <code>$(this).text()</code>, just a bit faster; it doesn't create a new jQuery object at every step in the loop.</p>\n\n<hr>\n\n<p>If all you want to do is update the text, you can pass a function to <a href=\"http://api.jquery.com/text/\" rel=\"nofollow\"><code>.text()</code></a> itself:</p>\n\n<pre><code>$('.something').text(function (i, oldText) {\n return jsondata[ 'CameraTypeLabel' + oldText ];\n});\n</code></pre>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-02-07T21:06:36.757", "Id": "21444", "ParentId": "21440", "Score": "3" } }, { "body": "<p>This answer assumes that the elements you want to replace are in the same order as the json content is. Ex.:</p>\n\n<pre><code>&lt;div class=\"something\"&gt;0&lt;/div&gt;\n &lt;div class=\"irrelevant shitty div that won't be selected\"&gt;&lt;/div&gt;\n&lt;div class=\"something\"&gt;1&lt;/div&gt;\n&lt;div class=\"something\"&gt;2&lt;/div&gt;\n</code></pre>\n\n<p>If so, no <code>.text()</code> check is needed and you can just use the index.</p>\n\n<pre><code> $('.something').each(function(i) {\n\n var arrayOfDivs = [\"something0\", \"something1\", \"something2\"], //array of html divs\n jsondata = \"whatevaaa is coming in from json\"; //value coming from json\n\n var index = arrayOfDivs.indexOf(\"something\" + [i]); //find element to be replaced\n\n if (index !== -1) { //check to see if element was found\n arrayOfDivs[index] = jsondata; // replace the current text of matched element, in arrayOfDivs, with what comes in from json\n //You can also replace the html in the div from here:\n //$(this).html(arrayOfDivs[index]);\n }\n });\n</code></pre>\n\n<p><strong><a href=\"http://jsfiddle.net/vyXPV/\" rel=\"nofollow\">http://jsfiddle.net/vyXPV/</a></strong></p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-02-08T17:11:45.107", "Id": "21482", "ParentId": "21440", "Score": "0" } } ]
{ "AcceptedAnswerId": "21444", "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-02-07T19:33:10.363", "Id": "21440", "Score": "3", "Tags": [ "javascript", "jquery" ], "Title": "Replacing text in an array" }
21440
<p>I'm just trying to learn how to write jQuery better so I wanted some smart peoples opinions.</p> <p>The code is checking the billing and shipping address fields to see if it contains a PO Box address by looking for variations of "PO" and then displays a warning message after the input if it does contain it.</p> <p>The code is duplicated for each one so there has to be a better way to write this.</p> <p><a href="http://jsfiddle.net/ferne97/6RnxG/" rel="nofollow">jsFiddle</a></p> <pre><code>(function ($) { 'use strict'; // Check for PO Box text in address fields on checkout var $shipAddress = $('#checkout input[name="user_data[s_address]"]'), $billAddress = $('#checkout input[name="user_data[b_address]"]'), message = '&lt;div class="message hidden"&gt;&lt;p&gt;We &lt;strong&gt;don\'t ship to PO Boxes&lt;/strong&gt;. Sorry for the inconvenience.&lt;/p&gt;&lt;/div&gt;'; $shipAddress.after(message); $billAddress.after(message); $shipAddress.keyup(function () { var $value = $(this).val(); if ($value === 'po' || $value === 'Po' || $value === 'PO' || $value === 'P.O' || $value === 'p.o') { $shipAddress.siblings('.message').removeClass('hidden'); } else if ($value === '') { $shipAddress.siblings('.message').addClass('hidden'); } }); $billAddress.keyup(function () { var $value = $(this).val(); if ($value === 'po' || $value === 'Po' || $value === 'PO' || $value === 'P.O' || $value === 'p.o') { $billAddress.siblings('.message').removeClass('hidden'); } else if ($value === '') { $billAddress.siblings('.message').addClass('hidden'); } }); }(jQuery)); </code></pre>
[ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-02-08T05:35:23.750", "Id": "34443", "Score": "0", "body": "Just so you know, there is a stack overflow question with a more complete PO box matching expression. It may help you out: http://stackoverflow.com/questions/5680050/po-box-regular-expression-validation" } ]
[ { "body": "<p>There's 2 obvious places to clean this up a bit. The first is the duplicated keyup handler and the second is the check for PO.</p>\n\n<p>Most jQuery functions can be called on a collection of elements. Since you are calling the same code on both your shipping address and billing address, we can combine them like so:</p>\n\n<pre><code>var $addresses = $('#checkout input[name=\"user_data[s_address]\"]')\n .add($('#checkout input[name=\"user_data[b_address]\"]));\n</code></pre>\n\n<p>For the PO check, you can just use a regular expression:</p>\n\n<pre><code>//p, optional period, o\nif(/p\\.?o/i.test($value)) { ... }\n</code></pre>\n\n<p>So the whole thing becomes:</p>\n\n<pre><code>(function ($) {\n 'use strict';\n\n // Check for PO Box text in address fields on checkout\n var $addresses = $('#checkout input[name=\"user_data[s_address]\"]')\n .add($('#checkout input[name=\"user_data[b_address]\"]')),\n message = \"&lt;div class='message hidden'&gt;&lt;p&gt;We &lt;strong&gt;don't ship to PO Boxes&lt;/strong&gt;. Sorry for the inconvenience.&lt;/p&gt;&lt;/div&gt;\";\n\n $addresses.after(message);\n\n $addresses.keyup(function () {\n var $value = $(this).val();\n\n if(/p\\.?o/i.test($value)) { \n $(this).siblings('.message').removeClass('hidden');\n } else if ($value === '') {\n $(this).siblings('.message').addClass('hidden');\n }\n });\n\n}(jQuery));\n</code></pre>\n\n<p>See: <a href=\"http://jsfiddle.net/6RnxG/7/\" rel=\"nofollow\">http://jsfiddle.net/6RnxG/7/</a></p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-02-08T02:16:37.463", "Id": "34439", "Score": "0", "body": "Thanks, that cleans it up a lot. Those were the exact spots I was looking to clean up." } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-02-08T01:38:44.057", "Id": "21448", "ParentId": "21445", "Score": "2" } }, { "body": "<p>In addition to drch's answser, this section</p>\n\n<pre><code>if(/p\\.?o/i.test($value)) { \n $(this).siblings('.message').removeClass('hidden');\n} else if ($value === '') {\n $(this).siblings('.message').addClass('hidden');\n}\n</code></pre>\n\n<p>could be rewritten as </p>\n\n<pre><code>var showMessage = ! /p\\.?o/i.test($value);\n $(this).siblings('.message').toggleClass('hidden', showMessage);\n</code></pre>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-02-08T17:18:06.250", "Id": "21483", "ParentId": "21445", "Score": "1" } }, { "body": "<p>It seems to be a good solution, BUT, what happens when the address is something like pollock road? It will throw an error.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2016-10-13T14:40:43.117", "Id": "144115", "ParentId": "21445", "Score": "1" } } ]
{ "AcceptedAnswerId": "21448", "CommentCount": "1", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-02-07T21:26:11.450", "Id": "21445", "Score": "1", "Tags": [ "javascript", "jquery", "validation", "form", "e-commerce" ], "Title": "Checking address fields for presence of a Post Office Box" }
21445
<p>Suppose User and Item are two models, and User has many Item. Both models are derived from the parent Model class. In order to retrieve the list of all items a particular user has:</p> <pre><code> $user = new User(100); // User with ID = 100 $items = $user-&gt;getItems(); </code></pre> <p>Now suppose that there are two tables in a database, users and items. In order to find all the items a particular user owns:</p> <pre><code> SELECT * FROM users INNER JOIN items ON (users.item_id = items.id) WHERE users.id = 100 </code></pre> <p>I'm trying to implement this functionality as a PHP magic method. Basically what this means is that if you call $users->getItems(), getItems() is not actually a defined method in User. Instead, it will invoke $users->__call('getItems', FUNCTION_ARGS); So basically:</p> <pre><code> class Model { ... function __call($method_name, $args) { /* ? */ } </code></pre> <p>How would I go about implementing this?</p>
[]
[ { "body": "<p>I have the feeling that there is something wrong with your database structure. According your query, user will have exactly one item?</p>\n\n<p>If one user can have many items and the items belongs only to this user, your schema should look like:</p>\n\n<pre><code>User:\nID Name ...\n\nItem\nID Name UserId ...\n</code></pre>\n\n<p>So your query will look like</p>\n\n<pre><code>SELECT * FROM Item where UserId=100\n</code></pre>\n\n<p>If the items are shared you need a additional table</p>\n\n<pre><code>UserItemRelation\nUserID ItemID\n\nSELECT i.* FROM Item as i, UserItemRelation as r WHERE i.ID=r.ItemID and r.UserID=100\n</code></pre>\n\n<p>In both cases there is no need to join the User table as you know already the user ID.</p>\n\n<hr>\n\n<p>Do get this into an abstract method in your model class you have to extract every information related to your concrete class into abstracts methods. Just as a draft:</p>\n\n<pre><code>function __call($method_name, $args) \n{\n if (isRelationGetter($method_name)) \n {\n return getRelatedEntities(extractField($method_name))\n }\n ....\n}\n\n\nfunction isRelationGetter ($method_name)\n{\n $field=extractField($method_name);\n return isRelationField($field)\n}\n\nabstract function isRelationField($field);\nabstract function getFieldInfo($field);\nabstract function getPrimaryKey();\n\nfunction getRelatedEntities($field)\n{\n $fieldInfo=getFieldInfo($field)\n $query=\"SELECT * FROM \"+$fieldInfo['foreignTable]+\" where $fieldInfo['foreignKeyField]=\"+getPrimaryKey();\n //any database abstraction here\n return fetchAll($query)\n}\n</code></pre>\n\n<hr>\n\n<p>As you see, a lot of magic.</p>\n\n<p>If you write your own ORM let me recommend to automatically generate some abstract classes between your entity classes and your model and add all the getter to this abstract class. The getter itself can then call <code>getRelatedEntities</code> and you get rid of all this name guessing. Of course it would be easier to use an existing ORM.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-02-08T16:09:00.273", "Id": "34497", "Score": "0", "body": "Thanks! And yeah I think I made a mistake with my original query, having that join operation in there." } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-02-08T06:49:47.950", "Id": "21456", "ParentId": "21450", "Score": "2" } } ]
{ "AcceptedAnswerId": "21456", "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-02-08T04:47:33.563", "Id": "21450", "Score": "1", "Tags": [ "php", "mvc" ], "Title": "How to implement HasMany() relationship with PHP?" }
21450
<p>I am creating a simple template engine that uses Regex to find special expressions, which are parsed and processed. They are enclosed in Ruby-style opening tags and have the format:</p> <pre><code> &lt;% label %&gt; OR: &lt;% function(arg1, arg2, arg3) %&gt; </code></pre> <p>However the problem is that I cannot have multiple entries on the same line, so I can't have this:</p> <pre><code> &lt;p&gt;&lt;% name %&gt; - &lt;% age %&gt; - &lt;% gender %&gt;&lt;/p&gt; </code></pre> <p>Instead I have to write it like this:</p> <pre><code> &lt;p&gt;&lt;% name %&gt; - &lt;% age %&gt; - &lt;% gender %&gt;&lt;p&gt; </code></pre> <p>How can I fix this? Below I included the code for the function that handles this. Basically what it does is read from a file, split everything line by line, then iterate through each line and do a regex match and return the results. </p> <pre><code>public function content() { if (!file_exists($this-&gt;path)) return; /* 0 = before, 1 = entry #1, 2 = entry #2, 3 = after */ $content = file_get_contents($this-&gt;path); $pattern = '/^(.*)\&lt;\%\s*(.+)\s*\%\&gt;(.*)$/'; $lines = explode("\n", $content); foreach ($lines as $line) { // Pattern match the line preg_match($pattern, $line, $matches); $result = ''; // If there are no matches, then don't parse it and add the raw string to output if (count($matches) == 0) { continue; } // Parse the matches and run the appropriate action $before = $matches[1]; $after = $matches[3]; $entry = $matches[2]; $return = ''; // Process the entry $return = $this-&gt;processEntry($entry); // Add the processed line to the final result if not empty $result = $before . $return . $after; if (!empty($result)) $final .= $result . "\n"; } return $final; } </code></pre>
[]
[ { "body": "<p>Your current regex is too greedy.</p>\n\n<p>When running against your single line input, I get this result:</p>\n\n<pre><code>/^(.*)\\&lt;\\%\\s*(.+)\\s*\\%\\&gt;(.*)$/\n\n[0] =&gt; &lt;p&gt;&lt;% name %&gt; - &lt;% age %&gt; - &lt;% gender %&gt;&lt;/p&gt;\n[1] =&gt; &lt;p&gt;&lt;% name %&gt; - &lt;% age %&gt; - \n[2] =&gt; gender \n[3] =&gt; &lt;/p&gt;\n</code></pre>\n\n<p>By upgrading the regex to be lazy and also using <code>preg_match_all</code>, we can get the following result:</p>\n\n<pre><code>/(.*?)\\&lt;\\%\\s*(.+?)\\s*\\%\\&gt;/\n\n[0] =&gt; [0] =&gt; &lt;p&gt;&lt;% name %&gt;\n [1] =&gt; - &lt;% age %&gt;\n [2] =&gt; - &lt;% gender %&gt;\n[1] =&gt; [0] =&gt; &lt;p&gt;\n [1] =&gt; - \n [2] =&gt; - \n[2] =&gt; [0] =&gt; name\n [1] =&gt; age\n [2] =&gt; gender\n</code></pre>\n\n<p>The only part missing from that match is the end, the last <code>&lt;/p&gt;</code>. I would use another regex match to grab that portion:</p>\n\n<pre><code>/.*\\%\\&gt;(.*)$/\n\n[0] =&gt; &lt;p&gt;&lt;% name %&gt; - &lt;% age %&gt; - &lt;% gender %&gt;&lt;/p&gt;\n[1] =&gt; &lt;/p&gt;\n</code></pre>\n\n<p>Recommended reading over greedy and lazy: <a href=\"http://www.regular-expressions.info/repeat.html\" rel=\"nofollow\">http://www.regular-expressions.info/repeat.html</a></p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-02-08T06:17:00.367", "Id": "21454", "ParentId": "21451", "Score": "2" } }, { "body": "<p>What to you thing about:</p>\n\n<pre><code>&lt;?=label ?&gt; OR:\n&lt;?=function(arg1, arg2, arg3) ?&gt;\n</code></pre>\n\n<p><strong>PHP is already a template engine</strong></p>\n\n<p>Just write a wrapper around a <code>include</code> call and your template system is ready to use and more flexible than anything you could write.</p>\n\n<hr>\n\n<p>That said, why to you match single lines? Please have a look at <a href=\"http://www.php.net/manual/de/function.preg-replace-callback.php\" rel=\"nofollow\">preg_replace_callback</a>.</p>\n\n<pre><code>/\\&lt;\\%\\s*(.+?)\\s*\\%\\&gt;/\n</code></pre>\n\n<p>If you want to put the whitespace trimming in the callback and as you don't need to escape <code>&lt;&gt;%</code>, you could even use</p>\n\n<pre><code>/&lt;%(.+?)%&gt;/\n</code></pre>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-02-08T06:30:28.377", "Id": "21455", "ParentId": "21451", "Score": "3" } } ]
{ "AcceptedAnswerId": "21454", "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-02-08T04:59:24.863", "Id": "21451", "Score": "1", "Tags": [ "php", "regex" ], "Title": "How to make this Regex more flexible?" }
21451
<p>I have two classes, Database and Logger. Database is responsible for handling SQL queries, and Logger logs messages to an external file. Whenever the database executes an SQL query, I want Logger to log it. Right now my implementation looks something like this:</p> <pre><code> class Database { public function query($sql) { Logger::log($sql); // ... } } class Logger { public static function log($msg) { // ... } } </code></pre> <p>But I feel that this is bad practice because Database shouldn't know about Logger. So instead I was thinking of creating a publisher-subscriber model (or something similar) where Database keeps a list of subscribers and has a method to subscribe to events, then it alerts subscribers when an event is fired (eg: when query is executed). I'm thinking something like this:</p> <pre><code> class Database { $subscribers = array(); public function subscribe($something) { $subscribers.push($something); } private function alert_subscribers($msg, $event_type) { foreach ($s as $subscribers) { // Alert all subscribers, somehow } } public function query($sql) { alert_subscribers($sql, SQL_QUERY_EXECUTED); // ... } } class Logger { public static function log($msg) { // ... } } </code></pre> <p>I want it to have multiple event types, so basically different groups are alerted when different events happen. I also don't know how the Logger should subscribe to Database under this design. </p> <p>How should I go about implementing this? I'm not sure how to start.</p>
[]
[ { "body": "<p>There is nothing wrong with having the loggers everywhere. If you clutter all your classes with some kind of event notification it would look worst :)</p>\n\n<p><strong>But</strong>, Logger should not be called with a static method. You can create a pool of Loggers and your call will look like:</p>\n\n<pre><code>$log=Logger::get(\"Database\");\n$log-&gt;info(\"foo\");\n</code></pre>\n\n<p>The big advantage is that you can put a configuration file in your project and define the log level of every logger independently. </p>\n\n<hr>\n\n<p>According your questions you have really big plans. You want to write a template engine, a logging framework, an ORM and I guess somewhere in between your real application. Trust me when I tell you, you will fail. (I and most likely everybody else here tried it already :) ). <strong>For all your components there are mature frameworks out there. Find the one you like!!</strong></p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-02-13T11:29:21.043", "Id": "34794", "Score": "1", "body": "For what it's worth. I think you need to atleast try it once. If you do this, you will learn a lot on how things are build up." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-02-13T12:00:14.100", "Id": "34796", "Score": "1", "body": "+1 But you should do it in your spare time not in a project you have to life with the next X years ;)" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-02-13T12:16:03.717", "Id": "34797", "Score": "0", "body": "That's true! :)" } ], "meta_data": { "CommentCount": "3", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-02-08T07:23:49.440", "Id": "21458", "ParentId": "21452", "Score": "4" } }, { "body": "<h2>Event</h2>\n\n<pre><code>class Event {\n\n private $_subscribers = array();\n\n public function Invoke() {\n foreach ($this-&gt;_subscribers as $subscriber) {\n call_user_func($subscriber);\n //call_user_func_array($subscriber, array(\"some argument\"));\n }\n }\n\n public function Subscribe($subscriber) {\n if (!is_callable($subscriber)) {\n throw new \\ArgumentException(\"Subscriber have to be callable\");\n }\n\n $this-&gt;_subscribers[] = $subscriber;\n }\n\n public function UnSubscribe($unsubscriber) {\n foreach ($this-&gt;_subscribers as $key =&gt; $subscriber) {\n if ($subscriber == $unsubscriber) {\n unset($this-&gt;_subscribers[$key]);\n return true;\n }\n }\n\n return false;\n }\n\n public final function __invoke() {\n $this-&gt;Invoke();\n }\n\n}\n</code></pre>\n\n<p>I would create at least a simple Event class to keep clean the code. The example above is a very simple one but if you have 5 more minutes for this you can create a DatabaseEvent class which have a Subscribe method what is expecting an IDatabaseEventHandler \"interface instance\" as parameter (public function Subscribe(IDatabaseEventHandler $handler)) which has a few or a lot of methods: LogConnectionError($arg), LogQueryError(QueryErrorArgument $arg) and so on. Whith this approach you will need an adapter class as a default interface implementation of the IDatabaseEventHandler for easier usage (for example when you are writing your unit tests). Of course the DatabaseEvent class have to have a lot of named log methods to call the subscribed handlers when it's neccessary.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-02-08T09:38:01.800", "Id": "21460", "ParentId": "21452", "Score": "2" } } ]
{ "AcceptedAnswerId": "21458", "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-02-08T05:11:42.560", "Id": "21452", "Score": "3", "Tags": [ "php", "design-patterns" ], "Title": "How to implement Publish-subscribe pattern in PHP?" }
21452
<p>I've started learning .NET with MVC 4 in C# and I built a basic application to display records from a MySQL database. It's incredibly basic, but it's the best I could come up with being a complete beginner to C# and all.</p> <p>Most of the programming I do is with Ruby on Rails and I tried to carry over some of the design patterns that I use there. I don't know the .NET conventions so if you see anything that should be changed please let me know.</p> <p>Also, I don't fully understand how to find records with LINQ and pass them to the view. I ended up getting lucky and finding an article that somewhat explained it, but I don't have a firm grasp on the subject.</p> <p>The naming conventions for my entities and models are wrong. It's a long story, basically it took me a while to connect to my MySQL database and when I generated them I didn't care how they were named.</p> <p><strong>RouteConfig.cs</strong></p> <pre><code>routes.MapRoute( name: "root", url: "", defaults: new { controller = "Authors", action = "Index" } ); routes.MapRoute( name: "author_books", url: "authors/{author_id}/books", defaults: new { controller = "Authors", action = "Books" } ); </code></pre> <p><strong>AuthorsController.cs</strong></p> <pre><code>public class AuthorsController : Controller { bookisticsEntities be = new bookisticsEntities(); // // GET: /Authors/ public ActionResult Index() { return View(be.authors.ToList()); } public ActionResult Books(int author_id = 0) { author aut = be.authors.Find(author_id); var books = from b in be.books join a in be.authors on b.author_id equals a.id where b.author_id == author_id select b; ViewBag.author_name = aut.name; return View(books.ToList()); } } </code></pre> <p>I've omitted the view files because I pretty much left them at default after they were generated.</p>
[]
[ { "body": "<h2>Dependency injection</h2>\n\n<p>Use dependency injection everywhere you can</p>\n\n<pre><code>public class AuthorsController : Controller\n{\n private readonly bookisticsEntities _booksEntities;\n\n public AuthorsController(bookisticsEntities entities)\n {\n _booksEntities = entities;\n }\n\n public ActionResult Index()\n {\n //all authors on one page can be slow, paging?\n //.ToList() is useless here\n return View(be.authors);\n }\n\n //default value is not neccessary becouse 0 is an invalid value\n public ActionResult Books(int author_id)\n {\n var author = _booksEntities.authors.SingleOrDefault(a =&gt; a.id == author_id);\n\n if (author == null)\n {\n return HttpNotFound();\n }\n\n /*var books = from b in be.books\n join a in be.authors\n on b.author_id equals a.id\n where b.author_id == author_id\n select b;\n\n ViewBag.author_name = aut.name;*/\n\n //pass the author to the view and in the view you can iterate on the author.Books collection\n //if the foreign keys are correct in the database\n //or you setted everything correctly in code first approach\n return View(author);\n }\n}\n</code></pre>\n\n<p>Now the controller expects a bookisticsEntities instance as constructor parameter but the default controller factory in the MVC framework only can use a parameterless constructor so you need a solution for this; use a dependency injection container like Ninject! It's easy to use available through Nuget.</p>\n\n<h2>N-tier</h2>\n\n<p>It seams to me your application missing one or two (maybe three) application level becouse currently you managing the database directly which is not a best practise. You have to build at leas one level between the MVC and the dataaccess tier which is called business layer (or two: a service layer and under that a business layer). In this way you controller will expect one or more different type of object instances but not your database model!</p>\n\n<p>If you are done whith this you can use simplified models in your application, for example in the Books action method you can use a model which can contain the author's name, identifier and the books also (books can be simplified also). </p>\n\n<h2>Learn Entity Framework</h2>\n\n<p>Read a lot about how EF works. :)</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-02-08T15:14:00.167", "Id": "34492", "Score": "0", "body": "Thank you for your suggestions. I'm definitely interested in implementing DI and Ninject looks like a really cool project. However, I couldn't get it work out of the box. I added it through Nuget, and I added a constructor to my class, but I'm getting an error about not having a parameterless constructor. After a couple of google searches I wasn't able to find a direct answer, do you have any ideas on what I should do?" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-02-09T02:51:43.340", "Id": "34534", "Score": "0", "body": "@BaylorRae' You need to ensure that the binding is setup so that the Ninject solution knows what class to create when the controller class is instantiated" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-02-09T06:18:19.717", "Id": "34539", "Score": "0", "body": "Add to the project the Ninject MVC3 extension and then you will have a NinjectWebCommon class where you can set up your bindings. This is not required you can use it for example in the Applocation_Start by creating a StandardKerel, setting up the bindings and then with a small adapter class register it as a DependencyResolver (DependencyResolver.SetResolver) and you are done." } ], "meta_data": { "CommentCount": "3", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-02-08T08:32:23.667", "Id": "21459", "ParentId": "21453", "Score": "2" } } ]
{ "AcceptedAnswerId": "21459", "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-02-08T05:19:12.250", "Id": "21453", "Score": "1", "Tags": [ "c#", "asp.net", "asp.net-mvc-4" ], "Title": "Displaying records from a MySQL database" }
21453
<p>I have decided to create a <a href="https://github.com/Patryczek/OptionType/blob/master/OptionType/Option.cs" rel="nofollow">simple <code>Option</code> type for C#</a>. I have essentially based it on the <a href="https://github.com/scala/scala/blob/master/src/library/scala/Option.scala" rel="nofollow">Scala's <code>Option</code></a>.</p> <p>It was mostly a fun exercise, but it might come in handy at work or any other project, even though it's less powerful than the Scala version.</p> <p>Now I'd appreciate all remarks regarding this little piece of code, but essentially now I'm thinking whether or not to introduce an implicit conversion between the type and the <code>Option</code>, which would allow for:</p> <pre><code>MyType obj; // ... something interesting happens (or not) Option&lt;MyType&gt; optionalObj = obj; </code></pre> <p>I have already included <code>ToOption</code> extension method for convenient creation of the option from existing object:</p> <pre><code>var optionalObj = obj.ToOption(); </code></pre> <p>which returns either <code>Some&lt;T&gt;</code> or <code>None&lt;T&gt;</code>and the implicit conversion would do just that, but I'm just wondering if it's not too 'hidden', non-obvious and/or counter-intuitive(?).</p> <p>Anyway, I'd like to see what you think.</p> <pre><code>public abstract class Option&lt;T&gt; { /// &lt;summary&gt; /// Option's value /// &lt;/summary&gt; public abstract T Value { get; } /// &lt;summary&gt; /// Indicates whether the option holds a value or not /// &lt;/summary&gt; public abstract bool IsEmpty { get; } /// &lt;summary&gt; /// Unwraps the option. /// &lt;/summary&gt; /// &lt;param name="defaultValue"&gt;&lt;/param&gt; /// &lt;returns&gt;Specified, default value if the option is empty, or the option's value if present&lt;/returns&gt; /// &lt;remarks&gt;It's recommended to use the &lt;see cref="GetOrElse(Func{T})"/&gt; when passing a parameter expression to be evaluated. /// In this case, the condition will get evaluated AFTER evaluation of the parameter, which may be costly.&lt;/remarks&gt; public T GetOrElse(T defaultValue) { return IsEmpty ? defaultValue : Value; } /// &lt;summary&gt; /// Unwraps the option /// &lt;/summary&gt; /// &lt;param name="defaultValue"&gt;Function returning the default value&lt;/param&gt; /// &lt;returns&gt;The evaluation of the specified function if option is empty, or the option's value if present&lt;/returns&gt; /// &lt;remarks&gt;Recommended overload. The function returning defaultValue will only get evaluated if /// the option is empty.&lt;/remarks&gt; public T GetOrElse(Func&lt;T&gt; defaultValue) { return IsEmpty ? defaultValue() : Value; } /// &lt;summary&gt; /// Unwraps the option /// &lt;/summary&gt; /// &lt;returns&gt;The default value for the type if option is empty, or the option's value if present&lt;/returns&gt; public T GetOrDefault() { return GetOrElse(default(T)); } private static readonly Lazy&lt;None&lt;T&gt;&gt; NoneInstance = new Lazy&lt;None&lt;T&gt;&gt;(() =&gt; new None&lt;T&gt;()); /// &lt;summary&gt; /// Shared &lt;code&gt;None{T}&lt;/code&gt; instance. /// &lt;/summary&gt; public static None&lt;T&gt; None { get { return NoneInstance.Value; } } public abstract override string ToString(); } public sealed class Some&lt;T&gt; : Option&lt;T&gt; { /// &lt;summary&gt; /// Creates a new option holding the value. /// &lt;/summary&gt; /// &lt;exception cref="ArgumentNullException"&gt;When the value passed is null. &lt;code&gt;None{T}&lt;/code&gt; (or the extension method which creates appropriate type) should be used instead.&lt;/exception&gt; /// &lt;param name="value"&gt;&lt;/param&gt; public Some(T value) { if(value == null) throw new ArgumentNullException("value", "Argument passed to Some was null - use None&lt;T&gt; instead."); this.value = value; } private readonly T value; public override T Value { get { return value; } } public override bool IsEmpty { get { return false; } } public override string ToString() { return Value.ToString(); } } public sealed class None&lt;T&gt; : Option&lt;T&gt; { /// &lt;summary&gt; /// &lt;exception cref="InvalidOperationException"&gt;Thrown when accessing the value. &lt;code&gt;None{T}&lt;/code&gt; has no value.&lt;/exception&gt; /// &lt;/summary&gt; public override T Value { get { throw new InvalidOperationException(); } } public override bool IsEmpty { get { return true; } } public override string ToString() { return "None"; } } namespace OptionType.Extensions { /// &lt;summary&gt; /// Extension methods for &lt;see cref="Option{T}"/&gt; /// &lt;/summary&gt; public static class OptionExtensions { /// &lt;summary&gt; /// Wraps the specified object in an option. If the object is null, returns &lt;see cref="None{T}"/&gt;, otherwise creates &lt;see cref="Some{T}"/&gt; /// &lt;/summary&gt; /// &lt;typeparam name="T"&gt;&lt;/typeparam&gt; /// &lt;param name="value"&gt;&lt;/param&gt; /// &lt;returns&gt;A new &lt;see cref="Option{T}"/&gt;&lt;/returns&gt; public static Option&lt;T&gt; ToOption&lt;T&gt;(this T value) { if (value == null) return Option&lt;T&gt;.None; return new Some&lt;T&gt;(value); } /// &lt;summary&gt; /// Applies a specified function to the option's value and yields a new option if the option is non-empty. /// &lt;/summary&gt; /// &lt;typeparam name="T"&gt;&lt;/typeparam&gt; /// &lt;typeparam name="U"&gt;&lt;/typeparam&gt; /// &lt;param name="option"&gt;&lt;/param&gt; /// &lt;param name="func"&gt;&lt;/param&gt; /// &lt;returns&gt;&lt;see cref="Some{T}"/&gt; if the option is non-empty, &lt;see cref="None{T}"/&gt; otherwise.&lt;/returns&gt; public static Option&lt;U&gt; Select&lt;T, U&gt;(this Option&lt;T&gt; option, Func&lt;T, U&gt; func) { if (option.IsEmpty) return Option&lt;U&gt;.None; return new Some&lt;U&gt;(func(option.Value)); } /// &lt;summary&gt; /// Applies a specified function to the option's value and yields a new option if the option is non-empty. /// &lt;remarks&gt;Different from &lt;see cref="Select{T,U}"/&gt;, expects a function that returns an &lt;see cref="Option{T}"/&gt;&lt;/remarks&gt; /// &lt;/summary&gt; /// &lt;typeparam name="T"&gt;&lt;/typeparam&gt; /// &lt;typeparam name="U"&gt;&lt;/typeparam&gt; /// &lt;param name="option"&gt;&lt;/param&gt; /// &lt;param name="func"&gt;&lt;/param&gt; /// &lt;returns&gt;&lt;see cref="Some{T}"/&gt; if the option is non-empty, &lt;see cref="None{T}"/&gt; otherwise.&lt;/returns&gt; public static Option&lt;U&gt; SelectMany&lt;T, U&gt;(this Option&lt;T&gt; option, Func&lt;T, Option&lt;U&gt;&gt; func) { if (option.IsEmpty) return Option&lt;U&gt;.None; return func(option.Value); } /// &lt;summary&gt; /// Filters the option by the passed predicate function /// &lt;/summary&gt; /// &lt;typeparam name="T"&gt;&lt;/typeparam&gt; /// &lt;param name="option"&gt;&lt;/param&gt; /// &lt;param name="func"&gt;&lt;/param&gt; /// &lt;returns&gt;Returns the option if the option is non-empty and the value underneath satisfied the predicate, &lt;see cref="None{T}"/&gt; otherwise.&lt;/returns&gt; public static Option&lt;T&gt; Where&lt;T&gt;(this Option&lt;T&gt; option, Func&lt;T, bool&gt; func) { if (option.IsEmpty || func(option.Value)) return option; return Option&lt;T&gt;.None; } /// &lt;summary&gt; /// Checks if the value 'exists' inside the option. /// &lt;/summary&gt; /// &lt;typeparam name="T"&gt;&lt;/typeparam&gt; /// &lt;param name="option"&gt;&lt;/param&gt; /// &lt;param name="func"&gt;&lt;/param&gt; /// &lt;returns&gt;&lt;code&gt;true&lt;/code&gt; if the option is not empty and if it satisfied the predicate, &lt;see cref="None{T}"/&gt; otherwise.&lt;/returns&gt; public static bool Any&lt;T&gt;(this Option&lt;T&gt; option, Func&lt;T, bool&gt; func) { return !option.IsEmpty &amp;&amp; func(option.Value); } /// &lt;summary&gt; /// Executes a specified action on the option, if the option is non-empty. /// &lt;/summary&gt; /// &lt;typeparam name="T"&gt;&lt;/typeparam&gt; /// &lt;param name="option"&gt;&lt;/param&gt; /// &lt;param name="action"&gt;&lt;/param&gt; public static void ForEach&lt;T&gt;(this Option&lt;T&gt; option, Action&lt;T&gt; action) { if (!option.IsEmpty) action(option.Value); } /// &lt;summary&gt; /// Returns the &lt;paramref name="alternative"/&gt; if the specified &lt;paramref name="option"/&gt; is empty. Returns the &lt;paramref name="option"/&gt; itself otherwise. /// &lt;/summary&gt; /// &lt;typeparam name="T"&gt;&lt;/typeparam&gt; /// &lt;param name="option"&gt;&lt;/param&gt; /// &lt;param name="alternative"&gt;&lt;/param&gt; /// &lt;remarks&gt;It's recommended to use &lt;see cref="OrElse{T}(Option{T}, Func{Option{T}}"/&gt; overload.&lt;/remarks&gt; /// &lt;returns&gt;&lt;/returns&gt; public static Option&lt;T&gt; OrElse&lt;T&gt;(this Option&lt;T&gt; option, Option&lt;T&gt; alternative) { return option.IsEmpty ? alternative : option; } /// &lt;summary&gt; /// Checks whether the current option is empty; if it is, the &lt;paramref name="alternative"/&gt; function is evaluated and the result is returned. Otherwise, /// the &lt;paramref name="option"/&gt; is returned. /// &lt;/summary&gt; /// &lt;typeparam name="T"&gt;&lt;/typeparam&gt; /// &lt;param name="option"&gt;&lt;/param&gt; /// &lt;param name="alternative"&gt;&lt;/param&gt; /// &lt;returns&gt;The current option if it's non-empty and the evaluation result of the alternative function otherwise.&lt;/returns&gt; public static Option&lt;T&gt; OrElse&lt;T&gt;(this Option&lt;T&gt; option, Func&lt;Option&lt;T&gt;&gt; alternative) { return option.IsEmpty ? alternative() : option; } /// &lt;summary&gt; /// Converts the option to a sequence (&lt;see cref="IEnumerable{T}"/&gt;) /// &lt;/summary&gt; /// &lt;typeparam name="T"&gt;&lt;/typeparam&gt; /// &lt;param name="option"&gt;&lt;/param&gt; /// &lt;returns&gt;One element sequence containing the option's value if the option was non-empty, empty sequence otherwise&lt;/returns&gt; public static IEnumerable&lt;T&gt; ToEnumerable&lt;T&gt;(this Option&lt;T&gt; option) { if (option.IsEmpty) yield break; yield return option.Value; } } } </code></pre>
[ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-02-08T13:35:02.007", "Id": "34458", "Score": "1", "body": "Also, I think you should consider that C# already has idiomatic way to do this: `null` for reference types and `Nullable<T>` for value types. What's worse a variable of type `Option<T>` can still be `null`, so your type doesn't really work like true `Option`." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-02-08T13:55:51.577", "Id": "34464", "Score": "4", "body": "Usually when I see people doing this, they make it a struct instead of a class. Also, for some reason the Haskell-ish names `Maybe`, `Just`, `Nothing` seem more popular in C# implementations than the ML-ish `Option`, `Some`, `None` as seen in Scala and F#." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-02-08T14:13:15.327", "Id": "34489", "Score": "1", "body": "Yeah, I guess struct would indeed be a better fit, and it would automatically alleviate the problem of the `Option<T>` being null itself. As for nullable, that's true, Option its superfluous for value types, but reference types can sometimes be a pain with null checks... I can't really say anything about the naming, I'm just more used to ML conventions, as I have dipped my toes in both F# and Scala, but not Haskell. :)" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-02-08T15:47:37.883", "Id": "34496", "Score": "0", "body": "@svick By the way, I was curious and I checked: `scala > val opt : Option[Int] = null` works, and then `opt.getOrElse(2)` throws `NullPointerException`, so I guess it works in the same way :) You have a point though, maybe that's why implementations from almaz' answer use extension methods on reference types and work with nulls instead..." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-02-08T17:17:42.227", "Id": "34501", "Score": "0", "body": "The `Option` names are certainly more traditional, and probably make more sense in C# than the `Maybe` naming scheme (and I say that as someone very familiar with Haskell and its influence on C#). Also, some people really don't like calling extension methods on a null reference, in which case a struct is the only reasonable choice." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-02-08T17:30:04.530", "Id": "34503", "Score": "0", "body": "@Trustme-I'maDoctor F# does something similar: there, `Option<T>` is a reference type and `null` is used as the value representing `None`." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-02-09T11:45:08.970", "Id": "34553", "Score": "0", "body": "@svick Oh, good to know. Although the F# `Option` is nicely packed in a form of discriminated union, which I don't know how to express in C#, hence I went with Scala's version (although I see it works the same). I have added an edit with modified reference type and a new value type, I guess the value type Option looks *better*, although I like the semantics of reference Option... :)" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-07-16T18:21:28.747", "Id": "102194", "Score": "0", "body": "You could just use http://sourceforge.net/projects/sasa/ or https://github.com/NICTA/xsharpx or https://github.com/fsprojects/fsharpx , etc..." } ]
[ { "body": "<p>What you have done is usually called a <a href=\"http://en.wikipedia.org/wiki/Monad_%28functional_programming%29#The_Maybe_monad\" rel=\"nofollow\"><strong>Maybe</strong> Monad</a>. There are several implementations of those for .NET (<a href=\"https://github.com/phlik/Monads.net/blob/master/Monads.NET/Maybe.cs\" rel=\"nofollow\">one</a>, <a href=\"https://github.com/sergun/monads.net/blob/master/Src/Monads/Maybe.Objects.cs\" rel=\"nofollow\">two</a>), and usually they just use extension methods to apply operations to nullable object.</p>\n\n<p>Concerning your code: you don't need a hierarchy here, since most of the code is already in base <code>Option</code> class.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-02-08T15:37:42.253", "Id": "34494", "Score": "0", "body": "Hey, thanks. I'm aware that it's a Maybe monad, I didn't know though that there are implementations ready. It was a fun exercise though :) I will definitely use the ready version if the need arises. I tried to make it as similar to Scala's `Option` as I could, and I guess the current version resembles it the most. Of course there are flaws, as others pointed out in comments, but I can't e.g. make it a struct without modifying it heavily. Thank you very much for your input though, I'll save the github links. :)" } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-02-08T14:54:28.723", "Id": "21476", "ParentId": "21461", "Score": "2" } }, { "body": "<ol>\n<li><p>You have several extension methods with <code>Option&lt;T&gt;</code> as first parameter, why don't you use normal instance methods?</p></li>\n<li><p>I prefer having an implicit conversion from <code>T</code> to <code>Option&lt;T&gt;</code></p>\n\n<p><code>Option&lt;T&gt;</code> seems like a nice choice for optional function parameters. In that case calling <code>ToOption()</code> everywhere is a bit annoying.</p></li>\n<li><p>Why make the initialization of <code>None</code> lazy? Creating a <code>None&lt;T&gt;</code> is probably cheaper than creating a <code>Lazy&lt;T&gt;</code>. I recommend lazy initialization only if it's expensive.</p></li>\n<li><p>I'd rename <code>IsEmpty</code> to <code>HasValue</code> to match <code>Nullable&lt;T&gt;</code>. (Inverted meaning obv.)</p></li>\n<li><p>I'd add some kind of protection against other classes deriving from <code>Option&lt;T&gt;</code>. For example an <code>internal abstract</code> method.</p></li>\n<li><p><code>public abstract override string ToString();</code> Seems weird. Don't touch it on <code>Option&lt;T&gt;</code> and simply override it in the child classes.</p></li>\n<li><p>Why disallow a value of <code>null</code>?</p></li>\n<li><p>I prefer using a struct, so the option itself cannot be <code>null</code>.</p></li>\n<li><p>One could consider implementing <code>IEnumerable&lt;T&gt;</code>, instead of a <code>ToEnumerable()</code> method. But I'm not sure if that's a good idea.</p></li>\n</ol>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-02-09T09:30:33.590", "Id": "21506", "ParentId": "21461", "Score": "4" } } ]
{ "AcceptedAnswerId": "21506", "CommentCount": "8", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-02-08T10:13:03.687", "Id": "21461", "Score": "6", "Tags": [ "c#", "functional-programming", "scala" ], "Title": "Option type in C# and implicit conversions" }
21461
<p>Is there a better way of creating this terminal animation without having a series of conditional statements (i.e. <code>if ... elif ... elif...)</code>?</p> <pre><code>import sys, time count = 100 i = 0 num = 0 def animation(): global num if num == 0: num += 1 return '[= ]' elif num == 1: num += 1 return '[ = ]' elif num == 2: num += 1 return '[ = ]' elif num == 3: num += 1 return '[ = ]' elif num == 4: num += 1 return '[ = ]' elif num == 5: num += 1 return '[ = ]' elif num == 6: num += 1 return '[ =]' elif num == 7: num += 1 return '[ =]' elif num == 8: num += 1 return '[ = ]' elif num == 9: num += 1 return '[ = ]' elif num == 10: num += 1 return '[ = ]' elif num == 11: num += 1 return '[ = ]' elif num == 12: num += 1 return '[ = ]' elif num == 13: num = 0 return '[= ]' while i &lt; count: sys.stdout.write('\b\b\b') sys.stdout.write(animation()) sys.stdout.flush() time.sleep(0.2) </code></pre>
[ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-02-08T14:06:17.480", "Id": "34488", "Score": "0", "body": "I guess that a progress bar, shouldn't you write \\b 9 times?" } ]
[ { "body": "<p>You can build up the string like this:</p>\n\n<pre><code>def animation(counter, length):\n stage = counter % (length * 2 + 2)\n if stage &lt; length + 1:\n left_spaces = stage\n else:\n left_spaces = length * 2 - 1 - stage\n return '[' + ' ' * left_spaces + '=' + ' ' * (length - left_spaces) + ']'\n\nfor i in range(100):\n sys.stdout.write('\\b\\b\\b')\n sys.stdout.write(animation(i, 6))\n sys.stdout.flush()\n time.sleep(0.2)\n</code></pre>\n\n<p>Alternatively store the animation strings in a tuple or list:</p>\n\n<pre><code>animation_strings = ('[= ]', '[ = ]', '[ = ]', '[ = ]',\n '[ = ]', '[ = ]', '[ =]', '[ =]',\n '[ = ]', '[ = ]', '[ = ]', '[ = ]',\n '[ = ]', '[= ]')\nfor i in range(100):\n sys.stdout.write('\\b\\b\\b')\n sys.stdout.write(animation_strings[i % len(animation_strings)])\n sys.stdout.flush()\n time.sleep(0.2)\n</code></pre>\n\n<p>You can replace the animation function with <a href=\"http://docs.python.org/2/library/itertools.html#itertools.cycle\"><code>cycle</code> from <code>itertools</code></a>:</p>\n\n<pre><code>import sys, time\nfrom itertools import cycle\nanimation = cycle('[= ]', '[ = ]', '[ = ]', '[ = ]',\n '[ = ]', '[ = ]', '[ =]', '[ =]',\n '[ = ]', '[ = ]', '[ = ]', '[ = ]',\n '[ = ]', '[= ]')\n# alternatively:\n# animation = cycle('[' + ' ' * n + '=' + ' ' * (6 - n) + ']' \n# for n in range(7) + range(6, -1, -1))\n\nfor _ in range(100):\n sys.stdout.write('\\b\\b\\b')\n sys.stdout.write(animation.next())\n sys.stdout.flush()\n time.sleep(0.2)\n</code></pre>\n\n<p>Finally, you could make your own generator function.</p>\n\n<pre><code>def animation_generator(length):\n while True:\n for n in range(length + 1):\n yield '[' + ' ' * n + '=' + ' ' * (length - n) + ']'\n for n in range(length + 1):\n yield '[' + ' ' * (length - n) + '=' + ' ' * n + ']'\n\nanimation = animation_generator(6)\nfor _ in range(100):\n sys.stdout.write('\\b\\b\\b')\n sys.stdout.write(animation.next())\n sys.stdout.flush()\n time.sleep(0.2)\n</code></pre>\n\n<p>EDIT: made the above suggestions less reliant on global variables</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-02-08T12:11:56.170", "Id": "34452", "Score": "3", "body": "+1 for `itertools.cycle`. (But I think you'd want to build up the animation programmatically so that it would be easy to change its length.)" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-02-09T00:42:39.453", "Id": "34531", "Score": "0", "body": "Alternatively, you could `sys.stdout.write('\\r')` instead of the `\\b\\b\\b`, since the animation steps have equal length." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-02-09T11:12:38.307", "Id": "34551", "Score": "0", "body": "@AttilaO. thanks, I use IDLE and don't actually know how these terminal characters work but I'll take your word for it..." } ], "meta_data": { "CommentCount": "3", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-02-08T11:41:43.353", "Id": "21464", "ParentId": "21462", "Score": "16" } }, { "body": "<p>Notes: </p>\n\n<ul>\n<li>Don't use global variables without a good (an extremely good) justification. A function is (should be) a black box that gets values and returns values (unless you have unavoidable side-effects to perform, for example reading a file or printing to the screen). </li>\n<li>It's very cumbersome and inflexible to write every possible string of the progressbar by hand, use code instead to build them.</li>\n</ul>\n\n<p>I'd write:</p>\n\n<pre><code>import sys\nimport time\n\ndef render(size, position):\n return \"[\" + (\" \" * position) + \"=\" + (\" \" * (size - position - 1)) + \"]\" \n\ndef draw(size, iterations, channel=sys.stdout, waittime=0.2): \n for index in range(iterations):\n n = index % (size*2)\n position = (n if n &lt; size else size*2 - n - 1)\n bar = render(size, position)\n channel.write(bar + '\\r')\n channel.flush()\n time.sleep(waittime) \n\nif __name__ == '__main__':\n draw(6, 100, channel=sys.stdout)\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-02-08T13:53:26.030", "Id": "34462", "Score": "0", "body": "Does not replicate the original animation" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-02-08T14:03:44.280", "Id": "34465", "Score": "0", "body": "@Stuart. I know, I thought it looked more beautiful without stopping at the limits. I'll update it. But I guess `\\b` is expected to match the string length, otherwise it makes no sense." } ], "meta_data": { "CommentCount": "2", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-02-08T13:44:17.150", "Id": "21467", "ParentId": "21462", "Score": "4" } }, { "body": "<p>Try this:</p>\n\n<pre><code>import time\nj = 0\nwhile True:\n for j in range(6):\n print(\"[\",j*\" \",\"=\",(6-j)*\" \",\"]\",end=\"\\r\", sep=\"\")\n time.sleep(0.2)\n for j in range(6):\n print(\"[\",(6-j)*\" \", \"=\",(j)*\" \",\"]\",end=\"\\r\", sep=\"\")\n time.sleep(0.2)\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2018-01-09T12:35:02.833", "Id": "351897", "Score": "1", "body": "[Answers that merely provide an alternate solution with no explanation or justification do not constitute valid Code Review answers](https://codereview.stackexchange.com/help/how-to-answer): argue *how* this is `better way`, why drop the `count`(100) limit?" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2018-01-09T16:39:45.527", "Id": "351941", "Score": "0", "body": "While the OP asked \"_Is there a better way of doing this terminal animation without having a load of `if ... elif ...`?_\", which does seem like it might be asking for just alternative code, \"_[Short answers are acceptable](http://meta.codereview.stackexchange.com/questions/1463/short-answers-and-code-only-answers), **as long as you explain your reasoning**._\" -see [How to answer](https://codereview.stackexchange.com/help/how-to-answer). That page also states: \"_Every answer must make at least one **insightful observation** about the code in the question._\"" } ], "meta_data": { "CommentCount": "2", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2018-01-09T11:29:24.100", "Id": "184649", "ParentId": "21462", "Score": "0" } }, { "body": "<p>A liitle modification:\n*Also reduce the size of python shell window</p>\n<pre><code>import sys, time\ncount = 100\ni = 0\nnum = 0\n\ndef animation():\n global num\n if num == 0:\n num += 1\n return '[= ]'\n elif num == 1:\n num += 1\n return '[ = ]'\n elif num == 2:\n num += 1\n return '[ = ]'\n elif num == 3:\n num += 1\n return '[ = ]'\n elif num == 4:\n num += 1\n return '[ = ]'\n elif num == 5:\n num += 1\n return '[ = ]'\n elif num == 6:\n num += 1\n return '[ =]'\n elif num == 7:\n num += 1\n return '[ =]'\n elif num == 8:\n num += 1\n return '[ = ]'\n elif num == 9:\n num += 1\n return '[ = ]'\n elif num == 10:\n num += 1\n return '[ = ]'\n elif num == 11:\n num += 1\n return '[ = ]'\n elif num == 12:\n num += 1\n return '[ = ]'\n elif num == 13:\n num = 0\n return '[= ]'\n\nwhile i &lt; count:\n sys.stdout.write('\\b\\b\\b\\n')\n sys.stdout.write(animation())\n sys.stdout.flush()\n time.sleep(0.2)\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-04-16T12:03:22.263", "Id": "512132", "Score": "1", "body": "Welcome to Code Review! You have presented an alternative solution, but haven't reviewed the code. Please [edit] to show what aspects of the question code prompted you to write this version, and in what ways it's an improvement over the original. It may be worth (re-)reading [answer]." } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-04-16T11:14:06.620", "Id": "259614", "ParentId": "21462", "Score": "-2" } } ]
{ "AcceptedAnswerId": "21464", "CommentCount": "1", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-02-08T11:13:04.773", "Id": "21462", "Score": "9", "Tags": [ "python" ], "Title": "Python terminal animation" }
21462
<p>I know i have some real problems with the following code (as others said). can you please help me to optimize it a little bit? Maybe some example of how to do it.</p> <p>(find the longest repeating substring with length between x and y)</p> <pre><code> public static String longestDuplicate(String text, int x, int y) { String longest = ""; for (int i = 0; i &lt; text.length() - 2 * longest.length() * 2; i++) { OUTER: for (int j = Math.min((text.length() - i -1)/2, y) ; j &gt; longest.length() &amp;&amp; j &gt;=x; j--) { String find = text.substring(i, i + j); for (int k = i + j; k &lt;= text.length() - j; k++) { if (text.substring(k, k + j).equals(find)) { longest = find; continue OUTER; } } break; } } return longest; } </code></pre>
[ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-02-08T11:29:42.337", "Id": "34449", "Score": "1", "body": "What do you want to optimize? The number of line breaks? What problems do you have?" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-02-08T11:42:12.043", "Id": "34450", "Score": "1", "body": "some programmers said that \" There are multiple problems with this code. Almost any time you have to use directed break or continue, you want to step back and say \"Hmmm, maybe I've got myself in some trouble here.\" Especially if you find yourself writing a loop that will never actually loop unless an inner loop throws a directed continue at it, as with your loop labelled OUTER. Having significant calculations in the terminal condition of a loop is another danger signal.\"" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-02-08T11:54:42.487", "Id": "34451", "Score": "0", "body": "Does this actually work ?" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-02-08T12:35:01.020", "Id": "34453", "Score": "0", "body": "@LuciC I am with Gabriel on this one. I dont think that it is working. Could you provide us with an example of how to use this? I copied your code into my idea and setup a JUnitTest on it. Give it a string (your intro) and put as expected out \"following\". (it might not be longest, but it was a test) and the returned result was <\"\"> (meaning empty)" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-02-08T12:47:47.250", "Id": "34454", "Score": "0", "body": "@LuciC Also your math that you impose on your first loop is a bit convoluted. longest.length is always going to evaluate as 0. 0*2 is always 0. When I pull out the math into a seperate function it always seems to return just the length of the string. That being said, just do `text.length()` if you do end up having to do math, make a int before you go into your for loop statement and put the math there. It will be easier to read." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-02-08T13:01:52.910", "Id": "34455", "Score": "0", "body": "@LuciC I think there might be a error in your math as well. I changed text to `\"longest longest duplicate duplicate\"` and the returned value is `duplicat` (no 'e' at the end)" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-02-08T13:45:37.490", "Id": "34459", "Score": "0", "body": "The problem you are describing can have more that one result. There can be 2 (or more) repeating substrings with the same length, both of them the longest." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-02-08T15:19:02.773", "Id": "34493", "Score": "0", "body": "@LuciC Please update the question with this information. Please give us some more information about what to optimize. If you just search for some working algorithm you could have a look at Sedgewick, Programming in Java here: http://introcs.cs.princeton.edu/java/42sort/ There is even an implementation." } ]
[ { "body": "<p>You may want to roll your own comparison method to compare two pieces of a string in-place, instead of using substring(), which as I understand creates an unnecessary temporary copy. It may look like this:</p>\n\n<pre><code>bool CompareInPlace(String text, int from1, int len1, int from2, int len2)\n{\n // ...\n}\n</code></pre>\n\n<p>Furthermore, instead of keeping a copy of the longest duplicat found, keep its indices from and len.\nThen in the end you can <code>return text.substring(longestFrom, longestLen);</code>.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-02-08T14:38:20.447", "Id": "34491", "Score": "3", "body": "substring() in java doesn't create a temporary copy of underlying char array but refers to to the same array as original string (start and end position in this array are different though)." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-02-08T22:12:06.000", "Id": "34525", "Score": "0", "body": "@Andrey - Agreed; due to the fact that `String`s are immutable, this is a trivial optimization. Still, a compare-in-place _may_ be warranted." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-02-11T11:57:30.447", "Id": "34665", "Score": "1", "body": "This probably depends on the JVM impelementation. If yours is not open source, benchmarking will tell. But even if the JVM is optimized in such a way, keeping only indices will at least save object creation and GC." } ], "meta_data": { "CommentCount": "3", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-02-08T11:54:33.330", "Id": "21466", "ParentId": "21463", "Score": "3" } }, { "body": "<ol>\n<li><p>I'd try using longer variable names and making the code a little bit <a href=\"http://www.codinghorror.com/blog/2006/01/flattening-arrow-code.html\" rel=\"nofollow\">more flatten</a>. Renaming <code>x</code> and <code>y</code> to <code>minLength</code> and <code>maxLength</code> seems a good start.</p></li>\n<li><p>Then I'd extract out some named variables for the following expressions:</p>\n\n<ul>\n<li><code>Math.min((text.length() - i -1)/2, y)</code></li>\n<li><code>i + j</code></li>\n<li><code>text.length() - 2 * longest.length() * 2</code></li>\n</ul>\n\n<p>Reference: <em>Chapter 6. Composing Methods</em>, <em>Introduce Explaining Variable</em> in <em>Refactoring: Improving the Design of Existing Code</em> by Martin Fowler</p>\n\n<blockquote>\n <p>Put the result of the expression, or parts of the expression, \n in a temporary variable with a name that explains the purpose.</p>\n</blockquote></li>\n</ol>\n\n<p>Here is a naive version which I think easier to understand:</p>\n\n<pre><code>public static String naiveLongestDuplicate(final String text, final int minLength, \n final int maxLength) {\n for (int length = maxLength; length &gt;= minLength; length--) {\n final String longestDuplicate = naiveLongestDuplicate(text, length);\n if (StringUtils.isNotEmpty(longestDuplicate)) {\n return longestDuplicate;\n }\n }\n\n return \"\";\n}\n\npublic static String naiveLongestDuplicate(final String text, final int length) {\n final Set&lt;String&gt; substrings = new HashSet&lt;String&gt;();\n for (int startIndex = 0; startIndex &lt;= text.length() - length; startIndex++) {\n final String substring = text.substring(startIndex, startIndex + length);\n if (substrings.contains(substring)) {\n return substring;\n }\n substrings.add(substring);\n }\n\n return \"\";\n}\n</code></pre>\n\n<p>And some tests:</p>\n\n<pre><code>import static org.junit.Assert.assertEquals;\n\nimport java.util.Arrays;\nimport java.util.Collection;\n\nimport org.junit.Test;\nimport org.junit.runner.RunWith;\nimport org.junit.runners.Parameterized;\nimport org.junit.runners.Parameterized.Parameters;\n\n@RunWith(value = Parameterized.class)\npublic class SearcherTest {\n\n private final String text;\n private final int minLength;\n private final int maxLength;\n private final String expectedResult;\n\n public SearcherTest(final String text, final int minLength, \n final int maxLength, final String expectedResult) {\n this.text = text;\n this.minLength = minLength;\n this.maxLength = maxLength;\n this.expectedResult = expectedResult;\n }\n\n @Parameters\n public static Collection&lt;Object[]&gt; data() {\n //@formatter:off\n final Object[][] data = new Object[][] {\n { \"abab\", 1, 2, \"ab\"}, // fails\n { \"abcabc\", 1, 2, \"ab\"},\n { \"abcabc\", 1, 3, \"abc\"}, // fails\n { \"abcabcd\", 1, 3, \"abc\"},\n { \"abcdxabce\", 1, 3, \"abc\"},\n { \"abcdxabce\", 3, 4, \"abc\"}, // fails\n { \"abcdxabcd\", 3, 4, \"abcd\"}, \n { \"abcdeabcde\", 3, 7, \"abcde\"}, // fails \n { \"aabbcc\", 3, 3, \"\"}, \n { \"WXabcWYabcWZ\", 1, 2, \"ab\"},\n { \"WXabcWYabcWZ\", 1, 3, \"abc\"},\n { \"WXaaWYbbWZccWW\", 3, 100, \"\"},\n { \"WWaaaaXXaaaaaYYaaaaaaZZaaaaaa\", 3, 6, \"aaaaaa\"},\n { \"WWaaaaXXaaaaaYYaaaaaaZZaaaaaa\", 3, 9, \"aaaaaa\"}\n };\n //@formatter:on\n return Arrays.asList(data);\n }\n\n @Test\n public void test() {\n assertEquals(expectedResult, \n Searcher.longestDuplicate(text, minLength, maxLength));\n }\n}\n</code></pre>\n\n<p>The ones which are marked with <code>// fails</code> fails with the posted code. (I haven't checked what's the cause. The test data looks fine for me but I'm not sure that I understood the requirements completely.)</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-02-11T21:16:00.883", "Id": "21592", "ParentId": "21463", "Score": "1" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "8", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-02-08T11:17:12.310", "Id": "21463", "Score": "1", "Tags": [ "java", "optimization" ], "Title": "Optimizing code: longest repeating substring" }
21463
<p>For the sake of learning JavaScript better and getting used to the Google Chrome Extension API, I'm currently writing a little Chrome extension.</p> <p>To keep things simple and being able to make use of prototypal inheritance, I decided to write a little instantiation/inheritance helper before I get started.</p> <p>But as I am still deep in the process of learning JavaScript, I would greatly appreciate if anyone could take a quick look at the code and clarify some points:</p> <ol> <li>Are there any pitfalls I could run into with some of the approaches?</li> <li>Is the code, as-is, or parts of it considered bad practice some weird constructions or similar?</li> <li>Did I miss some important aspects regarding inheritance itself?</li> </ol> <p></p> <pre><code>/* Inheritance Helper*/ var base = (function baseConstructor() { 'use strict'; var obj = { create: function instantiation() { if (this === base) { throw new SyntaxError("You can't create instances of base"); } else if (!this.hasOwnProperty("initclosure")) { throw new SyntaxError("Cannot create instances without an constructor"); } else if (this.singleton &amp;&amp; this.instances.length !== 0) { throw new SyntaxError("You can't create more than one Instance of a Singleton Class"); } else { var instance = Object.create(this.pub); this.init.apply(instance, arguments); this.instances.push(instance); return instance; } }, inherit: function inheritation(specsOpt) { specsOpt = specsOpt || {}; applyDefaults(specsOpt, { singleton: false, anonymous: false }); var sub = Object.create(this); sub.pub = Object.create(this.pub); sub.instances = []; sub.anonymous = specsOpt.anonymous; sub.sup = this; if (specsOpt.singleton) { sub.singleton = specsOpt.singleton; sub.getSingleton = getSingleton; protect.call(sub, { singleton: { writable: false, configurable: false, enumerable: false }, getSingleton: { writable: false, configurable: false } }); } return sub; }, initclosure: function Base() {}, instances: [], pub: { instanceOf: function (obj) { if (!obj) return this.className; return obj.pub.isPrototypeOf(this); } } }; /* Helper Functions. --- Use function expressions instead of declarations to get JSHint/Lint strict mode violations * * TODO: Maybe add an obj.helper Propertie with usefull functions */ var applyDefaults = function (target, obj) { for (var prop in obj) { if (obj.hasOwnProperty(prop)) { target[prop] = target[prop] || obj[prop]; } } }; var getSingleton = function () { //To get past the strict violation return this.instances[0]; }; var protect = function (props, desc) { //Maybe change it a little for (var prop in props) { if (props.hasOwnProperty) { Object.defineProperty(this, prop, props[prop] || desc); } } return this; }; /* End Helpers * * Protecting */ Object.defineProperty(obj, "init", { set: function (fn) { if (typeof fn !== "function") { throw new Error("Expected typeof init to be 'function'"); } else if (Boolean(fn.name) === this.anonymous) { throw new Error("Expected the constructor " + (!this.anonymous ? "not " : "") + "to be Anonymous"); } if (!this.hasOwnProperty("initclosure")) { this.initclosure = fn; this.pub.constructor = this.init; this.pub.className = fn.name; protect.call(this.pub, { constructor: false, className: false }, { enumerable: false }); } }, get: function () { var that = this; var init = function init() { if (that.pub.isPrototypeOf(this)) { that.initclosure.apply(this, arguments); } else { throw new Error("init can't be called directly"); } }; init.toString = function () { return that.initclosure.toString(); }; return init; } }); obj.toString = function () { return "[class " + (this.initclosure.name || "Class") + "]"; }; obj.pub.toString = function () { return "[instance " + (this.className || "Anonymous") + "]"; }; protect.call(obj, { create: false, inherit: false, toString: false, initclosure: { enumerable: false } }, { writable: false, configurable: false }); protect.call(obj.pub, { instanceOf: false, toString: false }, { writable: false, configurable: false, enumerable: false }); return obj; })(); </code></pre> <p>Here are some example console outputs as well as a <a href="http://jsbin.com/otiboy/1/edit" rel="nofollow noreferrer">JSBin</a>.</p> <pre><code>var Test = base.inherit(); Test.create(); //Uncaught SyntaxError: Cannot create instances without an constructor var Test2 = base.inherit(); Test2.init = function () { //Uncaught Error: Expected the constructor not to be Anonymous this.is = "a test"; }; var Test3 = base.inherit({singleton:true}); Test3.init = function Test() { this.is = "a test"; }; var instance1 = Test3.create(); console.log(instance1); //{is: "a test"} console.log(instance1.instanceOf()); //Test console.log(instance1.instanceOf(Test3)); //true alert(instance1); //[instance Test] var instance2 = Test3.create(); //Uncaught SyntaxError: You can't create more than one Instance of a Singleton Class var instance2 = new Test3.init(); //Uncaught Error: init can't be called directly </code></pre> <p>Here are a few more examples:</p> <pre><code>var Test4 = base.inherit(); Test4.init = function testingErrorStack(x) { this.prop = x.error; }; var instance1 = Test4.create({ error: "none" }); var instance2 = Test4.create({ error: "alsonone" }); try { var errorInstance = Test4.create(); } catch (e) { console.dir(e.stack); /*"TypeError: Cannot read property 'error' of undefined at init.testingErrorStack */ } console.log(instance1, instance2, errorInstance); //{"prop": "none"},{"prop": "alsonone"},undefined </code></pre> <p>You can see the constructor name in the errors stackTrace. And you can of course create multiple instances, as well as doing multiple inheritance and anonymous constructors.</p> <pre><code>var Test5 = base.inherit({ anonymous: true }); Test5.init = function (anotherProp, to) { this.anotherProp = anotherProp; this.from = "an"; this.to = to; }; var Test5_1 = Test5.inherit(); Test5_1.init = function test5SubClass(someProp) { Test5_1.sup.init.call(this, "has been passed", "a super class"); this.sub = someProp; }; var instance5 = Test5_1.create('"Class"'); console.log(instance5); //{"anotherProp": "has been passed", "from": "an", "sub": "\"Class\"", "to": "a super class"} </code></pre> <p>I thought about adding these as I got the feeling you might have misunderstood the purpose as an singleton pattern only helper.</p> <p>Isn't this still just a prototypal approach? I just thought it would be nice to have the benefits of proper prototypal inheritance through <code>Object.create</code> along with "constructors" to properly initialize the <code>Object</code>s.</p> <p>Here's a <a href="http://jsbin.com/oxabey/1/edit" rel="nofollow noreferrer">fiddle</a>.</p>
[]
[ { "body": "<blockquote>\n <p>Did I miss some important aspects regarding inheritance itself</p>\n</blockquote>\n\n<p>JavaScript uses prototypal inheritance, which is already quite simple. Here's an example:</p>\n\n<pre class=\"lang-js prettyprint-override\"><code>function Animal() {\n this.name = 'Animal';\n}\n\nAnimal.prototype.speak = function() {\n console.log('My name is ' + this.name);\n};\n\nvar animal = new Animal();\nanimal.speak(); // My name is Animal\n\nfunction Cat() {\n this.name = 'Cat';\n}\n\nCat.prototype = new Animal();\n\nvar cat = new Cat();\ncat.speak(); // My name is Cat\n</code></pre>\n\n<blockquote>\n <p>Are there any Pitfalls I could run into with some of the appraches</p>\n</blockquote>\n\n<p>This whole approach feels quite complicated, and I'm not sure that I understand the benefits of using this over prototypal inheritance. My advice would be to stick with existing patterns which are widely used and understood (e.g. this <a href=\"http://code.google.com/p/jslibs/wiki/JavascriptTips#Singleton_pattern\" rel=\"nofollow\">Singleton pattern</a>).</p>\n\n<blockquote>\n <p>Is the code, as is, or parts of it considered bad practice some weird constructions or similar</p>\n</blockquote>\n\n<p>Aside from feeling a little over-engineered, the only other feedback I have is that you don't need to name functions that are assigned to a variable. You could change</p>\n\n<pre class=\"lang-js prettyprint-override\"><code>var obj = {\n create: function instantiation() {\n } \n};\n</code></pre>\n\n<p>To</p>\n\n<pre class=\"lang-js prettyprint-override\"><code>var obj = {\n create: function() {\n } \n};\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-02-13T14:52:13.487", "Id": "34807", "Score": "0", "body": "The problem with this Approach is that you have to set the `prototype` of the constructor to an instance of another constructor which could lead to Problems, when initializing more complex constructors which require more parameters to get initialized correctly. You could of course use some intermediate constructors like described e.g in (this)[http://www.3site.eu/doc/#intermediate] article, but thats not what makes my heart goes boom." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-02-13T15:06:41.087", "Id": "34810", "Score": "1", "body": "And using named function expression gives you a huge benefit in debugging you applications as the stacktrace can provide you these names in case of errors, another good [article](http://kangax.github.com/nfe/) to read btw =)\nAlso does the Singleton pattern in the article you linked to use `arguments.callee` which is [forbidden](https://developer.mozilla.org/en-US/docs/JavaScript/Reference/Functions_and_function_scope/arguments/callee) in ES5s strict mode." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-02-13T15:26:04.520", "Id": "34811", "Score": "0", "body": "Many thanks for you answer and efforts btw, i really appreciate that =)" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-02-13T18:33:41.560", "Id": "34820", "Score": "0", "body": "I understand what you're saying, but it still seems to me like you're trying to bend and twist JavaScript into having classical inheritance. Once you \"get\" prototypal inheritance, you'll see that you can write much more simple code without the need for this sort of helper. If you do prefer classical inheritance though, you might want to check out [CoffeeScript](http://coffeescript.org/)." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-02-13T19:28:13.420", "Id": "34822", "Score": "0", "body": "=) It may be a kind of bending javascript.\nBut to be honest, i don't really have an idea of what classical inheritance really is, i just started programming about 8 Month ago, and 90% of what i did until now is learning javascript through trial/error a little bit of reading articles and answering questions on SO I didn't knew the Answer to.\nThe problem i had with the before ES5 prototypal inheritance, was the above mentioned, and Object.create alone couldn't construct Objects, so i started to kind of mix it. I wrote sth similar 8 month ago, and was being helped on SO. (many thx @Bergi)" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-02-13T19:30:13.720", "Id": "34823", "Score": "0", "body": "But as I wanted to write something in my free time again, i rewrote that (as it was nearly my first ever written javascript <- not good) with what i've learned until now.\nThe only thing i had to with classical inheritance was with the first java program i wrote a month ago(a simple 4connect with AI) but how inheritance worked there is not really what i got in mind with this inheritance helper." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-02-13T19:30:37.727", "Id": "34824", "Score": "0", "body": "Oh and coffeescript looks really interesting, though the syntax looks more complicated to me than javascript on the first look.\nand why coffeescript for classical inheritance? doesn't it compile to javscript?" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-02-13T20:52:36.713", "Id": "34826", "Score": "0", "body": "Yeah CoffeeScript does compile to JavaScript. It essentially gives JavaScript an almost Ruby-like syntax and in doing so reduces the amount of code you need to write for common tasks. I've used it a fair bit and while I do enjoy writing it, I find it a lot harder to read (and therefore maintain). I guess it's down to personal taste." } ], "meta_data": { "CommentCount": "8", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-02-13T14:32:40.363", "Id": "21662", "ParentId": "21469", "Score": "2" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-02-08T13:45:37.820", "Id": "21469", "Score": "4", "Tags": [ "javascript", "inheritance", "google-chrome" ], "Title": "Instantiation/Inheritance Helper" }
21469
<p>I'm trying to optimise my implementation of a static kd tree to perform orthogonal range searches in C++.</p> <p>My problem: The code performs slowly even for a small number of queries when the number of points is around 10<sup>5</sup>.</p> <p>I've constructed the tree based on <a href="http://en.wikipedia.org/wiki/K-d_tree" rel="nofollow">this</a> (i.e, It's a static kd tree where the data is stored both in the nodes and the leaves) and the orthogonal range searching algorithm based on Ch 11 of <a href="http://www.cs.umd.edu/~mount/754/Lects/754lects.pdf" rel="nofollow">this</a>.</p> <p>Relevant algorithm: (My implementation returns the points instead of count)</p> <pre><code>int rangeCount(Range Q, KDNode t, Rectangle C) (1) if (t is a leaf) (a) if (Q contains t) return 1, (b) else return 0. (2) if (t is not a leaf) (a) if (C does not intersect Q) return 0. (b) else if (C is a subset of Q) return t:size. (c) else, split C along t’s cutting dimension and cutting value, letting C1 and C2 be the two rectangles. Return (rangeCount(Q; t:left; C1) + rangeCount(Q; t:right; C2)). </code></pre> <p>My code (the relevant function is the 2nd <code>recursive_query()</code>):</p> <pre><code>#include &lt;iostream&gt; #include &lt;algorithm&gt; #include &lt;cstdio&gt; #include &lt;vector&gt; #include &lt;random&gt; #include &lt;chrono&gt; using namespace std; typedef long long ll; typedef pair&lt;int, int&gt; T; typedef pair&lt;pair&lt;int, int&gt;, pair&lt;int, int&gt; &gt; R; bool comp_x(const T &amp;a, const T &amp;b) { return a.first &lt; b.first; } bool comp_y(const T &amp;a, const T &amp;b) { return a.second &lt; b.second; } template&lt;int k=2&gt; class kd_tree { private: vector&lt;T&gt; array; // array[0] is a dummy int N; void recursive_build(int depth, int node, int begin, int end, vector&lt;T&gt; &amp;elements) { if(end &lt; begin) return; if(begin == end){ array[node] = elements[begin]; return; } int axis = depth % k; int median; // Find median for axis (Todo: Implement quickselect) if(axis == 0) // x-axis { sort(elements.begin()+begin, elements.begin()+end+1, comp_x); median = (begin+end+1)/2; } else { sort(elements.begin()+begin, elements.begin()+end+1, comp_y); median = (begin+end+1)/2; } array[node] = elements[median]; recursive_build(depth+1, 2*node, begin, median-1, elements); recursive_build(depth+1, 2*node+1, median+1, end, elements); } void return_subtree(int node, vector&lt;T&gt; &amp;query_list) { if(node &gt; N || array[node].first == 0) return; query_list.push_back(array[node]); return_subtree(2*node, query_list); return_subtree(2*node+1, query_list); } void recursive_query(int depth, int node, int x1, int y1, int x2, int y2, vector&lt;T&gt; &amp;query) { if(node &gt; N) return; int axis = depth % k; if(axis == 0) // x-axis { if(array[node].first &lt; x1) { recursive_query(depth+1, 2*node+1, x1, y1, x2, y2, query); } else if(array[node].first &gt; x2) { recursive_query(depth+1, 2*node, x1, y1, x2, y2, query); } else { if(array[node].second &gt;= y1 &amp;&amp; array[node].second &lt;= y2) query.push_back(array[node]); recursive_query(depth+1, 2*node, x1, y1, x2, y2, query); recursive_query(depth+1, 2*node+1, x1, y1, x2, y2, query); } } else { if(array[node].second &lt; y1) { recursive_query(depth+1, 2*node+1, x1, y1, x2, y2, query); } else if(array[node].second &gt; y2) { recursive_query(depth+1, 2*node, x1, y1, x2, y2, query); } else { if(array[node].first &gt;= x1 &amp;&amp; array[node].first &lt;= x2) query.push_back(array[node]); recursive_query(depth+1, 2*node, x1, y1, x2, y2, query); recursive_query(depth+1, 2*node+1, x1, y1, x2, y2, query); } } } void recursive_query(int depth, int node, R cell, R query, vector&lt;T&gt; &amp;query_list) { int left = 2*node; int right = 2*node+1; // node is a leaf node if(array[left].first == 0 &amp;&amp; array[right].first == 0) { // if the leaf lies inside the query rectangle then add it to query_list if(array[node].first &gt;= query.first.first &amp;&amp; array[node].first &lt;= query.second.first &amp;&amp; array[node].second &gt;= query.first.second &amp;&amp; array[node].second &lt;= query.second.second) { query_list.push_back(array[node]); } return; } // node is not a leaf // cell doesnt intersect the query if(cell.first.first &gt; query.second.first || cell.second.first &lt; query.first.first || cell.first.second &gt; query.second.second || cell.second.second &lt; query.first.second) { return; } // cell is a subset of query if(cell.first.first &gt;= query.first.first &amp;&amp; cell.second.first &lt;= query.second.first &amp;&amp; cell.first.second &gt;= query.first.second &amp;&amp; cell.second.second &lt;= query.second.second) { return_subtree(node, query_list); return; } // if the node lies within bounds then add it to query_list if(array[node].first &gt;= query.first.first &amp;&amp; array[node].first &lt;= query.second.first &amp;&amp; array[node].second &gt;= query.first.second &amp;&amp; array[node].second &lt;= query.second.second) { query_list.push_back(array[node]); } depth = depth % k; if(depth == 0) // splitting planes is the x-axis { if(array[left].first != 0){ R cell1 = make_pair(cell.first, make_pair(array[node].first, cell.second.second)); recursive_query(depth+1, left, cell1, query, query_list); } if(array[right].first != 0){ R cell2 = make_pair(make_pair(array[node].first, cell.first.second), cell.second); recursive_query(depth+1, right, cell2, query, query_list); } } else // splitting plane is the y-axis { if(array[left].first != 0){ R cell1 = make_pair(cell.first, make_pair(cell.second.first, array[node].second)); recursive_query(depth+1, left, cell1, query, query_list); } if(array[right].first != 0){ R cell2 = make_pair(make_pair(cell.first.first, array[node].second), cell.second); recursive_query(depth+1, right, cell2, query, query_list); } } } public: kd_tree(vector&lt;T&gt; &amp;elements) { N = elements.size(); array.resize(2*k*N+1); recursive_build(0, 1, 0, N-1, elements); } void orthogonal_query(int x1, int y1, int x2, int y2, vector&lt;T&gt; &amp;query_list) { // recursive_query(0, 1, x1, y1, x2, y2, query_list); recursive_query(0, 1, make_pair(make_pair(1, 1), make_pair(300000, 300000)), make_pair(make_pair(x1, y1), make_pair(x2, y2)), query_list); } }; int main(void) { std::mt19937_64 generator; std::uniform_int_distribution&lt;int&gt; distribution(0, 300000); int n, q, x, y, d, count; // scanf("%d %d", &amp;n, &amp;q); n = 30000; q = 2000; vector&lt;pair&lt;int, int&gt; &gt; points, query; vector&lt;pair&lt;int, int&gt; &gt;::iterator itr; // Input Phase while (n--){ // scanf("%d %d", &amp;x, &amp;y); x = distribution(generator); y = distribution(generator); points.push_back(make_pair(x, y)); } kd_tree&lt;2&gt; tree(points); std::chrono::time_point&lt;std::chrono::high_resolution_clock&gt; start, end; start = std::chrono::high_resolution_clock::now(); // Query Loop while(q--){ query.clear(); // scanf("%d %d %d", &amp;x, &amp;y, &amp;d); x = distribution(generator); y = distribution(generator); d = distribution(generator); int d1 = x+y+d; tree.orthogonal_query(x, y, x+d, y+d, query); // printf("%d\n", count); } end = std::chrono::high_resolution_clock::now(); ll elapsed_time = std::chrono::duration_cast&lt;std::chrono::milliseconds&gt;(end-start).count(); cout &lt;&lt; "\nElapsed Time: " &lt;&lt; elapsed_time &lt;&lt; "ms\n"; return 0; } </code></pre>
[ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-02-08T04:24:45.843", "Id": "34466", "Score": "0", "body": "That's a lot of code to have us look at. Might I consider using a profiler? http://www.cs.utah.edu/dept/old/texinfo/as/gprof_toc.html" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-02-08T05:00:54.407", "Id": "34467", "Score": "0", "body": "@Louis Most of the time seems to be spend in the return_subtree function. Commenting out this function seemed to improve the time taken by a factor of roughly log(n)/10, bringing the time for n = 10^5 and number of queries, q = 10^5 to around a few seconds. So I guess i'll have to modify my kdtree to preprocess this part" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-02-08T07:45:27.967", "Id": "34468", "Score": "1", "body": "@IshanBhatnagar: I really encourage you to use structures instead of \"pairs\", a pair of pairs of int is not too self-describing. A pair of points already makes a bit more sense. A rectangle (defined by two points) is even better." } ]
[ { "body": "<p>You could make the <code>return_subtree</code> function non-recursive by using a <code>stack</code> object by yourself:</p>\n\n<pre><code>void return_subtree(int node, vector&lt;T&gt; &amp;query_list)\n{\n if (node &gt; N) { return; }\n\n std::stack&lt;int&gt; st;\n st.push(node);\n\n while (not st.empty()) {\n int top = st.top();\n st.pop();\n\n // if array[top].first == 0, then the recursion ends...\n // ... BUT it still need be returned!\n if (top &gt; N) { continue; }\n\n query_list.push_back(array[top]);\n if(array[top].first == 0) { continue; }\n\n st.push(2 * top + 1);\n st.push(2*node+1);\n }\n}\n</code></pre>\n\n<p>This could lead to a speed up because <code>return_subtree</code> cannot be tail-call optimized (or at least, only the latest call may be optimized), and therefore the compiler is probably unable to come up with this optimization by itself...</p>\n\n<p>... which of course brings us to the crux of the matter: turn your compiler optimizations on (-Os or -O2 flag on the command line for gcc/clang).</p>\n\n<p>Other than that, I don't see any glaring inefficiency.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-02-08T09:02:57.277", "Id": "34469", "Score": "0", "body": "I actually eliminated this entire thing by storing a vector at each node that stores the points contained in its subtree. (Memory intensive (takes around 80MB for n = 10^5), but it reduced the time taken by a factor of around 10). Currently the entire code is 50 times slower than what it need it to be. So it has to something in the algorithm." } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-02-08T07:55:03.750", "Id": "21471", "ParentId": "21470", "Score": "1" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "3", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-02-08T04:13:41.700", "Id": "21470", "Score": "5", "Tags": [ "c++", "optimization", "c++11", "tree", "interval" ], "Title": "Orthogonal range search for a static kd tree" }
21470
<p>Can anyone please tell which one is the more effective way to write C# code, among the two options below?</p> <p>Option A:</p> <pre><code>internal static string GetLast3Years() { return (DateTime.Now.Year - 2).ToString() + "," + (DateTime.Now.Year - 1).ToString() + "," + DateTime.Now.Year.ToString(); } </code></pre> <p>Or option B:</p> <pre><code>internal static string GetLast3Years() { int currentYear = DateTime.Now.Year; return (currentYear - 2).ToString() + "," + (currentYear - 1).ToString() + "," + currentYear.ToString(); } </code></pre>
[ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-02-07T17:07:46.227", "Id": "34470", "Score": "0", "body": "Neither is particularly good..." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-02-07T17:08:04.793", "Id": "34471", "Score": "0", "body": "Option B, because it fetches the value only once. Ugly code though." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-02-07T17:08:19.487", "Id": "34472", "Score": "0", "body": "Maybe the second option is better, as you get only once DateTime.Now and cache it in an int variable, anyway I don't thing there is much difference in this case." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-02-07T17:08:37.827", "Id": "34473", "Score": "2", "body": "You should not usually worry about such trivial optimizations. A lot of times a release build and the CLR itself will take care of such things. Alternatively you could test which one is better in `your context` yourself with some diagnoses." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-02-07T17:09:50.330", "Id": "34474", "Score": "0", "body": "@VasilTrifonov _Cached_ in an int variable?" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-02-07T17:13:21.167", "Id": "34475", "Score": "0", "body": "With respect to the other comments, you may find that both are the same performance wise as the values may get inlined at compile time - the only way you can test which is the `best` is by testing. Also, what if you decide that you want the last 4 years. Last 5 years? Last 100 Years? Regardless of how neat the code is, your implementation is now fixed. What if you wanted the Last 3 years from a date in the past?" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-02-07T17:13:36.637", "Id": "34476", "Score": "1", "body": "I'd use: `return string.Join(\",\", Enumerable.Range(DateTime.Now.Year-2, 3));`" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-02-07T17:15:48.840", "Id": "34477", "Score": "0", "body": "@Servy That's brilliant as you can also parameterize every part of it; the start, and even the offset. Effectively - `GetNYearsFromDate(int startYear, int offset, int numberOfYears)`" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-02-07T17:20:41.770", "Id": "34478", "Score": "0", "body": "@dash Yes, exactly." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-02-07T17:25:25.150", "Id": "34479", "Score": "2", "body": "@Servy Nice, though that's a lot slower than the other two methods provided." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-02-07T17:28:13.957", "Id": "34480", "Score": "0", "body": "@DGibbs Did you actually time it at all? I would doubt it's significantly different. It's more likely to just be a tiny bit slower. Also this is almost certainly not a performance bottleneck in code; making the code \"better\" for a method like this is all about making it more readable, easier to maintain or generalize, etc. If it happens to take a few nanoseconds longer nobody is ever going to know." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-02-07T17:32:07.167", "Id": "34481", "Score": "0", "body": "@Servy Method A: 0.65ns, Method B: 0.15ns, Method C (yours): 3.43ns. Though it is obviously much more flexible/readable than the code OP has posted, plus _\"premature optimization is the root of all evil\"_ as a wise man once said." } ]
[ { "body": "<p>I will do it the following way</p>\n\n<pre><code> internal static string GetLast3Years()\n {\n int currentYear = DateTime.Now.Year; \n\n return String.Format(\"{0},{1},{2}\", currentYear - 2, currentYear - 1, currentYear);\n }\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-02-07T17:12:22.710", "Id": "34482", "Score": "1", "body": "technically not an answer to the question." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-02-07T17:14:22.157", "Id": "34483", "Score": "0", "body": "@Servy He wants the more effective way of writing between the two options he wrote. and I modify it and give him a better solution. What is the problem" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-02-07T17:14:26.157", "Id": "34484", "Score": "1", "body": "Can you explain why this is better than the code in the OP rather than just say you would do it a certain way, and not provide any reasoning?" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-02-07T17:15:41.970", "Id": "34485", "Score": "0", "body": "@DanHunex No, that's not what he asked at all. He asked which of the two options provided is better, he didn't ask for a third option that's better than both." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-02-07T17:17:27.283", "Id": "34486", "Score": "0", "body": "@Servy, you give him third option in the comment above . Btw, Yes I choose the second method he wrote but improved. U still didnt get" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-02-07T17:20:25.390", "Id": "34487", "Score": "0", "body": "@DanHunex You are correct I did. I was not answering the question when I provided that code, which is why it was posted as a comment and not an answer. No, you didn't say to use option B, you just incorporated part of that option in your answer. Your \"answer\" also has no explanation of it's code, no reasoning for your decisions, etc." } ], "meta_data": { "CommentCount": "6", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-02-07T17:11:40.850", "Id": "21473", "ParentId": "21472", "Score": "1" } }, { "body": "<p>Note that semantically these options are not equal. </p>\n\n<p>There is a chance (very-very small) that first option will output smth like <code>2011,2012,2014</code>, so second option is better at least because it will always generate consistent results (3 consecutive years).</p>\n\n<p>But second option is also quite cluttered. There is a <a href=\"http://msdn.microsoft.com/en-us/library/dd988350.aspx\" rel=\"nofollow\"><code>string.Join</code></a> method that is able to combine different values with separator, so your code may look like:</p>\n\n<pre><code>internal static string GetLast3Years()\n{\n int currentYear = DateTime.Now.Year;\n return string.Join(\",\", currentYear - 2, currentYear - 1, currentYear);\n}\n</code></pre>\n\n<p>But the question is still why would you need a string representation of last 3 years, comma-separated. I would consider having a method that will return enumerable of last N years instead...</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-02-08T15:05:50.960", "Id": "21477", "ParentId": "21472", "Score": "2" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "12", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-02-07T17:02:48.287", "Id": "21472", "Score": "2", "Tags": [ "c#" ], "Title": "Should I use an intermediate variable in a complex C# expression?" }
21472
<p>I'd like to find a way to do what this method does in a cleaner, less hacky looking way </p> <pre><code> def self.create_from_person!(person) spi = new(:person =&gt; person, :provider =&gt; person.provider) spi.age_eligible_code = participant.age_eligible?(person) ? 1 : 2 spi.county_of_residence_code = participant.psu_county_eligible?(person) ? 1 : 2 spi.first_prenatal_visit_code = participant.first_visit?(person) ? 1 : 2 spi.pregnancy_eligible_code = participant.pbs_pregnant?(person) ? 1 : 2 spi.save! end </code></pre> <p>Any thoughts?</p>
[ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-02-08T16:21:50.143", "Id": "34498", "Score": "0", "body": "where does `participant` come from?" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-02-08T16:26:07.027", "Id": "34499", "Score": "0", "body": "@tokland `participant` is from a different model. I have some doubt that the eligibility methods belong there instead of on `Person` but thats not directly related to the feature I am working on. In case your interested the `Participant` model and the rest of the project is [here](https://github.com/NUBIC/ncs_navigator_core/blob/master/app/models/participant.rb) I like the refactoring below and I'm thinking about submitting it as part of my commit, if thats okay with you" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-02-08T16:42:52.503", "Id": "34500", "Score": "0", "body": "It's ok, of course. But I still don't see where is `participant` defined. To be called from a classmethod it should be a classmethod as well, but with that name it doesn't look like one." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-02-08T17:23:39.217", "Id": "34502", "Score": "0", "body": "ah, right. its a bug with my implementation from above. Its defined as an association on person so there should be a line above that is like `participant = person.participant`. Thanks." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-02-08T17:34:20.817", "Id": "34505", "Score": "0", "body": "ok! that's what it seemed, a local variable yet to be defined." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-02-12T11:54:17.577", "Id": "34721", "Score": "0", "body": "What model is this method in?" } ]
[ { "body": "<p>Notes:</p>\n\n<ul>\n<li>Any reason not to set the attributes in a single <code>create</code> step? </li>\n<li>DRY by using procs for short-lived functions.</li>\n<li>Methods should return meaningful values. Here it makes sense to return the newly created object.</li>\n<li>(As Mark pointed out) The mismatch names between attributes makes the code more verbose that it should be. However, I guess part of this mismatch already comes from the app you are patching.</li>\n<li><code>:provider =&gt; person.provider</code>. Note that this can break referential integrity. Person may change its provider in the future, but this model will remain as it is.</li>\n</ul>\n\n<p>I'd write:</p>\n\n<pre><code>def self.create_from_person!(person)\n code = lambda { |value| value ? 1 : 2 }\n create!({\n :person =&gt; person, \n :provider =&gt; person.provider,\n :age_eligible_code =&gt; code[participant.age_eligible?(person)],\n :county_of_residence_code =&gt; code[participant.psu_county_eligible?(person)],\n :first_prenatal_visit_code =&gt; code[participant.first_visit?(person)],\n :pregnancy_eligible_code =&gt; code[participant.pbs_pregnant?(person)],\n })\nend\n</code></pre>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-02-08T15:37:38.137", "Id": "21479", "ParentId": "21475", "Score": "6" } }, { "body": "<p>The reason why it doesn't look clean is because the underlying models are inconsistent.</p>\n\n<p>In one, you return a boolean true/false for <code>age_eligible?</code> and in another, you call it <code>age_eligible_code</code> and store a 1 for true and 2 for false. If these were aligned such that they were both boolean values, you wouldn't need any ternary operators at all.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-02-12T13:47:35.693", "Id": "34741", "Score": "0", "body": "Indeed, also the \":provider => person.provider\" may create inconsistencies in the SQL tables." } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-02-12T12:39:34.793", "Id": "21618", "ParentId": "21475", "Score": "2" } } ]
{ "AcceptedAnswerId": "21479", "CommentCount": "6", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-02-08T14:45:11.067", "Id": "21475", "Score": "1", "Tags": [ "ruby", "ruby-on-rails" ], "Title": "An abundance of ternary operators" }
21475
<p>I'm working on a javascript intensive user-interface application. (At least it's intensive for me, it's my first serious javascript project).</p> <p>I have a few jquery functions going whenever a div is rolled over or mouseout. For example there are some divs which are draggable objects, and so when they are mouseovered, the cursor must look ready to move. But my interface so slow that my boss thinks my code isn't working, when in fact it is, but it's just slow and so the user has to sometimes wait upto 2-3 seconds for the cursor to look as expected, or for a div to look as expected. Just an example. My code is something like below, I can't reproduce it entirely or properly since my company has copyrights on this, so I've written some lines as comments just to give a clear idea of the way I'm doing things. There's more to it, but this is basically what it's like:</p> <pre><code>$.fn.extend({ mouseoverBox: function() { return this.each(function() { var $this = $(this); if(!$this.hasClass('ready')) { if($this.hasClass('activated')) { $this.removeClass('activated'); } $this.addClass('ready'); } var img_id = $this.children('.theimg').attr('id'); //someitem.children('somechildren').remove(); //someitem.append(somemenu div) //$this.draggable(); //$this.resizable(); if($this.hasClass('unlocked')) { $this.draggable( "option", "disabled", false ); $this.resizable( "option", "disabled", false ); } $this.bindUnlock(); }); } // end mouseoverBox }); </code></pre> <p>Now this is just the mouseoverBox function, which is triggered like myBox.mouseoverBox(). on the mouse over event. Then of course this plugin is calling bindUnlock() which has simple operations like changing classes and adding classes to a menu. Also, before any mouseover, there's usually been a mouseout out of another div... so as you can see there's a lot of stuff happening. There aren't usually more than 10 interactive divs on at any one moment though. How can I optimize this kind of code? I haven't given every specific but trust me most of the relevant is pretty much just like this.</p> <p>I've already gzipped my javascript, css, images and fonts. I also tried minifying using the Yahoo Compressor but it actually bloated one of my files instead of compressing it.</p>
[ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-02-09T13:44:38.413", "Id": "34560", "Score": "0", "body": "Can't help with the timing, but a small refactoring suggestion: replace the body of the first if with: $this.removeClass('activated').addClass('ready'). Depending on what you need, it may be suitable to replace both if's with $this.removeClass('ready').removeClass('activated').addClass('ready')" } ]
[ { "body": "<p>Without actual code, we cannot review it if it actually contains significant issues. Thus, I've set forth guidelines instead.</p>\n<h1>Compression</h1>\n<p>The real help that compression does is actually speeding up loading times. Unless you are actually loading scripts on demand on mouseover, then you might need to compress them.</p>\n<p>However, a better solution is to actually preload these resources, or load them in parallel, and execute once available. That's pretty much how RequireJS does things. That way, you are not actually waiting for resources. The same thing is also true for other resources like fonts, images, cursors, videos and all the rest.</p>\n<h1>Other scripts</h1>\n<p>Anyways, there are a lot of things that could cause your script to go wrong, and that includes other scripts on the page. Due to the fact that JS is naturally single-threaded (unless made to thread), any blocking operation, be it in other scripts or within your script, could potentially be slowing down your entire operation. An example is a very long loop, or SJAX (Synchronouse XHR).</p>\n<p>To make sure that it's not your script that's breaking apart, try isolating your development enviroment to only your script and a minimal version of the UI and without other scripts. Also, test other functionalities on the page <em>without</em> your script to verify that it's another script that is causing the problem.</p>\n<h1>&gt;700ms === lag</h1>\n<p>Yes, that's true. According to a YUI video on their YouTube channel, 200ms is considered &quot;instant&quot; in the perspective of the user. That also explains that game latencies of &lt;200 are best. However, in your case, 2-3 seconds? The user has already left your page by then.</p>\n<p>Aim for responsiveness that are less than or are in the range of 200-300ms. And yes, your boss is for real and knows what he's doing.</p>\n<h1>Hey! Cache!</h1>\n<p>Your script is potentially DOM heavy by its looks and description. But DOM manipulation is heavy work. Cache as much as possible whenever possible, especially on elements that don't change over the lifetime of the page.</p>\n<p>Also, minimize fetching stuff on the DOM.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-02-09T12:55:05.890", "Id": "34555", "Score": "0", "body": "Thanks! Yes I'm sure the problem would the DOM manipulation - I'm constantly doing that in my code. It's basically a WYSIWYG editor that allows users to play around with text boxes and upload images and move them around too, so I have no choice. But could you please elaborate a bit on the \"caching\"?" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-02-09T12:57:16.263", "Id": "34556", "Score": "1", "body": "@user961627 caching. If certain elements don't change throughout the life of the page, it makes no sense calling `$('selector_here')` every time to get that element. Instead, you store it in a variable and refer to that variable instead." } ], "meta_data": { "CommentCount": "2", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-02-09T12:25:44.397", "Id": "21513", "ParentId": "21480", "Score": "2" } } ]
{ "AcceptedAnswerId": "21513", "CommentCount": "1", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-02-08T16:12:43.463", "Id": "21480", "Score": "0", "Tags": [ "javascript", "jquery", "optimization", "user-interface" ], "Title": "Optimizing a jquery user interface application" }
21480
<p>I'm currently changing some legacy code over to PDO. The below code works, but not 100%. I would like to know if it's best practice or if anything can be done better.</p> <pre><code>//Database Array $config['db'] = array( 'host' =&gt; 'localhost', 'username' =&gt; 'root', 'password' =&gt; 'root', 'dbname' =&gt; 'local'); //New PDO $db = new PDO('mysql:host=' . $config['db']['host'] . ';dbname=' . $config['db']['dbname'], $config['db']['username'], $config['db']['password']); $db-&gt;setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION); //Check connection is ok try { $db-&gt;exec("SET CHARACTER SET utf8"); } catch (PDOException $ex) { print "Error!: " . $ex-&gt;getMessage() . "&lt;br/&gt;"; die(); } //Update users function function update($db, $fn, $ln, $email, $offers, $vlue, $response) { $stmt = $db-&gt;prepare("insert into local (fName_765, lName_765, email_765, signup_765) values (:fname, :lname, :email, :signup, NOW())"); $stmt-&gt;bindParam(':fname', $fn, PDO::PARAM_STR); $stmt-&gt;bindParam(':lname', $ln, PDO::PARAM_STR); $stmt-&gt;bindParam(':email', $email, PDO::PARAM_STR); $stmt-&gt;bindParam(':signup', $offers, PDO::PARAM_STR); try { $stmt-&gt;execute(); print $db-&gt;lastInsertId(); //show ID return true; } catch (PDOException $e) { print "Error!: " . $e-&gt;getMessage() . "&lt;br/&gt;"; // show error return false; } } //Test Attributes $fn = 'test'; $ln = 'test'; $email = 'tesst@test,com'; $offers = '1'; if (!update($db, $fn, $ln, $email, $offers, $vlue, $response)) { echo "no update there is a slight problem"; } else { echo "it seemed to work"; } </code></pre> <p><strong>Midified version:</strong></p> <pre><code>$functionError = array(); //Database Array $config['db'] = array( 'host' =&gt; 'localhost', 'username' =&gt; 'root', 'password' =&gt; 'root', 'dbname' =&gt; 'root'); //Check connection is ok try { $db = new PDO('mysql:host=' . $config['db']['host'] . ';dbname=' . $config['db']['dbname'], $config['db']['username'], $config['db']['password']); $db-&gt;setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION); } catch (PDOException $e) { $functionError[] = "&lt;p&gt;{DB} - Error!: " . $e-&gt;getMessage() . "&lt;/p&gt;"; errorhandler ($functionError); die (); } //Error Handler function errorhandler ($functionError) { print_r ($functionError); echo "Sorry we are experiencing issues we are aware of the problem"; } //Update users function function update($db, $fn, $ln, $email, $offers, $vlue, $response) { $stmt = $db-&gt;prepare("insert into kkt (fName_765, lName_765, email_765, signup_765, kkt_resp_765, kkt_respSate_765, stamp_765) values (:fname, :lname, :email, :signup, :kkt_rsp, :kkt_respState, NOW())"); $parameters = array( ':fname' =&gt; $fn, ':lname' =&gt; $ln, ':email' =&gt; $email, ':signup' =&gt; $offers, ':kkt_rsp' =&gt; $vlue, ':kkt_respState' =&gt; $response); try { $stmt-&gt;execute($parameters); return true; } catch (PDOException $ex) { $functionError[] = "&lt;p&gt;{INSERT} - Error!: " . $ex-&gt;getMessage() . "&lt;/p&gt;"; errorhandler ($functionError); return false; } } //Test Attributes $fn = 'test'; $ln = 'test'; $email = 'tesst@test,com'; $offers = '1'; $vlue = 'value'; $response = 'resp'; if (update($db, $fn, $ln, $email, $offers, $vlue, $response)) { echo "it seemed to work"; print $db-&gt;lastInsertId(); header('Location: thank-you.php'); exit; } </code></pre>
[ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-02-12T14:15:37.603", "Id": "34742", "Score": "0", "body": "Please declare cross-posting, to reduce duplication of effort (from [here](http://stackoverflow.com/q/14809804/472495)). Normally not declaring is a downvoteable offence, but I'll resist this time! `;-)`" } ]
[ { "body": "<p>Here are a few things I noticed.</p>\n\n<ol>\n<li><p>If you are going to catch a possible exception when you connect to your MySQL DB you want to include the PDO instantiation in the try block.</p>\n\n<pre><code>try { \n $db = new PDO('mysql:host=' . $config['db']['host'] . ';dbname=' . $config['db'}['dbname'], $config['db']['username'], $config['db']['password']);\n $db-&gt;setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);\n $db-&gt;exec(\"SET CHARACTER SET utf8\");\n} catch(PDOException $e) { \n print \"Error!: \" . $ex-&gt;getMessage() . \"&lt;br/&gt;\";\n die(); \n}\n</code></pre></li>\n<li><p>The arguments $vlue and $response don't do anything in your update function. You probably want to get rid of those.</p></li>\n<li><p>You can use a quicker syntax for binding parameters by defining an array that holds the values and passing it to PDOStatement::execute(). This has the benefit of less function calls. Doing it this way will default all parameter value datatypes to be PDO::PARAM_STR, which matches what you are doing currently.</p>\n\n<pre><code>$parameters = array(\n ':fname' =&gt; $fn,\n ':lname' =&gt; $ln,\n ':email' =&gt; $email,\n ':signup' =&gt; $offers\n);\n$stmt-&gt;execute($parameters);\n</code></pre></li>\n<li><p>The point of exceptions is to be able to handle, on your own terms, exceptional events. If a PDO exception occurs in your update function, more than likely it won't/shouldn't know how to handle it. It makes more sense for the code that calls update to take care of that situation. So I would suggest moving the try/catch block to wherever the update function is called.</p>\n\n<pre><code> try {\n update($db, $fn, $ln, $email, $offers, $vlue, $response)\n } catch (PDOException $e) {\n echo \"no update there is a slight problem \" . $e-&gt;getMessage();\n }\n</code></pre></li>\n</ol>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-02-11T09:54:06.913", "Id": "34660", "Score": "0", "body": "I have modified based on your feed back thank you, and it all makes sense. the reason behind the if(!update was i need to know if it was successful so i can carry on with the code. Is it best practice to add an if update was TRUE under my code to then run some other code. thanks in advance" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-02-11T11:59:05.727", "Id": "34666", "Score": "0", "body": "update with a few more functions if you have time would be great for some feedback" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-02-12T00:16:28.473", "Id": "34695", "Score": "0", "body": "PDOStatement::execute returns true on success and false on failure, so you can do something like $result = $stmt->execute($parameters), then at the end of function, return $result." } ], "meta_data": { "CommentCount": "3", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-02-09T04:30:18.680", "Id": "21493", "ParentId": "21481", "Score": "5" } } ]
{ "AcceptedAnswerId": "21493", "CommentCount": "1", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-02-08T16:52:30.007", "Id": "21481", "Score": "0", "Tags": [ "php", "pdo" ], "Title": "PDO connection / prep and execute in their own functions" }
21481
<p>I've began to read the book <em>Clean Code</em> by Robert Martin. I've had a strong desire to learn how to write clear, easy-to-understand from other people. The <code>ColorViewer</code> application allows you to view the color in different formats.</p> <p><a href="https://github.com/SemenovLeonid/ColorViewer" rel="nofollow">Application on GitHub.com</a></p> <p><strong>ColorViewerActivity.java</strong></p> <pre><code>public class ColorViewerActivity extends Activity { @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_color_viewer); setUp(); panelFactory.buildPanel(currentColorFormat); } @Override public boolean onCreateOptionsMenu(Menu menu) { radioButtonMenu = new RadioButtonMenu(menu); radioButtonMenu.addItems(ColorFormat.getNamesOfAllColorFormats()); radioButtonMenu.setChecked(currentColorFormat.name()); return true; } @Override public boolean onOptionsItemSelected(MenuItem item) { if (!item.isChecked()) { ColorFormat chosenColorFormat = getColorFormatOfMenuItem(item); panelFactory.rebuildPanel(chosenColorFormat); currentColorFormat = chosenColorFormat; radioButtonMenu.setChecked(item); } return true; } @Override protected void onDestroy() { if (isChangingConfigurations()) { saveCurrentColorFormatAndBackgroundColor(); } else { saverLoader.deleteAllStoredValues(); } super.onDestroy(); } // Bad method name. public void setColor(Color newColor) { activityLayout.setBackgroundColor(newColor.getIntegerValue()); descriptionOfColor.setText(newColor.getDescriptionText()); descriptionOfColor.setTextColor(getInvertedColor(newColor.getIntegerValue())); } public int getBackgroundColor() { ColorDrawable colorDrawable = (ColorDrawable) activityLayout.getBackground(); return colorDrawable.getColor(); } private SaverLoader saverLoader; private ColorFormat currentColorFormat; private ColorViewerPanelFactory panelFactory; private RadioButtonMenu radioButtonMenu; private TextView descriptionOfColor; private View activityLayout; private void setUp() { descriptionOfColor = (TextView) findViewById(R.id.descriptionOfColor); activityLayout = findViewById(R.id.activityLayout); saverLoader = SaverLoader.createForActivity(this); panelFactory = ColorViewerPanelFactory.createForActivity(this); activityLayout.setBackgroundColor(saverLoader.getTheStoredColor()); currentColorFormat = saverLoader.getTheStoredColorFormat(); } private ColorFormat getColorFormatOfMenuItem(MenuItem item) { String titleOfMenuItem = item.getTitle().toString(); return ColorFormat.valueOf(titleOfMenuItem); } private void saveCurrentColorFormatAndBackgroundColor() { saverLoader.saveColorFormat(currentColorFormat); saverLoader.saveColor(getBackgroundColor()); } private int getInvertedColor(int colorInteger) { int invertedRed = 255 - android.graphics.Color.red(colorInteger); int invertedGreen = 255 - android.graphics.Color.green(colorInteger); int invertedBlue = 255 - android.graphics.Color.blue(colorInteger); return android.graphics.Color.rgb(invertedRed, invertedGreen, invertedBlue); } } </code></pre> <p><strong>ColorFormat.java</strong></p> <pre><code>public enum ColorFormat { RGB, ARGB; public static ArrayList&lt;String&gt; getNamesOfAllColorFormats() { ColorFormat[] arrayOfColorFormats = ColorFormat.values(); ArrayList&lt;String&gt; namesOfColorFormats = new ArrayList&lt;String&gt;(arrayOfColorFormats.length); for (ColorFormat colorFormat : arrayOfColorFormats) { namesOfColorFormats.add(colorFormat.name()); } return namesOfColorFormats; } } </code></pre> <p><strong>RadioButtonMenu.java</strong></p> <pre><code>public class RadioButtonMenu { final private Menu menu; private MenuItem checkedMenuItem; private ArrayList&lt;String&gt; titlesOfMenuItems; public RadioButtonMenu(Menu menu) { this.menu = menu; titlesOfMenuItems = new ArrayList&lt;String&gt;(); checkedMenuItem = null; } public void addItems(ArrayList&lt;String&gt; menuItems) { for (String item : menuItems) { menu.add(item); } titlesOfMenuItems.addAll(menuItems); } public void setChecked(String titleOfMenuItem) { MenuItem menuItem = findMenuItemByTitle(titleOfMenuItem); setChecked(menuItem); } private MenuItem findMenuItemByTitle(String titleOfMenuItem) { int indexOfMenuItem = titlesOfMenuItems.indexOf(titleOfMenuItem); MenuItem menuItem = menu.getItem(indexOfMenuItem); return menuItem; } public void setChecked(MenuItem menuItem) { uncheckMenuItem(checkedMenuItem); checkMenuItem(menuItem); checkedMenuItem = menuItem; } private void checkMenuItem(MenuItem item) { item.setCheckable(true); item.setChecked(true); } private void uncheckMenuItem(MenuItem item) { if (item != null) { item.setChecked(false); item.setCheckable(false); } } } </code></pre> <p><strong>SaverLoader.java</strong></p> <pre><code>public class SaverLoader { private ColorViewerActivity activity; private SharedPreferences preferences; private static final int DEF_COLOR = android.graphics.Color.WHITE; private static final ColorFormat DEF_COLOR_FORMAT = ColorFormat.RGB; private static final String KEY_COLOR = "BACKGROUND_COLOR"; private static final String KEY_COLOR_FORMAT = "COLOR_FORMAT"; public static SaverLoader createForActivity(ColorViewerActivity activity) { return new SaverLoader(activity); } private SaverLoader(ColorViewerActivity activity) { this.activity = activity; } public void saveColor(int colorInteger) { preferences = activity.getPreferences(Activity.MODE_PRIVATE); Editor editor = preferences.edit(); editor.putInt(KEY_COLOR, colorInteger); editor.commit(); } public int getTheStoredColor() { preferences = activity.getPreferences(Activity.MODE_PRIVATE); return preferences.getInt(KEY_COLOR, DEF_COLOR); } public void saveColorFormat(ColorFormat colorFormat) { preferences = activity.getPreferences(Activity.MODE_PRIVATE); Editor editor = preferences.edit(); editor.putString(KEY_COLOR_FORMAT, colorFormat.name()); editor.commit(); } public ColorFormat getTheStoredColorFormat() { preferences = activity.getPreferences(Activity.MODE_PRIVATE); String nameOfSavedColorFormat = preferences.getString(KEY_COLOR_FORMAT, DEF_COLOR_FORMAT.name()); return ColorFormat.valueOf(nameOfSavedColorFormat); } public void deleteAllStoredValues() { preferences = activity.getPreferences(Activity.MODE_PRIVATE); Editor editor = preferences.edit(); editor.clear(); editor.commit(); } } </code></pre> <p><strong>Color.java</strong> </p> <pre><code>public interface Color { int getIntegerValue(); String getDescriptionText(); } </code></pre> <p><strong>RGBColor.java</strong></p> <pre><code>public class RGBColor implements Color { protected ColorDescriptionTextCreator colorDescriptionText; protected int red, green, blue; public RGBColor(int red, int green, int blue) { colorDescriptionText = new ColorDescriptionTextCreator(); this.red = red; this.green = green; this.blue = blue; } @Override public int getIntegerValue() { return android.graphics.Color.rgb(red, green, blue); } @Override public String getDescriptionText() { return colorDescriptionText.create( new String[] { "red", "green", "blue" }, new String[] { String.valueOf(red), String.valueOf(green), String.valueOf(blue) } ); } } </code></pre> <p><strong>ARGBColor.java</strong></p> <pre><code>public class ARGBColor extends RGBColor { protected int alpha; public ARGBColor(int alpha, int red, int green, int blue) { super(red, green, blue); this.alpha = alpha; } @Override public int getIntegerValue() { return android.graphics.Color.argb(alpha, super.red, super.green, super.blue); } @Override public String getDescriptionText() { return colorDescriptionText.create( new String[] { "alpha", "red", "green", "blue" }, new String[] { String.valueOf(alpha), String.valueOf(super.red), String.valueOf(super.green), String.valueOf(super.blue) } ); } } </code></pre> <p><strong>ColorDescriptionTextCreator.java</strong></p> <pre><code>public final class ColorDescriptionTextCreator { private String first; private String last; private String separatorOfComponentNameAndItsValue; private String separatorOfComponents; private String[] componentNames; private String[] componentValues; ColorDescriptionTextCreator() { this("", "", " = ", "\n"); } ColorDescriptionTextCreator(String first, String last, String separatorOfComponentNameAndItsValue, String separatorOfComponents) { this.first = first; this.last = last; this.separatorOfComponentNameAndItsValue = separatorOfComponentNameAndItsValue; this.separatorOfComponents = separatorOfComponents; } String create(String[] componentNames, String[] componentValues) { this.componentNames = componentNames; this.componentValues = componentValues; StringBuilder colorDescription = new StringBuilder(); colorDescription.append(first); for (int i = 0; i &lt; componentNames.length; ++i) { colorDescription.append(getColorComponentWithIndex(i)); } colorDescription.append(last); return colorDescription.toString(); } private StringBuilder getColorComponentWithIndex(int index) { StringBuilder colorComponent = new StringBuilder(); colorComponent.append(componentNames[index]); colorComponent.append(separatorOfComponentNameAndItsValue); colorComponent.append(componentValues[index]); colorComponent.append(isIndexOfLastComponent(index) ? "" : separatorOfComponents); return colorComponent; } private boolean isIndexOfLastComponent(int index) { return (index == componentNames.length - 1); } } </code></pre> <p><strong>ColorViewerPanelFactory.java</strong></p> <pre><code>public class ColorViewerPanelFactory { private ColorViewerActivity colorViewerActivity; private ColorViewerPanel colorViewerPanel = null; private ColorViewerPanelFactory(ColorViewerActivity colorViewerActivity) { this.colorViewerActivity = colorViewerActivity; } public static ColorViewerPanelFactory createForActivity(ColorViewerActivity colorViewerActivity) { return new ColorViewerPanelFactory(colorViewerActivity); } public void buildPanel(ColorFormat colorFormat) { switch (colorFormat) { case RGB: colorViewerPanel = new RGBPanel(colorViewerActivity); break; case ARGB: colorViewerPanel = new ARGBPanel(colorViewerActivity); break; default: throw new IllegalArgumentException( "ColorViewerPanelFactory.buildPanel(): undefined colorFormat"); } } public void destroyPanel() { colorViewerPanel.destroy(); } public void rebuildPanel(ColorFormat newColorFormat) { destroyPanel(); buildPanel(newColorFormat); } } </code></pre> <p><strong>ColorViewerPanel.java</strong></p> <pre><code>public abstract class ColorViewerPanel { private static final int DEFAULT_MAXIMUM_OF_COLOR_SEEKBAR = 255; private ColorViewerActivity activity; private LinearLayout panelLayout; private OnColorSeekBarChangeListener colorChangeListener; private ArrayList&lt;String&gt; namesOfColorComponents; private ArrayList&lt;SeekBar&gt; colorSeekBars; private ArrayList&lt;Integer&gt; maximumsOfColorSeekBars; private ArrayList&lt;Integer&gt; startPositionOfTheSeekBars; public abstract Color getColorSettingOnThePanel(); ColorViewerPanel(ColorViewerActivity activity) { this(activity, null); } ColorViewerPanel(ColorViewerActivity activity, ArrayList&lt;Integer&gt; maximumsOfColorComponentSeekBars) { this.activity = activity; this.maximumsOfColorSeekBars = maximumsOfColorComponentSeekBars; setUp(); fillPanel(); setOnSeekBarChangeListenersForColorSeekBars(); activity.setColor(getColorSettingOnThePanel()); } private void setUp() { panelLayout = (LinearLayout) activity.findViewById(R.id.panelLayout); namesOfColorComponents = getNamesOfColorComponents(); colorChangeListener = new OnColorSeekBarChangeListener(this, activity); colorSeekBars = new ArrayList&lt;SeekBar&gt;(); startPositionOfTheSeekBars = getThePositionOfTheSeekBarsForColor(activity.getBackgroundColor()); } protected abstract ArrayList&lt;String&gt; getNamesOfColorComponents(); // Bad method name // Return position of the seekbars that will be installed for colorIntegerValue. protected abstract ArrayList&lt;Integer&gt; getThePositionOfTheSeekBarsForColor(int colorIntegerValue); private void fillPanel() { LayoutInflater inflater = LayoutInflater.from(panelLayout.getContext()); for (int index = 0; index &lt; namesOfColorComponents.size(); ++index) { TextView nameOfColorComponent = prepareTextView(inflater, index); panelLayout.addView(nameOfColorComponent); SeekBar changerOfColorComponent = prepareSeekBar(inflater, index); panelLayout.addView(changerOfColorComponent); colorSeekBars.add(changerOfColorComponent); } } private TextView prepareTextView(LayoutInflater inflater, int index) { TextView textView = (TextView) inflater.inflate(R.layout.name_of_color_component, null); textView.setText(namesOfColorComponents.get(index)); return textView; } private SeekBar prepareSeekBar(LayoutInflater inflater, int index) { SeekBar seekBar = (SeekBar) inflater.inflate(R.layout.color_seekbar, null); seekBar.setMax(getMaxOfSeekBar(index)); seekBar.setProgress(startPositionOfTheSeekBars.get(index)); return seekBar; } private int getMaxOfSeekBar(int indexOfSeekBar) { int maxOfSeekBar = (maximumsOfColorSeekBars != null ? maximumsOfColorSeekBars.get(indexOfSeekBar) : DEFAULT_MAXIMUM_OF_COLOR_SEEKBAR); return maxOfSeekBar; } private void setOnSeekBarChangeListenersForColorSeekBars() { for (SeekBar seekBar : colorSeekBars) { seekBar.setOnSeekBarChangeListener(colorChangeListener); } } protected ArrayList&lt;Integer&gt; getValuesOfColorComponents() { ArrayList&lt;Integer&gt; valuesOfColorComponents = new ArrayList&lt;Integer&gt;(colorSeekBars.size()); for (SeekBar seekBar : colorSeekBars) { valuesOfColorComponents.add(seekBar.getProgress()); } return valuesOfColorComponents; } void destroy() { panelLayout.removeAllViewsInLayout(); } } </code></pre> <p><strong>RGBColorPanel.java</strong></p> <pre><code>public class RGBPanel extends ColorViewerPanel { private static final String[] colorComponents = { "Red", "Green", "Blue" }; protected ArrayList&lt;String&gt; getNamesOfColorComponents() { ArrayList&lt;String&gt; namesOfColorComponents = new ArrayList&lt;String&gt;(colorComponents.length); for (String component : colorComponents) { namesOfColorComponents.add(component); } return namesOfColorComponents; } RGBPanel(ColorViewerActivity activity) { super(activity); } @Override public Color getColorSettingOnThePanel() { ArrayList&lt;Integer&gt; valuesOfColorComponents = super.getValuesOfColorComponents(); int red = valuesOfColorComponents.get(0); int green = valuesOfColorComponents.get(1); int blue = valuesOfColorComponents.get(2); return new RGBColor(red, green, blue); } @Override protected ArrayList&lt;Integer&gt; getThePositionOfTheSeekBarsForColor(int colorIntegerValue) { ArrayList&lt;Integer&gt; positionOfTheSeekBars = new ArrayList&lt;Integer&gt;(); positionOfTheSeekBars.add(android.graphics.Color.red(colorIntegerValue)); positionOfTheSeekBars.add(android.graphics.Color.green(colorIntegerValue)); positionOfTheSeekBars.add(android.graphics.Color.blue(colorIntegerValue)); return positionOfTheSeekBars; } } </code></pre> <p><strong>ARGBColorPanel.java</strong></p> <pre><code>public class ARGBPanel extends ColorViewerPanel { private static final String[] colorComponents = { "Alpha", "Red", "Green", "Blue" }; protected ArrayList&lt;String&gt; getNamesOfColorComponents() { ArrayList&lt;String&gt; namesOfColorComponents = new ArrayList&lt;String&gt;(colorComponents.length); for (String component : colorComponents) { namesOfColorComponents.add(component); } return namesOfColorComponents; } ARGBPanel(ColorViewerActivity activity) { super(activity); } @Override public Color getColorSettingOnThePanel() { ArrayList&lt;Integer&gt; valuesOfColorComponents = super.getValuesOfColorComponents(); int alpha = valuesOfColorComponents.get(0); int red = valuesOfColorComponents.get(1); int green = valuesOfColorComponents.get(2); int blue = valuesOfColorComponents.get(3); return new ARGBColor(alpha, red, green, blue); } @Override protected ArrayList&lt;Integer&gt; getThePositionOfTheSeekBarsForColor(int colorIntegerValue) { ArrayList&lt;Integer&gt; positionOfTheSeekBars = new ArrayList&lt;Integer&gt;(); positionOfTheSeekBars.add(android.graphics.Color.alpha(colorIntegerValue)); positionOfTheSeekBars.add(android.graphics.Color.red(colorIntegerValue)); positionOfTheSeekBars.add(android.graphics.Color.green(colorIntegerValue)); positionOfTheSeekBars.add(android.graphics.Color.blue(colorIntegerValue)); return positionOfTheSeekBars; } } </code></pre> <p><strong>OnColorSeekBarChangeListener.java</strong></p> <pre><code>public class OnColorSeekBarChangeListener implements OnSeekBarChangeListener { private ColorViewerPanel panel; private ColorViewerActivity activity; public OnColorSeekBarChangeListener(ColorViewerPanel panel, ColorViewerActivity activity) { this.panel = panel; this.activity = activity; } @Override public void onProgressChanged(SeekBar seekBar, int progress, boolean fromUser) { activity.setColor(panel.getColorSettingOnThePanel()); } @Override public void onStartTrackingTouch(SeekBar seekBar) { } @Override public void onStopTrackingTouch(SeekBar seekBar) { } } </code></pre>
[ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-02-09T03:08:41.033", "Id": "34535", "Score": "3", "body": "one thing that Uncle Bob was clear about in that book was Unit Tests... :) I don't see any on your GitHub site either :) as for the rest it isn't horrible. Since there is a bunch of things I would like to point out that in both child classes of ColorPanel you implement the same method exactly the same way. This means you can move implementation to the abstract class. Just make your array `colorComponents` abstract" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-11-12T20:46:15.707", "Id": "57069", "Score": "3", "body": "you should break this up into multiple reviews." } ]
[ { "body": "<p>I'm not an Android developer, so just some notes from a Java developer's perspective.</p>\n\n<ol>\n<li><pre><code>List&lt;String&gt; namesOfColorComponents = new ArrayList&lt;String&gt;(colorComponents.length);\nfor (String component : colorComponents) {\n namesOfColorComponents.add(component);\n}\nreturn namesOfColorComponents;\n</code></pre>\n\n<p>The following is the same:</p>\n\n<pre><code>return new ArrayList&lt;String&gt;(Arrays.asList(colorComponents));\n</code></pre></li>\n<li><pre><code>String create(String[] componentNames, String[] componentValues) {\n ...\n}\n</code></pre>\n\n<p>It would be more encapsulated if you were using only one array (or List) with objects which encapsulates the name and the value:</p>\n\n<pre><code>public class ComponentData {\n private String name;\n private String value;\n\n // constructors, getters\n}\n</code></pre></li>\n<li><p>These indexes (0-3) looks very fragile because they could be changed in the superclass while it's too easy to forget changing them in the child class. Additionally, they are magic numbers. Named constants (with descriptive names) would be better but using named getter methods would be the best.</p>\n\n<pre><code>@Override\npublic Color getColorSettingOnThePanel() {\n ArrayList&lt;Integer&gt; valuesOfColorComponents = super.getValuesOfColorComponents();\n int alpha = valuesOfColorComponents.get(0);\n int red = valuesOfColorComponents.get(1);\n int green = valuesOfColorComponents.get(2);\n int blue = valuesOfColorComponents.get(3);\n return new ARGBColor(alpha, red, green, blue);\n}\n</code></pre></li>\n<li><pre><code>protected int red, green, blue;\n</code></pre>\n\n<p>I'd put the variable declarations to separate lines. From <em>Code Complete 2nd Edition</em>, p759:</p>\n\n<blockquote>\n <p>With statements on their own lines, the code reads from top to bottom, instead\n of top to bottom and left to right. When you’re looking for a specific line of code,\n your eye should be able to follow the left margin of the code. It shouldn’t have to\n dip into each and every line just because a single line might contain two statements.</p>\n</blockquote>\n\n<p>Furthermore, <code>protected</code> fields does not suggest good encapsulation. Check <em>Effective Java, Second Edition</em>, <em>Item 16: Favor composition over inheritance</em> if you haven't seen it already.</p></li>\n<li><p>I like that there is only one switch-case, it is inside the builder class and the default case throws an exception (fail early).</p></li>\n<li><p><code>ArrayList&lt;...&gt;</code> reference and return types should be simply <code>List&lt;...&gt;</code>. See: <em>Effective Java, 2nd edition</em>, <em>Item 52: Refer to objects by their interfaces</em></p></li>\n<li><pre><code>ColorDescriptionTextCreator(String first, String last,\n String separatorOfComponentNameAndItsValue,\n String separatorOfComponents) {\n</code></pre>\n\n<p><em>Effective Java 2nd Edition</em>, <em>Item 2: Consider a builder when faced with many constructor parameters</em></p></li>\n<li><pre><code>private SaverLoader saverLoader;\nprivate ColorFormat currentColorFormat;\nprivate ColorViewerPanelFactory panelFactory;\nprivate RadioButtonMenu radioButtonMenu;\nprivate TextView descriptionOfColor;\nprivate View activityLayout;\nprivate Andoid android;\n</code></pre>\n\n<p>Fields should be at the beginning of the class, then comes the constructor, then the other methods. (According to the <a href=\"http://www.oracle.com/technetwork/java/codeconv-138413.html\" rel=\"nofollow\">Code Conventions for the Java Programming Language</a>, 3.1.3 Class and Interface Declarations.)</p></li>\n</ol>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-03-02T20:15:09.360", "Id": "43247", "ParentId": "21484", "Score": "5" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "2", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-02-08T17:56:56.330", "Id": "21484", "Score": "6", "Tags": [ "java", "android" ], "Title": "ColorViewer mini-app for viewing colors in different formats" }
21484
<p>I just put together the skeletons for a priority queue using a binary heap in racket/scheme. Using racket/scheme is all about the educational experience and I was wondering if anyone wants to critique and improve the code. Bug reports are welcome</p> <pre><code>;; priority queues operations on integer values (define (heap) (let ((the-heap (make-vector 10)) (next-free 1)) (define (swim val) (begin (vector-set! the-heap next-free val) (set! next-free (+ next-free 1)) (let loop ((i (- next-free 1))) (if (and (&lt; (vector-ref the-heap (quotient i 2)) (vector-ref the-heap i)) (&gt; (quotient i 2) 0)) (begin (exch the-heap i (floor (/ i 2))) (loop (floor (/ i 2)))) the-heap)))) (define (sink index) ;; a call to this method is used to re-establish order within the ;; heap by 'sinking' the value rooted at index to its right position ;; within the whole heap (let loop ((node index) (kid (* 2 index))) (if (&lt;= kid next-free) (let ((larger-kid (if (&gt; (vector-ref the-heap kid) (vector-ref the-heap (+ kid 1))) kid (+ kid 1)))) (if (&gt; (vector-ref the-heap larger-kid) (vector-ref the-heap node)) (begin (exch the-heap node larger-kid) (loop larger-kid (* 2 larger-kid))) the-heap)) (newline)))) (define (delete-max) ;; delete and return the maximum value in the heap. ;; add the last item on the heap to the root position ;; sink to re-establish order within the heap of the heap and call ;; (begin (let ((val (vector-ref the-heap 1))) (vector-set! the-heap 1 (vector-ref the-heap (- next-free 1))) (set! next-free (- next-free 1)) (vector-set! the-heap next-free 0) (sink 1) val))) (define (put value) (swim value)) (define (size) (vector-length the-heap)) (define (empty?) (= next-free 1)) (define (exch vec lo j) (let ((lo-val (vector-ref vec lo)) (j-val (vector-ref vec j))) (begin (vector-set! vec lo j-val) (vector-set! vec j lo-val)))) (define (dispatch message . arg) (cond ((eq? message 'delete-max) (delete-max)) ((eq? message 'put) (put (car arg))) ((eq? message 'size) size) ((eq? message 'heap) the-heap) ((eq? message 'empty?) empty?))) dispatch)) </code></pre>
[]
[ { "body": "<p>Here are some general points before I start on more specific points:</p>\n\n<ul>\n<li>I don't see any unit tests. Racket programmers often write many unit tests for each function. You can use the <a href=\"http://docs.racket-lang.org/guide/Module_Syntax.html\"><code>module+</code></a> construct and <a href=\"http://docs.racket-lang.org/rackunit/\"><code>rackunit</code></a> to easily write internal unit tests.</li>\n<li>Indentation is important for clarity. I couldn't tell that everything was internal to <code>heap</code> at first because of the lack of indentation. Also, you can replace some of the <code>let</code>s with internal <code>define</code>s and make some of the internal functions into top-level functions to reduce right-ward drift.</li>\n</ul>\n\n<p>More specific points:</p>\n\n<ul>\n<li>It looks like you're using a dispatch function with internal state to keep track of the priority queue state. The more natural thing to do in Racket would be to create a new datatype using <code>struct</code>. This way, your implementation details don't leak through.</li>\n<li>You use a <code>dispatch</code> function as the entry point to your simulated object. Simulating OO style in this fashion is not a very natural thing to do in Racket. Racket programmers tend to either use (1) the built-in classes &amp; objects or (2) have a functional API with a function for each operation.</li>\n<li>You use <code>begin</code> to sequence multiple effecting operations inside functions. These are actually unnecessary since Racket functions can have as many expressions in the body as you like.</li>\n</ul>\n\n<p>Hope that helps. Cheers.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-03-06T20:38:22.320", "Id": "23549", "ParentId": "21485", "Score": "6" } } ]
{ "AcceptedAnswerId": "23549", "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-02-08T19:16:46.093", "Id": "21485", "Score": "6", "Tags": [ "algorithm", "scheme", "racket" ], "Title": "Improving a priority queue sketch in Racket/Scheme" }
21485
<p>In PHP, I have a parent/child class and am using dependency container to load them. I am trying to use the same database connection on all of them without duplicating the object.</p> <p>I used <code>$this-&gt;_db</code> to pull data from the database in a child class method (and my class stores that in the property <code>$this-&gt;_db-&gt;result</code>). I then went into the parent class and <code>print_r($this-&gt;_db-&gt;result)</code> and it worked. That leads me to believe that I am passing the database object and not duplicating it (maybe?).</p> <p>However, would still be nice if someone could tell me why my code would not be considered OOP, as someone had commented that it was not OOP. Can someone who understands this stuff better than me please have a look and let me know if I'm doing it right and if not, what I need to change in my code?</p> <pre><code>&lt;?php include('mysqliClass.php'); $db = new mysqliObject(); depCon::$_database = $db; $myObject = depCon::createNewObject(); class depCon { public static $_database; public static function createNewObject() { $newObject = new myChild(); $newObject-&gt;setDatabase(self::$_database); return $newObject; } } class myParent { private $_db; public function __construct() { } public function setDatabase($databaseConnection) { $this-&gt;_db = $databaseConnection; } } class myChild extends myParent { private $_db; public function __construct() { parent::__construct(); } public function setDatabase($databaseConnection) { $this-&gt;_db = $databaseConnection; parent::setDatabase($this-&gt;_db); } } ?&gt; </code></pre>
[ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-02-08T22:30:08.830", "Id": "34526", "Score": "0", "body": "Why have you overloaded `setDatabase` in `myChild`?" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-02-08T22:39:20.127", "Id": "34527", "Score": "0", "body": "What am I doing to overload it? I am just attempting to get the parent class to use the same database connection. If I don't do that, it won't let me do $this->_db in parent class methods." } ]
[ { "body": "<p>Why should an object know about a database (in an OOP sense)? I'm definitely no friend of the <a href=\"http://en.wikipedia.org/wiki/Singleton_pattern\" rel=\"nofollow\">Singleton</a> pattern, but a database is in most projects a valid use case.</p>\n\n<hr>\n\n<p>Your code might not be OO but <a href=\"http://en.wikipedia.org/wiki/Service-oriented_architecture\" rel=\"nofollow\">Service Oriented</a> as you are injecting the database(-service) to your objects.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-02-09T16:27:42.390", "Id": "34565", "Score": "1", "body": "This looks to be dependency-injection which is certainly OO, so I've got not clue why you think its Service Oriented." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-02-10T12:34:27.730", "Id": "34603", "Score": "0", "body": "I think this is a question of the definition. From my point of view using objects itself is not OO. In a plain OO approach the Object shouldn't know anything about the persistence layer. It's just holding some data and can to some operation. (Some kind of factory knows about the persistence details.) DI is usually related to some kind of Services, \"nobody\" is injecting plain objects." } ], "meta_data": { "CommentCount": "2", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-02-09T08:25:00.153", "Id": "21502", "ParentId": "21486", "Score": "0" } }, { "body": "<p>Don't use a private attribute for the database, use a protected one. That way both classes can share the same $_db, and you only need one setDatabase.</p>\n\n<p>As for your code being OO or not, there simply isn't enough code here to make the claim one way or the other. </p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-02-09T16:23:32.060", "Id": "21517", "ParentId": "21486", "Score": "2" } } ]
{ "AcceptedAnswerId": "21517", "CommentCount": "2", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-02-08T21:21:26.990", "Id": "21486", "Score": "1", "Tags": [ "php", "object-oriented", "database", "scope", "inheritance" ], "Title": "Using a dependency container to load a parent/child class" }
21486
<p>I decided to write an STL-style class as an exercise. I followed a tutorial of sorts that I found online, but I also made some modifications. I'd like to hear any criticisms you folks might have. Be harsh; I can take it.</p> <pre><code>#ifndef CIRCULARDEQUE_HPP_ #define CIRCULARDEQUE_HPP_ #include &lt;iterator&gt; #include &lt;stdexcept&gt; #include &lt;cassert&gt; template&lt;typename T, typename T_nonconst, typename elem_type = typename T::value_type&gt; class circular_deque_iterator { public: typedef circular_deque_iterator&lt;T, T_nonconst, elem_type&gt; self_type; typedef T deque_type; typedef std::random_access_iterator_tag iterator_category; typedef typename deque_type::value_type value_type; typedef typename deque_type::size_type size_type; typedef typename deque_type::pointer pointer; typedef typename deque_type::const_pointer const_pointer; typedef typename deque_type::reference reference; typedef typename deque_type::const_reference const_reference; typedef typename deque_type::difference_type difference_type; circular_deque_iterator(deque_type* b, size_t start_pos) : buf_(b), pos_(start_pos) { } // Converting a non-const iterator to a const iterator circular_deque_iterator( const circular_deque_iterator&lt;T_nonconst, T_nonconst, typename T_nonconst::value_type&gt; &amp;other) : buf_(other.buf_), pos_(other.pos_) { } friend class circular_deque_iterator&lt;const T, T, const elem_type&gt; ; elem_type&amp; operator*() { return (*buf_)[pos_]; } elem_type* operator-&gt;() { return &amp;(operator*()); } //prefix self_type&amp; operator++() { ++pos_; return *this; } //prefix self_type&amp; operator--() { --pos_; return *this; } self_type operator++(int) { self_type tmp(*this); ++(*this); return tmp; } self_type operator--(int) { self_type tmp(*this); --(*this); return tmp; } self_type&amp; operator+=(difference_type n) { pos_ += n; return *this; } self_type&amp; operator-=(difference_type n) { pos_ -= n; return *this; } difference_type operator-(const self_type &amp;c) const { return pos_ - c.pos_; } self_type operator-(difference_type n) const { self_type tmp(*this); tmp.pos_ -= n; return tmp; } difference_type operator+(const self_type &amp;c) const { return pos_ + c.pos_; } self_type operator+(difference_type n) const { self_type tmp(*this); tmp.pos_ += n; return tmp; } bool operator==(const self_type &amp;other) const { return mask(pos_) == mask(other.pos_) &amp;&amp; buf_ == other.buf_; } bool operator!=(const self_type &amp;other) const { return mask(pos_) != mask(other.pos_) || buf_ != other.buf_; } bool operator&gt;(const self_type &amp;other) const { return pos_ &gt; other.pos_; } bool operator&gt;=(const self_type &amp;other) const { return pos_ &gt;= other.pos_; } bool operator&lt;(const self_type &amp;other) const { return pos_ &lt; other.pos_; } bool operator&lt;=(const self_type&amp; other) const { return pos_ &lt;= other.pos_; } private: size_type mask(int val) const { return val &amp; (buf_-&gt;capacity() - 1); } deque_type *buf_; int pos_; }; template&lt;typename T, typename Alloc = std::allocator&lt;T&gt;&gt; class circular_deque { public: typedef circular_deque&lt;T, Alloc&gt; self_type; typedef Alloc allocator_type; typedef typename Alloc::value_type value_type; typedef typename Alloc::pointer pointer; typedef typename Alloc::const_pointer const_pointer; typedef typename Alloc::reference reference; typedef typename Alloc::const_reference const_reference; typedef typename Alloc::size_type size_type; typedef typename Alloc::difference_type difference_type; typedef circular_deque_iterator&lt;self_type, self_type&gt; iterator; typedef circular_deque_iterator&lt;const self_type, self_type, const value_type&gt; const_iterator; typedef std::reverse_iterator&lt;iterator&gt; reverse_iterator; typedef std::reverse_iterator&lt;const_iterator&gt; const_reverse_iterator; const static size_type default_capacity = 16; explicit circular_deque(size_type num_of_elmts_to_hold = default_capacity) : array_(alloc_.allocate(get_needed_capacity(num_of_elmts_to_hold))), capacity_( num_of_elmts_to_hold), head_(0), tail_(0) { assert(invariants()); } circular_deque(const circular_deque &amp;other) : array_(alloc_.allocate(other.capacity_)), capacity_( other.capacity_), head_(0), tail_(0) { try { assign_into(other.cbegin(), other.cend()); assert(invariants()); } catch (...) { destroy_all_elements(); alloc_.deallocate(array_, capacity_); throw; } } template&lt;class InputIterator&gt; circular_deque(InputIterator from, InputIterator to) : array_(alloc_.allocate(0)), capacity_(0), head_(0), tail_(0) { circular_deque tmp; tmp.assign_into(from, to); swap(tmp); assert(invariants()); } ~circular_deque() { destroy_all_elements(); alloc_.deallocate(array_, capacity_); } circular_deque &amp;operator=(const self_type &amp;other) { circular_deque tmp(other); swap(tmp); assert(invariants()); return *this; } private: //TODO make this relative to actual int type static size_type get_needed_capacity(size_type num_of_elmts_to_hold) { size_type initialCapacity = num_of_elmts_to_hold; initialCapacity |= (initialCapacity &gt;&gt; 1); initialCapacity |= (initialCapacity &gt;&gt; 2); initialCapacity |= (initialCapacity &gt;&gt; 4); initialCapacity |= (initialCapacity &gt;&gt; 8); initialCapacity |= (initialCapacity &gt;&gt; 16); initialCapacity++; return initialCapacity; } void destroy_all_elements() { for (size_type n = 0; n &lt; size(); ++n) { alloc_.destroy(array_ + mask(n)); } } template&lt;typename iter&gt; void assign_into(iter from, iter to) { while (from != to) { push_back(*from); ++from; } assert(invariants()); } public: void clear() { for (size_type n = 0; n &lt; size(); ++n) { alloc_.destroy(array_ + mask(n)); } head_ = tail_ = 0; } void swap(circular_deque&amp; other) { std::swap(array_, other.array_); std::swap(head_, other.head_); std::swap(tail_, other.tail_); std::swap(capacity_, other.capacity_); assert(invariants()); } iterator begin() { return iterator(this, 0); } const_iterator cbegin() const { return const_iterator(this, 0); } iterator end() { return iterator(this, size()); } const_iterator cend() const { return const_iterator(this, size()); } reverse_iterator rbegin() { return reverse_iterator(end()); } const_reverse_iterator rbegin() const { return const_reverse_iterator(cend()); } reverse_iterator rend() { return reverse_iterator(begin()); } const_reverse_iterator crend() const { return const_reverse_iterator(cbegin()); } reference at(size_type n) { return at_checked(n); } const_reference at(size_type n) const { return at_checked(n); } reference operator[](size_type n) { return at_unchecked(n); } const_reference operator[](size_type n) const { return at_unchecked(n); } private: size_type mask(int val) const { return val &amp; (capacity() - 1); } reference at_unchecked(size_type index) const { return array_[mask(head_ + index)]; } reference at_checked(size_type index) const { if (index &gt;= size()) { throw std::out_of_range("out of range"); } return at_unchecked(index); } public: iterator erase(iterator i) { size_type idx = i - begin(); circular_deque tmp(capacity()); auto start = begin(); while (start != end()) { if (start != i) { tmp.push_back(*start); } ++start; } swap(tmp); assert(invariants()); return begin() + idx; } void push_front(const value_type&amp; elem) { if (mask(head_ - 1) == tail_) { double_capacity(); } head_ = mask(head_ - 1); array_[head_] = elem; assert(front() == elem); assert(invariants()); } void push_back(const value_type&amp; elem) { if (mask(tail_ + 1) == head_) { double_capacity(); } array_[tail_] = elem; tail_ = mask(tail_ + 1); assert(back() == elem); assert(invariants()); } void pop_front() { if (empty()) { return; } int destroy_pos = head_; head_ = mask(head_ + 1); alloc_.destroy(array_ + destroy_pos); assert(invariants()); } void pop_back() { if (empty()) { return; } int destroy_pos = mask(tail_ - 1); tail_ = destroy_pos; alloc_.destroy(array_ + destroy_pos); assert(invariants()); } reference front() { return array_[head_]; } reference back() { return array_[mask(tail_ - 1)]; } const_reference front() const { return array_[head_]; } const_reference back() const { return array_[mask(tail_ - 1)]; } size_type size() const { return mask(tail_ - head_); } size_type capacity() const { return capacity_; } bool empty() const { return head_ == tail_; } private: bool invariants() const { assert(front() == this-&gt;operator [](0)); assert(front() == *cbegin()); // assert(front() == *(crend() + 1)); TODO doesn't compile assert(back() == this-&gt;operator [](size() - 1)); assert(back() == *(cend() - 1)); // assert(back() == *rbegin()); TODO this doens't compile either assert(size() &lt; capacity()); assert(size() &gt;= 0); assert( capacity() == 0 || mask(capacity()) == 0); return true; } void double_capacity() { circular_deque temp(capacity() * 2); assert(temp.capacity() == capacity() * 2); auto it = begin(); while (it != end()) { auto val = *it; temp.push_back(*it); ++it; } swap(temp); assert(invariants()); } allocator_type alloc_; value_type * array_; size_t capacity_; int head_; int tail_; }; template&lt;typename T, typename Alloc&gt; bool operator==(const circular_deque&lt;T, Alloc&gt; &amp;a, const circular_deque&lt;T, Alloc&gt; &amp;b) { return a.size() == b.size() &amp;&amp; std::equal(a.cbegin(), a.cend(), b.cbegin()); } template&lt;typename T, typename Alloc&gt; bool operator!=(const circular_deque&lt;T, Alloc&gt; &amp;a, const circular_deque&lt;T, Alloc&gt; &amp;b) { return a.size() != b.size() || !std::equal(a.cbegin(), a.cend(), b.cbegin()); } #endif </code></pre>
[]
[ { "body": "<p>Your code on the whole looks good, there's very little I can pick at. I can only offer a few minor suggestions for improvement.</p>\n\n<p>Firstly, your <code>operator=</code> can be made slightly shorter and cleaner:</p>\n\n<pre><code>circular_deque&amp; operator=(self_type other)\n{\n swap(*this, other);\n assert(invariants);\n return *this;\n}\n</code></pre>\n\n<p>Note that the parameter is passed by value, hence eliminating the need for a <code>tmp</code> in the function. This also uses a non-member <code>swap</code> function which you haven't provided, but probably should.</p>\n\n<p>Minor slip up with:</p>\n\n<pre><code>template&lt;typename iter&gt;\nvoid assign_into(iter from, iter to)\n</code></pre>\n\n<p><code>iter</code> should be upper case. It's not going to change the semantics of the code of course, just sticking to the template parameters should be upper case convention (which is followed everywhere else in this code).</p>\n\n<p>Your <code>iterator erase(iterator i)</code> function is less efficient than it could be - there's no good reason to construct a temporary here. Simply erase the position given and shift everything after it back one. If the iterator passed in is (say) the 2nd to last element, this should be effectively constant, whereas the current method will require a full construction, walking through the entire deque, and then complete destruction of the old deque.</p>\n\n<p>A minor nitpick, but I'd rename <code>double_capacity()</code>. Perhaps sometime in the future you'll profile and decide that doubling the current capacity is not the optimal technique - maybe some other multiple would result in less wasted memory, or will result in less allocations. Maybe <code>expand_capacity()</code> would be a better function name. It is a <code>private</code> function, though, so this is a very minor complaint.</p>\n\n<p>There's a missing include for <code>std::equal</code>: <code>#include &lt;algorithm&gt;</code>. Something else obviously pulls it in but it's best not to rely on that.</p>\n\n<p>There are some missing functions you should provide:</p>\n\n<p>Non-member: <code>operator&lt;</code>, <code>operator&lt;=</code>, <code>operator&gt;</code>, <code>operator&gt;=</code>. <code>std::lexicographic_compare</code> should be useful for this.</p>\n\n<p>Member: <code>const_iterator begin() const</code>, <code>const_iterator end() const</code> - both of these should still be available. You do have <code>cbegin()</code> and <code>cend()</code>, but these are designed to get <code>const_iterator</code> from a non-<code>const</code> container. <code>begin()</code> and <code>end()</code> should still be overloaded with <code>const</code> versions. If you want to adhere more closely to the standard, there should also be some other functions like <code>max_size</code>, <code>resize</code>, <code>get_allocator</code> and the like.</p>\n\n<p>Depending on if you want to add some <code>C++11</code> functionality to this or not, you might want to also add a move constructor and move assignment operator:</p>\n\n<pre><code>circular_deque&amp; operator=(circular_deque&amp;&amp; other);\ncircular_deque(circular_deque&amp;&amp; other);\n</code></pre>\n\n<p>With <code>swap</code> already implemented, these are pretty easy to implement.</p>\n\n<p>Edit: Ok, as to the question of getting your <code>invariants</code> to compile, this actually shows up a bit of a deeper problem. This minimal program won't compile (for two reasons, actually - you're missing a <code>crbegin()</code> method, but we'll assume that gets added in before we try and compile this).</p>\n\n<pre><code>#include &lt;iostream&gt;\n\ntemplate &lt;typename T&gt;\nvoid print(const circular_deque&lt;T&gt;&amp; c)\n{\n for(auto it = c.crbegin(); it != c.crend(); ++it)\n std::cout &lt;&lt; *it &lt;&lt; \", \";\n std::cout &lt;&lt; \"\\n\";\n}\n\nint main()\n{\n circular_deque&lt;int&gt; d;\n d.push_back(1);\n d.push_back(2);\n d.push_back(3);\n\n print(d);\n\n return 0;\n}\n</code></pre>\n\n<p>This spits out an error that looks something like the following:</p>\n\n<pre><code>stl_iterator.h:165:12: error: invalid initialization of reference of type\n'std::reverse_iterator&lt;circular_deque_iterator&lt;const circular_deque&lt;int&gt;,\ncircular_deque&lt;int&gt;, const int&gt; &gt;::reference {aka int&amp;}' from expression of type '\nconst int'\n</code></pre>\n\n<p>So what's this telling us? It's saying that <code>reverse_iterator</code> is trying to utilize <code>reference</code>, which is <code>int&amp;</code>, but we're giving it a <code>const int</code>. How do we fix this? Well, we can replace the <code>typedef</code> for <code>reference</code> in <code>circular_deque_iterator</code> with </p>\n\n<pre><code>typedef typename deque_type::const_reference reference;\n</code></pre>\n\n<p>This will let your code compile, but it is a bit of a hack. Generally, getting all the code for an <code>iterator</code> and a <code>const_iterator</code> into a single class is tricky. A <code>const_iterator</code> shouldn't have a method like:</p>\n\n<pre><code>elem_type&amp; operator*() {\n return (*buf_)[pos_];\n}\n</code></pre>\n\n<p>It should have the const-equivalent:</p>\n\n<pre><code>const elem_type&amp; operator*() const {\n return (*buf_)[pos_];\n}\n</code></pre>\n\n<p>Obviously with what you're passing in at the moment, <code>elem_type&amp;</code> will be equivalent to <code>const elem_type&amp;</code> for the <code>const</code> version, but it is still missing the guarantee that it won't modify the iterator class itself. Likewise with <code>operator-&gt;()</code>. There are some rather sophisticated tricks you can get into to (possibly) correct this, utilizing traits classes along with the curiously recurring template pattern (CRTP), but this post is long enough as is already, and it all gets somewhat complicated.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-02-12T15:10:31.957", "Id": "34746", "Score": "0", "body": "Great. Thank you very much. Everything you said makes sense." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-02-12T15:17:36.077", "Id": "34747", "Score": "0", "body": "If you don't mind, I have one more question that I meant to ask when I posted. If you look toward the bottom, my first private method is an invariants() method that I assert throughout. There are two lines that are commented out as TODOs. Neither of these lines compile. I know it has to do with const-ness, but I don't quite understand exactly why. Any ideas? Regardless, thanks again." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-02-13T01:17:49.553", "Id": "34782", "Score": "1", "body": "@piyo See my edit. You're correct in that it is to do with `const`ness." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-02-13T15:06:39.513", "Id": "34809", "Score": "0", "body": "Thanks again. The templating \"trick\" I'm using to attempt to get a const iterator class out of the iterator class is the only part of this that I basically just copied from other examples without really understanding how it works, so it makes sense that that's what is tripping me up." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-02-13T19:07:59.567", "Id": "34821", "Score": "0", "body": "OK, so I studied this a bit more, and I think I've got a better handle on it. With regards to the problem of getting both of the * operator methods into the same class, can I not just add the const qualifier to the method that I have now? Sure, when I have `const elem_type&` the code will be \"lying\", but is that so bad in this case?" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-02-14T00:37:08.083", "Id": "34835", "Score": "0", "body": "@piyo Well, yeah, it is. What if someone wants to modify the underlying values utilizing iterators? It'll need to be something like `reference operator*() const { ... }` where reference is a `const T&` for const_iterator and `T&` for normal iterator (and same for `pointer operator->()`)." } ], "meta_data": { "CommentCount": "6", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-02-11T01:34:43.980", "Id": "21561", "ParentId": "21487", "Score": "3" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-02-08T21:52:04.803", "Id": "21487", "Score": "7", "Tags": [ "c++", "beginner", "c++11", "queue", "stl" ], "Title": "STL-style deque class" }
21487
<p>I've built a small <code>hooks</code> class for adding some capabilities of basic plug-in functionality.</p> <p>Is there room for improvement? I am just beginning to learn OOP. I have two ways to manually add execution points and delete them:</p> <ul> <li>autoloading method for plugins in a specific folder</li> <li>method for execution</li> </ul> <p></p> <pre><code>defined('BASE_PATH') || (header("HTTP/1.1 403 Forbidden") &amp; die('403 - Acces direct interzis.')); class hooks { private static $hooks = []; private static $instance; /** * @param null $plugin_dir * @return hooks * @desc ne asiguram ca avem o singura instanta globala */ public static function init($plugin_dir = null) { if(self::$instance == null) self::$instance = new self($plugin_dir); return self::$instance; } /** * @param $plugin_dir * @desc instantierea efectiva, nu cred ca e nevoie de descriere si rulam load_action */ private function __construct($plugin_dir) { self::load_action($plugin_dir); } /** * @desc ne aisguram ca obiectul nu poate fi clonat */ private function __clone(){} /** * @param $plugin_dir * @return bool * @desc incarcarea dinamica de pluginuri (se efectueaza doar daca clasa este instantiata) * cautam directorul pt pluginuri le includem si le inregistram cu self::add_action */ private static function load_action($plugin_dir) { if($plugin_dir == null) return null; $hooks = new GlobIterator($plugin_dir.DIRECTORY_SEPARATOR.'*.php', FilesystemIterator::KEY_AS_FILENAME); foreach($hooks as $hook =&gt; $file) { require_once $file; (empty($priority)) ? self::add_action($where, $callback) : self::add_action($where, $callback, $priority); } return null; } /** * @param $where punctul de executie * @param $callback metoda chemata poate fi functie sau metoda * @ex add_action('punct executie',[SomeClass, 'someStaticMethod']); * @param int $priority ordinea in care sant executate callbackurile pt fiecare pct de executie * @desc inregistram pluginuri */ public static function add_action($where, $callback, $priority = 50) { if(!isset(self::$hooks[$where])) self::$hooks[$where] = []; self::$hooks[$where][$callback] = $priority; } /** * @param $where * @param $callback * @desc stergem un callback pt un pct de executie */ public static function remove_action($where, $callback) { if(isset(self::$hooks[$where][$callback])) unset(self::$hooks[$where][$callback]); } /** * @param $where * @param array $args * @desc executam callbackurile pt un pct de executie si ai dam parametri necesari (optionali) */ public static function execute_action($where, $args = []) { if(isset(self::$hooks[$where]) &amp;&amp; is_array(self::$hooks[$where])) { arsort(self::$hooks[$where]); foreach(self::$hooks[$where] as $callback =&gt; &amp;$priority) call_user_func_array($callback, $args); } } } </code></pre> <p><strong>index.php</strong></p> <pre><code>define('BASE_PATH', realpath(__DIR__).DIRECTORY_SEPARATOR); require_once BASE_PATH.'hooks.php'; hooks::init(BASE_PATH.'plugin'.DIRECTORY_SEPARATOR); $array_pt_test = [ 'Home' =&gt; 'Home.php', 'Top' =&gt; 'Top.php', 'Hello' =&gt; 'Hello.php' ]; function render_nav($array =[]) { $output = ''; foreach($array as $key =&gt; $value) { $output .= '&lt;li&gt;'; $output .= '&lt;a href="'.$value.'"&gt;'.$key.'&lt;/a&gt;'; $output .= '&lt;/li&gt;'; } echo $output; } hooks::add_action('nav', 'render_nav'); &lt;nav id="nav"&gt; &lt;ul&gt; &lt;?php hooks::execute_action('nav', [$array_pt_test]); ?&gt; &lt;/ul&gt; &lt;br class="clear" /&gt; &lt;/nav&gt; </code></pre> <p>This is a simple example of displaying a navigation menu. We register a default function (action) to process the array. In <code>overwrite.php</code>, the plugin directory, we register another function and give the <code>overwrite_nav</code> function a higher priority to be processed, and then call the <code>hooks::remove_action</code> method to unregister the default one. Just play with the <code>$priority</code> value in <code>overwrite.php</code> to see the effects. You can have multiple actions tied to the same execution point.</p> <p><strong>overwrite.php</strong></p> <pre><code> defined('BASE_PATH') || (header("HTTP/1.1 403 Forbidden") &amp; die('403 - Acces direct interzis.')); $where = 'nav'; $callback = 'overwrite_nav'; $priority = 57 ; function overwrite_nav($array = []) { hooks::remove_action('nav','render_nav'); $output = ''; foreach($array as $key =&gt; $value) { $output .= '&lt;li&gt;'; $output .= '&lt;a href="'.$value.'"&gt;'.strtolower($key).'&lt;/a&gt;'; $output .= '&lt;/li&gt;'; } echo $output; } </code></pre>
[ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-02-10T02:09:04.407", "Id": "34583", "Score": "0", "body": "Two suggestions immediately comes to my mind: don't use Singletons (they are just disguised globals) and always write in English both comments and code." } ]
[]
{ "AcceptedAnswerId": null, "CommentCount": "1", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-02-08T22:56:19.127", "Id": "21489", "Score": "3", "Tags": [ "php", "beginner", "object-oriented" ], "Title": "Hooks class for basic plugin functionality" }
21489
<p>I'm writing a card game (Dominion) as a pet project. I'm new to C++ but not programming.</p> <p>A player has a deck, containing the hand and cards in play (tableau). Outside the player, there are piles of cards to buy from (supply piles). I want to display these objects (the hand, tableau and supply piles) on the screen. I had chosen to represent the hand and tableau using <code>std::vector&lt;Card&gt;</code> and the supply piles as <code>std::vector&lt;SupplyPile&gt;</code>. <code>Card</code> and <code>SupplyPile</code> implement an interface for displaying contents to the screen</p> <pre><code>class IInfo { public: virtual std::string Info() const = 0; virtual std::string ToString() const = 0; }; </code></pre> <p>I have a class I'm calling <code>View</code> that will take on displaying things to the screen.</p> <pre><code>class View { public: View(const std::vector&lt;IInfo*&gt;&amp; items, int window_starty, int window_startx); virtual ~View() { } const IInfo&amp; CurrentItem() const; const int CurrentIndex() const; bool IsEmpty() const; void ItemDown(); void ItemUp(); void SetActive(); void SetInactive(); virtual void Update(); protected: virtual WINDOW* InitializeWindow(int lines, int cols, int starty, int startx); virtual ITEM** MakeMenuItems(); private: // Some constants const std::vector&lt;IInfo*&gt;&amp; items_; MENU *menu_; WINDOW *window_; }; </code></pre> <p>I now know that C++ doesn't support covariance in templates, so I can't create instances of <code>View</code> with the supply pile, hand, and tableau. How can I redesign the system to maximize DRY? The <code>View</code> class operates on its container member in a very simple way, ripe for abstraction.</p> <h2>Examples of things I want to do</h2> <pre><code>std::vector&lt;Card&gt; hand = player.hand(); std::vector&lt;Card&gt; tableau = player.tableau(); std::vector&lt;SupplyPile&gt; supply_piles = game.supply_piles(); View hand_view = new View(hand, starty, startx); View tableau_view = new View(tableau, starty, startx); View supply_piles_view = new View(supply_piles, starty, startx); </code></pre> <p>One answer suggested making <code>View</code> into a template, and it almost worked until I remembered that I want to track which <code>View</code> is active at a given time:</p> <pre><code>View active_ = hand_view; // Later active_ = supply_piles_view; </code></pre> <p>I can't do this with <code>View&lt;Card&gt;</code> and <code>View&lt;SupplyPile&gt;</code>.</p> <h2>Other code</h2> <pre><code>class Card : public IInfo { public: Card(std::string name, int cost, int initial_supply, std::string text, std::string type); ~Card(); void Play(); std::string Info() const; std::string ToString() const; int cost() const; int initial_supply() const; std::string name() const; std::string text() const; private: int cost_; int initial_supply_; std::string name_; std::string text_; std::string type_; std::string set_; }; class SupplyPile : public IInfo { public: SupplyPile(const Card&amp; card, int initial_count); SupplyPile(const SupplyPile&amp; other); virtual ~SupplyPile(); virtual bool operator==(const SupplyPile&amp; other) const; bool BuyOrGain(); std::string Info() const; std::string ToString() const; const Card&amp; card() const; int count() const; std::string name() const; private: const Card&amp; card_; int count_; }; </code></pre>
[ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-02-09T04:56:15.050", "Id": "34537", "Score": "0", "body": "Your question isn't fully clear to me. If you create a `std::vector<IInfo*> x;` then you can do `push_back(new Card(...)`, `push_back(new SupplyPile(...))`. Templates aren't covariant, no, so if you have `template <typename T> class Foo` then `Foo<A>` and `Foo<B>` are totally separate types for any `A` and `B` (even if B derives from A), but I don't see where that's an issue in any of your code." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-02-11T19:39:15.830", "Id": "34689", "Score": "0", "body": "Updated with a snippet of code I wanted to write but can't." } ]
[ { "body": "<p>Is there any reason why <code>View</code> itself can't be a template?</p>\n\n<pre><code>template &lt;typename T&gt; class View {\npublic:\n View(const std::vector&lt;T&gt;&amp; items, int window_starty, int window_startx);\n virtual ~View() { }\n\n const T&amp; CurrentItem() const;\n // ...\n const std::vector&lt;T&gt;&amp; items_;\n // ...\n};\n\nView&lt;Card&gt; hand_view = new View&lt;Card&gt;(hand, starty, startx);\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-02-12T02:19:11.737", "Id": "34700", "Score": "0", "body": "This had occurred to me, but I'm not sure if it will work. There is one method that needs to call `ToString()` on an element of `items_`. If I can do that, then I should be able to convert to a template. Perhaps a cast is in order?" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-02-12T09:26:12.380", "Id": "34717", "Score": "0", "body": "Not a problem. `items_[0].ToString()` _etc_ will work fine." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-02-12T20:01:24.363", "Id": "34765", "Score": "0", "body": "Still not there. I edited the original question to explain the new problem: I want to be able to track which `View` is active at a given moment." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-02-13T11:22:15.773", "Id": "34793", "Score": "1", "body": "You could derive `View<T>` from a base class/ interface, so you could maintain a reference to that instead. Or even just have an enumerated constant to represent it. At this point though, you're straying even further from the site remit..." } ], "meta_data": { "CommentCount": "4", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-02-11T22:08:06.053", "Id": "21594", "ParentId": "21490", "Score": "1" } }, { "body": "<p>I ended up doing something I don't much like, but it works.</p>\n\n<p>I redesigned <code>View</code> to work with disposable copies of a new interface, <code>IViewable</code>. <code>IViewable</code> will be the link between the UI and the core logic. Every time a UI update is needed, copies of the items to display will be passed as <code>std::vector&lt;IViewable*&gt;</code>. </p>\n\n<p>The new <code>View</code> ctor is:</p>\n\n<pre><code> View(std::vector&lt;IViewable*&gt; *initial_items, int window_starty, int window_startx)\n</code></pre>\n\n<p>Updates need a new set of items to display each time, rather than using a reference to the originals like I wanted:</p>\n\n<pre><code> void Update(std::vector&lt;IViewable*&gt; *items);\n</code></pre>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-02-15T22:48:13.550", "Id": "22772", "ParentId": "21490", "Score": "0" } } ]
{ "AcceptedAnswerId": "22772", "CommentCount": "2", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-02-08T22:58:50.373", "Id": "21490", "Score": "3", "Tags": [ "c++", "beginner", "game", "playing-cards" ], "Title": "Dominion card game - how can I take advantage of interfaces?" }
21490
<p>After I found the Change Tracking feature in SQL Server, I thought that I would love to have this information in a stream. That lead me to RX, and Hot Observables. I did some reading and came up with this. I'm wondering if it could be improved.</p> <p>First is how I would use it, followed by the class that implements it:</p> <pre><code> var test = new MonitorDB.Server.PollChangeEvents(ConfigurationManager.ConnectionStrings["MonitorDB.Properties.Settings.db"].ToString()); test.IntervalDuration = 1; test.SubscribeToChangeTracking("MessageQueueStatus", "MessageQueueStatusID"); test.StartMonitorChangesAcrossAllTables(); var subject = Guid.NewGuid(); var observer = test.Listen(subject.ToString()); var sub1 = observer.Subscribe(msg =&gt; Console.WriteLine(string.Format("Table {0} Operation {1} Key {2} Value {3}", msg.TableName, msg.Operation, msg.KeyName, msg.KeyValue))); Console.ReadLine(); test.StopMonitoringChangesAcrossAllTables(); Console.ReadLine(); </code></pre> <hr> <pre><code>using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using System.Timers; using System.Data.SqlClient; using System.Collections.Concurrent; using System.Collections.ObjectModel; using System.Reactive.Linq; using System.Reactive.Disposables; namespace MonitorDB.Server { public class PollChangeEvents { Timer _timer; string _connectionString; private readonly IDictionary&lt;string, IObservable&lt;ChangeTrackingEvent&gt;&gt; observers = new Dictionary&lt;string, IObservable&lt;ChangeTrackingEvent&gt;&gt;(); public PollChangeEvents(string pConnectionString) { _timer = new Timer(); GC.KeepAlive(_timer); //prevents attempts at garbadge collection _timer.Elapsed += _timer_Elapsed; _ChangeTrackingEvents = new ConcurrentDictionary&lt;string, IChangeTrackingSubscription&gt;(); _connectionString = pConnectionString; } void _timer_Elapsed(object sender, ElapsedEventArgs e) { TableMonitoring.AsParallel().ForAll(pTableSubscription =&gt; { using (SqlConnection conn = new SqlConnection(_connectionString)) { conn.Open(); using (SqlCommand cmd = new SqlCommand()) { string CmdString = string.Format("select *, CHANGE_TRACKING_CURRENT_VERSION() from Changetable(changes {0},{1}) as T", pTableSubscription.Key, pTableSubscription.Value.LastChangeVersion); cmd.CommandText = CmdString; cmd.Connection = conn; SqlDataReader reader = cmd.ExecuteReader(); while (reader.Read()) { var newEvent = new ChangeTrackingEvent(pTableSubscription.Key, reader.GetName(5)); newEvent.Operation = reader[2].ToString(); newEvent.KeyValue = reader[newEvent.KeyName].ToString(); newEvent.LastChangeVersion = Int64.Parse(reader[6].ToString()); FIFOQueue.Enqueue(newEvent); pTableSubscription.Value.LastChangeVersion = newEvent.LastChangeVersion; } } conn.Close(); } }); } //Taken mostly from here //http://awkwardcoder.blogspot.ca/2012/06/understanding-refcount-in-reactive.html#!/2012/06/understanding-refcount-in-reactive.html // public IObservable&lt;ChangeTrackingEvent&gt; Listen(string subject) { IObservable&lt;ChangeTrackingEvent&gt; value; if (observers.TryGetValue(subject, out value)) return value; IObservable&lt;ChangeTrackingEvent&gt; observable = Observable.Create&lt;ChangeTrackingEvent&gt;(o =&gt; { var disposable = Observable.Timer(TimeSpan.FromMilliseconds(1), TimeSpan.FromMilliseconds(1)) .Timestamp() .Subscribe(ts =&gt; { ChangeTrackingEvent dequeuedEvent = null; FIFOQueue.TryDequeue(out dequeuedEvent); if (dequeuedEvent != null) o.OnNext(dequeuedEvent); } ); return new CompositeDisposable(disposable, Disposable.Create(() =&gt; observers.Remove(subject))); }) .Publish() //this makes it a hot observable, throw events without a subscription .RefCount(); observers.Add(subject, observable); return observable; } private ConcurrentQueue&lt;ChangeTrackingEvent&gt; FIFOQueue = new ConcurrentQueue&lt;ChangeTrackingEvent&gt;(); private int _IntervalDuration; public int IntervalDuration { get { return _IntervalDuration; } set { _IntervalDuration = value; } } ConcurrentDictionary&lt;string, IChangeTrackingSubscription&gt; _ChangeTrackingEvents; private ConcurrentDictionary&lt;string, IChangeTrackingSubscription&gt; TableMonitoring { get { return _ChangeTrackingEvents; } } public bool SubscribeToChangeTracking(string pTableName, string pKeyName) { var ChangeTrackingEvent = new ChangeTrackingEvent(pTableName, pKeyName); return _ChangeTrackingEvents.TryAdd(pTableName, ChangeTrackingEvent); } public void StartMonitorChangesAcrossAllTables() { _timer.Interval = this.IntervalDuration * 1000; _timer.Start(); } public void StopMonitoringChangesAcrossAllTables() { _timer.Stop(); } } } </code></pre>
[ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-02-09T00:43:10.087", "Id": "34532", "Score": "0", "body": "Also found this which may be way more efficient .. http://bit.ly/WWEdp0" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-05-31T09:13:54.463", "Id": "90311", "Score": "0", "body": "hey can you please provide a sample code for this?" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2015-06-29T14:45:55.077", "Id": "173409", "Score": "0", "body": "This implementation only works for tables with a single field primary key" } ]
[ { "body": "<pre><code>ConfigurationManager.ConnectionStrings[\"MonitorDB.Properties.Settings.db\"].ToString()\n</code></pre>\n\n<p>I wouldn't rely on <code>ToString()</code> here. <code>ToString()</code> is useful for getting human-readable representation of an object, but I think you shouldn't use it like this. Instead, use <a href=\"http://msdn.microsoft.com/en-us/library/system.configuration.connectionstringsettings.connectionstring.aspx\" rel=\"nofollow\">the <code>ConnectionString</code> property</a>.</p>\n\n<pre><code>GC.KeepAlive(_timer); //prevents attempts at garbadge collection\n</code></pre>\n\n<p>This line is completely useless and indicates you don't understand how GC works. If you put an object into a filed, it won't be GCed as long as the current object is also alive. The only thing <code>GC.KeepAlive()</code> does is that it makes sure the object won't be collected before that call, but it doesn't have any lasting effect. Because of that, it can be useful in some rare cases (like PInvoke) for local variables, but it's certainly not useful for fields.</p>\n\n<pre><code>string CmdString = string.Format(\"select *, CHANGE_TRACKING_CURRENT_VERSION() from Changetable(changes {0},{1}) as T\", pTableSubscription.Key, pTableSubscription.Value.LastChangeVersion);\n</code></pre>\n\n<p>You should <strong>never</strong> use string manipulation to create SQL queries, because it's unsafe. Instead, you should get into habit of always using parametrized queries. Also, you probably shouldn't use <code>*</code>, especially if you want to retrieve the columns by number.</p>\n\n<pre><code>newEvent.Operation = reader[2].ToString();\nnewEvent.KeyValue = reader[newEvent.KeyName].ToString();\nnewEvent.LastChangeVersion = Int64.Parse(reader[6].ToString());\n</code></pre>\n\n<p>Again, I think you shouldn't use <code>ToString()</code> here. If a value is <code>string</code>, cast it to <code>string</code>: <code>newEvent.Operation = (string)reader[2];</code> This way, if something changes, you're going to get an exception instead of nonsensical value. If a value is <code>long</code>, cast it to <code>long</code>: <code>newEvent.LastChangeVersion = (long)reader[6];</code> This is more efficient and if something changes, you're going to get a better exception.</p>\n\n<pre><code>conn.Close();\n</code></pre>\n\n<p>This is unnecessary. <code>Dispose()</code>, which is called automatically at the end of <code>using</code> block also closes the connection.</p>\n\n<pre><code>IObservable&lt;ChangeTrackingEvent&gt; observable = Observable.Create&lt;ChangeTrackingEvent&gt;(o =&gt;\n{\n var disposable = Observable.Timer(TimeSpan.FromMilliseconds(1), TimeSpan.FromMilliseconds(1))\n .Timestamp()\n .Subscribe(ts =&gt;\n {\n ChangeTrackingEvent dequeuedEvent = null;\n FIFOQueue.TryDequeue(out dequeuedEvent);\n if (dequeuedEvent != null)\n o.OnNext(dequeuedEvent);\n }\n );\n return new CompositeDisposable(disposable, Disposable.Create(() =&gt; observers.Remove(subject)));\n})\n.Publish() //this makes it a hot observable, throw events without a subscription\n.RefCount();\n</code></pre>\n\n<p>I think this is more complicated than it has to be. You certainly don't need to tick every millisecond. Also, I don't understand why are you even using the intermediate queue, you could send each change directly to the observable.</p>\n\n<p>Also, this won't work correctly if you create several listeners, each will get only part of the results.</p>\n\n<p>And I don't understand what is the purpose of the (badly named) <code>subject</code> parameter.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-02-11T16:40:47.513", "Id": "34681", "Score": "0", "body": "Thanks - I should have spent more time cleaning up the SQL, but I was concentrating on the Hot Observable and how to tie it to Change Tracking. Also, the Select from ChangeTable function will return a new column each time for the key field. I don't know how to create this select without using dynamic sql, as I don't think it's possible" } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-02-09T10:35:37.860", "Id": "21509", "ParentId": "21491", "Score": "2" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "3", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-02-09T00:34:22.890", "Id": "21491", "Score": "2", "Tags": [ "c#", "system.reactive" ], "Title": "Hot Observable of Change Tracking Events from SQL Server 2008 R2" }
21491
<pre><code> #include&lt;stdio.h&gt; #include&lt;stdlib.h&gt; #include&lt;string.h&gt; #include&lt;ctype.h&gt; #define MAX_FILE_LENGTH 500 // Gets the next line from the text file, returns the pointer to that line char* getLine(char* loc, FILE* fileStream); // Returns whether the given string contains the specified search pattern int checkStringMatch(char* toSearch, char* pattern); // Returns a lowercase copy of the string char* switchToLower(char* string); // Prints the given line to stdout, with lineNum if nonzero void printLine(int lineNum, char* fileName, char* text); // Processes a file, printing any lines in that file that match the given search pattern void processfile(char* filename, char* pattern ); // Checks for possible options and returns the number of enabled options int checkoptions(char** argv); // Global variables hold option state int optionn = 0; int optioni = 0; int main(int argc, char**argv) { // Make sure the minimum number of arguments is present if(argc &lt; 3) { fputs("Must provide a search pattern and at least 1 file.\n", stderr); return 1; } // Number of enabled options, used to detemine where search pattern is in argv int numoptions = checkoptions(argv); // Holds the search pattern char* pattern = argv[numoptions+ 1]; // If "-i" is used, change the pattern to lowercase if(optioni) { pattern = switchToLower(pattern); } int i; for(i=numoptions + 2; i &lt; argc; i++) { char* filename = argv[i]; processfile(filename, pattern); } // the switchToLower function resulted in pattern being malloc'd if(optioni) { free(pattern); } return 0; } int checkoptions(char** argv) { int numOptions = 0; if(checkStringMatch(argv[1], "-n") || checkStringMatch(argv[2], "-n")) { optionn = 1; numOptions++; } if(checkStringMatch(argv[1], "-i") || checkStringMatch(argv[2], "-i")) { optioni = 1; numOptions++; } return numOptions; } void processfile(char* filename, char* pattern) { FILE* f = fopen(filename, "r"); // If the file does not exist print an error message and return, otherwise process it if(!f) { fprintf(stderr, "File %s unopenable.\n", filename); return; } // Will hold each line scanned in from the file char* line = (char*)malloc(MAX_FILE_LENGTH*sizeof(char)); int lineNum = 1; while(!feof(f)) { line = getLine(line, f); // Only proceed if the line is non-null if(line) { // If the "-i" option is used compare the string after stripping case if(optioni) { char* lowerLine = switchToLower(line); if(checkStringMatch(lowerLine, pattern)) { printLine(lineNum*optionn, filename, line); } free(lowerLine); } else { if(checkStringMatch(line, pattern)) { printLine(lineNum*optionn, filename, line); } } lineNum++; } } // Close file and free line fclose(f); free(line); } char* getLine(char* loc, FILE* fileStream) { return fgets(loc, MAX_FILE_LENGTH, fileStream); } int checkStringMatch(char* toSearch, char* pattern) { char* exists = strstr(toSearch, pattern); if(exists) { return 1; } return 0; } char* switchToLower(char* str) { char* newString = (char*)malloc(sizeof(char)*strlen(str)); //Iterate through charaters in str, switch each letter to lowercase int i; for(i = 0; str[i]; i++) { newString[i]=tolower(str[i]); } return newString; } void printLine(int lineNum, char* fileName, char* text) { if(lineNum) { printf("%d %s %s", lineNum, fileName, text); } else { printf("%s %s", fileName, text); } } </code></pre>
[ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-02-09T08:25:23.467", "Id": "34547", "Score": "2", "body": "Do you want to ask a question or just show your code?" } ]
[ { "body": "<h2>Use of Malloc:</h2>\n\n<p>Where you do:</p>\n\n<pre><code>char* line = (char*)malloc(MAX_FILE_LENGTH*sizeof(char));\n</code></pre>\n\n<p><code>MAX_FILE_LENGTH</code> is known at compile time, and the scope of <code>line</code> doesn't\noutlive the function, thus there is no reason to utilize <code>malloc</code> - better\nto simply automatically allocate and allow it to be cleaned up at the end\nof the function instead of having to <code>free</code> the storage at the end.</p>\n\n<pre><code>char line[MAX_FILE_LENGTH];\n</code></pre>\n\n<p>You can also simplify this code:</p>\n\n<pre><code>line = getLine(line, f);\n\n// Only proceed if the line is non-null\nif(line)\n{ ... }\n</code></pre>\n\n<p>to</p>\n\n<pre><code>if(getline(line, f) != NULL) { ... }\n</code></pre>\n\n<h2>Problems with <code>switchToLower</code>:</h2>\n\n<p>Firstly, you <code>malloc</code> and return a new string - this places the onus on the\ncaller to <code>free</code> it later. Generally, unless there is a really good reason\nfor this, you should prefer the caller to already have allocated the buffer\nwhich you then utilize:</p>\n\n<pre><code>void switchToLower(const char *str, char* buf, size_t bufflen);\n</code></pre>\n\n<p>Have the caller pass in a string buffer which can then be written to. The \n<code>bufflen</code> is there make sure you only copy that many characters - this will\nhelp stop potential buffer overflows, which can be dangerous. Finally, it uses\n<code>const</code> to show that you're not modifying the original string at all.</p>\n\n<p>There's another problem with this function too - the string you return isn't\nnull-terminated. You've got an off by one error here:</p>\n\n<pre><code>char* newString = (char*)malloc(sizeof(char)*strlen(str));\n</code></pre>\n\n<p>This allocates enough storage for the characters but does <strong>not</strong> include \nstorage\nfor the null terminator. Every time you see a <code>malloc</code> with a <code>strlen</code>, always\nremember it should be <code>malloc(strlen(str) + 1)</code>. Also, per the C standard,\n<code>sizeof(char)</code> is always 1, hence it is unnecessary. The cast at the front \nis also unnecessary in C (although it is needed in C++). I'd write this as:</p>\n\n<pre><code>char* newString = malloc(strlen(str) + 1);\n</code></pre>\n\n<p>In fact, in this function, is there any reason you're not simply modifying\nthe original string that gets passed in? From the rest of the code, it seems\nas though it isn't used anywhere else, so simply modifying the original line\nmight be the best idea.</p>\n\n<h2>Usage help:</h2>\n\n<p>Something of a minor problem, but your usage string could be a bit better.\nFor one thing, it doesn't mention the order of arguments. Secondly, it doesn't\nmention anything about options (someone using this would need to look at\nthe actual code to know there was a case-insensitive comparison option). All\nthese options and argument orders should be incorporated into your usage string. Remember, you want to make it as clear as possible how to use this; if the user has to look at your code to figure it out, then your usage help isn't doing its job. </p>\n\n<h2>Indentation:</h2>\n\n<p>It looks as though you're using 8 space indentation - this is a bit of a\npersonal thing, but I consider this too whitespace heavy (and I imagine a lot\nof other programmers do as well). 4 spaces looks much nicer to my eyes.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-02-09T04:44:50.340", "Id": "21494", "ParentId": "21492", "Score": "2" } }, { "body": "<p>Yuushi covered pretty much everything, but a few more minor things stood out to me.</p>\n\n<hr>\n\n<p>I'm not a fan of the overuse of MAX_FILE_LENGTH.</p>\n\n<p>When you're setting up automatic duration buffers, sure, use <code>MAX_FILE_LENGTH</code>. You're making your functions significantly less flexible though when you assume that things are <code>MAX_FILE_LENGTH</code>.</p>\n\n<p>For example:</p>\n\n<pre><code>char* getLine(char* loc, FILE* fileStream)\n{\n return fgets(loc, MAX_FILE_LENGTH, fileStream);\n}\n</code></pre>\n\n<p>Should probably be:</p>\n\n<pre><code>char* getLine(char* loc, FILE* fileStream, size_t bufSize)\n{\n return fgets(loc, bufSize, fileStream);\n}\n</code></pre>\n\n<p>Then you'd call it like (assuming a stack allocated array):</p>\n\n<pre><code>char buf[MAX_FILE_LENGTH];\ngetline(buf, fh, sizeof(buf));\n</code></pre>\n\n<p>Note that getline can now be used in situations where you have differing buffer sizes. There's no need to constrain your function to one very specific use.</p>\n\n<hr>\n\n<p>That brings me to my next point: <code>getLine</code> shouldn't exist. It's just a (very) thin wrapper around fgets. Just use fgets inline. It's basically a lazy way to avoid typing MAX_FILE_LENGTH again, but as I said, you should avoid hard coding things when (reasonably) possible. (And yes, using a <code>#define</code>d constant is in a lot of ways essentially hard coding -- centralized hard coding yes, but hard coding nonetheless.)</p>\n\n<hr>\n\n<p>I'm not a fan of your fgets loop. It's typically better to just loop directory on fgets:</p>\n\n<pre><code>char line[MAX_FILE_LENGTH];\nwhile (fgets(line, sizeof(line), fh)) {\n //Do something with line\n //Note that if the line is longer than MAX_FILE_LENGTH - 1, line will not\n //actually be a line. You could check line for that though.\n}\n</code></pre>\n\n<hr>\n\n<p>I'm not a fan of the global option variables. In this situation you could easily make the case that they don't matter, but on a site that specializes in pedantic code criticisms, I'm obligated to point out that they're unnecessary and couple the functionality of some of some of your functions to magical hidden state. If you passed the options around, you could would be more flexible (it would also be marginally more cumbersome to write, but such is the woe of high quality code :)).</p>\n\n<hr>\n\n<p><code>MAX_FILE_LENGTH</code> seems to be a misnomer. Should not it be <code>MAX_LINE_LENGTH</code> (or maybe <code>MAX_FILE_LINE_LENGTH</code>)?</p>\n\n<hr>\n\n<p>Speaking of misnomers, <code>checkStringMatch</code> fits that too. <code>checkStringContains</code> would be better. Or perhaps <code>stringContains</code>. Not a fan of the <code>check</code> prefix. It sounds like the function is responsible for ensuring that the string matches, not that it simply checks (and yes, that sounds like crazy talk since I just said \"not that it simply <em>checks</em> -- maybe I just have weird naming habits).</p>\n\n<p>(Note: if you plan on extending checkStringMatch to do more than check substring existence, ignore this comment.)</p>\n\n<hr>\n\n<p>If you're going to comment your functions, you might as well use doc comments. They can be parsed by a lot of existing programs to make prettified documentation (well, API documentation, not true documentation). They also tend to be a bit easier to visually scan:</p>\n\n<pre><code>/**\n * Determines whether the given string contains the specified search pattern.\n * @param toSearch The string in which to search\n * @param pattern The pattern for which to search\n * @return true (non-zero) if toSearch contains pattern, and false (0) otherwise\n*/\nint checkStringMatch(char* toSearch, char* pattern);\n</code></pre>\n\n<hr>\n\n<p>A lot of your pointers being passed around could point to constant characters.</p>\n\n<p>It's a lot clearer (and better guaranteed) that <code>int checkStringMatch(const char* toSearch, const char* pattern)</code> doesn't change <code>toSearch</code> or <code>pattern</code> than <code>int checkStringMatch(char* toSearch, char* pattern)</code>.</p>\n\n<hr>\n\n<pre><code>if(checkStringMatch(argv[1], \"-n\") || checkStringMatch(argv[2], \"-n\"))\n</code></pre>\n\n<p>That doesn't make sense. You should probably just use strcmp.</p>\n\n<p>You could, however, extend the use of strstr to support situations like <code>fakegrep -ni pattern file</code>. Basically you'd just need to check if the first char is a <code>-</code> (so you know it's not a pattern [though excluding <code>-</code> from allowed patterns seems odd]) and then check for the existence of <code>n</code> and <code>i</code>.</p>\n\n<hr>\n\n<p>Rather than printing straight to stderr in <code>processfile</code> in the case of an error, you could return an error flag. That would allow you to be more flexible with your error handling.</p>\n\n<p>For example, if you wanted to add a <code>-q</code> flag later to suppress \"couldn't open file\" error messages, you could do something like:</p>\n\n<pre><code>#define PROCFILE_ERR_OK 0\n#define PROCFILE_ERR_OPENFAIL 1\n//#define PROFILE_ERR_... x\nfor (i = numoptions + 2; i &lt; argc; ++i) {\n int err;\n char* filename = argv[i];\n err = processfile(filename, pattern);\n if (err != PROCFILE_ERR_OK &amp;&amp; !suppressErrors) {\n //Do something\n }\n}\n</code></pre>\n\n<hr>\n\n<p>It would be easy to just use strstr inline anywhere you use checkStringMatch.</p>\n\n<p>When reading through your code, I had to look to see what checkStringMatch is, but I know what strstr is. The level of indirection can cause a bit of confusion (though checkStringContains would not).</p>\n\n<p>Since a NULL pointer is guaranteed to evaluate to false, you could even have the same usage:</p>\n\n<p>For example:</p>\n\n<pre><code>if(checkStringMatch(lowerLine, pattern))\n</code></pre>\n\n<p>Could be:</p>\n\n<pre><code>if(strstr(lowerLine, pattern))\n</code></pre>\n\n<p>If you plan to extend or change the functionality of checkStringMatch though, then this should obviously be ignored.</p>\n\n<hr>\n\n<p>This is 100% opinion, but <code>#include&lt;stdio.h&gt;</code> has always looked odd to me. <code>#include &lt;stdio.h&gt;</code> looks cleaner. Once again though, 100% opinion. To each his own.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-02-09T10:07:48.937", "Id": "21508", "ParentId": "21492", "Score": "2" } }, { "body": "<p>In addition to comments by others:</p>\n\n<ul>\n<li>reverse the order of functions to avoid prototypes.</li>\n<li>all functions except <code>main</code> should be <code>static</code></li>\n<li>use <code>getopt</code> for shell arg handling rather than rolling your own. See the\nmanual page for how to use it.</li>\n<li><code>argc &lt; 3</code> is wrong if there are options on the command line</li>\n<li><p>if there are lines longer than 500 characters, line numbers printed\nthereafter are wrong and the pattern string will not be found if it\nstraddles the 500 character boundary</p></li>\n<li><p>your grep does not read from <code>stdin</code> when there are no file arguments, for\nexample to detect \"string\" in the output of <code>program</code></p>\n\n<pre><code>program | grep -i \"string\"\n</code></pre></li>\n<li><p>if, while, for, etc should be followed by a space</p></li>\n<li><p>note that <code>strcasestr</code> can be used to do a case-insensitive search instead\nof modifying the pattern text and copying each input line.</p></li>\n<li><p>inconsistent capitalisation in naming: checkoptions, processfile, but\ngetLine, checkStringMatch</p></li>\n<li><p>Some comments are noisy (i.e. useless)</p></li>\n<li><p>use <code>perror</code> instead of <code>fprintf(stderr, ...)</code> on printing errors</p></li>\n<li><p><code>optionn</code> and <code>optioni</code> are too similar and do not convey meaning. Try\n<code>print_lines</code> and <code>ignore_case</code> if they are going to be global. There is\nlittle overhead in passing them as parameters in this program, so the\nglobals are unnecessary.</p></li>\n<li><p>passing <code>lineNum * optionn</code> to <code>printLine</code> is a hack. Just pass the line\nnumber and <code>optionn</code> or use the global in the function.</p></li>\n<li><p>you don't check for failure of <code>malloc</code>.</p></li>\n<li><p>the real grep doesn't always print the filename. When it does, it adds a\ncolon. It also adds a colon after the line numner.</p></li>\n<li><p>your <code>-i</code> does not work because you fail to terminate the string copy - as\n@Yuushi says, you must allocate an extra char and you must also set it</p>\n\n<pre><code>`newString[i] = '\\0';`\n</code></pre></li>\n<li><p>be aware that not everyone likes \"doc comments\". @Corbin's example could be\nrewritten more concisely as: </p>\n\n<pre><code>/* Return non-zero if input string 's' contains pattern 'p'\n*/\nstatic int checkStringMatch(const char *s, const char *p);\n</code></pre></li>\n</ul>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-02-09T23:49:49.480", "Id": "21526", "ParentId": "21492", "Score": "2" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "1", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-02-09T03:34:31.407", "Id": "21492", "Score": "-2", "Tags": [ "c" ], "Title": "c code emulating grep" }
21492
<p>I am trying to understand how genetic algorithms work. As with everything, I learn by attempting to write something on my own;however, my knowledge is very limited and I am not sure if I am doing this right.</p> <p>The purpose of this algorithm is to see how long it will take half of a herd to be infected by a disease if half of that population are already infected. It is just an example I came up with in my head so I am not sure if this would even be a viable example. </p> <p>Some feedback on how I can improve my knowledge would be nice.</p> <p>Here is the code:</p> <pre><code>import random def disease(): herd = [] generations = 0 pos = 0 for x in range(100): herd.append(random.choice('01')) print herd same = all(x == herd[0] for x in herd) while same == False: same = all(x == herd[0] for x in herd) for animal in herd: try: if pos != 0: after = herd[pos+1] before = herd[pos-1] if after == before and after == '1' and before == '1' and animal == '0': print "infection at", pos herd[pos] = '1' #print herd pos += 1 except IndexError: pass pos = 0 generations += 1 random.shuffle(herd) #print herd print "Took",generations,"generations to infect all members of herd." if __name__ == "__main__": disease() </code></pre> <p>I am looking for comments based on the logic of this algorithm. What can be improved, and what has to be improved to make this a true genetic algorithm if it isn't one already.</p>
[]
[ { "body": "<p>Extract methods <code>initHerd</code>, <code>processGeneration</code> and <code>infect</code>.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-02-09T08:12:27.293", "Id": "21501", "ParentId": "21495", "Score": "1" } }, { "body": "<p>your algorithm is not a genetic algorithm, it is a simple model of infection.</p>\n\n<p>genetic algorithm normally uses at least the following concepts: <strong>inheritance</strong>, <strong>mutation</strong>, <strong>selection</strong> (or fitness).<br>\nsee, e.g. <a href=\"http://en.wikipedia.org/wiki/Genetic_algorithm\">here</a></p>\n\n<p>if - for the sake of introductory understanding - you want to apply these concepts to your example: </p>\n\n<ul>\n<li><strong>inheritance</strong>:<br>\n<em>conceptual</em>: you need a <em>genetic identity</em> of your unit (the animal).<br>\n<em>code</em>: i.e. you need animals with state, different instances.<br>\n<em>how</em>: each animal inherits this <em>genetic identity</em> to the next generation when it is reproduced.</li>\n<li><strong>mutation</strong>:<br>\n<em>conceptual</em>: each generation is slightly different from the other.<br>\n<em>code</em>: each animal in a new generation has slightly different values than its parent.<br>\n<em>how</em>: apply some random modification. </li>\n<li><strong>selection</strong> of fitness:<br>\n<em>conceptual</em>: you select which units are reproduced for the next generation by the differences between the units. choose the fittest.<br>\n<em>code</em>: when assembling the new generation, choose only those units for reproduction that satisfy a certain fitness limit (e.g. the best 90%).<br>\n<em>how</em>: define a <em>fitness-function</em> which returns a value indicating relative fitness for each unit.</li>\n</ul>\n\n<p>to put it together, you could make e.g. different herds of animals that have different starting values for the 'genetic' attributes (e.g. preferred_proximity_to_next_animal, skin_color, height, aggressiveness, etc\n.).<br>\nThen, in your <em>fitness function</em>, you define how each of the attributes is connected to fitness, i.e. how they are related to the probability to get infected. then let the program run for a some of generations and see how at each iteration the global probability of infection decrease in relation to the genetic setup of your herd. </p>\n\n<p>Like that you might find favourable combinations of attributes.\nGenerally, genetic algorithms are used in <a href=\"http://en.wikipedia.org/wiki/Genetic_algorithm#Problem_domains\">search-related problems</a>. </p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-02-09T11:53:37.643", "Id": "21511", "ParentId": "21495", "Score": "5" } }, { "body": "<pre><code>import random\n\ndef disease():\n herd = []\n generations = 0\n pos = 0\n</code></pre>\n\n<p>Don't assign variables ahead of their use</p>\n\n<pre><code> for x in range(100):\n herd.append(random.choice('01'))\n print herd\n same = all(x == herd[0] for x in herd)\n while same == False:\n same = all(x == herd[0] for x in herd)\n</code></pre>\n\n<p>Firstly, don't check for <code>== False</code>, use <code>not</code>. Also, there isn't any point in storing it in same, just test it:</p>\n\n<pre><code> while not all(x == herd[0] for x in herd):\n</code></pre>\n\n<p>I'd suggest testing using:</p>\n\n<pre><code>while len(set(herd)) != 1:\n</code></pre>\n\n<p>Which will be more efficient.</p>\n\n<pre><code> for animal in herd:\n try:\n if pos != 0:\n after = herd[pos+1]\n before = herd[pos-1]\n if after == before and after == '1' and before == '1' and animal == '0':\n</code></pre>\n\n<p>There is no point in checking if <code>after == before</code> if you are already checking that after and before are both equal to '1'. I'd consider doing:</p>\n\n<pre><code>if (after, animal, before) == ('1','0','1'):\n</code></pre>\n\n<p>which in this case I think shows more clearly what's going on.</p>\n\n<pre><code> print \"infection at\", pos\n herd[pos] = '1'\n #print herd\n pos += 1\n except IndexError:\n pass\n</code></pre>\n\n<p>Its generally not a good idea to catch an IndexError. Its too easy to get an accidental IndexError and then have your code miss the real problem. It also doesn't communicate why you are getting an index error.</p>\n\n<p>Instead of updating pos, I suggest you use</p>\n\n<pre><code>for pos, animal in enumerate(herd):\n</code></pre>\n\n<p>However, since you don't want the first and last elements anyways, I'd suggest</p>\n\n<pre><code> for pos in xrange(1, len(herd) - 1):\n before, animal, after = herd[pos-1,pos+2]\n</code></pre>\n\n<p>Back to your code:</p>\n\n<pre><code> pos = 0\n</code></pre>\n\n<p>You should reset things just before a loop, not afterwards. That way its easier to follow. Although its even better if you can avoid the resting altogether</p>\n\n<pre><code> generations += 1\n random.shuffle(herd)\n #print herd\n print \"Took\",generations,\"generations to infect all members of herd.\"\nif __name__ == \"__main__\":\n disease()\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-02-10T01:42:23.037", "Id": "34582", "Score": "0", "body": "This was an amazing response. Thank you for breaking down my code, it was really informative." } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-02-09T15:53:47.347", "Id": "21515", "ParentId": "21495", "Score": "3" } } ]
{ "AcceptedAnswerId": "21511", "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-02-09T05:14:55.343", "Id": "21495", "Score": "1", "Tags": [ "python", "algorithm", "random" ], "Title": "What is wrong with my Genetic Algorithm?" }
21495
<p>I'm trying to learn Python by working my way through problems on the Project Euler website. I managed to solve problem #3, which is </p> <blockquote> <p>What is the largest prime factor of the number 600851475143 ?</p> </blockquote> <p>However, my code looks horrible. I'd really appreciate some advice from experienced Python programmers.</p> <pre><code>import math import unittest def largestPrime(n, factor): """ Find the largest prime factor of n """ def divide(m, factor): """ Divide an integer by a factor as many times as possible """ if m % factor is 0 : return divide(m / factor, factor) else : return m def isPrime(m): """ Determine whether an integer is prime """ if m is 2 : return True else : for i in range(2, int(math.floor(math.sqrt(m))) + 1): if m % i is 0 : return False return True # Because there is at most one prime factor greater than sqrt(n), # make this an upper limit for the search limit = math.floor(math.sqrt(n)) if factor &lt;= int(limit): if isPrime(factor) and n % factor is 0: n = divide(n, factor) if n is 1: return factor else: return largestPrime(n, factor + 2) else: return largestPrime(n, factor + 2) return n </code></pre>
[]
[ { "body": "<p>Some thoughts:</p>\n\n<p><code>Divide</code> function has been implemented recursively. In general, recursive implementations provide clarity of thought despite being inefficient. But in this case, it just makes the code cumbersome.</p>\n\n<pre><code>while m % factor == 0:\n m /= factor\nreturn m\n</code></pre>\n\n<p>should do the job.</p>\n\n<hr>\n\n<p>A lot of computational work is done by <code>isPrime</code> which is unnecessary. Eg: when <code>factor</code> 15 is being considered, the original n would've been already <code>Divide</code>d by 3 and 5. So, if <code>factor</code> is not a prime then n%factor will not be 0.</p>\n\n<hr>\n\n<p>So, the following should do:</p>\n\n<pre><code>import math\ndef largestPF(n):\n limit = int(math.sqrt(n)) + 1\n for factor in xrange(2, limit+1):\n while n % factor == 0:\n n /= factor\n if n == 1:\n return factor\n return n\n</code></pre>\n\n<p>You can of course, include the 'run through factors in steps of 2' heuristic if you want.</p>\n\n<hr>\n\n<p>PS: Be careful with the <code>is</code> statement for verifying equality. It might lead to unexpected behaviour. Check out <a href=\"https://stackoverflow.com/questions/1504717/python-vs-is-comparing-strings-is-fails-sometimes-why\">https://stackoverflow.com/questions/1504717/python-vs-is-comparing-strings-is-fails-sometimes-why</a></p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-02-09T10:04:35.397", "Id": "21507", "ParentId": "21497", "Score": "5" } } ]
{ "AcceptedAnswerId": "21507", "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-02-09T06:35:13.020", "Id": "21497", "Score": "4", "Tags": [ "python", "project-euler", "primes" ], "Title": "Largest Prime Factor" }
21497
<p>I am trying to insert into a database using JDBC and each thread will be inserting into the database. I need to insert around 30-35 columns. I wrote a stored procedure that will UPSERT into those columns. </p> <p>The problem I am facing is that in the <code>run()</code> method, I have around 30 columns written over there for insertion. Is there any way I can simplify my run method so that it doesn't looks so messy which is looking right now for me? And I have a few more columns as well. So if I keep on adding new columns there, it will be looking so messy at one point in my run method.</p> <p>Is there any way to clean this, keeping in mind the thread safety issues?</p> <pre><code>class Task implements Runnable { private Connection dbConnection = null; private CallableStatement callableStatement = null; public Task() { } @Override public void run() { dbConnection = getDbConnection(); callableStatement = dbConnection.prepareCall(Constants.UPSERT_SQL); callableStatement.setString(1, String.valueOf(userId)); callableStatement.setString(2, Constants.getaAccount(userId)); callableStatement.setString(3, Constants.getaAdvertising(userId)); callableStatement.setString(4, Constants.getaAvgSellingPriceMainCats(userId)); callableStatement.setString(5, Constants.getaCatAndKeywordRules(userId)); callableStatement.setString(6, Constants.getaClvBehavior(userId)); callableStatement.setString(7, Constants.getaClvChurn(userId)); callableStatement.setString(8, Constants.getaClvInfo(userId)); callableStatement.setString(9, Constants.getaClvSegmentation(userId)); callableStatement.setString(10, Constants.getaCsaCategoriesPurchased(userId)); callableStatement.setString(11, Constants.getaCustomerService(userId)); callableStatement.setString(12, Constants.getaDemographic(userId)); callableStatement.setString(13, Constants.getaFinancial(userId)); callableStatement.setString(14, Constants.getaGeolocation(userId)); callableStatement.setString(15, Constants.getaInterests(userId)); callableStatement.setString(16, Constants.getaLastContributorsPurchased(userId)); callableStatement.setString(17, Constants.getaLastItemsLost(userId)); callableStatement.setString(18, Constants.getaLastItemsPurchased(userId)); callableStatement.setString(19, Constants.getaLastProductsPurchased(userId)); callableStatement.setString(20, Constants.getaLastSellersPurchasedFrom(userId)); callableStatement.setString(21, Constants.getaMainCategories(userId)); callableStatement.setString(22, Constants.getaMessaging(userId)); callableStatement.setString(23, Constants.getaPositiveSellers(userId)); callableStatement.setString(24, Constants.getaPromo(userId)); callableStatement.setString(25, Constants.getaScores(userId)); callableStatement.setString(26, Constants.getaSegmentation(userId)); callableStatement.setString(27, Constants.getaSellers(userId)); callableStatement.setString(28, Constants.getaSrpBuyerUpiCount(userId)); } } private Connection getDBConnection() { Connection dbConnection = null; Class.forName(Constants.DRIVER_NAME); dbConnection = DriverManager.getConnection(url,user,password); return dbConnection; } </code></pre>
[ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-02-09T07:55:28.153", "Id": "34542", "Score": "3", "body": "I have the felling that your Constants are not constant." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-02-09T08:09:11.997", "Id": "34544", "Score": "0", "body": "Yeah, they are not constants. Before posting here I have renamed the name just to shorten it." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-02-09T08:27:48.057", "Id": "34548", "Score": "0", "body": "As callableStatement is an instance field it is not shared and there is no need to synchronize it." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-02-09T08:59:53.080", "Id": "34549", "Score": "0", "body": "Thanks mnhg for the suggestion. In general how do we decide when we want to synchronize the method? If you cane explain me then I can understand more. Thanks for the help." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-02-09T13:21:01.607", "Id": "34558", "Score": "0", "body": "Can you provide a bit more detail on what the \"constant\" methods are doing? Are they retrieving a simple value, or calculating some things? Given the only argument is userId it looks like it might be a simple lookup. Is it from a database, or something hard-coded, or previously read in from the database? If there is an explicit table mapping userId to various values you could simplify things by iterating the table to create the callableStatement. Any new additions to the table would automatically be picked up then when creating the statement." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-02-10T01:26:15.670", "Id": "34581", "Score": "0", "body": "There's nothing ugly about this code - it's well-written, clear, and straightforward. You can't make it any better, even by refactoring out all the `setString()`s." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-02-11T23:00:56.620", "Id": "34693", "Score": "0", "body": "You might want to look at using a library such as iBatis to do much of the legwork for you. Here's a simple example that demonstrates [calling a stored function with iBatis](http://3rdstage.blogspot.com/2008/12/using-stored-procedure-with-ibatis.html)." } ]
[ { "body": "<p><strong>Extract a method.</strong></p>\n\n<pre><code>class Task implements Runnable {\n\n ... \n private completeStatement (CallableStatement stmt, Strung userId)\n {\n callableStatement.setString(1, String.valueOf(userId));\n ...\n } \n\n @Override\n public void run() {\n dbConnection = getDbConnection();\n callableStatement = dbConnection.prepareCall(Constants.UPSERT_SQL);\n completeStatement(callableStatement,userId) \n\n }\n}\n\nprivate Connection getDBConnection() {\n ...\n}\n</code></pre>\n\n<p>But find a more suitable name for what your statement is doing.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-02-09T08:08:35.943", "Id": "34543", "Score": "0", "body": "I was not able to understand what do you mean? Can provide some example so that I can understand better?" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-02-09T08:15:43.510", "Id": "34545", "Score": "0", "body": "I update the code." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-02-09T08:19:07.297", "Id": "34546", "Score": "0", "body": "Thanks mnhg for the suggestion. Now it is more clear. One more doubt I have is, in this case we won't be making `completeStatement ` method `synchronized`?" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-02-09T09:10:54.087", "Id": "34550", "Score": "0", "body": "There are many discussion on stackoverflow regarding this topic: [start here](http://stackoverflow.com/questions/9840959/how-to-judge-which-object-to-be-synchronized-in-java-thread/9841004#9841004)" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-02-09T13:26:37.040", "Id": "34559", "Score": "0", "body": "+1 because the first step is to isolate the code in its own method. I think more may be possible, depending what those Constants.xxx() methods are doing." } ], "meta_data": { "CommentCount": "5", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-02-09T07:58:26.853", "Id": "21499", "ParentId": "21498", "Score": "4" } }, { "body": "<p>Some minor notes:</p>\n\n<ol>\n<li><p><code>dbConnection</code> and <code>callableStatement</code> might be local variables.</p></li>\n<li><p>If more than one thread calls the <code>run</code> method at the same time the shared <code>dbConnection</code> and <code>callableStatement</code> references might lead to resource leaks/race conditions.</p></li>\n<li><p>I'd consider using <a href=\"http://docs.oracle.com/javase/6/docs/api/java/sql/CallableStatement.html#setString%28java.lang.String,%20java.lang.String%29\" rel=\"nofollow\"><code>setString(String parameterName, String x)</code></a> which uses readable parameter names instead of integer indexes.</p></li>\n</ol>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-02-18T14:43:03.793", "Id": "35130", "Score": "1", "body": "(10k! Whoah! Congrats!)" } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-02-11T21:27:43.900", "Id": "21593", "ParentId": "21498", "Score": "2" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "7", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-02-09T07:51:19.410", "Id": "21498", "Score": "2", "Tags": [ "java", "database", "jdbc" ], "Title": "Inserting into a database using JDBC" }
21498
<p>My program calculates the determinant of a matrix of any degree. If you really can't understand my comments or indentifiers please let me know.</p> <pre><code>//;;MakeShift make element number 'ind' the head of list: (defun MakeShift (ind L buf) (if (= ind 1) (cons (car L) (append buf (cdr L))) (makeReplace (- ind 1) (cdr L) (append buf (list (car L)))) ) ) //;;Shift call MakeShift: (defun Shift (ind L) (MakeShift ind L nil)) //;;makeTransp make transposition of two elements list: (defun makeTransp (L) (cons (cadr L) (cons (car L) nil))) //;;PushForEach put element elem into a heads of all lists of L: (defun PushForEach (elem L) (if (null L) nil (cons (cons elem (car L)) (PushForEach elem (cdr L))) ) ) //;;MakeTranspositions create a list of all transpositions //;;using first transposition like '(1 2 3 ...). //;;transpNum is transpositions number and numOfElem //;;is amount of elements in transposition: (defun MakeTranspositions (transp transpNum numOfElem) (cond ((&gt; transpNum numOfElem) nil) ((= numOfElem 2) (cons transp (cons (makeTransp transp) nil))) (T (append (PushForEach (car transp) (MakeTranspositions (cdr transp) 1 (- numOfElem 1))) (MakeTranspositions (Shift (+ transpNum 1) transp) (+ transpNum 1) numOfElem))) ) ) //;;MakeFirstTransp make a first transpositiion like '(1 2 3 ... ) //;;which has number of element equal matrix degree: (defun MakeFirstTransp (matrixDegree transp) (if (= matrixDegree 0) transp (MakeFirstTransp (- matrixDegree 1) (cons matrixDegree transp)) ) ) //;;Transpositions make all transpositions of matrix using MakeTranspositions: (defun Transpositions (matrixDegree) (MakeTranspositions (MakeFirstTransp matrixDegree nil) 1 matrixDegree) ) //;;GetCol return elemnt number col in row (row belong to matrix): (defun GetCol (col rowVector) (if (= col 1) (car rowVector) (GetCol (- col 1) (cdr rowVector)) ) ) //;;GetElem return element a[row][col] which belong to matrix: (defun GetElem (row col matrix) (if (= row 1) (GetCol col (car matrix)) (GetElem (- row 1) col (cdr matrix)) ) ) //;;CheckFirst check first element in transposition (cons first transp) for even: (defun CheckFirst (first transp) (cond ((null transp) 1) ((&lt; first (car transp)) (CheckFirst first (cdr transp))) (T (* -1 (CheckFirst first (cdr transp)))) ) ) //;;Sign return sign of transposition (1 or -1): (defun Sign (transp) (if (null (cdr transp)) 1 (* (CheckFirst (car transp) (cdr transp)) (Sign (cdr transp))) ) ) //;;Product return product of elements of matrix by transposition transp: (defun Product (matrix transp) (GetProduct matrix 1 transp)) //;;GetProduct are called by Product: (defun GetProduct (matrix ind transp) (if (null transp) 1 (* (GetElem ind (car transp) matrix) (GetProduct matrix (+ ind 1) (cdr transp)) ) ) ) //;;GetSumm return summ of all products by transpositions whith their signs: (defun GetSumm (matrix transps) (if (null transps) 0 (+ (* (Sign (car transps)) (Product matrix (car transps))) (GetSumm matrix (cdr transps)) ) ) ) //;;Determinant call GetSumm: (defun Determinant (matrix matrixDegree) (GetSumm matrix (Transpositions matrixDegree)) ) //;;So, programm work fast. </code></pre>
[ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-02-09T11:50:32.597", "Id": "34554", "Score": "1", "body": "You may want to document the data structures used and provide an example how the code is supposed to be used." } ]
[ { "body": "<p><strong>The first thing is to learn proper indentation.</strong></p>\n\n<pre><code>//;;PushForEach put element elem into a heads of all lists of L:\n(defun PushForEach (elem L)\n (if (null L) nil (cons (cons elem (car L)) (PushForEach elem (cdr L)))\n )\n)\n</code></pre>\n\n<p>What's wrong with the code layout?</p>\n\n<ul>\n<li>Common Lisp has built-in documentation features. A documentation string can be placed inside the function and can be retrieved with the <code>DOCUMENTATION</code>function.</li>\n<li>trailing parentheses are a big DON'T DO THAT. It just wastes space without adding much information. Your editor will count parentheses or will show the corresponding parentheses.</li>\n<li>put constructs, when they are too long on a line, over several lines.</li>\n<li>don't use CamelCase, use hyphens</li>\n</ul>\n\n<p>Let's do the editing step by step:</p>\n\n<pre><code>(defun PushForEach (elem L)\n \"put element elem into a heads of all lists of L\"\n (if (null L) nil (cons (cons elem (car L)) (PushForEach elem (cdr L)))\n )\n)\n\n(defun PushForEach (elem L)\n \"put element elem into a heads of all lists of L\"\n (if (null L) nil (cons (cons elem (car L)) (PushForEach elem (cdr L)))))\n</code></pre>\n\n<p>Now we get the version which is best readable:</p>\n\n<pre><code>(defun push-for-each (elem L)\n \"put element elem into a heads of all lists of L\"\n (if (null L)\n nil\n (cons (cons elem (car L))\n (push-for-each elem (cdr L)))))\n</code></pre>\n\n<p>Above function has a documentation string and useful code layout.</p>\n\n<p>Next: can we write it better? You can bet that basic recursion in Lisp has been provided as a higher-order function. Applying a function over all items in a list is called <em>mapping</em>. The basic mapping function is <code>MAPCAR</code>.</p>\n\n<pre><code>(defun push-for-each (element list)\n \"adds element as head of all sublists of list\"\n (mapcar #'(lambda (item)\n (cons element item))\n list))\n</code></pre>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-02-09T11:46:52.707", "Id": "21510", "ParentId": "21503", "Score": "3" } } ]
{ "AcceptedAnswerId": "21510", "CommentCount": "1", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-02-09T08:58:35.680", "Id": "21503", "Score": "2", "Tags": [ "matrix", "common-lisp" ], "Title": "Determinant calculation of a matrix of any degree" }
21503
<p>I'm writing a dependency injection plugin for the <a href="http://backbonejs.org/" rel="nofollow">Backbone</a> javascript framework, and I'm not sure what the API for constructor argument injection should look like. </p> <p>Just for reference, Backbone objects are defined as follows:</p> <pre><code>var LoginView = Backbone.View.extend({ //constructor initialize: function(options) { //define an instance property this.loginProvider = options.loginProvider; }, //method authenticate: function() { }, //prototypal property (available via instance, shared between all instances) navigation: App.navigationService }); </code></pre> <p>My plugin supports instance property injection as follows:</p> <pre><code>var LoginView = Backbone.View.extend({ //... loginProvider: needs.property('LoginProvider') }); var loginView = new LoginView(); loginView.loginProvider.doLogin(); //loginProvider is auto-injected </code></pre> <p>I'm quite happy with this, but I also want to support constructor argument injection. Here I have run into doubt regarding best way forward. Here are the options I've considered:</p> <ol> <li><p>Add <strong>class method <code>inject</code></strong></p> <pre><code>var LoginView = Backbone.View.extend({ initialize: function(options, bar) { //property "foo" will be injected to options //second argument "bar" will be injected } }).inject({foo:'Foo'}, 'Bar'); </code></pre> <p>This is clean, but it "hides" the injection to the bottom of the class definition. I feel the constructor injection configuration should be somewhere <em>near</em> the constructor, at the very least.</p></li> <li><p><strong>Wrap the <code>initialize</code> method</strong></p> <pre><code>var LoginView = Backbone.View.extend({ initialize: needs.args({foo:'Foo'}, 'Bar', function(options, bar) { //property "foo" will be injected to options //second argument "bar" will be injected } }); </code></pre> <p>Now the injected arguments are right next to the constructor definition, but this gets a bit messy when you have more than one or two dependencies:</p> <pre><code>var LoginView = Backbone.View.extend({ initialize: needs.args( { foo:'Foo', bar:'Bar' }, 'BazService', 'QuxFactory', function(options, baz, qux) { //... }) }); </code></pre> <p>This method also lies to the user, because the arguments are not <strong>actually</strong> injected to the <code>initialize</code> method directly. Instead they are injected into the class constructor function, which in turn passes them to <code>initialize</code>.</p></li> <li><p><strong>Define a "convention-based" property <code>injectArgs</code>, which is used, if present</strong></p> <pre><code>var LoginView = Backbone.View.extend({ injectArgs: [{foo:'Foo'}, 'Bar'], initialize: function(options, bar) { //property "foo" will be injected to options //second argument "bar" will be injected } }); </code></pre> <p>This solves problems posed by options 1 and 2, but it feels... icky. Because the property is defined on the class prototype, it will continue to hang around on every instance of the object even after initialization and I don't think it has any business being there.</p></li> <li><p><strong>None of the above</strong></p> <p>Got a better idea? I want to keep the plugin unobtrusive, so there are two maxima I want to keep to: No modifying <code>Object</code> prototype, and the <code>Backbone</code> objects must be creatable by <code>extend</code>, so no factory tricks.</p></li> </ol>
[ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-05-02T03:55:37.817", "Id": "60209", "Score": "0", "body": "There is a good article http://www.merrickchristensen.com/articles/javascript-dependency-injection.html that could help you out." } ]
[ { "body": "<p>If I had to pick, I would pick the second option. It's the clearest to me and aligns well with how the plugin injects properties. I don't think it's \"lying\" to the user because it's obvious that the needs.args function is doing something with the arguments before passing back control to the actual initialize function. But like you said, long arg lists will be annoying.</p>\n\n<p>My only other note would be that I'm unsure how useful injection is in a dynamic language like javascript. I've used in statically typed languages like Java where it's definitely useful, but never entertained the idea in js. I'd definitely be curious to see the final result.</p>\n\n<p>Edit: After some research there looks like another alternative - reflection: <a href=\"http://merrickchristensen.com/articles/javascript-dependency-injection.html\" rel=\"nofollow\">http://merrickchristensen.com/articles/javascript-dependency-injection.html</a></p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-03-01T13:49:20.237", "Id": "35934", "Score": "0", "body": "Thanks for your input, and sorry for the delay in reply. Argument name reflection would be neat, but unfortunately it breaks down when code is minified and argument names get mangled. I think DI in JS can be very helpful (especially for testability), since it gives structure to dependency resolution as compared to just using some global object and attaching properties to it. Work in progress is here: https://github.com/fencliff/needly - haven't had a chance to work on it for a while, but hope to make the push to get it good and going soon." } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-02-14T04:17:50.810", "Id": "22694", "ParentId": "21514", "Score": "2" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "1", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-02-09T13:29:09.370", "Id": "21514", "Score": "4", "Tags": [ "javascript", "api", "backbone.js" ], "Title": "Backbone.js Dependency Injection API Design" }
21514
<p>I was thinking about a solution to store preferences and access to them in a most natural way. I came up with the solution below. My questions are: what do you think about the solution? Can it be improved (except maybe using macros)? Is it too complicated (to use)? </p> <p>And most important: <strong>does anyone know of a project where something like this has already been solved?</strong> Maybe even using macros? Could also be done using ".properties"-files or some other file-based storage. Thanks.</p> <pre><code>trait PrefsStorage { def get(key: String, default: String): String def put(key: String, newValue: String) } abstract class UserPrefs[P &lt;% PrefsStorage, T] { protected val prefs: P protected val key: String protected val default: T private[this] var bufferedValue: T = fromString(prefs.get(key, stringFrom(default))) // conversion from and to String def fromString(str: String): T def stringFrom(newValue: T): String = newValue.toString // setter and getter final def value_=(newValue: T) = { prefs.put(key, stringFrom(newValue)); bufferedValue = newValue } final def value: T = bufferedValue // setter and getter for easier access from the outside final def getter() = value final def setter = {value_=_} } abstract class DefaultUserPrefs[P &lt;% PrefsStorage, T](protected val prefs: P, protected val key: String, protected val default: T) extends UserPrefs[P, T] class FunUserPrefs[P &lt;% PrefsStorage, T](protected val prefs: P, protected val key: String, protected val default: T, convertFromString: String =&gt; T) extends UserPrefs[P, T] { def fromString(str: String) = convertFromString(str) } class IntUserPrefs[P &lt;% PrefsStorage](protected val prefs: P, protected val key: String, protected val default: Int) extends UserPrefs[P, Int] { def fromString(str: String) = str.toInt } class BooleanUserPrefs[P &lt;% PrefsStorage](protected val prefs: P, protected val key: String, protected val default: Boolean) extends UserPrefs[P, Boolean] { def fromString(str: String) = str.toBoolean } class StringUserPrefs[P &lt;% PrefsStorage](protected val prefs: P, protected val key: String, protected val default: String) extends UserPrefs[P, String] { def fromString(str: String) = str } class DoubleUserPrefs[P &lt;% PrefsStorage](protected val prefs: P, protected val key: String, protected val default: Double) extends UserPrefs[P, Double] { def fromString(str: String) = str.toDouble } // Helper object to create preferences object UserPrefs { class UserPrefsCreate[P &lt;% PrefsStorage](val prefs: P) { def apply(key: String, default: Int) = new IntUserPrefs[P](prefs, key, default) def apply(key: String, default: Boolean) = new BooleanUserPrefs[P](prefs, key, default) def apply(key: String, default: String) = new StringUserPrefs[P](prefs, key, default) def apply(key: String, default: Double) = new DoubleUserPrefs[P](prefs, key, default) def apply[T](key: String, default: T, fun: String =&gt; T) = new FunUserPrefs[P, T](prefs, key, default, fun) } def apply(prefs: PrefsStorage) = new UserPrefsCreate(prefs) } // some implicit helpers object UseAsPreferencesImplicits { import java.util.prefs.Preferences import scala.language.implicitConversions implicit def preferences2PrefsStorage(prefs: Preferences) = new PrefsStorage { def get(key: String, default: String) = prefs.get(key, default) def put(key: String, newValue: String) { prefs.put(key, newValue) } } } object UserPrefsImplicits { import scala.language.implicitConversions implicit def UserPrefsToType[P &lt;% PrefsStorage, T](up: UserPrefs[P, T]) = up.value implicit def userPrefs2Getter[T](userPrefs: UserPrefs[PrefsStorage, T]) = userPrefs.getter implicit def userPrefs2Setter[T](userPrefs: UserPrefs[PrefsStorage, T]) = userPrefs.setter } </code></pre> <p>The basic types String, Int, Double and Boolean are wrapped easily. But also tuples, arrays, etc. can be extended. The usage is displayed in the test code below. I haven't written unit tests (yet), but the sample progam should work nicely, storing some values to the user preferences.</p> <pre><code>object TestUserPrefs extends App { class Sample { import UseAsPreferencesImplicits._ import java.util.prefs.Preferences.userNodeForPackage // sample usage of UserPrefsCreate protected val createPrefs = UserPrefs(userNodeForPackage(Sample.this.getClass)) // numTuple and numberOfCalls are saved to the preferences val numTuple = createPrefs("numTuple", (1, 2), str =&gt; { val idx = str.indexOf(',') str.substring(1, idx).toInt -&gt; str.substring(idx + 1, str.length - 1).toInt }) val intArray = new DefaultUserPrefs(createPrefs.prefs, "intArray", Array(8, 9)) { override def stringFrom(newValue: Array[Int]) = newValue.mkString(",") def fromString(str: String) = str.split(',').map(_.toInt) } val numberOfCalls = createPrefs("numberOfCalls", 0) } val sample = new Sample println(sample.numTuple.value) // (1,2) when executed the first time, (5,6) afterwards sample.numTuple.value = (3, 4) println(sample.numTuple.value) // (3,4) sample.numTuple.value = (5, 6) println(sample.numTuple.value) // (5,6) println(sample.intArray.value.mkString(",")) // 8,9 first, then 1,2,3 sample.intArray.value = Array(1, 2, 3) sample.numberOfCalls.value += 1 // incremented for each execution of TestUserPrefs println("number of calls: " + sample.numberOfCalls.value) } </code></pre>
[ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-02-09T20:43:53.143", "Id": "34570", "Score": "0", "body": "Could you describe your design goals and requirements? To _store and access preferences in a natural way_ is too vague. For example, why not just use Scala's case classes to represent preferences and serialize them to JSON or YAML? Do you need dynamic preferences (with keys unknown at compile time)? If so, in what way you want them to be type-safe?" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-02-09T22:09:16.630", "Id": "34574", "Score": "0", "body": "My design goal is to save some user preferences that can be configured in a dialog and some implicit settings like \"last opened files\". This should be done in a transparent way - the user of that library wouldn't need to call \"save\" explicitly and the save location is configured automatically. Also a value that is used as an Int should be loaded as such. But YAML is a good point - maybe a wrapper to snakeyaml (defining setters and getters in a scala-like fashion) would be nice. The [YAML-example](http://code.google.com/p/snakeyaml/wiki/Documentation#Type_safe_collections) looks pretty nice!" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-02-10T10:03:44.843", "Id": "34595", "Score": "0", "body": "That doesn't seem to be very transparent though - example:\n`val bar = config.getInt(\"simple-lib.bar\")` - in my example code you could use `config.bar` directly as `Int`." } ]
[ { "body": "<p>You had asked if anyone has solved this. Take a look at, <a href=\"https://github.com/paradigmatic/Configrity\" rel=\"nofollow\">Configrity</a>. It has the same functionality, however it doesn't use <code>java.util.prefs.Preferences</code>, to store preferences in. Does have interoperability with <code>java.util.Properties</code>, that's close enough for me. </p>\n\n<p>Also it supports YAML import/export. </p>\n\n<p>I have a feeling the author of Configrity was not thinking of desktop usage.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-10-16T01:00:30.953", "Id": "32734", "ParentId": "21521", "Score": "2" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "3", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-02-09T20:10:51.330", "Id": "21521", "Score": "2", "Tags": [ "scala" ], "Title": "Type-safe user preferences in scala" }
21521
<p>This is the first program (that is not doing much basically), and I know usually you define classes in separate files. I just wanted to see if I got the syntax right, and the concept of using objects from the first chapter of the book. </p> <pre><code>#import &lt;Foundation/Foundation.h&gt; //interface section @interface Watch: NSObject -(void) setHours: (int) h; -(void) setMinutes: (int) m; -(int) getHours; -(int) getMinutes; -(void) printTime; @end //implemetation section @implementation Watch { int hours; int minuts; } - (void) setHours: (int) h { hours = h; } - (void) setMinutes:(int) m { minuts = m; } - (int) getHours { return hours; } - (int) getMinutes { return minuts; } -(void) printTime { NSLog(@"Time is %i:%i", hours, minuts); } @end //the program section int main(int argc, const char * argv[]) { @autoreleasepool { Watch *myWatch = [[Watch alloc]init]; [myWatch getHours]; [myWatch getMinutes]; [myWatch setHours: 5]; [myWatch setMinutes: 30]; [myWatch printTime]; } return 0; } </code></pre>
[]
[ { "body": "<p>You should definitely check out how <a href=\"http://developer.apple.com/library/mac/documentation/Cocoa/Conceptual/ProgrammingWithObjectiveC/EncapsulatingData/EncapsulatingData.html#//apple_ref/doc/uid/TP40011210-CH5-SW5\" rel=\"nofollow\">properties</a> can make your code shorter, by adding some standard setter/getter </p>\n\n<pre><code>@interface Watch: NSObject\n\n@property int hours;\n@property int minutes;\n-(void) printTime;\n\n@end\n\n\n@implementation Watch \n\n-(void) printTime\n{\n NSLog(@\"Time is %i:%i\", _hours, _minutes);\n}\n\n@end\n</code></pre>\n\n<p>Also the naming convention of a getter is the property name</p>\n\n<pre><code>int main(int argc, const char * argv[])\n{\n\n @autoreleasepool\n {\n Watch *myWatch = [[Watch alloc]init];\n [myWatch setHours: 5];\n [myWatch setMinutes: 30];\n\n int hours = [myWatch hours]; //standard getter\n int minutes = [myWatch minutes];\n [myWatch printTime];\n }\n return 0;\n}\n</code></pre>\n\n<p><a href=\"http://developer.apple.com/library/mac/#documentation/Cocoa/Conceptual/ProgrammingWithObjectiveC/Conventions/Conventions.html#//apple_ref/doc/uid/TP40011210-CH10-SW1\" rel=\"nofollow\">naming conventions</a> are important in Cocoa, as higher level technologies as Key-Value-Observing depends on them.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-02-13T02:30:42.420", "Id": "21648", "ParentId": "21527", "Score": "2" } } ]
{ "AcceptedAnswerId": "21648", "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-02-10T00:50:11.517", "Id": "21527", "Score": "1", "Tags": [ "objective-c", "datetime" ], "Title": "Defining a 'Watch' class" }
21527
<p>I'm attempting to write a piece of code that is supposed to remove consecutive appearances of a <code>string</code> (not a single character) in a <code>StringBuilder</code>.<br> It's <strong>extremely</strong> important that the method works well and does not remove or change anything that it shouldn't. Solid performance is a secondary requirement.</p> <p>for example:</p> <pre><code>Input: "xxxxABCxxxxABCABCxxxxABABCxxABCABCABC" Remove consecutive: "ABC" Output: "xxxxABCxxxxABCxxxxABABCxxABC" </code></pre> <p>I've written a method that does this and testing shows that it works as expected, but it will be catastrophic if I use it and it results in changing the <code>StringBuilder</code> in an unexpected way - that's why I want another opinion on whether my code is really 'safe' in all cases:</p> <pre><code>public static void RemoveConsecutive(this StringBuilder sb, string value) { if (sb == null) throw new ArgumentNullException("sb"); if (value == null) throw new ArgumentNullException("value"); if (value == string.Empty) throw new ArgumentException("value cannot be an empty string.", "value"); bool justRemoved = false; for (int i = 0; i &lt; sb.Length - value.Length; i++) { if (justRemoved || Util.ExistsAt(sb, i, value)) { if (Util.ExistsAt(sb, i + value.Length, value)) { sb.Remove(i, value.Length); justRemoved = true; i--; } else { justRemoved = false; } } } } // Checks if the provided string appears in the StringBuilder at the specified index public static bool ExistsAt(StringBuilder sb, int startIndex, string str) { if (startIndex &lt; 0 || startIndex &gt;= sb.Length) throw new ArgumentOutOfRangeException("startIndex", "startIndex must be a valid index in the provided StringBuilder."); if (startIndex + str.Length &gt; sb.Length) return false; for (int i = 0; i &lt; str.Length; i++) { if (str[i] != sb[i + startIndex]) return false; } return true; } </code></pre> <p>While this piece of code does something rather trivial, I just want another set of eyes to look at it and possibly find faults I could not. Again, any sort of unexpected behavior might be catastrophic.</p>
[ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-02-10T02:22:08.047", "Id": "34585", "Score": "0", "body": "If it's so important, have you written unit tests for it?" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-02-10T03:39:16.720", "Id": "34586", "Score": "0", "body": "@svick Yes. I have tested it rather extensively, but what I'm scared of is some sort of 'edge case' that I might not come across in my tests." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-02-10T13:47:30.830", "Id": "34606", "Score": "0", "body": "You state the problem as \"remov[ing] consecutive appearances of a substring\" and give an example of `\"xxxxABCxxxxABCABCxxxxABABCxxABCABCABC\" ->\n\"xxxxABCxxxxABCxxxxABABCxxABC\"`. But (replacing your `x`s with digits for visibility) shouldn't that result be `0123ABC45678901ABABC23`?" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-02-10T13:57:57.747", "Id": "34608", "Score": "0", "body": "@RossPatterson The additional instances of `ABC` you removed were not consecutive." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-02-10T14:31:49.393", "Id": "34613", "Score": "0", "body": "@svick I beg to differ. \"ABC\" -> \"ABC\", \"ABCABC\" -> \"\", \"ABABC\" -> \"ABABC\", \"ABCABCABC\" -> \"\". The second and fourth cases have consecutive ABCs. The example suggests eliminating groups of doubled ABCs, which is not the same thing. Hence my question." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-02-10T14:53:50.763", "Id": "34614", "Score": "0", "body": "@RossPatterson Sorry, you're right, I looked incorrectly at the original string. I think what the code should do is that if you have several consecutive instances, remove *all but one*." } ]
[ { "body": "<p>Your code looks like it does exactly what you want to me.</p>\n\n<p>Some notes:</p>\n\n<ol>\n<li><code>StringBuilder</code> methods (which you're emulating by using an extension method) return the modified <code>StringBuilder</code>, so they can be used in a <a href=\"http://en.wikipedia.org/wiki/Fluent_interface\" rel=\"nofollow\">fluent</a> manner. You should probably do the same.</li>\n<li>I don't like changing the index of a <code>for</code> loop. Especially since <code>i--</code> means “stay at the same index”, I think that's confusing. You should use a <code>while</code> loop instead.</li>\n<li><p>You can shorten your code by quite a bit by using <code>Regex</code>:</p>\n\n<pre><code>public static string RemoveConsecutive(string text, string value)\n{\n // validation omited\n\n string regex = string.Format(@\"({0})+\", Regex.Escape(value));\n return Regex.Replace(text, regex, match =&gt; value);\n}\n</code></pre>\n\n<p>Shorter code is usually less error prone. But in this case, I'm not so sure about that, because there are some intricacies in this code:</p>\n\n<ol>\n<li>Calling <code>Escape()</code> is crucial if <code>value</code> contains some regex special characters (e.g. <code>*</code>).</li>\n<li>If the <code>value</code> was used directly as the replacement (instead of a delegate), it wouldn't work correctly if it contained any <a href=\"http://msdn.microsoft.com/en-us/library/ewy2t5e0.aspx\" rel=\"nofollow\">substitution</a> (e.g. <code>$0</code>).</li>\n</ol></li>\n</ol>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-02-10T13:55:32.220", "Id": "34607", "Score": "2", "body": "Indeed, this would seem to be one of those occasions when using regular expressions does not give you two problems." } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-02-10T12:36:15.437", "Id": "21538", "ParentId": "21528", "Score": "2" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "6", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-02-10T02:01:12.587", "Id": "21528", "Score": "4", "Tags": [ "c#", "strings" ], "Title": "A reliable way to remove consecutive appearances of a substring" }
21528
<p>I am trying to create an invert index structure in C++. An invert index, in this case, refers to image retrieval system, where each invert index refers to a numbers of "Patch ID". (simply called "ID" in the code) These IDs are basically for describing many kind of pixel gradient patches from all images in the database.</p> <p>The invert index is a map container and will be very sparse and each index of the invert index will contain a sub-map. A sub-map will have an "Image ID" and frequency counting integer. For example, if we have 2 images with "Image ID" 10 and 20, and both of these images have "Patch ID" 999, appear once in "Image ID" 10 and appear twice in "Image ID" 20, we will have the following:</p> <blockquote> <p><code>invertID[999] == sub-map</code> with &lt;10,1> and &lt;20,2> </p> </blockquote> <p>I've written the code below for this, but somehow I am not quite satisfied. </p> <p>One instance, I have to put back the sub-map into the invert ID's index as you can see below.</p> <p>Another thing is I am not quite sure whether I am using the correct type of container for the correct job or not. I have about 5000 images (so that's 5000 "Image ID") and I see that "Patch ID" could vary from 1 to numbers as high as 40 billion.</p> <p>In this case, performance-wise and design-wise, should I be using map or should I go for some other container? Suggestions are welcome.</p> <p>Note: this will be run in a server that doesn't have a C++11 compiler.</p> <pre><code>unsigned long long int ID, index = 0; map&lt;unsigned long long int, map&lt;int, int&gt;&gt; invertID; ... ... //for the sake of convenient, two for loops below are shown as pseudocode. for each image{ //loop with imageID, incrementing variable imageID in each iteration //for each gradient patches in the image for each gradient patch of this image{ //loop with index, incrementing variable index in each iteration. //processID encapsulates the procedure to generate an ID for each interesting point in the image. We basically read values in the respective file and do some calculation. ID = processID(index); //if this ID exists in InvertID, map&lt;unsigned long long int, map&lt;int,int&gt;&gt;::iterator mainMapIt = invertID.find(ID); if (mainMapIt != invertID.end()){ //if this ImageID key exists in InvertID sub-map, map&lt;int,int&gt; M = mainMapIt-&gt;second; map&lt;int,int&gt;::iterator subMapIt = M.find(imageID); if (subMapIt != M.end()){ //the index already exists, so increment the number (frequency) of this ImageID key ++M[imageID]; } else{ //the index does not exist, so add ImageID key with value 1 into the InvertID M[imageID] = 1; } //get this sub-Map back to the invert ID's index. invertID[ID] = M; } else{ //the ID does not exist in the InvertId, yet, so //create the first empty map with the key as image ID with value 1 and put it into the invertID. map&lt;int,int&gt; M; M[imageID] = 1; invertID[ID] = M; } } } </code></pre>
[]
[ { "body": "<p>You are taking a copy of the inner map, modifying it, then putting it back. That could well be inefficient. You could take the inner map by reference then modify it.</p>\n\n<p>However you can actually make use of the fact that <code>map operator[]</code> inserts if it does not find the element. As that is the behaviour here you can do what you did in 2 lines:</p>\n\n<pre><code>map&lt; int, int &gt; &amp; innerMap = mainMapIt[ID]; // will be created as empty if not found\n++innerMap[ imageID ];\n</code></pre>\n\n<p>On a style issue, one does not commonly use an upper case letter as a variable. You also have ID as a variable but elsewhere your variables begin with a lower case letter. You should be consistent throughout in your style, and ideally adopt what is the most common style for C++ programmers (which is generally agreed to be beginning with a lower-case. Some prefer camel-case and some under-score delimited).</p>\n\n<p>You could also decide instead of nested maps, to have a single map with a key consisting of <code>std::pair&lt;unsigned long long, int &gt;</code>. This might be slightly more efficient as copying maps around could be expensive. It would mean however that you could not as easily search for all the elements from ID.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-02-13T11:13:23.137", "Id": "21657", "ParentId": "21529", "Score": "1" } }, { "body": "<p>Inverted indexes are often implemented using <a href=\"http://nlp.stanford.edu/IR-book/html/htmledition/faster-postings-list-intersection-via-skip-pointers-1.html\" rel=\"nofollow\">skip lists</a> instead of maps (which are elaborate search trees). The issue with <code>std::map</code> is that even though the complexity is good, for real lists the overhead of the map is too important. Plain vectors are usually way more efficient for small lists, and skip lists avoid the biggest issue with vectors: search in linear time.</p>\n\n<p>For an inverted index with a small number of items, I've seen a great increase in performance simply from switching from <code>map</code> to <code>vector</code> in C++.</p>\n\n<p>Otherwise, as CashCow said, the [] operator use the default constructor of your value when the key doesn't exist, so it isn't a real issue.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-02-14T15:17:36.500", "Id": "22712", "ParentId": "21529", "Score": "1" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-02-10T02:14:22.703", "Id": "21529", "Score": "3", "Tags": [ "c++", "algorithm", "image", "container" ], "Title": "Inverting index structure in C++" }
21529
<p>I have an MVC framework I've written. I'm trying to abstract out ASP.NET specific bits as well as make it more testable. Previously, I relied on <code>HttpContext.Current</code> in many places, which proves to be very unfriendly to unit testing. So, I started designing my own minimalistic interface for everything I'd need from there. However, it seems to keep on growing.</p> <pre><code>/// &lt;summary&gt; /// This is a very simplified context for server requests and responses /// It should not cover "everything", but should instead have only what BarelyMVC needs to function /// As a result, it will usually only have the most commonly used things in it /// All "get" methods should normally return null if a given name/key doesn't exist /// &lt;/summary&gt; public interface IServerContext { /// &lt;summary&gt; /// Gets a cookie from the current request /// &lt;/summary&gt; HttpCookie GetCookie(string name); /// &lt;summary&gt; /// Sets a cookie to send with the current response /// &lt;/summary&gt; void SetCookie(HttpCookie cookie); /// &lt;summary&gt; /// Kills the current request. Kills it with fire! This function should never return(for security purposes) /// &lt;/summary&gt; void KillIt(); /// &lt;summary&gt; /// Gets the user agent sent by the current request /// &lt;/summary&gt; string UserAgent{get;} /// &lt;summary&gt; /// Maps a relative URL path to an absolute path on the host (is this needed?) /// &lt;/summary&gt; string MapPath(string path); /// &lt;summary&gt; /// Gets the client's IP address /// &lt;/summary&gt; string UserIP{get;} /// &lt;summary&gt; /// Gets an HTTP header by name from the current request /// &lt;/summary&gt; string GetHeader(string name); /// &lt;summary&gt; /// Sets an HTTP header to be sent back in the response to the current request /// &lt;/summary&gt; void SetHeader(string name, string value); /// &lt;summary&gt; /// Performs a server-side transfer to another URL to service the current request (is this needed?) /// Should perform a KillIt() afterwards and never return /// &lt;/summary&gt; void Transfer(string url); /// &lt;summary&gt; /// Send a 302 redirect back to the client for the given URL and use KillIt() to end the request /// &lt;/summary&gt; void Redirect(string url); /// &lt;summary&gt; /// Gets a generic item from a key/value store associated with the current request only /// &lt;/summary&gt; object GetItem(string name); /// &lt;summary&gt; /// Sets a generic item to a key/value store associated with the current request only /// &lt;/summary&gt; object SetItem(string name, object value); /// &lt;summary&gt; /// Gets or sets the HTTP status code /// &lt;/summary&gt; string HttpStatus{get;set;} /// &lt;summary&gt; /// Gets a TextWriter which can be used to send content back as the response /// &lt;/summary&gt; TextWriter Writer{get;} /// &lt;summary&gt; /// Gets a parameter dictionary corresponding to the FORM values passed in by a POST request /// &lt;/summary&gt; ParameterDictionary Form{get;} /// &lt;summary&gt; /// Gets the URL of the current request /// &lt;/summary&gt; Uri RequestUrl{get;} } </code></pre> <p>Is this interface already too big? I know I could abstract out the <code>Request</code> and <code>Response</code> parts, but I tend to think it make it a bit harder to use, especially because of my limits on "get" and "set" being stuck to request and response respectively.</p> <p>What do you think? Refactoring into <code>Request</code>/<code>Response</code> interfaces, or is it OK how it is?</p>
[ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-02-10T08:30:21.303", "Id": "34591", "Score": "1", "body": "I would try and keep my controllers as skinny as possible and then unit testing them is not really necessary. Hopefully this way you might be able to keep your interface smaller and combine them if required." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2015-12-10T01:08:16.740", "Id": "209985", "Score": "1", "body": "Newlines are cheap. An extra one before each doc comment would improve readability IMO." } ]
[ { "body": "<p>You have to keep in mind that the earlier version of the .NET framework suffered in applying the interface segregation principle. In this case, the HTTP context includes methods associated with the request (ex. URL), the response (ex. HTTP status) and server utility functions (ex. map path).</p>\n\n<p>With that in mind, the interface looks OK and familiar in terms of usage in comparison to the original HttpContext (System.Web) and HttpContextBase (System.Web.Mvc) and should be fine.</p>\n\n<p>One aspect in regards to MVC that is hard to manage is the multiple data sources (query parameters, URL parameters, HTTP post Form values, routing parameters, session and the per request key/value store (HttpContext.Current.Items)) - perhaps it would be worthwhile to create an intermediary to manage these.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-02-10T17:12:57.643", "Id": "21546", "ParentId": "21530", "Score": "4" } }, { "body": "<p>As a framework author, you have the responsibility to do a lot of the heavy lifting for your users. Put yourself in their shoes. Ask what you'd like? Think about scenarios in which someone might need a <code>request</code> without a <code>response</code> or vis versa. Also note any properties/operations of HttpContext that are about the server (MapPath) and not related to requests or responses at all.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2015-12-10T14:11:48.127", "Id": "210076", "Score": "0", "body": "Your answer feels more like a rant, and is very generic. The usefulness for the OP is not very clear. Can you be more specific, and point out specific points in the posted code? Otherwise it's not much of a \"code review\"." } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-02-17T23:20:04.413", "Id": "22838", "ParentId": "21530", "Score": "-1" } }, { "body": "<p>Right now your goal is to create a shim to make it easier to unit test code that interacts with <code>HttpContext.Current</code>. Since you add methods to this interface as you need them, it must meet your needs in that regard. So, keeping it as is definitely improves your code, and you should not change it unless you need to.</p>\n\n<p>You may indeed need to change it. The interface segregation principle is really useful. If you are injecting this interface into other classes, you would get a lot more flexibility out of passing just the interface those classes need. </p>\n\n<p>If you change this interface to use methods, and you only have one (or two, including a stub) implementations of this interface, refactoring toward a segregated model will be fairly easy with extension methods. Something like this:</p>\n\n<pre><code>public interface IServerContext\n{\n IResponseDetails {get;}\n IRequestDetails {get;}\n //etc\n}\n\npublic interface IRequestDetails\n{\n Uri GetRequestUrl();\n //etc\n}\n\npublic static IServerContextExtensions\n{\n public static Uri GetRequestUrl(this IServerContext context)\n {\n return context.RequestDetails.GetRequestUrl();\n }\n //etc\n}\n</code></pre>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-02-19T02:55:46.927", "Id": "22880", "ParentId": "21530", "Score": "4" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "2", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-02-10T04:14:04.393", "Id": "21530", "Score": "7", "Tags": [ "c#", "interface", "server" ], "Title": "Interface for server requests and responses" }
21530
<p>I am working on a project in which I need to pass multiple arguments from the command line-</p> <p>Below is the use case I have-</p> <ol> <li><p>From the command line, I will be passing atleast four paramaters- <code>noOfThreads</code>, <code>noOfTasks</code>, <code>startRange</code> and <code>tableName1</code>, so if I am passing these four thing, then I need to store them in a variable and for any table names- I need to add it into the string list so that I can use them in my other code.</p></li> <li><p>Secondly, I can pass five parameters instead of four just like above- So five parameters can be- <code>noOfThreads</code>, <code>noOfTasks</code>, <code>startRange</code> , <code>tableName1</code> and <code>tableName2</code>. So here <code>tableName2</code> is extra. so if I am passing these five thing, then I need to store them in a variable and here I am passing <code>tableName1</code> and <code>tableName2</code> as two tables so I will be storing these two tables in a string list.</p></li> <li><p>Thirdly, I can pass six parameters instead of five just like above- So sixparameters can be- <code>noOfThreads</code>, <code>noOfTasks</code>, <code>startRange</code> , <code>tableName1</code>, <code>tableName2</code> and <code>tableName3</code>. So here <code>tableName3</code> is extra. so if I am passing these six thing, then I need to store them in a variable and here I am passing <code>tableName1</code> , <code>tableName2</code> and <code>tableName3</code> as three tables so I will be storing these three tables in a string list again.</p></li> </ol> <p>So for above scenario, I have the below code with me. It is looking very ugly currently as I have lot of repetition in my code as mentioned below. Is there any way I can make it more cleaner?</p> <p>Below is my code-</p> <pre><code>private static List&lt;String&gt; databaseNames = new ArrayList&lt;String&gt;(); private static int noOfThreads; private static int noOfTasks; private static int startRange; private static String tableName1; private static String tableName2; private static String tableName3; public static void main(String[] args) { if (args.length &gt; 0 &amp;&amp; args.length &lt; 5) { noOfThreads = Integer.parseInt(args[0]); noOfTasks = Integer.parseInt(args[1]); startRange = Integer.parseInt(args[2]); tableName1 = args[3]; databaseNames.add(tableName1); } else if (args.length &gt; 0 &amp;&amp; args.length &lt; 6) { noOfThreads = Integer.parseInt(args[0]); noOfTasks = Integer.parseInt(args[1]); startRange = Integer.parseInt(args[2]); tableName1 = args[3]; tableName2 = args[4]; databaseNames.add(tableName1); databaseNames.add(tableName2); } else { noOfThreads = Integer.parseInt(args[0]); noOfTasks = Integer.parseInt(args[1]); startRange = Integer.parseInt(args[2]); tableName1 = args[3]; tableName2 = args[4]; tableName3 = args[5]; databaseNames.add(tableName1); databaseNames.add(tableName2); databaseNames.add(tableName3); } } </code></pre>
[]
[ { "body": "<ol>\n<li><p>Extract out the common logic before the <code>if</code>. The following is more or less the same:</p>\n\n<pre><code>noOfThreads = Integer.parseInt(args[0]);\nnoOfTasks = Integer.parseInt(args[1]);\nstartRange = Integer.parseInt(args[2]);\ntableName1 = args[3];\ndatabaseNames.add(tableName1);\nif (args.length &gt;= 5) {\n tableName2 = args[4];\n databaseNames.add(tableName2);\n}\nif (args.length &gt;= 6) {\n tableName3 = args[5];\n databaseNames.add(tableName3);\n}\n</code></pre></li>\n<li><p>Note that running the program with less than five parameters only prints an exception:</p>\n\n<pre><code>Exception in thread \"main\" java.lang.ArrayIndexOutOfBoundsException: 0\n at ...Main.main(Main.java:16)\n</code></pre>\n\n<p>You should handle this and print a user friendly error message or usage help.</p></li>\n</ol>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-02-10T07:01:15.157", "Id": "21533", "ParentId": "21531", "Score": "4" } }, { "body": "<p>It might be worth checking out <a href=\"http://commons.apache.org/cli/\" rel=\"nofollow\">Commons CLI</a>. It's a library that handles complicated command-line arguments and provides a lot of nice stuff like pretty error messages and succinct ways of specifying optional vs required arguments. Right now, your code is probably borderline on whether it will actually be simplified by this addition, but it will definitely help those who are using your code, and it will be far easier to add or modify the arguments in the future.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-02-12T01:55:04.130", "Id": "21603", "ParentId": "21531", "Score": "3" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-02-10T05:47:51.827", "Id": "21531", "Score": "3", "Tags": [ "java" ], "Title": "Passing multiple parameters from the command line in Java" }
21531
<p>I have written a piece of code that finds common patterns in two strings. These patterns have to be in the same order, so for example "I am a person" and "A person I am" would only match "person". The code is crude, all characters, including whitespace and punctuation marks, receive the same treatment. The longest patterns are matched first.</p> <p>The main function then returns two lists (one per string) of tuples with two elements. The first element is 1 if a substring has been matched, else 0. The second element is the substring.</p> <p>So the format of returned lists will be like this:</p> <pre><code>[(1, 'I '), (0, 'am a person\n')] [(1, 'I '), (0, 'can see\n')] </code></pre> <p>Now to the question -- what do you think about my code? I somehow feel that it's not quite top-notch, and I'm not an experienced coder. Any suggestions on coding style or the algorithms? I hope the code is reasonably clear.</p> <p>The <code>find_raw_patterns</code> function returns lists with alternating integers and strings, so the only thing <code>find_common_patterns</code> does in addition to calling <code>find_raw_patterns</code>, is to arrange the lists' elements in two-element-tuples.</p> <p>The function <code>longest_common_substring</code> is copied directly from <a href="http://en.wikibooks.org/wiki/Algorithm_implementation/Strings/Longest_common_substring" rel="nofollow">Wikibooks</a>, and I'm not very concerned about that function.</p> <p>Code:</p> <pre><code>def longest_common_substring(S1, S2): M = [[0]*(1+len(S2)) for i in range(1+len(S1))] longest, x_longest = 0, 0 for x in range(1,1+len(S1)): for y in range(1,1+len(S2)): if S1[x-1] == S2[y-1]: M[x][y] = M[x-1][y-1] + 1 if M[x][y]&gt;longest: longest = M[x][y] x_longest = x else: M[x][y] = 0 return S1[x_longest-longest: x_longest] def find_common_patterns(s1, s2): arranged1 = [] arranged2 = [] (ptr1, ptr2) = find_raw_patterns(s1, s2) #ptr - pattern for i in range(len(ptr1) - 1): if type(ptr1[i]) == int: arranged1.append((ptr1[i], ptr1[i+1])) for i in range(len(ptr2) - 1): if type(ptr2[i]) == int: arranged2.append((ptr2[i], ptr2[i+1])) return (arranged1, arranged2) def find_raw_patterns(s1, s2): # used recursively one = [] # used to reassemble strings, but with patterns and integer showing whether it's been matched or not two = [] # same, but for the second string com = longest_common_substring(s1, s2) if len(com) &lt; 2: return ((0, s1), (0, s2)) elif len(com) &gt;= 2: i1 = s1.index(com) i2 = s2.index(com) s1_bef = s1[:i1] #part of string before the matched pattern s1_aft = s1[i1 + len(com) : ] # -//- after matched pattern s2_bef = s2[:i2] s2_aft = s2[i2 + len(com) : ] if len(s1_bef) &gt; 0 and len(s2_bef) &gt; 0: # find patterns in first parts of strings res = find_raw_patterns(s1_bef, s2_bef) one.extend(res[0]) two.extend(res[1]) one.extend((1, com)) # add current pattern two.extend((1, com)) if len(s1_aft) &gt; 0 and len(s2_aft) &gt; 0: # find patterns from second parts res = find_raw_patterns(s1_aft, s2_aft) one.extend(res[0]) two.extend(res[1]) return (one, two) </code></pre>
[ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-02-26T21:33:10.350", "Id": "73955", "Score": "1", "body": "stdlib solution: if `a, b = \"same order words\", \"not same but order words matched\"` then `[a[i:i+n] for i, _, n in difflib.SequenceMatcher(None, a, b).get_matching_blocks()\nif n]` returns `['same', ' order words']`. It works with arbitrary hashable sequences, not just strings." } ]
[ { "body": "<p>You can simplify the two functions quite a bit. For <code>find_raw_patterns</code> you can use <code>partition</code> instead of manually splitting the strings up, and simplify the formation of the list.</p>\n\n<pre><code>def find_raw_patterns(s1, s2): # used recursively\n if s1 == '' or s2 == '':\n return [], []\n com = longest_common_substring(s1, s2)\n if len(com) &lt; 2:\n return ([0, s1], [0, s2])\n s1_bef, _, s1_aft = s1.partition(com)\n s2_bef, _, s2_aft = s2.partition(com)\n before = find_raw_patterns(s1_bef, s2_bef)\n after = find_raw_patterns(s1_aft, s2_aft)\n return (before[0] + [1, com] + after[0],\n before[1] + [1, com] + after[1])\n</code></pre>\n\n<p>For <code>find_common_patterns</code>, you can use list indices to get the even and odd values rather than checking the type of each value, and use <code>zip</code> to get a list of pair tuples.</p>\n\n<pre><code>def find_common_patterns(s1, s2):\n (ptr1, ptr2) = find_raw_patterns(s1, s2) #ptr - pattern\n return (zip(ptr1[::2], ptr1[1::2]),\n zip(ptr2[::2], ptr2[1::2]))\n</code></pre>\n\n<p>But I think you can also combine the two functions with a minor adjustment to put the found values into paired tuples.</p>\n\n<pre><code>def find_common_patterns(s1, s2): # used recursively\n if s1 == '' or s2 == '':\n return [], []\n com = longest_common_substring(s1, s2)\n if len(com) &lt; 2:\n return ([(0, s1)], [(0, s2)])\n s1_bef, _, s1_aft = s1.partition(com)\n s2_bef, _, s2_aft = s2.partition(com)\n before = find_common_patterns(s1_bef, s2_bef)\n after = find_common_patterns(s1_aft, s2_aft)\n return (before[0] + [(1, com)] + after[0],\n before[1] + [(1, com)] + after[1])\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-02-10T10:46:27.290", "Id": "34596", "Score": "0", "body": "Thank you! That makes the code a lot more compact and probably makes it easier to understand, too.\nThere's a problem with the: `if s1 == '' or s2 == '': return [], []`\nIt makes the result break off the other string when one string is \"finished\". Like this:\n\n`>>> find_raw_patterns('aoesunthaoesnutheoau', 'oaeurolqsnjthkoaeun')\n([0, 'aoes', 1, 'un'], [0, 'oaeurolqsnjthkoae', 1, 'un'])`\nI just removed that if clause and it solves the problem, just have to deal with possible empty strings in the list but that may be a fair trade-off." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-02-10T11:14:20.700", "Id": "34597", "Score": "0", "body": "Okay, glad it helped. You may want to try something like `if s1 == '' and not s2 == '': return [], [(0, s2)]`, etc." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-02-10T11:52:29.683", "Id": "34599", "Score": "0", "body": "I'm a bit ashamed I didn't think of that myself, haha. The following worked fine: \n`if s1 == '' or s2 == '': \n\n return ([(0, s1)] if s1 != '' else []), ([(0, s2)] if s2 != '' else [])\n`" } ], "meta_data": { "CommentCount": "3", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-02-10T09:47:12.910", "Id": "21535", "ParentId": "21532", "Score": "3" } } ]
{ "AcceptedAnswerId": "21535", "CommentCount": "1", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-02-10T06:16:47.460", "Id": "21532", "Score": "4", "Tags": [ "python", "strings" ], "Title": "Python 3: Finding common patterns in pairs of strings" }
21532
<p>I've developed a code for a Hangman game and what I need help in is basically simplifying, correcting and removing parts of the code that are not needed (or there is an easier way to do it). I think there are parts where I could have done it easier but I do not know where they are. I would appreciate any/ all help and will welcome all constructive criticism.</p> <pre><code>package Hangman; import javax.swing.*; import java.awt.*; import java.awt.event.*; import java.io.*; import javax.swing.Icon; import javax.swing.ImageIcon; import javax.swing.JButton; import java.awt.BorderLayout; import java.awt.Color; import javax.swing.JFrame; import javax.swing.JLabel; import java.net.URL; @SuppressWarnings("serial") public class HangManGUI extends JFrame implements ActionListener, KeyListener { // Panels where everything is drawn on DrwPnl dPnl1 = new DrwPnl(), dPnl2 = new DrwPnl(), pnlBoard = new DrwPnl(); JPanel align = new JPanel(), pnl2 = new JPanel(), pnl3 = new JPanel(), pnl4 = new JPanel(), pnl5 = new JPanel(), pnl6 = new JPanel(), pnl7 = new JPanel(); String p1 = "Dixon", p2 = "Computer", puz = "", selected = "Easy"; String[] categories = { "Easy", "Food", "Standard", "Geography", "Hard", "Holidays", "Animals", "Sports" }, allPuz, puzzle; JTextField cusPuz = new JTextField("Custom Puzzle"), txtName = new JTextField("Player"), txtOpponent = new JTextField( "Opponent"); JLabel lblName = new JLabel(), lblOpponent = new JLabel(), wordlist = new JLabel(); JButton[] btnLetters = new JButton[26], close = new JButton[3], lblWordList = new JButton[8]; JButton player1 = new JButton(), player2 = new JButton(), btnBack = new JButton("Back"), btnStart = new JButton("Start"), resetBtn = new JButton("Reset Scores"), newGameBtn = new JButton( "New Game"), btnMain = new JButton("Menu"); int length, count = 0, chances = 7, linenum, randomnum, pScore = 0, oScore = 0, theSource = 1, move = 0, rong, players = 1; int[] wrLetter = new int[26], checked = new int[26]; Icon[] cate = new ImageIcon[7]; Icon py1 = new ImageIcon("Player 1.png"), py2 = new ImageIcon( "Player 2.png"), wList = new ImageIcon("WordList.png"), name = new ImageIcon("Name.png"), opponent = new ImageIcon( "Opponent.png"), closeIMG = new ImageIcon("closeBtn.png"); char[] puzle, hid, leter = { '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' }, leter2 = { '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' }; Boolean wrong = true, undecorated, gameDone = false; JFrame fr1 = new JFrame(""), fr2 = new JFrame(""); // Import Font File-----------------------&gt; File f = new File("VTK.ttf"); FileInputStream in = new FileInputStream(f); Font dFont = Font.createFont(Font.TRUETYPE_FONT, in); Font f1 = dFont.deriveFont(12f), f2 = dFont.deriveFont(11f), f3 = dFont .deriveFont(12f), f4 = dFont.deriveFont(50f), f5 = dFont .deriveFont(16f), f6 = dFont.deriveFont(13f), f7 = dFont .deriveFont(35f), f8 = dFont.deriveFont(22f); // &lt;----------------------- End Import Font File // Import Images-----------------------&gt; ClassLoader cl = HangManGUI.class.getClassLoader(); URL imageURL = cl.getResource("chalkBG.png"), imageURL2 = cl .getResource("hanger.png"), imageURL3 = cl .getResource("alphaDock.png"); Image image, image2, image3; Toolkit toolkit = Toolkit.getDefaultToolkit(); // &lt;----------------------- End Import Images public static void main(String[] args) throws Exception { new HangManGUI(); } public HangManGUI() throws Exception { this.addKeyListener(this); this.setFocusable(true); // Initialize the Checklists-------------&gt; for (int x = 0; x &lt; 26; x++) { checked[x] = 0; wrLetter[x] = 0; } // &lt;------- End Initializing Checklists // Close button---------------------------&gt; for (int x = 0; x &lt; 3; x++) { close[x] = new JButton(); close[x].addActionListener(this); close[x].setOpaque(false); close[x].setContentAreaFilled(false); close[x].setBorderPainted(false); close[x].setBounds(275, 0, 25, 25); close[x].setIcon(closeIMG); } dPnl1.add(close[0]);// Add Close button to 1st Screen dPnl2.add(close[1]);// Add Close button to 2nd Screen this.add(close[2]);// Add Close button to Board close[2].setBounds(475, 0, 25, 25); // &lt;------End Close Button // Put image into Image Variable-------------&gt; if (imageURL != null) { image = toolkit.createImage(imageURL); image2 = toolkit.createImage(imageURL2); image3 = toolkit.createImage(imageURL3); } // &lt;-------------Put image into Image Variable // ////Chose Player Menu(1)==============&gt; dPnl1.setLayout(null); // /Player 1 button initialize---------&gt; player1.setBounds(25, 125, 250, 50); player1.setOpaque(false); player1.setContentAreaFilled(false); player1.setBorderPainted(false); player1.addActionListener(this); player1.setIcon(py1); dPnl1.add(player1); // /Player 2 button initialize---------&gt; player2.setBounds(25, 200, 250, 50); player2.setOpaque(false); player2.setContentAreaFilled(false); player2.setBorderPainted(false); player2.addActionListener(this); player2.setIcon(py2); dPnl1.add(player2); // /End Player Button Initialzing-------&gt; fr1.add(dPnl1); fr1.setUndecorated(true);// Take out preset border undecorated = fr1.isUndecorated();// Take out preset border fr1.setVisible(true); fr1.setSize(300, 300); fr1.setLocation(300, 300); // ////&lt;========End Chose Player Menu(1) // ////Chose Categories Menu(2)========&gt; dPnl2.setLayout(null); // /Initialize WordList Icon\Label---&gt; dPnl2.add(wordlist); wordlist.setBounds(100, 75, 150, 75); wordlist.setIcon(wList); // /Initialize Go To 1st Menu Button----------&gt; dPnl2.add(btnBack); btnBack.setBounds(0, 250, 75, 25); btnBack.setFont(f2); btnBack.addActionListener(this); btnBack.setOpaque(false); btnBack.setContentAreaFilled(false); btnBack.setBorderPainted(false); btnBack.addActionListener(this); // /Initialize Start Game/Go to Board----------&gt; dPnl2.add(btnStart); btnStart.setBounds(225, 250, 75, 25); btnStart.setFont(f2); btnStart.addActionListener(this); btnStart.setOpaque(false); btnStart.setContentAreaFilled(false); btnStart.setBorderPainted(false); btnStart.addActionListener(this); // /Add Categories into grid-------------&gt; align.setLayout(new GridLayout(4, 2)); for (int x = 0; x &lt; 8; x++) { lblWordList[x] = new JButton(categories[x] + ""); lblWordList[x].setFont(f3); lblWordList[x].setOpaque(false); lblWordList[x].setContentAreaFilled(false); lblWordList[x].setBorderPainted(false); lblWordList[x].addActionListener(this); align.add(lblWordList[x]); } // /&lt;-------------End Category Initializing and Layout Setiing fr2.add(dPnl2); fr2.setSize(300, 300); fr2.setLocation(300, 300); fr2.setUndecorated(true);// Take out preset border undecorated = fr2.isUndecorated();// Take out preset border // ////&lt;==================End Chose Player Menu(2) // ////Create Playing Board================&gt; // Add Board to main form-------------&gt; pnlBoard.setLayout(new GridLayout(1, 1)); pnl2.setLayout(new BorderLayout()); pnl2.add(pnlBoard, BorderLayout.CENTER); // &lt;---------End Add Board to main form pnl7.setLayout(new GridLayout(1, 1)); pnl7.add(pnl2); // Initialize New Game Button----------&gt; newGameBtn.setFont(f2); newGameBtn.addActionListener(this); newGameBtn.setFocusable(false); newGameBtn.setOpaque(false); newGameBtn.setContentAreaFilled(false); newGameBtn.setBorderPainted(false); this.add(newGameBtn); newGameBtn.setBounds(225, 0, 100, 25); // Initialize Reset Scores Button----------&gt; resetBtn.setFont(f2); resetBtn.addActionListener(this); resetBtn.setFocusable(false); resetBtn.setOpaque(false); resetBtn.setContentAreaFilled(false); resetBtn.setBorderPainted(false); this.add(resetBtn); resetBtn.setBounds(100, 0, 125, 25); // Initialize Go To Main Menu Button----------&gt; btnMain.setFont(f2); btnMain.addActionListener(this); btnMain.setFocusable(false); btnMain.setOpaque(false); btnMain.setContentAreaFilled(false); btnMain.setBorderPainted(false); this.add(btnMain); btnMain.setBounds(0, 0, 100, 25); this.add(pnl7); this.setUndecorated(true);// Take out preset border undecorated = this.isUndecorated();// Take out preset border this.setVisible(false); this.setLocation(200, 200); this.setSize(500, 325); // ////&lt;===========End Create Playing Board } public void actionPerformed(ActionEvent e) { if (e.getSource() == player1) { System.out.println("Player 1 was pressed"); fr1.setVisible(false); fr2.setVisible(true); theSource = 2; players = 1; lblWordList[1].setForeground(Color.BLUE); dPnl2.add(align); align.setBounds(25, 125, 250, 100); align.setOpaque(false); dPnl2.add(lblName); lblName.setBounds(50, 50, 75, 25); lblName.setFont(f2); lblName.setIcon(name); dPnl2.add(txtName); txtName.setBounds(125, 50, 125, 25); txtName.setFont(f6); txtName.setOpaque(false); txtName.setBorder(null); dPnl2.add(wordlist); wordlist.setBounds(100, 75, 150, 75); dPnl2.remove(lblOpponent); dPnl2.remove(txtOpponent); dPnl2.remove(cusPuz); } else if (e.getSource() == player2) { System.out.println("Player 2 was pressed"); lblWordList[1].setForeground(Color.BLUE); players = 2; theSource = 2; selected = "Custom"; fr1.setVisible(false); fr2.setVisible(true); dPnl2.remove(align); dPnl2.remove(wordlist); dPnl2.add(lblOpponent); lblOpponent.setBounds(75, 125, 100, 25); lblOpponent.setFont(f2); lblOpponent.setIcon(opponent); dPnl2.add(txtOpponent); txtOpponent.setBounds(175, 125, 100, 25); txtOpponent.setFont(f6); txtOpponent.setOpaque(false); txtOpponent.setBorder(null); dPnl2.add(cusPuz); cusPuz.setBounds(100, 175, 100, 25); dPnl2.add(lblName); lblName.setBounds(75, 75, 75, 25); lblName.setFont(f2); lblName.setIcon(name); dPnl2.add(txtName); txtName.setBounds(150, 75, 125, 25); txtName.setFont(f6); txtName.setOpaque(false); txtName.setBorder(null); } if (e.getSource() == btnBack) { theSource = 1; System.out.println("Back was pressed"); fr2.setVisible(false); fr1.setVisible(true); } for (int x = 0; x &lt; 8; x++) { lblWordList[x].setForeground(Color.BLACK); if (e.getSource() == lblWordList[x]) { if (players == 1) { selected = lblWordList[x].getText(); lblWordList[x].setForeground(Color.BLUE); System.out.println(x); } else selected = p2 + "'s Puzzle"; } } if (e.getSource() == btnStart) { theSource = 3; System.out.println("Start was pressed"); p1 = txtName.getText(); if (players == 2) p2 = txtOpponent.getText(); fr2.setVisible(false); try { if (players == 1) getPuz(); createPuz(); } catch (IOException f) { System.out.println("Problem Creating Puzzle"); } this.setVisible(true); } for (int x = 0; x &lt; 3; x++) { if (e.getSource() == close[x]) { System.exit(0); } } if (e.getSource() == resetBtn) { oScore = 0; pScore = 0; repaint(); } else if (e.getSource() == newGameBtn) { imageURL2 = cl.getResource("hanger.png"); image2 = toolkit.createImage(imageURL2); move = 0; count = 0; gameDone = false; for (int x = 0; x &lt; 26; x++) { checked[x] = 0; wrLetter[x] = 0; } try { getPuz(); createPuz(); } catch (IOException f) { System.out.println("Problem Creating Puzzle"); } repaint(); } if (e.getSource() == btnMain) { oScore = 0; pScore = 0; move = 0; count = 0; gameDone = false; p2 = "Opponent"; p1 = "Player"; for (int x = 0; x &lt; 26; x++) { checked[x] = 0; wrLetter[x] = 0; } this.setVisible(false); fr2.setVisible(true); theSource = 2; } } class DrwPnl extends JPanel { public void paintComponent(Graphics g) { Graphics2D g2 = (Graphics2D) g; if ((theSource == 1) || (theSource == 2)) { g2.drawImage(image, 0, 0, 300, 300, 0, 0, 300, 300, this); g2.setColor(Color.WHITE); g2.setFont(f4); if (theSource == 1) g2.drawString("Hang Man", 12, 100); g2.setColor(Color.BLACK); } else if (theSource == 3) { g2.drawImage(image, 0, 0, 500, 275, 0, 0, 300, 300, this); if ((move &lt; 5) &amp;&amp; (move &gt;= 0)) g2.drawImage(image2, 300 - 25 * move, 125, 350 - 25 * move, 200, 0, 0, 131, 300, this); if ((move &gt;= 5) &amp;&amp; (move &lt; 7)) g2.drawImage(image2, 300 - 25 * move, 100, 350 - 25 * move, 175, 0, 0, 131, 300, this); if ((move == 7) || (move &gt;= 8)) { g2.drawImage(image2, 125, 50, 175, 150, 0, 0, 131, 300, this); if (move == 7) { g2.setColor(Color.RED); g2.fillRect(125, 150, 50, 25); } } g2.setColor(Color.YELLOW); g2.drawLine(365, 25, 365, 215); g2.drawLine(25, 210, 375, 210); g2.setColor(Color.RED); g2.fillRect(50, 175, 125, 25); g2.fillRect(75, 25, 25, 150); g2.fillRect(100, 25, 75, 25); g2.fillRect(175, 175, 25, 25); g2.setStroke(new BasicStroke(10)); g2.drawLine(100, 75, 125, 50); g2.setColor(Color.BLACK); g2.setFont(f8); g2.drawImage(image3, 0, 275, 500, 325, 0, 0, 320, 48, this); for (int x = 0; x &lt; 26; x++) { if (wrLetter[x] == 0) g2.setColor(Color.BLACK); else if (wrLetter[x] == 1) g2.setColor(Color.GREEN); else if (wrLetter[x] == 2) g2.setColor(Color.RED); g2.drawString("" + leter[x], 5 + 19 * x, 305); } g2.setFont(f7); g2.setColor(Color.BLACK); for (int x = 0; x &lt; length; x++) g2.drawString("" + hid[x], 25 + 35 * x, 250); g2.setFont(f5); g2.setColor(Color.WHITE); g2.drawString("Category:", 375, 50); g2.drawString(p1, 375, 100); g2.drawString(p2, 375, 150); g2.setColor(Color.BLACK); g2.drawString(selected, 375, 75); g2.drawString("" + pScore, 375, 125); g2.drawString("" + oScore, 375, 175); } } } public void getPuz() throws IOException { BufferedReader in = null; String line = "A B 1"; File f = new File("Word List/" + selected + ".txt"); int num = 0; LineNumberReader reader = new LineNumberReader(new FileReader(f)); String lineRead = ""; while ((lineRead = reader.readLine()) != null) { } linenum = reader.getLineNumber(); reader.close(); try { allPuz = new String[linenum]; in = new BufferedReader(new FileReader(f)); System.out.println("File Opening"); } catch (FileNotFoundException e) { System.out.println("Problem opening File"); } while (line != null) { try { line = in.readLine(); if (line != null) { allPuz[num] = "" + line; num++; } } catch (IOException e) { System.out.println("Problem reading data from file"); } if (line != null) { } } try { in.close(); System.out.println("Closing File"); } catch (IOException e) { System.out.println("Problem Closing " + e); } } public void createPuz() throws IOException { randomnum = (int) (Math.random() * linenum); if (players == 1) puz = "" + allPuz[randomnum]; else if (players == 2) puz = cusPuz.getText(); System.out.println(puz); length = puz.length(); puzle = new char[length]; hid = new char[length]; for (int x = 0; x &lt; length; x++) { puzle[x] = (puz.charAt(x)); if (puzle[x] == ' ') { hid[x] = (' '); count += 1; } else hid[x] = ('_'); } } public void keyTyped(KeyEvent f) { if (gameDone == false) { String key = "" + f.getKeyChar(); Boolean rightletter = false; wrong = true; for (int x = 0; x &lt; 26; x++) { if (("" + leter[x]).equalsIgnoreCase(key)) { if (checked[x] == 1) { JOptionPane.showMessageDialog(this, "Already pressed " + leter[x] + "."); for (int y = 0; y &lt; length; y++) { if ((leter[x] == puzle[y]) || (leter2[x] == puzle[y])) { hid[y] = puzle[y]; rightletter = true; wrLetter[x] = 1; wrong = false; checked[x] = 1; if (count == length) { JOptionPane.showMessageDialog(this, "You Win"); gameDone = true; pScore += 1; } } } } else if (checked[x] == 0) { for (int y = 0; y &lt; length; y++) { if ((leter[x] == puzle[y]) || (leter2[x] == puzle[y])) { hid[y] = puzle[y]; rightletter = true; wrLetter[x] = 1; count += 1; wrong = false; checked[x] = 1; if (count == length) { JOptionPane.showMessageDialog(this, "You Win"); gameDone = true; pScore += 1; } } } } rong = x; } } if (rightletter == false) { for (int x = 0; x &lt; 26; x++) { if (("" + leter[x]).equalsIgnoreCase(key)) { move++; wrLetter[x] = 2; checked[x] = 1; rong = x; } } } if (wrong == true) wrLetter[rong] = 2; wrong = true; if (move == 7) { imageURL2 = cl.getResource("hanger2.png"); image2 = toolkit.createImage(imageURL2); } else if (move &gt;= 8) { imageURL2 = cl.getResource("hanger3.png"); JOptionPane.showMessageDialog(this, "You Lose"); oScore += 1; gameDone = true; pnlBoard.setEnabled(false); resetBtn.setEnabled(true); image2 = toolkit.createImage(imageURL2); for (int x = 0; x &lt; 26; x++) { for (int y = 0; y &lt; length; y++) { if ((leter[x] == puzle[y]) || (leter2[x] == puzle[y])) { hid[y] = puzle[y]; } } } } else { imageURL2 = cl.getResource("hanger.png"); image2 = toolkit.createImage(imageURL2); } repaint(); } } public void keyPressed(KeyEvent f) { } public void keyReleased(KeyEvent f) { } } </code></pre> <p>If any one wants to see the images/files and/or download them to use while checking, I uploaded this code to <a href="https://github.com/Exikle/HangmanOriginal" rel="nofollow">Github</a>.</p>
[]
[ { "body": "<p>Thank you for sharing your code. Quite frankly, it's a bit of a mess, so let's try to clean it up. </p>\n\n<h1>General Code Issues</h1>\n\n<p>Here are a few examples of issues with your code that can easily be corrected. All these issues can be automatically detected by a good IDE such as the free, open-source and excellent <a href=\"http://www.jetbrains.com/idea/\" rel=\"nofollow\">IntelliJ IDEA Community Edition</a><sup>1</sup> <em>(Analyze->Inspect Code)</em>. </p>\n\n<ul>\n<li><p>You import many classes that you never use. Remove all unnecessary imports, keeping only the ones your code requires. You should also be consistent in your use of <code>*</code> wildcards; either use them always or never. </p></li>\n<li><p>Why are you suppressing a warning that is not affecting your code? Remove it.</p>\n\n<pre><code>@SuppressWarnings(\"serial\")\n</code></pre></li>\n<li>Why are you declaring but never using <code>pnl3</code>, <code>pnl4</code>, <code>pnl5</code> and <code>pnl6</code>? Remove them.</li>\n<li>Why are you declaring the constructor and <code>main</code> as <code>throws Exception</code> when they don't? Remove. The same goes for <code>throws IOException</code> on <code>createPuz</code>.</li>\n<li><a href=\"http://docs.oracle.com/javase/tutorial/java/package/namingpkgs.html\" rel=\"nofollow\">Package names in Java</a> are expected to be lower-case,<br>\nso you should change <code>package Hangman;</code> to <code>package hangman;</code></li>\n<li>Version logs should be kept in source control, not in the source files (I noticed this in your upload)</li>\n<li><p>Remove redundant comments that say nothing, such as this one:</p>\n\n<pre><code>// Panels where everything is drawn on\n</code></pre></li>\n<li><p>There's no need to add compare Boolean values with <code>true</code> or <code>false</code> literals, just use them directly:</p>\n\n<ul>\n<li><code>if (gameDone == false)</code> becomes <code>if (gameDone)</code></li>\n<li><code>if (rightletter == false)</code> becomes <code>if (!rightletter)</code></li>\n<li><code>if (wrong == true)</code> becomes <code>if (wrong)</code></li>\n</ul></li>\n</ul>\n\n<hr>\n\n<p><strong>Footnotes</strong></p>\n\n<p><sup>1</sup> If you download it, be sure to use the new <em>Darcula</em> theme.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-02-11T03:27:08.173", "Id": "34647", "Score": "1", "body": "this is amazing, just out curiosity do you have like a checklist of things you check throughout the code and if you do, perhaps you could tell me because instead of bringing a fully raw code, i could self check first?" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-02-12T08:19:49.697", "Id": "34709", "Score": "0", "body": "so i have done all this, as well i also have modified the code using the program you mentioned (pretty cool program) and have created a custom JButton class and shortened the code. I have uploaded the code on Git and here too." } ], "meta_data": { "CommentCount": "2", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-02-10T21:12:44.443", "Id": "21554", "ParentId": "21534", "Score": "7" } }, { "body": "<p>I'd like to focus on the <code>getPuz()</code> function to make the work of codesparkle more manageable. :)</p>\n\n<h2>Exceptions handling</h2>\n\n<p>The first, high-level problem is the way you use try/catch blocks. Exceptions are not here to get into your way! They're great tools that let you write robust programs and focus on error conditions only where necessary. Writing \"Problem opening file\" and continuing execution as if nothing had happened is a really bad idea. The truth is that if you can't open that file then your program is useless. So you might as well show the error to your users and quit the program once they acknowledged it. I removed all try/catch blocks from the code since your function already says <code>throws Exception</code> and because <code>getPuz()</code> is not the place to handle exceptions.</p>\n\n<h2>Declarations</h2>\n\n<pre><code>public void getPuz() throws IOException {\n BufferedReader in = null;\n String line = \"A B 1\";\n</code></pre>\n\n<p>Why \"A B 1\"? When programming, you optimize for reading: reading your code should be effortles. This is not the case when an arbitrary string shows up like this. Also try avoiding setting anything to <code>null</code> when possible. Here this means not declaring the <code>BufferedReader</code> right away.</p>\n\n<h2>Line count and better container</h2>\n\n<pre><code> File f = new File(\"Word List/\" + selected + \".txt\");\n int num = 0;\n LineNumberReader reader = new LineNumberReader(new FileReader(f));\n String lineRead = \"\";\n while ((lineRead = reader.readLine()) != null) {\n }\n linenum = reader.getLineNumber();\n reader.close();\n</code></pre>\n\n<p>You're going through a lot of trouble to count the number of lines in the file. The first think a reader thinks when looking at this is \"wtf?\". This is where good comments can help: you could have written \"Count the number of lines in f\". But the better thing to do is to actually use a better container for <code>allPuz</code>. You could use a <code>ArrayList</code> instead which allows you to append new elements without losing performance. This would allow you to change the real reading code:</p>\n\n<pre><code> allPuz = new ArrayList&lt;String&gt;();\n BufferedReader in = new BufferedReader(new FileReader(f));\n System.out.println(\"File Opening\");\n</code></pre>\n\n<p>See, it's simpler to declare <code>in</code> here. Also, <code>allPuz</code> is a <code>ArrayList</code> now, I'll be able to use the <code>add</code> method later on.</p>\n\n<h2>Reading lines</h2>\n\n<pre><code> while (line != null) {\n line = in.readLine();\n if (line != null) {\n allPuz[num] = \"\" + line;\n num++;\n }\n }\n</code></pre>\n\n<p>There's another way to write this kind of code which avoids you from writing the <code>null</code> test twice:</p>\n\n<pre><code> while ((line = in.readline()) != null) {\n allPuz.append(line)\n }\n\n if (line != null) {\n }\n</code></pre>\n\n<h2>Useless declarations</h2>\n\n<p>As codesparkle mentioned for other declaration, this is useless: remove it!</p>\n\n<pre><code> in.close();\n System.out.println(\"Closing File\");\n}\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-02-11T10:12:11.007", "Id": "34661", "Score": "0", "body": "Thanks - and good review! But I'd suggest `ArrayList<E>` instead of `Vector<E>` as the latter [is considered outdated](http://stackoverflow.com/questions/1386275/why-is-java-vector-class-considered-obsolete-or-deprecated) (it synchronizes each individual operation, which doesn't have any benefits for concurrency but slows down the code. Also, the name `Vector` is misleading)." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-02-12T08:21:09.773", "Id": "34710", "Score": "0", "body": "@Cygal What is an ArrayList and what does it do? I'm not exactly sure how to implement it due to that lack of knowledge, sorry. And thanks :)" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-02-12T08:37:25.250", "Id": "34711", "Score": "0", "body": "It's a collection that stores objects, just like the array you used. See [Collections](http://docs.oracle.com/javase/tutorial/collections/index.html), [List interface](http://docs.oracle.com/javase/tutorial/collections/interfaces/list.html) and [List implementations](http://docs.oracle.com/javase/tutorial/collections/implementations/list.html) from the official Java tutorials." } ], "meta_data": { "CommentCount": "3", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-02-11T09:34:40.597", "Id": "21573", "ParentId": "21534", "Score": "7" } } ]
{ "AcceptedAnswerId": "21573", "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-02-10T09:27:07.587", "Id": "21534", "Score": "4", "Tags": [ "java", "hangman" ], "Title": "Hangman game code" }
21534
<p>I've written this <code>module</code> (using a tutorial on the web I can't find now to stop unusual requests from clients. It's working as I've tested it on a local system. </p> <ol> <li><p>Is the logic fine enough?</p></li> <li><p>Another problem is that it counts requests for non-aspx resources (images, css, ...), but it shouldn't. How can I filter request for aspx pages ?</p></li> </ol> <p>This is the module code:</p> <pre><code>public class AntiDosModule : IHttpModule { const string blockKey = "IsBlocked"; const string reqsKey = "Requests"; public void Dispose() { } public void Init(HttpApplication context) { context.BeginRequest += ValidateRequest; } private static void ValidateRequest(object sender, EventArgs e) { // get configs from web.config AntiDosModuleSettings setting = AntiDosModuleSettings.GetConfig(); int blockDuration = setting.IPBlockDuration; // time window in which request are counted e.g 1000 request in 1 minute int validationTimeWindow = setting.ValidationTimeWindow; // max requests count in specified time window e.g 1000 request in 1 minute int maxValidRequests = setting.MaxValidRequests; string masterKey = setting.MasterKey; HttpContextBase context = new HttpContextWrapper(HttpContext.Current); CacheManager cacheMgr = new CacheManager(context, masterKey); // is client IP blocked bool IsBlocked = (bool)cacheMgr.GetItem&lt;Boolean&gt;(blockKey); if (IsBlocked) { context.Response.End(); } // number of requests sent by client till now IPReqsHint hint = cacheMgr.GetItem&lt;IPReqsHint&gt;(reqsKey) ?? new IPReqsHint(); if (hint.HintCount &gt; maxValidRequests) { // block client IP cacheMgr.AddItem(blockKey, true, blockDuration); context.Response.End(); } hint.HintCount++; if (hint.HintCount == 1) { cacheMgr.AddItem(reqsKey, hint, validationTimeWindow); } } } internal class IPReqsHint { public int HintCount { get; set; } public IPReqsHint() { HintCount = 0; } } </code></pre> <p>and this is the <code>CacheManager</code> class:</p> <pre><code>public class CacheManager { HttpContextBase context; string masterKey; public CacheManager(HttpContextBase context, string masterKey) { this.context = context; this.masterKey = masterKey; } public void AddItem(string key, object value, int duration) { string finalKey = GenerateFinalKey(key); context.Cache.Add( finalKey, value, null, DateTime.Now.AddSeconds(duration), System.Web.Caching.Cache.NoSlidingExpiration, System.Web.Caching.CacheItemPriority.Normal, null); } public T GetItem&lt;T&gt;(string key) { string finalKey = GenerateFinalKey(key); var obj = context.Cache[finalKey] ?? default(T); return (T)obj; } string GenerateFinalKey(string key) { return masterKey + "-" + context.Request.UserHostAddress + "-" + key; } } </code></pre>
[]
[ { "body": "<p>There definitely are not enough of these tools in the .NET world, but I've found that there are a lot in the WordPress/php world. My recommendation would be to review the code in those modules to determine if the logic is good enough. Certainly, \"good enough\" depends on your needs though. </p>\n\n<p>Regarding the filtering of specific file types, perhaps <a href=\"https://stackoverflow.com/questions/331398/how-to-have-http-module-on-fire-events-only-for-specific-page-types\">https://stackoverflow.com/questions/331398/how-to-have-http-module-on-fire-events-only-for-specific-page-types</a> will help? </p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-11-12T20:59:29.960", "Id": "35250", "ParentId": "21537", "Score": "2" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-02-10T12:31:12.277", "Id": "21537", "Score": "1", "Tags": [ "c#", "asp.net" ], "Title": "Optimizing this AntiDos HttpModule" }
21537
<p>My data is in this format:</p> <blockquote> <p>龍舟 龙舟 [long2 zhou1] /dragon boat/imperial boat/\n</p> </blockquote> <p>And I want to return:</p> <pre><code>('龍舟', '龙舟', 'long2 zhou1', '/dragon boat/imperial boat/') </code></pre> <p>In C I could do this in one line with <code>sscanf</code>, but I seem to be f̶a̶i̶l̶i̶n̶g̶ writing code like a schoolkid with Python:</p> <pre><code> working = line.rstrip().split(" ") trad, simp = working[0], working[1] working = " ".join(working[2:]).split("]") pinyin = working[0][1:] english = working[1][1:] return trad, simp, pinyin, english </code></pre> <p>Can I improve?</p>
[ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-02-10T13:04:27.373", "Id": "34604", "Score": "0", "body": "This is a little hard to parse because the logical field separator, the space character, is also a valid character inside the last two fields. This is disambiguated with brackets and slashes, but that obviously make the parse harder and uglier." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-02-10T16:08:16.803", "Id": "34615", "Score": "1", "body": "If your code doesn't work correctly, then this question is off topic here. See the [FAQ]." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-02-10T17:07:16.690", "Id": "34616", "Score": "3", "body": "@svick it works perfectly - by \"failing\" I meant \"failing to write neat code\"" } ]
[ { "body": "<p>My goal here is clarity above all else. I think a first step is to use the <code>maxsplit</code> argument of <a href=\"http://docs.python.org/2/library/stdtypes.html#str.split\" rel=\"nofollow\"><code>split</code></a> to get the first two pieces and the remainder:</p>\n\n<pre><code>trad, simp, remainder = line.rstrip().split(' ', 2)\n</code></pre>\n\n<p>Now, to parse the leftovers I'm afraid I only see slightly ugly choices. Some people like regular expressions and others hate them. Without regular expressions, I think it's easiest to view the remainder as two field separated with <code>\"] \"</code></p>\n\n<pre><code>pinyin, english = remainder.split(\"] \")\npinyin = pinyin[1:] # get rid of leading '['\n</code></pre>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-02-10T13:34:52.573", "Id": "21540", "ParentId": "21539", "Score": "2" } }, { "body": "<p>I would split around the square brackets first</p>\n\n<pre><code>def parse_string(s):\n a, b = s.rstrip().split(' [', 2)\n return a.split(' ') + b.split('] ', 2)\n</code></pre>\n\n<p>or more explicitly</p>\n\n<pre><code>def parse_string(s):\n first, rest = s.rstrip().split(' [', 2)\n trad, simp = first.split(' ', 2)\n pinyin, english = rest.split('] ', 2)\n return trad, simp, pinyin, english\n</code></pre>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-02-10T13:51:37.160", "Id": "21541", "ParentId": "21539", "Score": "0" } }, { "body": "<p>You can use <a href=\"https://en.wikipedia.org/wiki/Regular_expression\" rel=\"nofollow\">Regular Expressions</a> with <a href=\"http://docs.python.org/2.7/library/re.html\" rel=\"nofollow\">re</a> module. For example the following regular expression works with binary strings and Unicode string (I'm not sure which version of Python you use).</p>\n\n<p>For Python 2.7.3:</p>\n\n<pre><code>&gt;&gt;&gt; s = \"龍舟 龙舟 [long2 zhou1] /dragon boat/imperial boat/\\n\"\n&gt;&gt;&gt; u = s.decode(\"utf-8\")\n&gt;&gt;&gt; import re\n&gt;&gt;&gt; re.match(r\"^([^ ]+) ([^ ]+) \\[([^]]+)\\] (.+)\", s).groups()\n('\\xe9\\xbe\\x8d\\xe8\\x88\\x9f', '\\xe9\\xbe\\x99\\xe8\\x88\\x9f', 'long2 zhou1', '/dragon boat/imperial boat/')\n&gt;&gt;&gt; re.match(r\"^([^ ]+) ([^ ]+) \\[([^]]+)\\] (.+)\", u).groups()\n(u'\\u9f8d\\u821f', u'\\u9f99\\u821f', u'long2 zhou1', u'/dragon boat/imperial boat/')\n</code></pre>\n\n<p>For Python 3.2.3:</p>\n\n<pre><code>&gt;&gt;&gt; s = \"龍舟 龙舟 [long2 zhou1] /dragon boat/imperial boat/\\n\"\n&gt;&gt;&gt; b = s.encode(\"utf-8\")\n&gt;&gt;&gt; import re\n&gt;&gt;&gt; re.match(r\"^([^ ]+) ([^ ]+) \\[([^]]+)\\] (.+)\", s).groups()\n('龍舟', '龙舟', 'long2 zhou1', '/dragon boat/imperial boat/')\n&gt;&gt;&gt; re.match(br\"^([^ ]+) ([^ ]+) \\[([^]]+)\\] (.+)\", b).groups()\n(b'\\xe9\\xbe\\x8d\\xe8\\x88\\x9f', b'\\xe9\\xbe\\x99\\xe8\\x88\\x9f', b'long2 zhou1', b'/dragon boat/imperial boat/')\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-02-10T18:21:43.390", "Id": "34619", "Score": "0", "body": "`groups()` and `groupdict()` are great!" } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-02-10T14:05:11.600", "Id": "21543", "ParentId": "21539", "Score": "5" } }, { "body": "<p>You could perhaps try using the <a href=\"http://pypi.python.org/pypi/parse\" rel=\"nofollow\">parse</a> module, which you need to download from <a href=\"http://pypi.python.org\" rel=\"nofollow\">pypi</a>. It's intended to function in the opposite manner from the <code>format</code> method.</p>\n\n<pre><code>&gt;&gt;&gt; import parse\n&gt;&gt;&gt; data = \"龍舟 龙舟 [long2 zhou1] /dragon boat/imperial boat/\\n\"\n&gt;&gt;&gt; match = \"{} {} [{}] {}\\n\"\n&gt;&gt;&gt; result = parse.parse(match, data)\n&gt;&gt;&gt; print result\n&lt;Result ('龍舟', '龙舟', 'long2 zhou1', '/dragon boat/imperial boat/') {}&gt;\n&gt;&gt;&gt; print result[0] \n'龍舟'\n</code></pre>\n\n<p>If you want to be able to access the result as a dictionary, you could name each of the parameters inside the brackets:</p>\n\n<pre><code>&gt;&gt;&gt; import parse\n&gt;&gt;&gt; data = \"龍舟 龙舟 [long2 zhou1] /dragon boat/imperial boat/\\n\"\n&gt;&gt;&gt; match = \"{trad} {simp} [{pinyin}] {english}\\n\"\n&gt;&gt;&gt; result = parse.parse(match, data)\n&gt;&gt;&gt; print result\n&lt;Result () {'english': '/dragon boat/imperial boat/', 'trad': '龍舟', 'simp': '龙舟', 'pinyin': 'long2 zhou1'}&gt;\n&gt;&gt;&gt; print result['trad'] \n'龍舟'\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-02-10T17:38:01.657", "Id": "34618", "Score": "0", "body": "Is there some way to specify that the first two groups shouldn't contain spaces? Because I think unexpected input should cause an error, not silently return unexpected results." } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-02-10T17:20:32.417", "Id": "21547", "ParentId": "21539", "Score": "0" } } ]
{ "AcceptedAnswerId": "21543", "CommentCount": "3", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-02-10T12:37:25.733", "Id": "21539", "Score": "3", "Tags": [ "python", "strings", "parsing", "unicode" ], "Title": "String parsing with multiple delimeters" }
21539
<p>I have two loops which I am using to create a file, if the clientID in the client loop is the same as the id in the valuation loop then create a row. Then if the month value is the same as the previous month value we need to add up the values.</p> <p>This all works fine but i was wondering if anyone can think of a better way?</p> <pre><code> for (Clients cl : clientList) { //in loop so use stringbuilder StringBuilder sb = new StringBuilder(); sb.append(cl.getId()); sb.append(","); sb.append(cl.getFirstName()); sb.append(" "); sb.append(cl.getLastName()); sb.append(","); row = sb.toString(); for (Valuations vl : valList) { year = vl.getYear(); //if we are on a new month if (!month.equals(vl.getMonth()) &amp;&amp; !month.equals("")) { //add row and reset values if(!vl.isNanError()){ data.add(row + month + "," + year + ",£" + cash); } cash = 0; month = ""; done = false; } if (cl.getId().equals(vl.getClientId())) { if (!done) { row = sb.toString(); cash = 0; month = vl.getMonth(); done = true; } } cash += vl.getValue(); } } //add the last row after the loop breaks. data.add(row + month + "," + year + ",£" + cash); </code></pre>
[]
[ { "body": "<p>If you add a <code>toString()</code> method inside the client class you could, replace this code:</p>\n\n<pre><code>//in loop so use stringbuilder\n StringBuilder sb = new StringBuilder();\n sb.append(cl.getId());\n sb.append(\",\");\n sb.append(cl.getFirstName());\n sb.append(\" \");\n sb.append(cl.getLastName());\n sb.append(\",\");\n row = sb.toString();\n</code></pre>\n\n<p>for just:</p>\n\n<pre><code>row = sb.toString();\n</code></pre>\n\n<p>Furthermore, you can append the second with the third if condition inside the second loop, this: </p>\n\n<pre><code>if (cl.getId().equals(vl.getClientId())) {\n if (!done) {\n row = sb.toString();\n cash = 0;\n month = vl.getMonth();\n done = true;\n }\n }\n</code></pre>\n\n<p>can became this:</p>\n\n<pre><code> if (!done &amp;&amp; cl.getId().equals(vl.getClientId()))\n {\n row = sb.toString();\n cash = 0;\n month = vl.getMonth();\n done = true;\n }\n</code></pre>\n\n<p>Another thing, in the above code the <code>row = sb.toString</code> instruction should it be remove?\nSince you are calculated the row right below the first loop:</p>\n\n<pre><code>row = sb.toString();\nfor (Valuations vl : valList) {\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-02-11T08:37:02.250", "Id": "34653", "Score": "0", "body": "Thanks that's a great help, I'm trying to make the code as efficient as possible, I find it quite difficult when dealing with loops in loops lol" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-02-11T14:43:37.053", "Id": "34672", "Score": "0", "body": "@KPZ Yes, especially if you have to permute all (clients) against all (Valuations). Maybe you could try to parallelize the outer loop." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-02-11T15:33:07.147", "Id": "34674", "Score": "0", "body": "Sorry I'm not sure what you mean by 'parallelize the outer loop'?" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-02-11T15:57:02.000", "Id": "34677", "Score": "0", "body": "I am referring about using multi-thread. Each thread would take a range of clients to compute, of course you may have change quite a bit your code." } ], "meta_data": { "CommentCount": "4", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-02-10T19:15:12.100", "Id": "21553", "ParentId": "21548", "Score": "3" } } ]
{ "AcceptedAnswerId": "21553", "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-02-10T17:24:28.407", "Id": "21548", "Score": "1", "Tags": [ "java" ], "Title": "Calculating sum of certain values in a list" }
21548
<p>I'm on a high school robotics team and I'm trying to code a Xbox 360 controller so that it'll controller the motors with variable speed. So far it works alright, but where I'm quite the novice coder I'd like to have more experienced eyes peer at my code and see if they can find a better way, or more effective way to do the same thing. As of now, as the code shows, when the sticks are moved it causes the value (-1 to 1) to be multiplied by 100 and sent to the motor controller as a value for its speed. A timer is also attached to continuously update the values to have the most accuracy possible. So far the only issue I've encountered is a minor dead zone at each perfect diagonal. I've pondered just coding in the diagonals just like the other directions but I've had little luck. Any pointers would be appreciated! Here's the current code:</p> <pre><code>Private Sub JoySticks() 'Left Joystick drive motor controls. Dim LY As Integer Dim LX As Integer LY = GamePad.GetState(PlayerIndex.One).ThumbSticks.Left.Y * 100 LX = GamePad.GetState(PlayerIndex.One).ThumbSticks.Left.X * 100 HScrollLX.Value = LX VScrollLY.Value = LY If LY &gt; 0 Then MC1.Velocity(0) = LY MC1.Velocity(1) = LY ElseIf LY &lt; 0 Then MC1.Velocity(0) = LY MC1.Velocity(1) = LY ElseIf LX &gt; 0 Then MC1.Velocity(0) = LX MC1.Velocity(1) = LX * -1 ElseIf LX &lt; 0 Then MC1.Velocity(0) = LX MC1.Velocity(1) = LX * -1 ElseIf LX Or LY = 0 Then MC1.Velocity(0) = 0 MC1.Velocity(1) = 0 End If End Sub Private Sub TimerJoysticks_Tick(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles TimerJoysticks.Tick JoySticks() End Sub </code></pre>
[ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-02-09T00:45:18.077", "Id": "34620", "Score": "2", "body": "As the code is working without issue, this would be more appropriate on codereview.SE" } ]
[ { "body": "<p>Just on the if statements. Could you do something like:</p>\n\n<pre><code> Dim LY As Integer = GamePad.GetState(PlayerIndex.One).ThumbSticks.Left.Y * 100\n Dim LX As Integer = GamePad.GetState(PlayerIndex.One).ThumbSticks.Left.X * 100\n\n HScrollLX.Value = LX\n VScrollLY.Value = LY\n\n SetVelocity(LY);\n SetVelocity(LX,-1);\n\n // Private method to set the Velocity values\n private sub SetVelocity(position, factor = 1)\n dim v as integer\n\n if position = 0 then\n MC1.Velocity(0) = 0\n MC1.Velocity(1) = 0\n else\n MC1.Velocity(0) = position\n MC1.Velocity(1) = position * factor\n end if\n end sub\n</code></pre>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-02-11T05:59:53.807", "Id": "21567", "ParentId": "21551", "Score": "1" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "1", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-02-09T00:32:55.870", "Id": "21551", "Score": "3", "Tags": [ "vb.net", "xna" ], "Title": "I was wondering if there was a better way to improve my XNA joystick code? (Vb. Net)" }
21551
<p>So, my question is more of a 'best practices' question rather than a question with a particular aim. This is my current understanding of PHP factories and how to incorporate them into a project using PDOs and dependency injection. I'm pretty new at this and I still don't understand a lot about this subject. As such, I really don't know if I'm doing this quite right. Could someone point me in the right direction?</p> <pre><code>&lt;?php class PDOSettings_Factory { private function __construct() {} public static function build(Array $args = NULL) { $settings = array(); // Set default values. $settings["dbType"] = 'mysql'; $settings["dbName"] = 'test'; $settings["host"] = 'localhost'; $settings["user"] = 'guest'; $settings["pass"] = '1234'; // If keys are the same, they will be overwritten. if(isset($args)) { foreach($args as $key =&gt; $val) { $settings[$key] = $val; } } // Return setings. return $settings; } } $settings = PDOSettings_Factory::build(); class PDOConnection_Factory { private function __construct() {} public static function build($args) { // Set up PDO connection if(!isset($args)) { return NULL; } else { $statement = $args['dbType'].':'. 'host='.$args['host'].';'. 'dbname='.$args['dbName']; try { $dbh = new PDO( $statement, $args['user'], $args['pass']); $dbh-&gt;setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION); // Return DBH return $dbh; } catch (PDOException $e) { echo 'Error: ', $e-&gt;getMessage(), "\n"; } } return NULL; } } </code></pre> <p>And how to use the factories:</p> <pre><code>class demo { private $dbh = NULL; public function set($args) { if (!isset($args)) {return FALSE;} else { $this-&gt;dbh = $args; return TRUE; } } public function __construct($args = NULL) { $this-&gt;set($args); } public function doSomething() { // Set SQL command here. $sql = 'SELECT * FROM test'; $results = $this-&gt;dbh-&gt;prepare($sql); // Perform param binds here. $results-&gt;execute(); return $results; } } $db = PDOConnection_Factory::build($settings); $test = new demo($db); foreach ($test-&gt;doSomething() as $row) {print_r($row[0].PHP_EOL);} ?&gt; </code></pre>
[]
[ { "body": "<p><code>demo</code> should be <code>Demo</code> and in new classes you might want to use namespaces instead of underscores in your class names. See <a href=\"https://github.com/php-fig/fig-standards/blob/master/accepted/PSR-0.md\" rel=\"nofollow\">PSR-0</a></p>\n\n<p>As non of your <code>$args</code> is optional and there are only 5 I would recommend the use real method parameters instead of this array. Otherwise some validation and documentation of this array is missing.</p>\n\n<p>Furthermore you could refactor your ifs to real guard conditions and skip the else branch. This makes the code more readable and you get rid of a indentation level. There are also no braces on one-line-ifs.</p>\n\n<p><strong>Edit Sample for guard conditions</strong></p>\n\n<pre><code>class PDOConnection_Factory {\n private function __construct() {}\n public static function build($args) {\n if (!isset($args)) return NULL;\n $statement = ...\n try {\n $dbh = ...\n return $dbh;\n } catch (PDOException $e) {\n //as Cygal stated this is not very nice\n echo 'Error: ', $e-&gt;getMessage(), \"\\n\";\n return NULL;\n }\n }\n}\n</code></pre>\n\n<p><strong>Edit 2 Handle many and optimal method/constructor parameter</strong></p>\n\n<p>First the usage:</p>\n\n<pre><code>new PDOConnectionBuilder().name(\"test\").user(\"guest\").password(\"1234\").create();\n</code></pre>\n\n<p>And now the details:</p>\n\n<pre><code>class PDOConnectionBuilder()\n{\n private type=\"mysql\"; //defaults\n private name;\n private host=\"localhost\";\n private user;\n private password;\n\n public function create()\n {\n //guards again\n if (empty($name)) throw new PDOConnectionBuilderException(\"Name is not optional\");\n if (empty($user)) throw ...\n if (empty($password)) $passwordToUse=$user; //fallback to default\n else $passwordToUse=$password;\n\n //do the required stuff\n return $connection;\n }\n\n public function name ($name)\n {\n $this-&gt;name=$name;\n return $this;\n }\n //...\n} \n</code></pre>\n\n<p>This is a really awesome pattern for building complex object in larger system and in tests. You could even reuse the builder and call create twice. Or change only one property and call create again.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-02-11T07:49:26.637", "Id": "34649", "Score": "1", "body": "While I agree and upvoted for the first two paragraphs, I don't think removing braces for one line ifs is such a good idea. @Adam: If it isn't clear, \"guard conditions\" means that you can return early in PDOConnection_Factory::build() and get rid of the `else` keyword." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-02-11T08:17:52.573", "Id": "34652", "Score": "0", "body": "My comment only holds for real one-lines as `if (!isset($args)) {return FALSE;} `, as soon as there is a line break you \"have to\" add braces." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-02-11T08:52:57.377", "Id": "34654", "Score": "0", "body": "@mnhg, Thanks for the responses, I'll update the code to reflect the changes. I have a question about the $args being set as optional. I tried to make the settings factory args as optional as possible, trying to keep the arguments as clean as possible without hard-coding them because I am still not sure how many arguments I will have, what I will do with all of them, and I don't want to force the user to input an argument to get to the next one. Also, for tooltips, I'd prefer to show that you can/should put them in. Could you show me what you mean by refactoring the guard conditions?" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-02-11T09:06:56.743", "Id": "34656", "Score": "0", "body": "@mnhg right, sorry." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-02-11T09:21:54.937", "Id": "34657", "Score": "0", "body": "Actually you don't have optional arguments. So no need to start an optimization here. If you want to be prepared for the future please check my updated post about the builder pattern." } ], "meta_data": { "CommentCount": "5", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-02-11T05:07:38.277", "Id": "21564", "ParentId": "21555", "Score": "1" } }, { "body": "<h2>Formatting strings</h2>\n\n<p>You should try to avoid those kind of things:</p>\n\n<pre><code>$statement = $args['dbType'].':'.'host='.$args['host'].';'.'dbname='.$args['dbName'];\n</code></pre>\n\n<p>It's easy to miss something, and it's also this kind of constructions that leads to difficult to read code and (in other contexts) SQL injections. I would argue that using <a href=\"http://php.net/manual/en/function.sprintf.php\" rel=\"nofollow\"><code>sprintf</code></a> is a better idea here:</p>\n\n<pre><code>$format = '%s:host=%s:dbname=%s';\necho sprintf($format, $args['dbType'], $args['host'], $args['dbName']);\n</code></pre>\n\n<p>I don't know if it is considered idiomatic PHP or not, but it seems more readable and less error-prone to me.</p>\n\n<h2>PDO and exceptions</h2>\n\n<p><code>mnhg</code> already gave you a way to get rid of the first <code>return NULL</code> in <code>PDOConnection_Factory::build()</code>, but it's not enough, you should also remove the second one. I assume it comes from the possible exceptions in <code>PDO::__construct</code> and <code>PDO::setAttribute</code>. The issue is that you're catching the exception but doing nothing with them.</p>\n\n<p>You should instead embrace exceptions. :) A good first step is the <code>setAttribute</code> call. Since there's nothing you can do to handle them in the factory: you should instead let the application code decide what to do if something fails: for example, display a warning message to users and send an email to the administrator.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-02-11T08:00:43.667", "Id": "21571", "ParentId": "21555", "Score": "2" } } ]
{ "AcceptedAnswerId": "21564", "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-02-10T22:14:56.477", "Id": "21555", "Score": "4", "Tags": [ "php", "pdo" ], "Title": "PHP PDO Factory Classes" }
21555
<p>I'm wondering if there is anything i'm overlooking in the code below. I've taken the <a href="http://doc.akka.io/docs/akka/2.0.2/intro/getting-started-first-scala.html#Bootstrap_the_calculation" rel="nofollow">Pi calculation</a> example, simplified it and converted it to Akka 2.1. </p> <p>More specifically, i use the ask pattern to replace the Listener actor.</p> <p>So is this</p> <ol> <li>A proper and valid conversion?</li> <li>A reasonable approach? </li> <li>And is there a better approach to waiting for a result from an optionally distributed parallel reduction of a collection? In other words, is this an Akka equivalent of <code>collection.par.map(work).par.reduce(result)</code> or is there a better way?</li> </ol> <pre><code>object Work extends App { // This is just some collection of data to process (possibly remotely). val collection = 1 to 10000 val start = System.currentTimeMillis val system = ActorSystem(f"Work${start}%08x${hashCode}%04x") // The collection is converted into a stream since it could // potentially be huge. val master = system.actorOf(Props(new Master(collection.toStream)), name = "master") // This replaces what the Listener was doing, i think. implicit val timeout = Timeout(12.seconds) val result = Await.result(master ? Run, timeout.duration) println(s"\n${result}") system.shutdown() sealed trait WorkMessage case object Run extends WorkMessage case class Work(start: Int) extends WorkMessage case class Result(value: Double) extends WorkMessage sealed trait ControlMessage case class Complete(elapsed:Long) extends ControlMessage class Worker extends Actor { def doWork(element: Int): Double = { print(s" ${element}") return element.toDouble } def receive = { case Work(element) ⇒ sender ! Result(doWork(element)) } } class Master(work: Seq[Int]) extends Actor { val nrOfCPUs = Runtime.getRuntime().availableProcessors(); val nrOfWorkers = nrOfCPUs * 4 val workSize = work.size var nrOfResults: Int = _ val workerRouter = context.actorOf( Props[Worker].withRouter(RoundRobinRouter(nrOfWorkers)), name = "workerRouter") var done: ActorRef = _ def receive = { case Run ⇒ // Save the sender for responding to the ask once all the work is processed. done = sender work.foreach(element ⇒ workerRouter ! Work(element)) case Result(value) ⇒ nrOfResults += 1 if (nrOfResults &gt;= workSize) { done ! Complete(System.currentTimeMillis - start) context.stop(self) } } } } </code></pre> <p>Here's <a href="https://gist.github.com/nicerobot/4751388" rel="nofollow">a gist</a> with the full code and a build.sbt to try:</p> <pre class="lang-bsh prettyprint-override"><code>curl -ks https://gist.github.com/nicerobot/4751388/raw/run.sh | sh </code></pre>
[]
[ { "body": "<p>I'm not an akka expert but I did used akka in a project so these are just some of my observations:</p>\n\n<ol>\n<li><p><code>result</code> is blocking.</p>\n\n<pre><code>val result = Await.result(master ? Run, timeout.duration)\n</code></pre>\n\n<p>On case the master takes longer due to load or whatever, the pending result will\nexceed the timeout. Try async ask directly. </p>\n\n<pre><code>val result ask(actor, msg).mapTo[String]\n</code></pre></li>\n<li><p>In order to remain async you may carry on with an onComplete as\nFuture callback:</p>\n\n<pre><code>result onComplete {\n case Success(result) =&gt; doSomethingOnSuccess(result)\n case Failure(failure) =&gt; doSomethingOnFailure(failure)\n}\n</code></pre>\n\n<p>In this case no operation ever blocks the running thread. Read the <a href=\"http://doc.akka.io/docs/akka/snapshot/scala/futures.html\" rel=\"nofollow\">Akka docs</a> for more details </p></li>\n</ol>\n\n<blockquote>\n <p>And is there a better approach to waiting for a result from an\n optionally distributed parallel reduction of a collection? In other\n words, is this an Akka equivalent of\n collection.par.map(work).par.reduce(result) or is there a better way?</p>\n</blockquote>\n\n<p>Operating on distributed data-sets is much better done on an in-memory data processing engine. Using the distributed word count as example, in <a href=\"https://spark.incubator.apache.org/\" rel=\"nofollow\">Spark</a> you do: </p>\n\n<pre><code> file.flatMap(line =&gt; line.split(\" \"))\n .map(word =&gt; (word, 1))\n .reduceByKey(_ + _) \n</code></pre>\n\n<p>Actors are made for message processing such as Twitter or WhatsApp but for computing tasks that must be fast, you use either MapReduce (Hadoop) for offline crunching of Spark/Storm for real-time processing. Hope that answers your question. </p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-03-15T19:02:05.920", "Id": "44463", "ParentId": "21557", "Score": "3" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-02-11T00:22:15.037", "Id": "21557", "Score": "3", "Tags": [ "scala", "akka" ], "Title": "Is this Scala/Akka idiomatic and correct for Akka 2.1?" }
21557
<p>I was trying to explain the mediator pattern to a new developer, and ended up writing a simple event mediator. Thoughts?</p> <p><strong>EventMediator</strong></p> <pre><code>class EventMediator { private $events = array(); public function attach($event, Closure $callback) { if(!is_string($event)) throw new \InvalidArgumentException(); $event = strtolower(trim($event)); if(!isset($this-&gt;events[$event])) $this-&gt;events[$event] = array(); $this-&gt;events[$event][] = $callback; return $this; } public function trigger($event, $data = null) { if(!is_string($event)) throw new \InvalidArgumentException(); $event = strtolower(trim($event)); if(!isset($this-&gt;events[$event])) return false; foreach($this-&gt;events[$event] as $callback) $callback($event, $data); return true; } public function getEvents() { return $this-&gt;events; } } </code></pre> <p><strong>EventfulTrait</strong></p> <pre><code>trait EventfulTrait { private $eventMediator; public function attachEventMediator(EventMediator $eventMediator) { $this-&gt;eventMediator = $eventMediator; return $this; } public function detachEventMediator() { $this-&gt;eventMediator = null; return $this; } public function getEventMediator() { return $this-&gt;eventMediator; } public function attachEvent($name, $callback) { if(!is_null($this-&gt;eventMediator)) $this-&gt;eventMediator-&gt;attach($name, $callback); return $this; } public function triggerEvent($name, $data = null) { if(!is_null($this-&gt;eventMediator)) return $this-&gt;eventMediator-&gt;trigger($name, $data); return false; } } </code></pre> <p><strong>Example</strong></p> <pre><code>require "EventMediator.php"; require "EventfulTrait.php"; class Log { public function write($message) { echo "{$message}\n"; } } class Eventful { use EventfulTrait; private $log; public function __construct() { $this-&gt;log = new Log(); } public function attachLoadEvent() { $self = $this; $log = $this-&gt;log; $this-&gt;attachEvent( "load", function() use($self, $log) { $self-&gt;runOutOfNames(); $log-&gt;write("log message"); } ); } public function doSomething() { $this-&gt;triggerEvent("load"); $this-&gt;triggerEvent("event1"); } public function doSomethingElse() { $this-&gt;triggerEvent("load"); $this-&gt;triggerEvent("event1"); $this-&gt;triggerEvent("event2"); } public function runOutOfNames() { echo "load\n"; } } $eventMediator = new EventMediator(); $eventMediator-&gt;attach("event1", function() { echo "event1\n"; }); $eventMediator-&gt;attach("event2", function() { echo "event2\n"; }); $eventMediator-&gt;attach("done", function() { echo "done\n"; }); $eventful = new Eventful(); $eventful-&gt;attachEventMediator($eventMediator); $eventful-&gt;attachLoadEvent(); $eventful-&gt;doSomething(); $eventful-&gt;doSomethingElse(); $eventMediator-&gt;trigger("load"); $eventMediator-&gt;trigger("done"); </code></pre> <p>This will echo:</p> <pre><code>load log message event1 load log message event1 event2 load log message done </code></pre>
[]
[ { "body": "<p>I think this is a very clean looking code base, so congrats getting that down. I also think that the the way you implemented the pattern worked out very well.</p>\n\n<p>I don't have much to say, it's mostly just formatting.</p>\n\n<ul>\n<li>Throughout, you insist on keeping block sections condensed to one line. It's perfectly okay to add the brackets and break apart the code into multiple lines.</li>\n<li>In <code>attach()</code>, you return the current object. I don't see why you're doing so as in the example you didn't utilize this feature. Don't write code that's not in use yet!</li>\n<li>You might consider moving <code>strtolower(trim($event))</code> to a function with the appropriate parameters. Don't repeat yourself.</li>\n<li>Why is <code>!isset($this-&gt;events[$event])</code> returning false. I would expect an exception to be throw, that way if the code needs to watch for other errors later on, <code>false</code> could mean many things.</li>\n<li><code>attachEventMediator</code> I think needs a new name. You're not just <em>attaching</em> a mediator, you're <em>setting</em> it. If you had support for multiple mediators, then attach would be appropriate. Similarly, <code>detach</code> should be <em>remove</em> or <em>delete</em>.</li>\n<li>Perhaps in replace of <code>echo \"{$message}\\n\";</code>, you could use the <code>sprintf</code> function. I personally think this would clear up the line.</li>\n<li>To improve your dependency injection in <code>Eventful</code>, pass the <code>Log</code> as a parameter.</li>\n<li>Will the message always be <code>\"log message\"</code>? Maybe pass that as an argument.</li>\n</ul>\n\n<p>Overall I think the code is well-written. A couple more comments and better example code could have improved it even more!</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-07-21T00:23:33.700", "Id": "57545", "ParentId": "21558", "Score": "2" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-02-11T00:35:56.697", "Id": "21558", "Score": "3", "Tags": [ "php", "php5", "mediator" ], "Title": "Simple event mediator" }
21558