body
stringlengths
25
86.7k
comments
list
answers
list
meta_data
dict
question_id
stringlengths
1
6
<p>I've written a cache class which implements a last-recently-used (LRU) cache. I would like to know what you think about it and whether it's worth using it or not (due to performance issues for instance).</p> <pre><code>#include &lt;functional&gt; #include &lt;iterator&gt; #include &lt;list&gt; #include &lt;utility&gt; #include &lt;unordered_map&gt; #include &lt;boost/functional/hash.hpp&gt; class nop { public: void operator()(...) const volatile { } }; /* class nop */ /* ------------------------------------------------------------------------------------- */ template&lt;typename T&gt; class scale : public std::unary_function&lt;T, std::size_t&gt; { public: std::size_t operator()(T const&amp;) const { return 1; } }; /* template class scale */ /* ------------------------------------------------------------------------------------- */ template&lt;typename key_type, typename T&gt; struct cache_traits { typedef key_type key_type; typedef T cached_type; typedef std::pair&lt;key_type const, T&gt; value_type; typedef value_type&amp; reference; typedef value_type const&amp; const_reference; typedef typename allocator_traits&lt;value_type&gt;::difference_type difference_type; typedef typename allocator_traits&lt;value_type&gt;::size_type size_type; typedef typename allocator_traits&lt;value_type&gt;::pointer pointer; typedef typename allocator_traits&lt;value_type&gt;::const_pointer const_pointer; }; /* template struct cache_traits */ /* ------------------------------------------------------------------------------------- */ /********************************************************************************************************* template class cache; *********************************************************************************************************/ template&lt; typename key_type, typename T, class drop = nop&lt;T&gt;, class hash = boost::hash&lt;key_type&gt;, class pred = std::equal_to&lt;key_type&gt;, class scale = scale&lt;T&gt;, class alloc = std::allocator&lt;std::pair&lt;key_type const, T&gt;&gt; &gt; class cache : public cache_traits&lt;key_type, T&gt; { public: typedef drop drop_func; typedef hash hasher; typedef pred key_equal; typedef scale scale_func; typedef alloc allocator_type; /* --------------------------------------------------------------------------------- */ private: typedef std::list&lt;value_type, alloc&gt; storage_type; typedef typename storage_type::iterator storage_iterator; typedef typename storage_type::const_iterator const_storage_iterator; typedef std::pair&lt;key_type const, storage_iterator&gt; index_pair; typedef std::unordered_map&lt;key_type, storage_iterator, hash, pred, typename alloc::template rebind&lt;index_pair&gt;::other&gt; index_type; typedef typename index_type::iterator index_iterator; typedef typename index_type::const_iterator const_index_iterator; /* --------------------------------------------------------------------------------- */ public: typedef storage_iterator iterator; typedef const_storage_iterator const_iterator; typedef std::reverse_iterator&lt;iterator&gt; reverse_iterator; typedef std::reverse_iterator&lt;const_iterator&gt; const_reverse_iterator; /* --------------------------------------------------------------------------------- */ cache(cache const&amp; other) : m_cur_size(other.m_cur_size), m_max_size(other.m_max_size), m_drop(other.m_drop), m_scale(other.m_scale), m_stg(other.m_stg), m_idx(other.m_idx) { } cache(cache const&amp; other, alloc const&amp; alloc) : m_cur_size(other.m_cur_size), m_max_size(other.m_max_size), m_drop(other.m_drop), m_scale(other.m_scale), m_stg(other.m_stg, alloc), m_idx(other.m_idx, alloc) { } cache(size_type n, alloc const&amp; alloc) : m_cur_size(0), m_max_size(n), m_stg(alloc), m_idx(n, alloc) { } cache(size_type n = 0, drop const&amp; df = drop(), hash const&amp; hf = hash(), pred const&amp; eq = pred(), scale const&amp; sf = scale(), alloc const&amp; alloc = alloc()) : m_cur_size(0), m_max_size(n), m_drop(df), m_scale(sf), m_stg(alloc), m_idx(n, hf, eq, alloc) { } template&lt;class input_iterator&gt; cache(size_type n, input_iterator first, input_iterator last, drop const&amp; df = drop(), hash const&amp; hf = hash(), pred const&amp; eq = pred(), scale const&amp; sf = scale(), alloc const&amp; alloc = alloc()) : m_cur_size(0), m_max_size(n), m_drop(df), m_scale(sf), m_stg(alloc), m_idx(n, hf, eq, alloc) { insert(first, last); } virtual ~cache() { } cache&amp; operator=(cache other) { swap(other); return *this; } alloc get_allocator() const { return this-&gt;m_stg.get_allocator(); } /* --------------------------------------------------------------------------------- */ // iterators: iterator begin() { return m_stg.begin(); } const_iterator begin() const { return m_stg.begin(); } iterator end() { return m_stg.end(); } const_iterator end() const { return m_stg.end(); } /* --------------------------------------------------------------------------------- */ reverse_iterator rbegin() { return m_stg.rbegin(); } const_reverse_iterator rbegin() const { return m_stg.rbegin(); } reverse_iterator rend() { return m_stg.rend(); } const_reverse_iterator rend() const { return m_stg.rend(); } /* --------------------------------------------------------------------------------- */ const_iterator cbegin() const { return m_stg.cbegin(); } const_iterator cend() const { return m_stg.cend(); } const_reverse_iterator crbegin() const { return m_stg.crbegin(); } const_reverse_iterator crend() const { return m_stg.crend(); } /* --------------------------------------------------------------------------------- */ // capacity: bool empty() const { return size() == 0; } size_type max_size() const { return m_max_size; } void resize(size_type n) { m_max_size = n; adjust(); } size_type size() const { return m_cur_size; } /* --------------------------------------------------------------------------------- */ // element access: T&amp; at(key_type const&amp; key) { const_index_iterator pos = m_idx.find(key); if (pos != m_idx.end()) return pos-&gt;second-&gt;second; throw std::out_of_range("cache::at() : no such element is present"); } T const&amp; at(key_type const&amp; key) const { return const_cast&lt;cache*&gt;(this)-&gt;at(key); } iterator fetch(key_type const&amp; key) { const_index_iterator pos = m_idx.find(key); if (pos != m_idx.end()) { touch(pos-&gt;second); return pos-&gt;second; } return end(); } bool touch(key_type const&amp; key) { const_index_iterator pos = m_idx.find(key); if (pos != m_idx.end()) { touch(pos-&gt;second); return true; } return false; } /* --------------------------------------------------------------------------------- */ // modifiers: std::pair&lt;iterator, bool&gt; insert(const_reference x) { if (m_idx.find(x.first) == m_idx.end()) { iterator pos = add(x); return std::make_pair(pos, pos == end()); } return std::make_pair(m_stg.end(), false); } template&lt;class input_iterator&gt; void insert(input_iterator first, input_iterator last) { for (; first != last; ++first) store(*first); } size_type erase(key_type const&amp; key) { const_index_iterator pos = m_idx.find(key); if (pos != m_idx.end()) { remove(pos); return 1; } return 0; } iterator erase(const_iterator pos) { const_index_iterator index_pos = m_idx.find(pos-&gt;first); if (index_pos != m_idx.end()) return remove(index_pos); return end(); } iterator erase(const_iterator first, const_iterator last) { for (const_iterator i = first; i != last; ++i) { m_drop(i-&gt;second); m_cur_size -= m_scale(i-&gt;second); m_idx.erase(i-&gt;first); } return m_stg.erase(first, last); } void clear() { m_idx.clear(); m_stg.clear(); m_cur_size = 0; } void swap(cache&amp; other) { using std::swap; swap(m_idx, other.m_idx); swap(m_stg, other.m_stg); swap(m_cur_size, other.m_cur_size); swap(m_max_size, other.m_max_size); } iterator store(const_reference x) { const_index_iterator pos = m_idx.find(x.first); if (pos != m_idx.end()) { pos-&gt;second-&gt;second = x.second; touch(pos-&gt;second); return pos-&gt;second; } return add(x); } size_type exchange_key(key_type const&amp; x, key_type const&amp; y) { const_index_iterator xpos = m_idx.find(x); if (xpos != m_idx.end()) { const_index_iterator ypos = m_idx.find(y); if (ypos != m_idx.end()) { swap(const_cast&lt;key_type&amp;&gt;(xpos-&gt;second-&gt;first), const_cast&lt;key_type&amp;&gt;(ypos-&gt;second-&gt;first)); touch(xpos-&gt;second); touch(ypos-&gt;second); return 1; } } return 0; } size_type replace_key(key_type const&amp; old_key, key_type const&amp; new_key) { const_index_iterator pos = m_idx.find(old_key); if (pos != m_idx.end()) { if (m_idx.insert(std::make_pair(new_key, pos-&gt;second)).second) { const_cast&lt;key_type&amp;&gt;(pos-&gt;second-&gt;first) = new_key; touch(pos-&gt;second); m_idx.erase(pos); return 1; } } return 0; } /* --------------------------------------------------------------------------------- */ // observers: drop drop_function() const { return m_drop; } hash hash_function() const { return m_idx.hash_function(); } pred key_eq() const { return m_idx.key_eq(); } scale scale_function() const { return m_scale; } /* --------------------------------------------------------------------------------- */ // map operations: size_type count(key_type const&amp; key) const { return m_idx.find(key) != this-&gt;m_idx.end() ? 1 : 0; } iterator find(key_type const&amp; key) { const_index_iterator pos = m_idx.find(key); if (pos != m_idx.end()) return pos-&gt;second; return end(); } const_iterator find(key_type const&amp; key) const { return const_cast&lt;cache*&gt;(this)-&gt;find(key); } /* --------------------------------------------------------------------------------- */ iterator lower_bound(key_type const&amp; key) { const_index_iterator lower_bound = m_idx.lower_bound(key); if (lower_bound != m_idx.end()) return lower_bound-&gt;second; return end(); } const_iterator lower_bound(key_type const&amp; key) const { return const_cast&lt;cache*&gt;(this)-&gt;lower_bound(key); } iterator upper_bound(key_type const&amp; key) { const_index_iterator upper_bound = m_idx.upper_bound(key); if (upper_bound != m_idx.end()) return upper_bound-&gt;second; return end(); } const_iterator upper_bound(key_type const&amp; key) const { return const_cast&lt;cache*&gt;(this)-&gt;upper_bound(key); } /* --------------------------------------------------------------------------------- */ std::pair&lt;iterator, iterator&gt; equal_range(key_type const&amp; key) { const_index_iterator equal_range = m_idx.find(key); if (equal_range != m_idx.end()) return std::make_pair(equal_range-&gt;second, equal_range-&gt;second); iterator end = end(); return std::make_pair(end, end); } std::pair&lt;const_iterator, const_iterator&gt; equal_range(key_type const&amp; key) const { return const_cast&lt;cache*&gt;(this)-&gt;equal_range(key); } /* --------------------------------------------------------------------------------- */ private: iterator add(const_reference x) { m_stg.push_front(x); iterator pos = m_stg.begin(); size_type size = m_scale(pos-&gt;second); if (size &lt;= m_max_size) { m_cur_size += size; m_idx[pos-&gt;first] = pos; adjust(); return pos; } m_stg.erase(pos); return end(); } void adjust() { while (m_cur_size &gt; m_max_size) overflow(); } void overflow() { erase(boost::prior(m_stg.end())-&gt;first); } iterator remove(const_index_iterator const&amp; pos) { T const&amp; x = pos-&gt;second-&gt;second; m_drop(x); m_cur_size -= m_scale(x); iterator next = m_stg.erase(pos-&gt;second); m_idx.erase(pos); return next; } void touch(const_storage_iterator const&amp; pos) { m_stg.splice(m_stg.begin(), m_stg, pos); } /* --------------------------------------------------------------------------------- */ drop m_drop; scale m_scale; /* --------------------------------------------------------------------------------- */ index_type m_idx; storage_type m_stg; size_type m_cur_size, m_max_size; /* --------------------------------------------------------------------------------- */ friend void swap(cache&amp; x, cache&amp; y) { x.swap(y); } }; /* template class cache */ /* ------------------------------------------------------------------------------------- */ </code></pre>
[]
[ { "body": "<ul>\n<li><p>For one thing, this is not gonna work if <code>m_idx</code> contains iterators into <code>m_stg</code>:</p>\n\n<pre><code>cache(cache const&amp; other)\n : m_cur_size(other.m_cur_size), m_max_size(other.m_max_size),\n m_drop(other.m_drop), m_scale(other.m_scale),\n m_stg(other.m_stg), m_idx(other.m_idx) {\n</code></pre></li>\n<li><p>you cannot shuffle keys of <code>unordered_map</code>s like that:</p>\n\n<pre><code>size_type exchange_key(key_type const&amp; x, key_type const&amp; y)\n {\n const_index_iterator xpos = m_idx.find(x);\n if (xpos != m_idx.end())\n {\n const_index_iterator ypos = m_idx.find(y);\n if (ypos != m_idx.end())\n {\n swap(const_cast&lt;key_type&amp;&gt;(xpos-&gt;second-&gt;first),\n const_cast&lt;key_type&amp;&gt;(ypos-&gt;second-&gt;first));\n</code></pre></li>\n<li><p>this may cause UB when <code>overflow()</code> unfortunately removes <code>pos</code>.</p>\n\n<pre><code>iterator add(const_reference x)\n {\n m_stg.push_front(x);\n iterator pos = m_stg.begin();\n\n size_type size = m_scale(pos-&gt;second);\n if (size &lt;= m_max_size)\n {\n m_cur_size += size;\n m_idx[pos-&gt;first] = pos;\n adjust();\n return pos;\n }\n</code></pre></li>\n<li><p>I'd be happier if accessor functions hadn't thrown exceptions on missing data, since you can't really control what is and what isn't in the cache. A return of eg. <code>boost::optional&lt;T&gt;</code> would be appropriate.</p>\n\n<pre><code> // element access:\nT&amp; at(key_type const&amp; key)\n {\n const_index_iterator pos = m_idx.find(key);\n if (pos != m_idx.end())\n return pos-&gt;second-&gt;second;\n throw std::out_of_range(\"cache::at() : no such element is present\");\n }\n</code></pre></li>\n</ul>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-10-12T18:29:04.997", "Id": "8026", "Score": "0", "body": "The at() method is supposed to throw. Traditionally at() is a checked access into a container that throws when the key is invalid. That is why you have other accessors that return iterators (in this case fetch()) so you can compare the iterator against end() to validate if the key is in the container." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-10-12T19:15:16.403", "Id": "8027", "Score": "0", "body": "@LokiAstari: That is traditional for `vector`s, but not really appropriate for caches. Using this interface (even `fetch()`) would be terribly annoying, I'd suggest something like `T get(Key k, function<T()> gen)` that would return the cached value or recompute it with `gen`, other designs are possible too. Still, a method that throws an exception unpredictably is really bad design." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-10-12T19:19:44.507", "Id": "8028", "Score": "0", "body": "I have to disagree. I think it perfectly appropriate for caches where you can quite literally miss. Also returning an iterator with end() fits with all the standard usage patterns of C++ and is not going to confuse anybody." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-11-04T21:27:12.403", "Id": "8803", "Score": "0", "body": "Depends what level you want to work at. I don't want my CPU's caches to draw my attention to the fact every time I fetch some RAM which isn't cached... I just want them to transparently go away and get hold of the value. Ditto OS's RAM caching of disk... the OS can take care of some data not being present, and I'm happy for my app/process to block while I wait. See my answer for more." } ], "meta_data": { "CommentCount": "4", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-10-12T17:06:02.433", "Id": "5325", "ParentId": "5324", "Score": "4" } }, { "body": "<p>On the cache miss issue specifically: in my experience, for most applications of LRU caches, rather than having the cache throwing or returning an empty <code>boost::optional</code> on a cache miss, it's more usable if the cache knows how to compute the missing value (e.g by providing it with a function object to do such). Then the user can just use the cache as though it was a more efficient (assuming a reasonable proportion of cache hits) version of the the function. Like function memoisation but with a limited size.</p>\n\n<p>Examples of such a style of cache interface <a href=\"http://www.bottlenose.demon.co.uk/article/lru.htm\" rel=\"nofollow\">here</a> (although considerably less configurable than yours).</p>\n\n<p>Such an interface could just be implemented as a thin wrapper around your class of course.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-11-04T21:23:02.067", "Id": "5812", "ParentId": "5324", "Score": "1" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-10-12T16:29:10.137", "Id": "5324", "Score": "8", "Tags": [ "c++", "cache" ], "Title": "Last-recently-used (LRU) cache container class" }
5324
<p>I am writing simple file validator for my java ee app and I am stack with my class api. I need specific error descriptions, but also I would like to have boolean values indicating whether file is valid or not. Please give me some hints how to do it 'smart'.</p> <pre><code>package pl.poznan.put.ims.business.attachments; import java.util.List; import java.util.ArrayList; import com.google.inject.Inject; import pl.poznan.put.ims.business.entities.Attachment; import pl.poznan.put.ims.business.exceptions.AttachmentValidationException; import pl.poznan.put.ims.settings.IFileSystemSettings; public class AttachmentValidator implements IAttachmentValidator { IFileSystemSettings messageSettings; private List&lt;String&gt; errors; @Inject public AttachmentValidator(IFileSystemSettings messageSettings) { this.messageSettings = messageSettings; this.errors = new ArrayList&lt;String&gt;(); } @Override public boolean validate(List&lt;Attachment&gt; attachments) throws AttachmentValidationException { for (Attachment attachment : attachments) { validate(attachment); } if(attachments.size() &gt; messageSettings.getMaxFilesCount()) errors.add("Attachments max number exceeded."); if(!errors.isEmpty()) throw new AttachmentValidationException(errors); return true; } @Override public boolean validate(Attachment attachment) { boolean isValid = validateLimitExceeded(attachment); isValid &amp;= validateNull(attachment); return !isValid; } private boolean validateLimitExceeded(Attachment attachment) { boolean exceeded = attachment.getFileSize() &gt; messageSettings.getMaxFileSize(); if(exceeded) errors.add("Max file size limit exceeded. File: " + attachment.getFileDisplayName() + ". Size: "+ attachment.getFileSize()/1024/1024 + "MB."); return exceeded; } private boolean validateNull(Attachment attachment) { if(attachment == null) { errors.add("No attachment."); return false; } return true; } @Override public List&lt;String&gt; getErrors() { return errors; } @Override public long getTotalMaxFilesSize() { return messageSettings.getMaxFilesCount() * messageSettings.getMaxFileSize(); } } </code></pre>
[]
[ { "body": "<p>Some notes:</p>\n\n<ul>\n<li>The <code>boolean validate(...)</code> method never returns <code>false</code> so it should be <code>void</code> method. </li>\n<li>I'd pass immutable <code>ValidationResult</code> objects to the clients. The clients could check the results and could signal to their clients if there is an error or prints the messages etc.</li>\n<li>I'd omit the <code>&amp;=</code> operator, it's really hard to read.</li>\n<li><code>getTotalMaxFilesSize()</code> should be in the <code>FileSystemSettings</code> class. (Feature or data envy smell.)</li>\n</ul>\n\n<p>After a few refactoring steps the following came out:</p>\n\n<p><code>AttachmentValidatorService.java</code></p>\n\n<pre><code>import java.util.List;\n\npublic interface AttachmentValidatorService {\n\n ValidationResult validate(List&lt;Attachment&gt; attachments);\n\n ValidationResult validate(Attachment attachment);\n\n long getTotalMaxFilesSize();\n}\n</code></pre>\n\n<p><code>ValidationResult.java</code></p>\n\n<pre><code>import static com.google.common.base.Preconditions.checkNotNull;\n\nimport java.util.ArrayList;\nimport java.util.List;\n\nimport javax.annotation.concurrent.Immutable;\n\n@Immutable\npublic class ValidationResult {\n\n private final List&lt;String&gt; errors;\n\n public ValidationResult(final List&lt;String&gt; errors) {\n checkNotNull(errors, \"errors cannot be null\");\n this.errors = new ArrayList&lt;String&gt;(errors);\n }\n\n public boolean isValid() {\n if (errors.isEmpty()) {\n return true;\n }\n return false;\n }\n\n public List&lt;String&gt; getErrors() {\n return new ArrayList&lt;String&gt;(errors);\n }\n\n // If lots of the clients use this\n // public void checkErrors() {\n // if (!isValid()) {\n // throw new ...\n // }\n // }\n}\n</code></pre>\n\n<p><code>AttachmentValidatorServiceImpl</code>:</p>\n\n<pre><code>import static com.google.common.base.Preconditions.checkNotNull;\n\nimport java.util.Collections;\nimport java.util.List;\n\npublic class AttachmentValidatorServiceImpl implements\n AttachmentValidatorService {\n private final FileSystemSettings messageSettings;\n\n public AttachmentValidatorServiceImpl(\n final FileSystemSettings messageSettings) {\n this.messageSettings = checkNotNull(messageSettings,\n \"messageSettings cannot be null\");\n }\n\n @Override\n public ValidationResult validate(final List&lt;Attachment&gt; attachments) {\n final AttachmentValidator attachmentValidator = new AttachmentValidator(\n messageSettings, attachments);\n return attachmentValidator.getValidationResult();\n }\n\n @Override\n public ValidationResult validate(final Attachment attachment) {\n return validate(Collections.singletonList(attachment));\n }\n\n @Override\n public long getTotalMaxFilesSize() {\n return messageSettings.getMaxFilesCount()\n * messageSettings.getMaxFileSize();\n }\n}\n</code></pre>\n\n<p><code>AttachmentValidator.java</code></p>\n\n<pre><code>import static com.google.common.base.Preconditions.checkNotNull;\n\nimport java.util.ArrayList;\nimport java.util.List;\n\npublic class AttachmentValidator {\n\n private final List&lt;String&gt; errors = new ArrayList&lt;String&gt;();\n\n private final FileSystemSettings messageSettings;\n\n public AttachmentValidator(\n final FileSystemSettings messageSettings,\n final List&lt;Attachment&gt; attachments) {\n this.messageSettings = checkNotNull(messageSettings,\n \"messageSettings cannot be null\");\n checkNotNull(attachments, \"attachments cannot be null\");\n for (final Attachment attachment : attachments) {\n validate(attachment);\n }\n\n validateSize(attachments);\n }\n\n private void validate(final Attachment attachment) {\n validateNull(attachment);\n validateLimitExceeded(attachment);\n }\n\n private void validateSize(final List&lt;Attachment&gt; attachments) {\n if (attachments.size() &gt; messageSettings.getMaxFilesCount()) {\n errors.add(\"Attachments max number exceeded.\");\n }\n }\n\n private void validateLimitExceeded(final Attachment attachment) {\n if (attachment == null) {\n return;\n }\n final int fileSize = attachment.getFileSize();\n final boolean exceeded = fileSize &gt; messageSettings\n .getMaxFileSize();\n if (exceeded) {\n final String fileDisplayName = attachment\n .getFileDisplayName();\n final int fileSizeInMegaBytes;\n if (fileSize == 0) {\n fileSizeInMegaBytes = 0;\n } else {\n fileSizeInMegaBytes = fileSize / 1024 / 1024;\n }\n final String errorMsg = \"Max file size limit exceeded. File: \"\n + fileDisplayName\n + \". Size: \"\n + fileSizeInMegaBytes + \"MB.\";\n errors.add(errorMsg);\n }\n }\n\n private void validateNull(final Attachment attachment) {\n if (attachment == null) {\n errors.add(\"No attachment.\");\n }\n }\n\n public ValidationResult getValidationResult() {\n return new ValidationResult(errors);\n }\n\n}\n</code></pre>\n\n<p>Feel free to ask if you have any questions.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-10-26T08:28:20.613", "Id": "5584", "ParentId": "5326", "Score": "2" } } ]
{ "AcceptedAnswerId": "5584", "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-10-12T18:31:43.517", "Id": "5326", "Score": "2", "Tags": [ "java", "exception-handling" ], "Title": "Validating files and returning errors messages/boolean values" }
5326
<p>I have three ways of reordering a list (think baseball order) and I am sure you can come up with more. What is a the best way?</p> <p>For example if input is list is 1,2,3,4 and current is 3 then the output should be 3,4,1,2. Another example list: 1,2,3,4 and current 4 output is 4,1,2,3.</p> <pre><code>public void reOrder(List&lt;String&gt; list, String current) { if (list.size() &gt; 1) { for (int i = 0; i &lt; list.size(); i++) { String host = list.remove(0); if (host.equals(current)) { list.add(0, host); break; } list.add(host); } } } public void reOrder2(List&lt;String&gt; list, String current) { if (list.size() &gt; 1) { int indexOfWorkingHost = list.indexOf(current); if (indexOfWorkingHost != -1) { for (int i = 0; i &lt; indexOfWorkingHost; i++) { list.add(list.remove(0)); } } } } public void reOrder3(List&lt;String&gt; list, String current) { if (list.size() &gt; 1) { List&lt;String&gt; tmpServers = new ArrayList&lt;String&gt;(); tmpServers.addAll(list); for (String host : tmpServers) { if (host.equals(current)) { break; } String first = list.remove(0); list.add(first); } } } </code></pre>
[ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-10-14T07:44:39.217", "Id": "198454", "Score": "0", "body": "You might consider other data structures, e.g. a [ring buffer](http://en.wikipedia.org/wiki/Circular_buffer)." } ]
[ { "body": "<p>The first thing you need to do is define what you mean with \"best\". Fastest to execute? Most readable? Best Java-ness?</p>\n\n<p>In any case neither solution is very \"nice\". The first one unecessarily removes the \"current\" item und re-adds it, the second one uses indexOf, thus indirectly has two loops, and finally the third one makes a copy of the list, which is even slower.</p>\n\n<p>When using \"low level\" removing/adding and modification of the original list, I guess I'd do it like this (untested):</p>\n\n<pre><code>public void reOrder(List&lt;String&gt; list, String current) {\n int i = list.length;\n while (i-- &gt; 0 &amp;&amp; list.get(0) != current)\n list.add(list.remove(0));\n}\n</code></pre>\n\n<p>(BTW, consider making use of the generics: <code>public &lt;T&gt; void reOrder(List&lt;T&gt; list, T current) {...</code>)</p>\n\n<p>There is also a Java API function that does this (<a href=\"http://download.oracle.com/javase/6/docs/api/java/util/Collections.html#rotate%28java.util.List,%20int%29\" rel=\"nofollow\">Collections.rotate</a>), but it requires the index of the \"current\" element. If you have a \"better\" or more optimized why to get the index, other than the \"left to right\" search of <code>indexOf</code> (such as a binary search, or a map), then that would be a better solution.</p>\n\n<p>In any case, using the current item's index instead of the item itself is something you should consider (depending on the the architecture of your project), because it generally not a good idea to have to search for the index of an item every time you do something with the list.</p>\n\n<p>If speed is really a practical problem for you, then another thing you should check, is if you really need to reorder the actual list. There are ways just to create a \"view\" of the list in the desired order which would basically take virtually no additional time (especially it would be independently from the length of the list) to create and use.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-10-13T13:53:50.973", "Id": "5339", "ParentId": "5327", "Score": "2" } }, { "body": "<p>Since there is a current, I'd imagine it's done via iterator.</p>\n\n<p>Something among the lines:</p>\n\n<pre><code>for (Iterator&lt;T&gt; i = list.iterator(); i.hasNext(); ){\n if (current.equals(i.next()){\n i.remove();\n list.add(0, current);\n break;\n }\n}\n</code></pre>\n\n<p>The code works perfectly for <code>LinkedList</code>, yet LinkLists do suck very bad b/c of the indirection on each iteration (heavily cache miss prone). <code>ArrayList</code> (and array back ones) will exhibit 2 times System.arrayCopy but they are the better type of List most of the time, and last but not least you might wish to have a look at <code>ArrayDequeu</code>.</p>\n\n<p>Either way this is the best way to do in terms of speed and readability.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-10-13T15:40:49.023", "Id": "5341", "ParentId": "5327", "Score": "1" } } ]
{ "AcceptedAnswerId": "5339", "CommentCount": "1", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-10-12T19:32:59.690", "Id": "5327", "Score": "2", "Tags": [ "java", "optimization" ], "Title": "reorder a list in java" }
5327
<p>I am attempting to build a small JavaScript library (similar to jQuery)</p> <p>The purpose behind this is mostly a learning exercise, so asking why I don't just use an existing library is moot.</p> <p>So far I have just got my basic constructor, a 'caller' function to invoke a new object, and some basic functions for an example.</p> <pre><code>var lemon = function() { var prop = { collection: [] }; var fn = { init: function(selector, context) { context = context || document; if (!selector) { return; } else if (typeof selector == "string") { prop.collection = fn.toArray(context.querySelectorAll(selector)); } else if (selector instanceof Array || selector instanceof NodeList) { fn.toArray(selector).forEach(function(obj) { prop.collection.push(obj); }); } else if (selector instanceof Element) { prop.collection.push(selector); } prop.length = prop.collection.length; fn.extend.apply(this, [this, prop, fn]); }, toArray: function(target) { var array = []; for (var i = target.length &gt;&gt;&gt; 0; i--;) { array[i] = target[i]; } return array; }, extend: function(target) { var objects = Array.prototype.slice.call(arguments, 1); objects.forEach(function(obj) { var props = Object.getOwnPropertyNames(obj); props.forEach(function(key) { target[key] = obj[key]; }); }); return target; }, addClass: function(klass) { for (var i = 0, l = this.length; i &lt; l; i++) { this.collection[i].className += " " + klass; } return this; } }; fn.init.apply(this, fn.toArray(arguments)); }; var $ = function(selector, context) { return new lemon(selector, context); }; </code></pre>
[ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-10-12T21:19:46.453", "Id": "8035", "Score": "0", "body": "Why is your API identical to jQuery. Why not sit down and think what you need for this javascript library." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-10-12T22:01:18.360", "Id": "8037", "Score": "0", "body": "I have sat down and thought of what i need, and it's 1/8th of jQuery. so i'm basically building the functionality I need and basing it off of jQuery user-end look and feel. *without all of the bloat, or trying*" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-10-12T23:06:47.443", "Id": "8039", "Score": "0", "body": "@rlemon There is a reason for the jQuery Bloat/'try'-ing It would be good to first find out why this is such a bloat to you. If you use the minified files jQuery is quite small and then just put good expires headers when you serve them or link to a CDN. Otherwise things like you are doing can get quite tricky." } ]
[ { "body": "<p>There is quite a performance problem with your code: it will rebuild the <code>fn</code> object and all its methods every time the <code>lemon(selector, context)</code> constructor gets called. You can avoid that behavior by using the module design pattern: </p>\n\n<pre><code>this.lemon = (function () {\n\n var fn = {\n /* The code for the fn object here\n init: function (selector, context) {\n var prop = this.prop;\n ...\n */\n\n return function lemon() {\n this.prop = {\n collection: []\n };\n fn.init.apply(this, fn.toArray(arguments));\n };\n\n })();\n</code></pre>\n\n<p>However, you will have to add a line <code>var prop = this.prop;</code> in the beginning of every method of the <code>fn</code> object that requires <code>prop</code>.</p>\n\n<p>Also, when introducing a new global variable, it is better for the readability of your code to use <code>this.myVar = myValue;</code> or <code>window.myVar = myValue;</code>. In fact, the <code>var</code> keyword should only be used for local variables.</p>\n\n<p>Finally, it is often recommended to put a space between the <code>function</code> keyword and the following parenthesis, but that's not mandatory.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-10-14T18:08:13.393", "Id": "8091", "Score": "0", "body": "that spacing was due to jsfiddle 'tidyup' function ;) and I noticed that performance improvement. So I have actually implemented a version of what you have noted :)" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-10-15T11:17:17.287", "Id": "8113", "Score": "0", "body": "I'm glad to help you... Keep up the good work!" } ], "meta_data": { "CommentCount": "2", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-10-14T16:08:15.540", "Id": "5360", "ParentId": "5328", "Score": "2" } } ]
{ "AcceptedAnswerId": "5360", "CommentCount": "3", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-10-12T20:56:06.633", "Id": "5328", "Score": "2", "Tags": [ "javascript", "library" ], "Title": "jQuery-like library for learning purposes" }
5328
<p>I just wrote a small card game in JavaScript, CSS and HTML. This is kind of my first project that I have cared about front-end. So I got things to work, but I am sure that this is not the smartest way to do it.</p> <p>If someone could give me some guidelines on how this would have been done in a more professional way I would be very thankful.</p> <pre><code>window.turn_counter = 0; window.kings = 0; window.game = false; $(document).ready(function(){ $('#help').hide(); $('#turn').hide(); $('#card').hide(); $('#count').hide(); $('#rule_text').hide(); $('#game_buttons').hide(); $('#set_up').hide(); $(document).keydown(function(e) { //Add this to all the inputs if (e.keyCode == '32' || e.keyCode == 13) { if (game == true){ pull_card(); } } }); }); function start(){ $('#welcome_screen').hide(); $('#set_up').show(); $('#set_up').append('&lt;input type="text" ' + 'class="input_field center" id="num" ' + 'value="Number of players"&gt;' + '&lt;img alt="setup button" ' + 'class="button center" ' + 'onclick="set_players()" ' + 'src="static/button_proceed.png"&gt;'); } function hide_help(){ $('#help').hide(); $('#game_components').show(); } function show_help(){ $('#game_components').hide(); $('#help').show(); } function set_players(){ var number = document.getElementById('num').value; number = parseInt(number); //Need do something if string is entered. window.number_of_players = number; $('#set_up').empty(); for(i = 0; i &lt; window.number_of_players; i++){ var player_number = i + 1; $('#set_up').append('&lt;input class="input_field center"' + ' value="Player #' + player_number + '" type="text" id="' + i + '" &gt;'); } $('.set_up').append('&lt;img alt="proceed button" id="proceed_button" ' + 'class="center button" src="static/button_proceed.png"' + ' onclick=register_players()&gt;'); } function register_players(){ players = new Array(); for (i = 0; i &lt; window.number_of_players; i++){ players[i] = document.getElementById(i).value; } window.players = players; set_up_rules(); } function set_up_rules(){ $('.set_up').empty(); for (i = 0; i &lt; 12; i++){ if (i == 0){ name = 'Ace'; } else if (i == 10){ name = 'Jack'; } else if (i == 11){ name = 'Queen'; } else{ name = 'card ' + (i + 1); } $('.set_up').append('&lt;input value="Rule for ' + name + '" class="input_field center" id="other' + i + '" type="text"&gt;'); } $('.set_up').append('&lt;br&gt;&lt;img alt="setup button" class="button center"' + ' src="static/button_startgame.png" ' + 'onclick="set_rules()"&gt;'); } function set_rules(){ rule_set = new Array(); for (i = 0; i &lt; 12; i++){ card_rule = document.getElementById('other' + i).value; rule_set[i] = card_rule; } rule_set[12] = 'KINGS CUP!!' window.rule_set = rule_set; start_game(); } function start_game(){ new_deck(); pull_card(); $('#help_button').hide(); $('#set_up').hide(); $('#turn').show(); $('#card').show(); $('#game_buttons').show(); game = true; } function pull_card(){ item = Math.random() * deck.length; card = window.deck.splice(item,1); display_card(card); } function display_card(card){ //weird flash, need to empty content for each card game_buttons = '&lt;img class="center button" alt="next card button" ' + 'src="static/button_nextcard.png" ' + 'onclick="pull_card()" &gt;' + '&lt;img class="center button" alt="remind me of rule button" ' + 'src="static/button_remindme.png" ' + 'onclick="display_rule()" &gt;'; if(card &lt; 1){ alert("Deck is empty. The game will reload"); window.location.reload(); } current_turn = get_current_turn() turn = get_next_turn() //need to be called to check if it is the last king get_rule(card, current_turn) //needs to be done to prevent weird flash $('#game_buttons').empty(); $('#card').empty(); $('#card').append('&lt;img class="center" alt="' + card + '"src=/static/cards/' + card + '.png &gt;'); $('#game_buttons').append(game_buttons); $('#turn').empty(); if (current_turn != undefined){ $('#turn').append('&lt;h2 class="center" &gt;Current player: ' + current_turn + '&lt;/h2&gt;'); } if (turn != undefined){ $('#turn').append('&lt;h2 class="center"&gt;Next player: ' + turn + '&lt;/h2&gt;'); } } function get_next_turn(){ //add test on get number if (window.turn_counter == (window.players.length - 1)){ window.turn_counter = -1; } window.turn_counter += 1; player = window.players[window.turn_counter]; return player; } function get_current_turn(){ return window.players[window.turn_counter]; } function get_rule(card, player){ num = String(card); num = num.substring(1); if (num == 13){ window.kings +=1; if (window.kings == 4){ if (player == undefined){ alert('LAST KING! Congratulations!') } else{ alert('LAST KING! Congratulations ' + player + '!') } } } return window.rule_set[num - 1]; } function display_rule(){ rule = get_rule(card, get_current_turn()); alert(rule); } function new_deck(){ var deck = new Array( 'd1', 'd2', 'd3', 'd4', 'd5', 'd6', 'd7', 'd8', 'd9', 'd10', 'd11', 'd12', 'd13', 'h1', 'h2', 'h3', 'h4', 'h5', 'h6', 'h7', 'h8', 'h9', 'h10', 'h11', 'h12', 'h13', 'c1', 'c2', 'c3', 'c4', 'c5', 'c6', 'c7', 'c8', 'c9', 'c10', 'c11', 'c12', 'c13', 's1', 's2', 's3', 's4', 's5', 's6', 's7', 's8', 's9', 's10', 's11', 's12', 's13' ); window.deck = deck; } </code></pre> <p>I won't post the HTML and CSS for now, but you can find the game <a href="http://kingscuponline.appspot.com/" rel="nofollow">here</a>.</p>
[ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-10-12T21:28:04.290", "Id": "8036", "Score": "3", "body": "My eyes. The code is far too procedural. Modularize it." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-11-02T14:43:29.917", "Id": "8709", "Score": "0", "body": "You might also have a look at CoffeeScript. It helps you write nicer JS." } ]
[ { "body": "<p>This is a great start. To Raynos' point you could modularize this into more manageable chunks. Here are a is jQuery Pattern article to help you get started: <a href=\"http://coding.smashingmagazine.com/2011/10/11/essential-jquery-plugin-patterns/\" rel=\"nofollow\">Essential jQuery Plugin Patterns by Addy Osmani</a></p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-10-13T01:16:28.063", "Id": "8040", "Score": "0", "body": "Thanks a lot for that article. I think that is something I am looking for." } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-10-12T22:14:15.747", "Id": "5331", "ParentId": "5329", "Score": "1" } }, { "body": "<p>A couple of things would make this cleaner.</p>\n\n<p>Like the others said ... modularize/plugin-ize it etc. in the proccess don't have</p>\n\n<pre><code>window.GlobalVariableName = someVal;\n</code></pre>\n\n<p>instead make an object:</p>\n\n<pre><code>window.MyCardGame = {\n GlobalVariableName: somVal,\n\n GlobalFunction: function (){ ... }\n};\n</code></pre>\n\n<p>Or a closure</p>\n\n<pre><code>(function(){\n var Global = val; // Global variable to anything in this closure only.\n})();\n</code></pre>\n\n<p>patterns like:</p>\n\n<pre><code>for(i = 0; i &lt; 12; i++){\n if (i == 0){\n name = 'Ace';\n }\n else if (i == 10){\n name = 'Jack';\n }\n else if (i == 11){\n name = 'Queen';\n }\n\n else{\n name = 'card ' + (i + 1);\n }\n // etc.\n}\n</code></pre>\n\n<p>can be expressed with a switch which is \ncleaner/easier to read (IMHO):</p>\n\n<pre><code>for(i = 0; i &lt; 12; i++){\n switch(i)\n {\n case 0:\n name = 'Ace';\n break;\n case 10:\n name = 'Jack';\n break;\n case 11:\n name = 'Queen';\n break;\n default:\n name = 'card ' + (i + 1);\n break;\n }\n // etc.\n}\n</code></pre>\n\n<p><em>ps: Where is the king?</em></p>\n\n<p>When you do</p>\n\n<pre><code>$(\"#elementID\").someFN();\n$(\"#elementID\").otherFN();\n</code></pre>\n\n<p>It has to get the same element twice. jQuery has the ability to chain:</p>\n\n<pre><code>$(\"#elementID\").someFN().otherFN();\n// OR\n$(\"#elementID\")\n .someFN()\n .otherFN();\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-10-13T01:19:52.397", "Id": "8041", "Score": "0", "body": "Thanks. This makes a lot of sense. But the closure, that is just a function that wraps around a set of functions to isolate things?\nAnd the King can't be changed, so I have not included it in that method/array" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-10-13T01:26:05.970", "Id": "8042", "Score": "0", "body": "@Pecock Long live the King! ... The closure is just to isolate your variables/namespace so it doesn't screw up other code. Us developers can be an unoriginal bunch in naming things at times and two developers might use the same name for two different pieces of code. Closures minimise this sort of conflict. I'm not the best teacher of this so I would suggest a quick google search for them." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-10-13T01:37:24.927", "Id": "8044", "Score": "1", "body": "@JamesKhoury, your example isn't really a closure, thats an Instantly Invoked Function Expression AKA IIFE, which is part of the JavaScript module pattern." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-10-13T01:40:56.047", "Id": "8045", "Score": "0", "body": "@bittersweetryan No but a self invoking function creates a closure. As I said I'm not the best teacher on that subject but: http://jibbering.com/faq/notes/closures/ and http://www.javascriptkit.com/javatutors/closures.shtml and http://robertnyman.com/2008/10/09/explaining-javascript-scope-and-closures/ and http://blog.morrisjohns.com/javascript_closures_for_dummies.html seem to be good places to start learning." } ], "meta_data": { "CommentCount": "4", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-10-12T23:03:32.737", "Id": "5332", "ParentId": "5329", "Score": "1" } }, { "body": "<p>For starters don't store any of your variables in the global scope (I.E. window.xxx). Your whole came can be enclosed using the module pattern. To use the module pattern you'll do something like this:</p>\n\n<pre><code>//note that the var game isn't even required if you are only attaching events in here, the var is only needed if there are methods that your module needs to return properties or functions for other parts of your page to use them. \nvar game = (function(window, document, undefined){\n //so here you are caching your display elements and putting them in a Object\n var displayElements = {\n help : $('#help'),\n turn : $('#turn'),\n card : $('#card'),\n welcomeScreen : $('#welcome_screen'),\n setUp : $('#set_up'),\n ....\n },\n numberOfPlayers = 0;\n //anyother stuff you have in your window here\n\n function start(){\n displayElements.welcomeScreen.hide();\n displayElements.welcomeScreen.hide();\n $('#set_up').append('&lt;input type=\"text\" ' +\n 'class=\"input_field center\" id=\"num\" ' +\n 'value=\"Number of players\"&gt;' +\n '&lt;img alt=\"setup button\" ' + \n 'class=\"button center\" ' +\n 'onclick=\"set_players()\" ' +\n 'src=\"static/button_proceed.png\"&gt;');\n }\n\n function hide_help(){\n displayElements.help.hide();\n displayElements.gameComponents.show();\n }\n\n //put your other functions here\n}(window, window.document);\n</code></pre>\n\n<p>Another thing I'd do is create some generic functions for things like hiding elements. This is a typical pattern called a forEach:</p>\n\n<pre><code> function hideElems(elems){\n for(var i = 0; i &lt; elemen.len; i++){\n var elem = elems[i];\n function hide(){\n elem.hide(); //here you won't need jquery since you alredy have jquery objects that you created in the elements object\n }\n }\n }\n</code></pre>\n\n<p>Now instead of having:</p>\n\n<pre><code>$('#help').hide();\n$('#turn').hide();\n$('#card').hide();\n$('#count').hide();\n$('#rule_text').hide();\n$('#game_buttons').hide();\n$('#set_up').hide();\n</code></pre>\n\n<p>you'd have:</p>\n\n<pre><code> hideElems([displayElements.help,displayelements.turn...]); \n</code></pre>\n\n<p>The nice thing about this is that you can call it with any number of elements at a time. There's a lot more I can add but I have to get back to work. I'll see if I can come back tomorrow and add some more. </p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-10-13T02:43:23.230", "Id": "8047", "Score": "0", "body": "Thanks a lot. This is exactly what I was looking for. And it makes a lot of sense." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-10-14T13:54:31.923", "Id": "8084", "Score": "0", "body": "@Pecock You're welcome. I'm curious to what I'd else you'd like me to add to my answer to make it \"upvote\" worthy." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-10-14T21:05:49.447", "Id": "8102", "Score": "0", "body": "Sorry, This is perfect, but I can't vote up before I have gained 15 reputaion. And this is my first question, I will do it once I've reached the limit." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-10-14T21:11:37.283", "Id": "8104", "Score": "0", "body": "@Pecock No, worries. I just was wondering if I could do anything to make my answer better in your opinion." } ], "meta_data": { "CommentCount": "4", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-10-13T01:56:32.003", "Id": "5335", "ParentId": "5329", "Score": "3" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "2", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-10-12T21:14:55.930", "Id": "5329", "Score": "4", "Tags": [ "javascript", "html", "css", "game", "playing-cards" ], "Title": "King's Cup game" }
5329
<p>I found this method kinda tough to get for a beginner like me, but I tried to do my best, and here's what I came up with.</p> <p>Is this good code regarding performance? Is there anything wrong with it?</p> <pre><code>var notPrime = [] ; var prime = [] ; var n = prompt("Enter n: "); for(var i = 2 ; i &lt; n ; i++ ){ if(notPrime.indexOf(i) != -1){ continue; } for(var j = i ; i &lt;= j ; j++){ if((i * j) &lt; n){ notPrime.push(i*j); } else { break; } } prime.push(i); } for(var f in prime){ console.log(prime[f]); } </code></pre>
[]
[ { "body": "<p>Lets say that there is room for improvement. ;)</p>\n<hr />\n<p>The <code>prompt</code> method returns a string, but you want a number, so you should parse the string:</p>\n<pre><code>var n = parseInt(prompt(&quot;Enter n: &quot;), 10);\n</code></pre>\n<hr />\n<p>Using <code>indexOf</code> on an array is slow. Instead of putting all the non-primes in a bucket and rummaging through it, you should use an array containing boolean values where the index is the number and the values tells you if it's a prime or not.</p>\n<p>Accessing an array by index is an O(1) operation, while searching for a value in an array is an O(n) operaton. As n grows, this code will get slower and slower the longer you let it run.</p>\n<p>As you are pushing a lot of duplicate non-primes in the array, an array of boolean values will actually use about 70% less memory eventhough the primes also takes up space in it.</p>\n<hr />\n<p>This loop is pretty pointless:</p>\n<pre><code>for(var j = i ; i &lt;= j ; j++){\n</code></pre>\n<p>The condition will never be false. You should instead use the <code>i * j &lt; n</code> condition to break out of the loop:</p>\n<pre><code>for(var j = i; i * j &lt; n; j++){\n notPrime[i * j] = true;\n}\n</code></pre>\n<hr />\n<h3>Edit:</h3>\n<p>You are still using the array as a kind of collection. You should set all values to true at start, and then set all non-primes to false. This code (based on the algorithm <a href=\"http://en.wikipedia.org/wiki/Sieve_of_Eratosthenes\" rel=\"nofollow noreferrer\">here</a>) is about five times faster:</p>\n<pre><code>var n = parseInt(prompt(&quot;Enter n: &quot;), 10);\nvar i, j;\nvar prime = new Array(n);\nfor (i = 2; i &lt; n ; i++) prime[i] = true;\n\nfor (i = 2; i * i &lt; n ; i++) {\n if (prime[i]) {\n for (j = 0; i * i + i * j &lt; n ; j++) {\n prime[i * i + i * j] = false;\n }\n }\n}\n\nvar cnt = 0;\nfor (i = 2 ; i &lt; n ; i++) {\n if (prime[i]){\n console.log(i);\n }\n}\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-10-16T22:47:21.727", "Id": "8146", "Score": "0", "body": "Thanks .. The array of boolean values note really helped. It accelerate the whole process, eg: finding primes in from 0 to 20000 with the old code hangs the browser. But with the boolean values it works great. Thanks" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-10-17T07:27:59.653", "Id": "8155", "Score": "0", "body": "@Rafael: You are still using the array as a kind of collection. You should use the value in the array instead of checking for the existance of items. See the code added above." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-10-17T08:15:06.100", "Id": "8157", "Score": "0", "body": "mmmm, i tried the code you wrote. I'm afraid i don't notice a big difference, it's actually the same as the one i edited it." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-10-17T08:26:52.333", "Id": "8158", "Score": "0", "body": "@Rafael: I see a big difference: http://jsperf.com/sieve-versions" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-10-17T08:50:26.540", "Id": "8159", "Score": "0", "body": "mmmm, maybe it's just my computer. I don't really know, i'll try it again though. Thanks :)" } ], "meta_data": { "CommentCount": "5", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-10-13T16:40:55.180", "Id": "5342", "ParentId": "5334", "Score": "5" } }, { "body": "<p>I made some improvements and speed up this code.</p>\n\n<hr>\n\n<pre><code>var prime = new Array(n);\nfor (i = 2; i &lt; n ; i++) prime[i] = true;\n</code></pre>\n\n<p>replaced by 2x faster</p>\n\n<pre><code>var prime = [];\nfor (i = 0; i &lt;= n ; i++) prime.push(true);\n</code></pre>\n\n<hr>\n\n<pre><code>for (i = 2; i * i &lt; n ; i++) {\n</code></pre>\n\n<p><code>i * i</code> is calculated every time, replaced by</p>\n\n<pre><code>for (var i = 2; i &lt;= Math.sqrt(n)|0; i++) {\n</code></pre>\n\n<p>Math.sqrt(n)|0 reduces unneeded calculations</p>\n\n<hr>\n\n<pre><code>for (j = 0; i * i + i * j &lt;= n ; j++) {\n prime[i * i + i * j] = false;\n</code></pre>\n\n<p>Here are so many calculations iterated every time. I reduced them to:</p>\n\n<pre><code>for (var j = i*i; j &lt;= n; j += i) {\n prime[j] = false;\n</code></pre>\n\n<hr>\n\n<pre><code>function sieve5(n) {\n var i,j;\n // true-table\n var prime = [];\n for (i = 0; i &lt;= n; i++) prime.push(true); // mark 'numbers' 0..n as 'true'\n\n // mark for swipe\n for (i = 2; i &lt;= Math.sqrt(n)|0; i++) {\n if (prime[i]) {\n for (j = i*i; j &lt;= n ;j += i) {\n prime[j] = false; // eliminate all none prime numbers and mark them as 'false'\n }\n }\n }\n\n // extract primes\n var primes = [];\n for (i = 2; i &lt;= n; i++) { // 'zero' and 'one' is not prime\n if (prime[i]) primes.push(i) // get all primes from 2..n\n }\n\n return primes;\n}\nconsole.time(\"sieve5\");\nprimes = sieve5(1000000);// 62ms on my PC\nconsole.timeEnd(\"sieve5\");\nconsole.log('length=',primes.length);\n\nprimes = sieve5(100);\nconsole.log(primes);\n// [2,3,5,7,11,13,17,19,23,29,31,37,41,43,47,53,59,61,67,71,73,79,83,89,97]\nconsole.log(sieve5(11));//[2,3,5,7,11]\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2016-07-18T04:25:55.307", "Id": "253124", "Score": "1", "body": "I do not totally get why downvote. The code improvements are good, left alone without pushes gives more than twice speedup. And the killer comes from [push](http://stackoverflow.com/questions/614126/why-is-array-push-sometimes-faster-than-arrayn-value). Funny thing - alone push test in Firefox is faster than loop (fill also), on Chrome oposite, but *sieve5* consistently outperforms other sieves. +1 from me." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2016-08-15T06:16:42.360", "Id": "259362", "Score": "0", "body": "@Evil What was faster for you, `prime[i] = true;` or `prime.push(true);` ? For me `prime.push(true);`" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2016-08-15T06:23:49.553", "Id": "259363", "Score": "0", "body": "`prime.push(true)` on Firefox, `prime[i] = true` on Chrome, I have tried with `prime.fill(true)` but this is a bit of lottery. Also I tried with things like to store `Math.sqrt(n) | 0` to a variable, but it gives neglible saving." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2016-08-15T06:40:07.660", "Id": "259365", "Score": "0", "body": "`var max = Math.sqrt(n) | 0` is a good idea, I do not remember I tested it, but I believe I did." } ], "meta_data": { "CommentCount": "4", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2015-08-14T13:20:48.423", "Id": "100927", "ParentId": "5334", "Score": "0" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-10-13T01:39:24.237", "Id": "5334", "Score": "4", "Tags": [ "javascript", "performance", "beginner", "sieve-of-eratosthenes" ], "Title": "Sieve of Eratosthenes in JavaScript" }
5334
<p>I'm trying to validate an HTTP Request, and first I want to get sure that all of the information has been posted (and then I'll check the correct format of each incoming data), so to get sure that no Form Spoofing attack is made. However, since this HTTP Post comes from a form, and that form contains almost 40 fields, I came across an <code>if</code> clause like this:</p> <pre><code>// Here, the if clause has almost 40 conditions to check // first, second, third, etc. are imaginary names of incoming variables if (Request["first"] == null || Request["second"] == null || ...) { throw new ApplicationException("Incoming data is incomplete"); } else { // Now trying to validate the format of incoming data } </code></pre> <p>Is it a normal checking mechanism? Is there a better way for doing it?</p>
[ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-10-13T06:41:25.903", "Id": "8053", "Score": "1", "body": "Are you expecting them all to be null, if so a const array of strings might do it, if not a key/value pair should work." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-10-13T12:27:53.313", "Id": "8054", "Score": "0", "body": "Why don't you simply loop through the Request?" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-10-13T17:44:44.580", "Id": "8070", "Score": "0", "body": "@Ramhound: Because there are no null values in it. By looping through the items you don't see which are missing." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-10-14T03:54:18.097", "Id": "8072", "Score": "2", "body": "This isn't a code review question. Best practices are off topic for code review." } ]
[ { "body": "<p>Looks unreadable.</p>\n\n<p>I would normally extract such a condition to a private boolean function and reformat it for readability. That would be the first step.</p>\n\n<p>A second refactoring may present itself after this - perhaps having a list of string corresponding to the field names and iterating over it with the <code>Request</code> indexer, checking for <code>null</code> values. This assumes that all the parts of the <code>if</code> are essentially doing the same nullity check. This is essentially what @Ant is presenting in his answer.</p>\n\n<p>To answer your question - how many conditions are acceptable? It is a subjective thing, but in general as many as are <em>readable</em>. Personally, if the <em>meaning</em> of the conditions is not clear, the extract a method refactoring with a good meaningful name is a great start.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-10-13T08:30:42.870", "Id": "8055", "Score": "0", "body": "+1 for putting the most important step first. Personally, I'll never see how adding an unnecessary iterator to these situations makes things *more* readable." } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-10-13T06:41:36.403", "Id": "5344", "ParentId": "5343", "Score": "32" } }, { "body": "<p>You could put all of your variable names into an array and loop over it, something like this (pseudocode):</p>\n\n<pre><code>var names = { 'First', 'Second', 'Third' };\n\nfor (var name in names) {\n if (Request[names[name]] == null) {\n throw new ApplicationException('Error');\n }\n}\n\n// No errors if we reach here\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-10-13T07:19:28.157", "Id": "8056", "Score": "4", "body": "application of the good old 0 1 infinity rule" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-10-13T09:10:19.967", "Id": "8057", "Score": "0", "body": "Also, if the language supports LINQ this could be simplified even further :)" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-10-13T09:41:47.050", "Id": "8058", "Score": "0", "body": "@MattDavey: How?" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-10-13T09:46:59.230", "Id": "8059", "Score": "5", "body": "`Request[names[name]]` looks odd to me, shouldn't that be `Request[name]` ?" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-10-13T09:55:51.117", "Id": "8060", "Score": "4", "body": "@ammoQ: The code is written in a pseudocode derived from an abhorrent mix of C# and JavaScript. The loop iteration style is from JS, but Request[name] would be more appropriate for C#. For more bizarreness note the single quotes and array initialisation style (JS) vs the use of null and exception handling (C#)." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-10-13T10:19:00.030", "Id": "8061", "Score": "4", "body": "@pdr using C# as an example: var requiredFields = new[] { \"First\", \"Second\", \"Third\", etc... }; if (requiredFields.Any(x => Request[x] == null)) { /* request is incomplete */ }" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-10-13T11:21:18.097", "Id": "8062", "Score": "0", "body": "@Ant: But in neither does the `names[name]` make sense. I believe ammoQ is right." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-10-13T11:30:15.307", "Id": "8063", "Score": "0", "body": "@MattDavey: See your point. When people say LINQ, my mind always strays to the language-integrated part." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-10-13T12:18:38.027", "Id": "8064", "Score": "1", "body": "@Jan Hudec: In JS, `name` is an integer that represents an index within the `names` array. So, `names[name]` is correct." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-10-13T12:32:44.420", "Id": "8065", "Score": "0", "body": "@Ant: Ah, ok. Not being a web developer I tend to forget how weird JS can be. Sorry." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-10-13T13:11:02.833", "Id": "8066", "Score": "0", "body": "@Jan Hudec: Technically, we're both right - that is the correct way to do it, but it *doesn't* make any sense. That's JS for you..." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-10-13T14:59:41.473", "Id": "8067", "Score": "1", "body": "+1 for this answer, but also for the one that suggests separating the validation block to a different method. Keeping your validation logic in a separate method will allow you to both keep your methods shorter (in case the validation code needs to grow) and also to make changes to your actual method in a more confident manner." } ], "meta_data": { "CommentCount": "12", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-10-13T06:42:07.540", "Id": "5345", "ParentId": "5343", "Score": "45" } }, { "body": "<p>Any if-statement clause system is acceptable provided it is easily readable and understandable.</p>\n\n<p>First off, when the number of clauses gets above one (1), put each clause in parentheses. That way you don't have to think about operator precedence.</p>\n\n<p>Second, when the if-line gets long, break it into multiple lines, one for each clause.</p>\n\n<p>Third, whenever coding lines that parallel each other, add blanks in order to make the components line up. That way you can instantly see the parallelism and be confident that you haven't thrown in an extra character somewhere.</p>\n\n<p>I would recode your example as:</p>\n\n<pre><code>if ( ( Request[ \"first\" ] == null )\n || ( Request[ \"second\" ] == null )\n || ( Request[ \"third\" ] == null )\n || (...) )\n{\n</code></pre>\n\n<p>Fourth, if the clauses involve both AND and OR, be sure to parenthesise the sub-clauses and vary the indenting to show what pices oare sub-components of other pieces. And, when it gets this complex, think about breaking it up into multiple if-statements.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-10-13T22:35:24.657", "Id": "8071", "Score": "0", "body": "XLNT!! - I prefer the logicals at the end" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-11-04T16:41:11.417", "Id": "8802", "Score": "2", "body": "I prefer them at the start - easier to align for readability, and I can easily inspect the logicals without having to skim over the conditions." } ], "meta_data": { "CommentCount": "2", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-10-13T08:36:21.127", "Id": "5346", "ParentId": "5343", "Score": "6" } }, { "body": "<p>I would extract the validation into its own method:</p>\n\n<pre><code>if (RequestIsIncomplete(Request))\n{\n throw new ApplicationException(\"Incoming data is incomplete\");\n}\nelse\n{\n // Now trying to validate the format of incoming data\n}\n\nprivate bool RequestIsIncomplete(Request request)\n{\n if (request[\"First\"] == null)\n return false;\n\n if (request[\"second\"] == null)\n return false;\n\n // etc...\n\n return true;\n}\n</code></pre>\n\n<p>Seperating the decision making from the grunt work is a good win. As the grunt-work is seperated out, you're free to refactor it as necessary (honestly, don't leave it the way I've done it here - see Ants answer).</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-10-13T08:51:06.130", "Id": "5347", "ParentId": "5343", "Score": "27" } }, { "body": "<p>I don't know what language you're using (maybe C#?) but you should be referring to the fields posted form data as a collection rather than listing them individually. I think you should do this in an OOP approach using a Form object which contains field objects.</p>\n\n<p>This is a very crude example of what I mean. You could actually have a Field interface implemented by concrete field classes like int, text, file etc.</p>\n\n<pre><code>class Field {\n public bool isValid = true;\n public string errorMessage;\n public string value;\n public Field(string name, string label, string type, bool required) {\n\n }\n}\nclass Form {\n public List&lt;Field&gt; fields;\n public bool isValid = false;\n public void validate() {\n foreach(Field field in fields) {\n if(field.required &amp;&amp; field.value = \"\") {\n this.isValid = false;\n field.isValid = false;\n field.errorMessage = field.name+\" field is required\";\n }\n }\n }\n\n public void loadData(Array request) {\n //stuff the request data into the field objects\n foreach(KeyValuePair&lt;string, string&gt; kvp in request) {\n fields.Where(x =&gt; x.name = kvp.Key).first().value = kvp.value;\n }\n }\n}\n</code></pre>\n\n<p>On your post request you could do this</p>\n\n<pre><code>Form form = new Form();\n//name, type, required\nform.fields(new Field('field1','text',true);\n\n\nif(Page.IsPostBack) {\n form.loadData(Request);\n form.Validate();\n if(!form.isValid) {\n //print some errors or whatever\n throw new Exception(...);\n }\n}\n</code></pre>\n\n<p>Most web frameworks have Form and field classes, you could look at some framework APIs for ideas. You can also state exactly which field is left empty rather than just displaying a generic <code>one or more fields are blank</code> message. Even if this is only for a web service it can be helpful to state which of the 40 or so fields are not valid.</p>\n\n<p>Your other option is to define required fields in a collection and use a loop to check if each <code>Request[fieldName]</code> is null.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-10-13T09:11:09.467", "Id": "8068", "Score": "1", "body": "Yeah @Keyo. Good OOP approach. However, it really complicates the situation without any benefit at all. I prefer to work procedurally in UI, and work OO in business, data access, services, etc. +1 for a new point of view." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-10-13T09:22:40.967", "Id": "8069", "Score": "0", "body": "I don't agree that there is no benefit. You get to keep all the form handling code in one place. It can be refactored and extended with new methods and validation rules that will work everywhere. If you wanted you could have a render function for your form object. `I prefer to work procedurally in UI, and work OO in business...` Is form validation not business logic? It isn't UI code. I don't know what your context is, but in any project with more than a few forms doing it procedurally would get messy." } ], "meta_data": { "CommentCount": "2", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-10-13T09:01:58.083", "Id": "5348", "ParentId": "5343", "Score": "8" } }, { "body": "<p>You've received good answers for doing a simplistic check against all the fields. If this isn't the case, I'd suggest encapsulating the check. </p>\n\n<p>Create an object which is a <code>validHTTPrequest</code>. It has all forty of your fields and the values are set to be what you consider correct. Take your input values, and assign them to an new object, then do an equality check. If you've overloaded the equals operator for that object to check is var and see if they are the same, then you've solved the problem.</p>\n\n<p>Your statement then becomes:</p>\n\n<pre><code>if (currentRequest = validRequest)\n{\n //do stuff\n}\nelse\n{\n throw new ApplicationException(\"Incoming data is incomplete\");\n}\n</code></pre>\n\n<p>If the definition of a valid request ever changes, you just modify the vaildRequest object initialization.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-10-13T14:20:44.080", "Id": "5349", "ParentId": "5343", "Score": "2" } }, { "body": "<p>You could make it simpler using linq.</p>\n\n<pre><code>var requiredFiels = new [] { \"First\", \"Second\", ... };\nif (requiredFields.Any(x =&gt; Request[x] == null))\n throw new ApplicationException(...);\n</code></pre>\n\n<p>I think that I would take a different approach, though. I would probably have developed the application following a domain driven approach. That means I would already have classes in my system representing the business entities to which the data in the form belongs. I would then simply fill out the domain objects with the data posted in the form, and place the responsibility of validating the data in the domain object itself.</p>\n\n<p>However, neither of these techniques prevent you from form spoofing attack (which you said was the goal). To prevent this you should use an anti-forgery token.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-11-06T17:09:44.503", "Id": "5836", "ParentId": "5343", "Score": "3" } } ]
{ "AcceptedAnswerId": "5345", "CommentCount": "4", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-10-13T06:37:21.793", "Id": "5343", "Score": "23", "Tags": [ "c#" ], "Title": "How many conditions in an \"if clause\" is acceptable?" }
5343
<p>This is a sample program that I intend to post as part of a series of beginner level Java tutorials. Please provide any feedback on improvements that would make example more clear or illustrate/emphasize best practices. The example drawns a ball object to a panel on a mouse click and then moves it randomly with another mouse click.</p> <p>Class BouncingBall </p> <pre><code>import java.awt.BorderLayout; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import javax.swing.JButton; import javax.swing.JFrame; import javax.swing.JPanel; /* * this class will add a red ball to a canvas or play area, when a button is clicked and * then move about randomly when another button is clicked * * jmergenthaler 10/1/2011 */ public class BouncingBall { private JFrame frame = new JFrame(); private JPanel actionPanel = new JPanel(); private JPanel playarea = new JPanel(); private JButton btnNew = new JButton("Add Red Ball"); private JButton movebtn = new JButton("Move it"); //constructor BouncingBall(){ buildTheGUI(); } public void buildTheGUI(){ frame.setLayout( new BorderLayout()); btnNew.addActionListener( new ButtonClickHandler() ); movebtn.addActionListener( new MoveButtonClickHandler() ); actionPanel.add(btnNew); actionPanel.add(movebtn); frame.add(BorderLayout.NORTH,actionPanel); frame.add(BorderLayout.SOUTH,playarea); frame.setSize(500, 500); frame.setVisible(true); } public static void main(String args[]){ new BouncingBall(); } class ButtonClickHandler implements ActionListener{ public void actionPerformed(ActionEvent e){ //create initial Ball object add to the frame frame.add(new Ball() ); //draw frame.validate(); } } class MoveButtonClickHandler implements ActionListener{ public void actionPerformed(ActionEvent e){ //polymorphic behavior, calling the Ball constructor differently frame.add(new Ball(1) ); //redraw frame.validate(); } }// end class MoveButtonClickHandler }//end class BouncingBall </code></pre> <p>class 2 - the Ball class</p> <pre><code>import java.awt.Color; import java.awt.Graphics; import java.util.Random; import javax.swing.JPanel; class Ball extends JPanel{ //private instance variables avail. only avail to methods in this class private int x,y,w,h; //constructor Ball(){ this.x = 200; this.y = 200; this.w = 100; this.h = 100; } //constructor with different behavior Ball(int a){ Random rand = new Random(); this.w = 100; this.h = 100; this.x = rand.nextInt(300); this.y = rand.nextInt(300); } //draw the ball //@override public void paintComponent(Graphics g){ super.paintComponent(g); g.setColor(Color.RED); g.fillOval(x, y, h, w); } }//end class Ball </code></pre>
[]
[ { "body": "<ul>\n<li>Swing GUIs should be built inside the EDT, e.g. using <code>SwingWorker.invokeLater()</code>. See <a href=\"http://leepoint.net/JavaBasics/gui/gui-commentary/guicom-main-thread.html\" rel=\"nofollow\">http://leepoint.net/JavaBasics/gui/gui-commentary/guicom-main-thread.html</a> for details.</li>\n<li>I think calling a <code>JPanel</code> descendant \"Ball\" is just confusing. If you <em>really</em> want that a panel can handle only <em>one</em> Ball, call it <code>BallPanel</code> or so. But it would be more flexible if you had a <code>DrawPanel</code>, which accepts a number of objects to draw, and the objects themself. That makes it much easier to extend the system later:</li>\n</ul>\n\n<p>.</p>\n\n<pre><code>public class DrawPanel {\n private List&lt;Drawable&gt; drawables = new ArrayList&lt;Drawable&gt;();\n ...\n public void addDrawable(Drawable d) { drawables.add(d); }\n\n public void paintComponent(Graphics g){\n super.paintComponent(g);\n for(Drawable d : drawables) {\n d.draw(g, getWidth(), getHeight()); \n } \n }\n ...\n //for animation a timer task, calling Drawable.update\n}\n\ninterface Drawable {\n public void draw(Graphics g, int width, int height);\n\n //when you need animation \n public void update(long ms); \n}\n\npublic class Ball implements Drawable {\n ...\n}\n</code></pre>\n\n<p>This is only <em>one</em> possibility to split view and model, the \"right\" way depends on your needs. But keeping both model and view in one class is a receipt for trouble.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-10-18T17:19:51.233", "Id": "8228", "Score": "0", "body": "help me with this, im an old procedural programmer..." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-10-18T17:35:04.253", "Id": "8229", "Score": "0", "body": "Class DrawPanel would be the \"view\", Class Ball and Interface Drawable would be the \"model\"? I am trying to implement the feedback provided, but i am struggling with parts of it" } ], "meta_data": { "CommentCount": "2", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-10-15T15:23:47.480", "Id": "5389", "ParentId": "5350", "Score": "3" } }, { "body": "<p>@Landei - this is what i have now. I am trying to understand and implement your ideas...</p>\n\n<pre><code>import java.awt.Graphics;\n\npublic interface Drawable {\n\n //this is an interface method - no body\n public void draw(Graphics g, int w, int h); \n\n public void update(long ms);\n\n}\n</code></pre>\n\n<p>Next class</p>\n\n<pre><code>import java.awt.Color;\nimport java.awt.Graphics;\nimport java.util.Random;\n\nclass Ball implements Drawable{\n\n//private instance variables avail. only avail to methods in this class\nprivate int x,y,w,h;\n\n//constructor\nBall(){\n this.x = 200;\n this.y = 200;\n this.w = 100;\n this.h = 100;\n} \n\n//constructor with different behavior\nBall(int a){\n Random rand = new Random();\n\n this.w = 100;\n this.h = 100;\n this.x = rand.nextInt(300);\n this.y = rand.nextInt(300);\n}\n\n\n@Override\npublic void draw(Graphics g, int w, int h) {\n //super.paintComponent(g);\n g.setColor(Color.red);\n g.fillOval(x, y, w, h); \n}\n\n@Override\npublic void update(long ms) {\n // TODO Auto-generated method stub\n\n}\n\n}//end class Ball\n</code></pre>\n\n<p>3rd class</p>\n\n<pre><code>import java.awt.BorderLayout;\nimport java.awt.event.ActionEvent;\nimport java.awt.event.ActionListener;\nimport java.util.ArrayList;\nimport javax.swing.JButton;\nimport javax.swing.JFrame;\nimport javax.swing.JPanel;\nimport javax.swing.SwingUtilities;\n\n\npublic class DrawPanel {\n\nprivate ArrayList drawable = new ArrayList&lt;Drawable&gt;();\nprivate JFrame frame = new JFrame();\nprivate JPanel actionPanel = new JPanel();\nprivate JPanel playarea = new JPanel();\nprivate JButton btnNew = new JButton(\"Add Red Ball\");\nprivate JButton movebtn = new JButton(\"Move it\");\n\n//constructor\nDrawPanel(){\n buildTheGUI(); \n}\n\npublic void addDrawable(Drawable d){\n drawable.add(d);\n}\n\npublic void buildTheGUI(){\n frame.setLayout( new BorderLayout());\n btnNew.addActionListener( new ButtonClickHandler() );\n movebtn.addActionListener( new MoveButtonClickHandler() );\n actionPanel.add(btnNew);\n actionPanel.add(movebtn);\n frame.add(BorderLayout.NORTH,actionPanel);\n frame.add(BorderLayout.SOUTH,playarea);\n frame.setSize(500, 500);\n frame.setVisible(true); \n}\n\npublic static void main(String args[]){\n //launch GUI on the EDT (event dispatch thread) - per best practice\n SwingUtilities.invokeLater(new Runnable(){\n public void run(){\n new DrawPanel();\n }\n }\n);\n\n}\n\nclass ButtonClickHandler implements ActionListener{\n public void actionPerformed(ActionEvent e){ \n\n //create initial Ball object add to the frame\n addDrawable( new Ball() ) ;\n //draw\n frame.validate();\n }\n}\n\nclass MoveButtonClickHandler implements ActionListener{\n public void actionPerformed(ActionEvent e){\n\n //polymorhic behavior, calling the Ball constructor differently\n addDrawable( new Ball(1) ) ;\n //redraw\n frame.validate();\n }\n}// end class MoveButtonClickHandler\n}//end class DrawPanel\n</code></pre>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-10-18T17:51:40.570", "Id": "5454", "ParentId": "5350", "Score": "0" } } ]
{ "AcceptedAnswerId": "5389", "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-10-13T18:42:03.440", "Id": "5350", "Score": "2", "Tags": [ "java", "swing" ], "Title": "Bouncing ball - for swing event handling tutorial" }
5350
<p>Suppose we have an enum called "Planet" and it has a custom attribute of class "PlanetAttr", these methods will give you the attribute value for a given Planet value:</p> <pre><code>private static PlanetAttr GetAttr(Planet p) { return (PlanetAttr)Attribute.GetCustomAttribute(ForValue(p), typeof(PlanetAttr)); } private static MemberInfo ForValue(Planet p) { return typeof(Planet).GetField(Enum.GetName(typeof(Planet), p)); } </code></pre> <p>But is this a good way to retrieve the value of a custom attribute from an enum? I am uncomfortable with the number of method calls involved. Is there a more efficient way, e.g. can it be done without looking up the enum constant's name?</p> <p>This code is from <a href="https://stackoverflow.com/questions/469287/c-vs-java-enum-for-those-new-to-c/4778347#4778347">a StackOverflow question</a>.</p> <pre><code>using System; using System.Reflection; class PlanetAttr: Attribute { internal PlanetAttr(double mass, double radius) { this.Mass = mass; this.Radius = radius; } public double Mass { get; private set; } public double Radius { get; private set; } } public static class Planets { public static double GetSurfaceGravity(this Planet p) { PlanetAttr attr = GetAttr(p); return G * attr.Mass / (attr.Radius * attr.Radius); } public static double GetSurfaceWeight(this Planet p, double otherMass) { return otherMass * p.GetSurfaceGravity(); } public const double G = 6.67300E-11; private static PlanetAttr GetAttr(Planet p) { return (PlanetAttr)Attribute.GetCustomAttribute(ForValue(p), typeof(PlanetAttr)); } private static MemberInfo ForValue(Planet p) { return typeof(Planet).GetField(Enum.GetName(typeof(Planet), p)); } } public enum Planet { [PlanetAttr(3.303e+23, 2.4397e6)] MERCURY, [PlanetAttr(4.869e+24, 6.0518e6)] VENUS, [PlanetAttr(5.976e+24, 6.37814e6)] EARTH, [PlanetAttr(6.421e+23, 3.3972e6)] MARS, [PlanetAttr(1.9e+27, 7.1492e7)] JUPITER, [PlanetAttr(5.688e+26, 6.0268e7)] SATURN, [PlanetAttr(8.686e+25, 2.5559e7)] URANUS, [PlanetAttr(1.024e+26, 2.4746e7)] NEPTUNE, [PlanetAttr(1.27e+22, 1.137e6)] PLUTO } </code></pre>
[ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-10-14T09:07:41.450", "Id": "8078", "Score": "4", "body": "I'm curious as to why you decided to use meta annotations to represent this data? Seems like an odd choice - attributes are designed to store meta data (data about data), but in this case you're storing properties of an entity - which is what object-orientated programming is all about! The fact that these extra properties are required means that an enum is not the appropriate data type to be using.." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-10-14T09:19:06.400", "Id": "8080", "Score": "1", "body": "@MattDavey fair enough, its a contrived example and a dictionary or array would probably be a better way to link the enum to the object. The enum is still appropriate though - it represents the *name* of the planet, not the properties of the planet (which are in a separate class.)" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-10-21T17:22:50.150", "Id": "8356", "Score": "1", "body": "@MattDavey: 'meta' is a matter of perspective. One man's data can be another's metadata, and vice versa. You may consider database table definitions to be metadata for an LOB application, but it's data for an ORM designer. I draw the line in a pretty simple way - I consider any data written in the source code to be metadata (excluding sample data). The planets enum is not a shining example for the use of metadata, but continuing with that – in a program that manages servers by naming them after planets, any additional information about the actual astronomical bodies is metadata." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-10-21T17:25:57.727", "Id": "8357", "Score": "1", "body": "@finnw: A dictionary would indeed be an appropriate run-time container for the metadata, but not a compile-time container. The dictionary can be constructed and populated from the metadata contained within the attributes either when the program starts up or when needed (lazy-loaded)." } ]
[ { "body": "<p>Make it general purpose using generics.</p>\n\n<p>Though I'd strongly suggest you rename your attribute to follow .NET guidelines. It should always be in the form <code><i>AttributeName</i>Attribute</code>. Enum values should be in CamelCase. And it is common to name classes containing extension methods to be named the same as the class it is extending followed by <code>Extensions</code>.</p>\n\n<p>Otherwise, that's pretty much how you'd get custom attributes of a field.</p>\n\n<pre><code>public static class EnumExtensions\n{\n public static TAttribute GetAttribute&lt;TAttribute&gt;(this Enum value)\n where TAttribute : Attribute\n {\n var type = value.GetType();\n var name = Enum.GetName(type, value);\n return type.GetField(name) // I prefer to get attributes this way\n .GetCustomAttributes(false)\n .OfType&lt;TAttribute&gt;()\n .SingleOrDefault();\n }\n}\n\npublic class PlanetInfoAttribute : Attribute\n{\n internal PlanetInfoAttribute(double mass, double radius)\n {\n this.Mass = mass;\n this.Radius = radius;\n }\n public double Mass { get; private set; }\n public double Radius { get; private set; }\n}\n\n\npublic enum Planet\n{\n [PlanetInfo(3.303e+23, 2.43970e6)] Mecury,\n [PlanetInfo(4.869e+24, 6.05180e6)] Venus,\n [PlanetInfo(5.976e+24, 6.37814e6)] Earth,\n [PlanetInfo(6.421e+23, 3.39720e6)] Mars,\n [PlanetInfo(1.900e+27, 7.14920e7)] Jupiter,\n [PlanetInfo(5.688e+26, 6.02680e7)] Saturn,\n [PlanetInfo(8.686e+25, 2.55590e7)] Uranus,\n [PlanetInfo(1.024e+26, 2.47460e7)] Neptune,\n [PlanetInfo(1.270e+22, 1.13700e6)] Pluto,\n}\n\npublic static class PlanetExtensions\n{\n public static double GetSurfaceGravity(this Planet p)\n {\n var attr = p.GetAttribute&lt;PlanetInfoAttribute&gt;();\n return G * attr.Mass / (attr.Radius * attr.Radius);\n }\n\n public static double GetSurfaceWeight(this Planet p, double otherMass)\n {\n return otherMass * p.GetSurfaceGravity();\n }\n\n public const double G = 6.67300E-11;\n}\n</code></pre>\n\n<hr>\n\n<p>It should be pointed out that there are methods to retrieve custom attributes in the framework now as of .Net 4.5. See the <a href=\"https://msdn.microsoft.com/en-us/library/system.reflection.customattributeextensions(v=vs.110).aspx\" rel=\"noreferrer\">CustomAttributeExtensions</a> class. This should simplify the extension method a bit. It might be worth changing the name of the extension to <code>GetCustomAttribute()</code> as well since it will always be a custom attribute.</p>\n\n<pre><code>public static class EnumExtensions\n{\n public static TAttribute GetAttribute&lt;TAttribute&gt;(this Enum value)\n where TAttribute : Attribute\n {\n var type = value.GetType();\n var name = Enum.GetName(type, value);\n return type.GetField(name) // I prefer to get attributes this way\n .GetCustomAttribute&lt;TAttribute&gt;();\n }\n}\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2016-08-18T11:53:44.537", "Id": "260028", "Score": "4", "body": "Dude, this is totally awesome! I just created an account only to upvote this. I've rewritten that for me so it works with enums. So I can associate enum-values to enums. Pure awesomeness, seriously! :D" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-01-09T12:57:05.897", "Id": "408350", "Score": "1", "body": "can you write your rewritten code please" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-02-23T01:24:27.320", "Id": "466333", "Score": "0", "body": "Similarly, just join to community to vote you up" } ], "meta_data": { "CommentCount": "3", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-10-13T23:27:21.710", "Id": "5354", "ParentId": "5352", "Score": "73" } } ]
{ "AcceptedAnswerId": "5354", "CommentCount": "4", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-10-13T21:04:10.347", "Id": "5352", "Score": "54", "Tags": [ "c#", "enum", "extension-methods" ], "Title": "Getting the value of a custom attribute from an enum" }
5352
<p>I am using 2 nested SortedDictionaries to construct sparse matrix </p> <p>Here is the custom simularity(sim) function I wrote . Now it has O(n^2) complexity. I looking for suggestions to improve robustness and efficiency.Thanks for any help.</p> <pre><code> double a = 0, b = 0, sqrta = 0, sqrtb = 0, sim = 0; foreach (var word_i in dict) { foreach (var word_j in dict) { if (word_i.Key == word_j.Key) continue; sim=a=b=sqrta=sqrtb=0; foreach (var term in word_j.Value.Keys) { if (word_i.Value.ContainsKey(term)) { word_i.Value.TryGetValue(term,out a); word_j.Value.TryGetValue(term,out b); sim += a * b; sqrta += Math.Pow(a,2); sqrtb += Math.Pow(b,2); } } sim /= Math.Sqrt(sqrta) * Math.Sqrt(sqrtb); } } </code></pre>
[ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-10-14T08:56:19.577", "Id": "8077", "Score": "0", "body": "`sim` is set to 0 in every iteration of the middle loop; isn't `sim` supposed to be the output value?" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-10-14T09:28:51.427", "Id": "8081", "Score": "0", "body": "Can you post the declaration of `dict`? Seeing the type will make it easier to follow. I am guessing its a `Dictionary<string, Dictionary<string, double>>`? Also what are the keys of the inner dictionary? And are most of them common to all words or present on only a few words each?" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-10-14T15:11:20.590", "Id": "8088", "Score": "0", "body": "@S.L.Barth yes,it is. but it take too much time to find all cosines between every posible pair of 500k strings and their definitions." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-10-14T15:12:04.380", "Id": "8089", "Score": "0", "body": "@finnw SortedDictionary<string, SortedDictionary<string, double>> dict = new SortedDictionary<string, SortedDictionary<string, double>>();" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-10-14T16:56:38.983", "Id": "8090", "Score": "0", "body": "@finnw sparse matrix is used to construct term-document matrix[link](http://en.wikipedia.org/wiki/Document-term_matrix) ,where words ( as documents) are used as keys for outer SortedDictionary and unique terms in word definitions(as terms).unique terms are keys for inner SortedDictionary" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-10-21T15:06:28.010", "Id": "8348", "Score": "0", "body": "Could you please, provide some small set of sample data?" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-10-21T23:05:17.507", "Id": "8373", "Score": "0", "body": "Why are you using `TryGetValue` after asserting that the key does in fact exist in `word_i.Value`? I don't think it's a performance issue as it is not going to be throwing exceptions, but still... unnecessary. Also, if you can guarantee that the dictionaries will always contain the keys you are looking for you cut down your lookups by 1/3." } ]
[ { "body": "<p>As you are doing calculations on all values where the result depends on both loops, there isn't much that can be done about the complexity, at least not without knowing what you do with the result (which seems to be just discarded in the code shown).</p>\n\n<p>There are some things that you can do in the innermost loop:</p>\n\n<p>Instead of first using <code>Contains</code> and then get the value, you can use <code>TryGetValue</code> directly.</p>\n\n<p>You know that <code>term</code> exists in the other collection, so you don't need <code>TryGetValue</code> for that one.</p>\n\n<p>Squaring is done a lot faster by just multiplying instead of using <code>Math.Pow</code>.</p>\n\n<pre><code>if (word_i.Value.TryGetValue(term,out a)) {\n b = word_j.Value[term];\n sim += a * b;\n sqrta += a * a; \n sqrtb += b * b;\n}\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-10-14T15:02:51.570", "Id": "8086", "Score": "0", "body": "Thank you for your comment. Sim is used to find k nearest neigbors. maybe i can reduce amount of calculations because of sim(word_i,word_j)=sim(word_j,word_i). how can i modify this algorithm from sequential to run in parallel?" } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-10-14T11:16:24.430", "Id": "5359", "ParentId": "5357", "Score": "2" } }, { "body": "<p>You can try this</p>\n\n<pre><code>public class Term\n{\n public string Value { get; set; }\n public Dictionary&lt;string, double&gt; Definitions { get; set; }\n\n public Term(string value, Dictionary&lt;string, double&gt; definitions)\n {\n this.Value = value;\n this.Definitions = definitions;\n }\n}\n\npublic class TermPair\n{\n public Term Left { get; private set; }\n public Term Right { get; private set; }\n public double Similarity { get; private set; }\n\n public TermPair(Term left, Term right)\n {\n this.Left = left;\n this.Right = right;\n }\n\n public void CalculateSimilarity()\n {\n var sim = 0D;\n var sqrta = 0D;\n var sqrtb = 0D;\n\n var leftDefinitions = this.Left.Definitions;\n var rightDefinitions = this.Right.Definitions;\n\n foreach (var kv in leftDefinitions)\n {\n double a;\n var term = kv.Key;\n if (rightDefinitions.TryGetValue(term, out a))\n {\n var b = kv.Value;\n sim += a * b;\n sqrta += a * a;\n sqrtb += b * b;\n }\n }\n\n sim /= Math.Sqrt(sqrta) * Math.Sqrt(sqrtb);\n\n this.Similarity = sim;\n }\n}\n</code></pre>\n\n<p>Use these classes like this:</p>\n\n<pre><code>List&lt;Term&gt; terms = ...\n\nvar idx = 0;\nvar totalTerms = terms.Count;\nvar pairs = new TermPair[((totalTerms - 1) * (totalTerms)) / 2];\nfor (var i = 0; i &lt; totalTerms; i++)\n{\n for (var j = 0; j &lt; totalTerms; j++)\n {\n if (i &gt; j)\n {\n pairs[idx++] = new TermPair(terms[i], terms[j]);\n }\n }\n}\n\nforeach (var pair in pairs.AsParallel())\n{\n pair.CalculateSimilarity();\n}\n</code></pre>\n\n<p>I don't know your scenario but I hope this help. You can experiment with SortedDictionary &amp; Dictionary. BTW I'm not quite sure if TryGetValue is thread safe for reading from multiple threads.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-10-21T16:21:32.150", "Id": "5505", "ParentId": "5357", "Score": "1" } } ]
{ "AcceptedAnswerId": "5359", "CommentCount": "7", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-10-14T08:06:48.277", "Id": "5357", "Score": "4", "Tags": [ "c#", "performance" ], "Title": "Cosine simularity perfomance c#" }
5357
<p>Is there anything you would change about the following function? I welcome any feedback on style, correctness, etc. Thank you for reading.</p> <p>Some of my questions are:</p> <ol> <li>Obviously, I catch the exception and convert it to a return value because I don't want to take down the application in case of an error. Would it be better to allow the exception to propagate up and handle it there (in the function that is coordinating the creation of the set of import files)?</li> <li><p>Is there another, "better-in-general" way of writing to files?</p> <pre><code>private static bool CreateImportFile(string path, string content) { try { using (var fileStreamWriter = File.CreateText(path)) { fileStreamWriter.Write(content); fileStreamWriter.Close(); } } catch (IOException e) { Console.WriteLine("Failed to write import file due to IOException. " + e.Message); return false; } return true; } </code></pre></li> </ol>
[ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-10-14T23:10:47.213", "Id": "8107", "Score": "0", "body": "It's just about as idiomatic as it can be, just leave out the `Close()` call, it will be handled by the `using` block." } ]
[ { "body": "<p>I think this is more idiomatic but I think this style does not really add much benefit over calling <code>File.WriteAllText</code> directly. Consider what your client code will need to do to handle a single <code>bool</code> result with no other information as to why it failed.</p>\n\n<pre><code>private static bool CreateImportFile(string path, string content)\n{\n try\n {\n File.WriteAllText(path, content);\n }\n catch (IOException e)\n {\n Console.WriteLine(\"Failed to write import file due to IOException. \" + e.Message);\n return false;\n }\n\n return true;\n}\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-10-14T18:59:14.767", "Id": "8093", "Score": "0", "body": "Thanks for the feedback. Obviously my .NET knowledge is still pretty weak-- looks like my function is superfluous as WriteAllText is basically exactly what I need." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-02-25T21:23:46.423", "Id": "14836", "Score": "0", "body": "This is pretty good. I would write to stderr instead." } ], "meta_data": { "CommentCount": "2", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-10-14T18:15:49.813", "Id": "5365", "ParentId": "5361", "Score": "3" } } ]
{ "AcceptedAnswerId": "5365", "CommentCount": "1", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-10-14T17:41:27.860", "Id": "5361", "Score": "3", "Tags": [ "c#" ], "Title": "More idiomatic way to handle simple file writing in C#?" }
5361
<p>My implementation:</p> <pre><code>Array.prototype.binarySearchFast = function(search) { var size = this.length, high = size -1, low = 0; while (high &gt; low) { if (this[low] === search) return low; else if (this[high] === search) return high; target = (((search - this[low]) / (this[high] - this[low])) * (high - low)) &gt;&gt;&gt; 0; if (this[target] === search) return target; else if (search &gt; this[target]) low = target + 1, high--; else high = target - 1, low++; } return -1; }; </code></pre> <p>Normal Implementation:</p> <pre><code>Array.prototype.binarySearch = function(find) { var low = 0, high = this.length - 1, i, comparison; while (low &lt;= high) { i = Math.floor((low + high) / 2); if (this[i] &lt; find) { low = i + 1; continue; }; if (this[i] &gt; find) { high = i - 1; continue; }; return i; } return null; }; </code></pre> <p>The difference being my implementation makes a guess at the index of the value based on the values at the start and end positions instead of just going straight to the middle value each time.</p> <p>I wondered if anyone could think of any case scenarios where this would be slower than the original implementation.</p> <p>UPDATE: Sorry for the bad examples. I have now made them a little easier to understand and have setup some tests on jsPerf. See here:</p> <p><a href="http://jsperf.com/binary-search-2" rel="nofollow">http://jsperf.com/binary-search-2</a></p> <p>I'm seeing about 75% improvement by using my method.</p>
[ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-10-14T21:49:04.247", "Id": "8106", "Score": "0", "body": "I'm sorry, but information theory dooms your attempt. The only way to speed up the binary search is by making assumptions about the kind of data you are storing." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-10-19T23:25:49.893", "Id": "28273", "Score": "2", "body": "I believe what you're doing is called an interpolation search. http://en.wikipedia.org/wiki/Interpolation_search" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-02-05T17:25:17.793", "Id": "62802", "Score": "0", "body": "You'll get a performance boost by changing: Math.floor((low + high) / 2) to: (low + high) >> 1" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-02-05T18:08:10.090", "Id": "62803", "Score": "0", "body": "Maybe so, but the (very) minor performance gain you may get from this almost certainly isn't worth the reduced readability." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-02-08T12:11:02.527", "Id": "62804", "Score": "1", "body": "That's always the question, isn't it... Nevertheless, perhaps the goal for a binary search is always maximum speed?" } ]
[ { "body": "<p>Updated: based on your description, it's easy to derive a scenario where your algorithm turns into a linear search rather than a binary one. Just set up one equation per step that it would take and solve them simultaneously.</p>\n\n<p>Your code is still buggy, by the way. If you search for a value smaller than all existing values then you'll get <code>target</code> set to a negative index. In general, there's no guarantee that <code>target</code> will be between <code>low</code> and <code>high</code>, and if it isn't bad things happen (like the space you're searching getting larger. With a bit of effort it might be possible to design a case where your current version loops forever).</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-10-14T19:48:04.160", "Id": "8098", "Score": "0", "body": "Sorry for the mistakes in the code - I was in a rush and didn't expect such a quick reply. I have now fixed the examples and uploaded a benchmark - let me know what you think of the results." } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-10-14T18:52:08.253", "Id": "5367", "ParentId": "5363", "Score": "0" } }, { "body": "<p>I thought that I should test them, but then I notices that neither implementation takes a parameter so they don't know what to look for...</p>\n\n<p>Anyway, the \"fast\" implementation would be slower whenever you don't have an even distribution in the array. For example looking for <code>5</code> in <code>[1,2,3,4,5,6,7,10000]</code> would make something like four iterations instead of one.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-10-14T19:47:25.347", "Id": "8097", "Score": "0", "body": "I've now fixed the algorithm to try and avoid that being an issue." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-10-14T20:57:35.243", "Id": "8101", "Score": "0", "body": "@OliverMorgan: Just adding another value to the test array makes the \"fast\" search as slow as indexOf: http://jsperf.com/binary-search-2/2" } ], "meta_data": { "CommentCount": "2", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-10-14T18:59:14.177", "Id": "5368", "ParentId": "5363", "Score": "5" } }, { "body": "<p>The Normal implementation is shorter and easier to follow.</p>\n\n<p>To convert the Normal to your \"guess\" version, it is only necessary to change one line - the line where <code>i</code> is assigned to the midpoint. The rest of your changes try to short-circuit the search when one of your variables lands directly on the index of the item you're searching for, and in my opinion these extra checks will slow it down more often than they'd speed it up.</p>\n\n<p>By trying to guess at the optimal partition, you're doing a trade-off which will give better best-case performance but worse worst-case performance. You'd need to test this with a wide range of input to see if it really helps.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-10-14T21:20:32.797", "Id": "5374", "ParentId": "5363", "Score": "1" } }, { "body": "<p>My advice is to not mess about with something that's been well and truly tested :-)</p>\n\n<p>No, not really: if you find an algorithm that's better then, by all means, use it. However, in this case, for <em>general</em> data, this isn't going to be an improvement.</p>\n\n<p>The power of binary search, and other <code>O(log N)</code> type algorithms, lies in the fact that you dispose of half the remaining search space with each iteration. In other words, if the initial search space (array size) was 1000, the first iteration removes 500 of them.</p>\n\n<p>Any change to the \"midpoint\" (the divider between what you're keeping in the search space and what you're disposing of) that you select during an iteration has the <em>potential</em> to improve or degrade the performance. For example, putting the midpoint at 25% has the potential to reduce the search space even faster (if you're right) or slower (if you're wrong).</p>\n\n<p>Now, if you know of some <em>property</em> of the data, you can use that to your advantage to improve an algorithm. In fact, it's the \"extra\" knowledge about your list (the fact that it's sorted) that allows you to optimise what would normally be a sequential search into a binary one.</p>\n\n<p>So it all comes down to how good your extra information is. In this case, the values of the two end nodes alone are not really indicative of where the midpoint should be. You only have to look at the list:</p>\n\n<pre><code>[ 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 500, 1000]\n</code></pre>\n\n<p>to see this in action.</p>\n\n<p>If you were looking for <code>500</code> in that list, you might decide that, based on the first and last elements being <code>1</code> and <code>1000</code>, it would be in the middle somewhere, which is clearly not the case.</p>\n\n<p>Similarly, if you were looking for <code>14</code>, you might first check elements around the 1.4% mark (14/1000) which would probably be the first element, despite the fact it's right up at the other end.</p>\n\n<p>Of course, that's not to say that <em>other</em> extra information would not help. If you knew that the data was fairly evenly distributed over the range, then your improvement may be worth it.</p>\n\n<p>You also need to be aware that it's usually only going to be important with <em>large</em> data inputs, so it may not necessarily be worth it even if it turns out to be much better. Even bubble sort is blindingly fast for 100 elements :-)</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-10-14T23:44:55.157", "Id": "5375", "ParentId": "5363", "Score": "16" } }, { "body": "<p>If you want to speed up a binary search, \"unroll\" the loop. For 1,000 items you are looping 10 times. 10 discreet pieces of code remove the \"looping overhead\". If you have a specific search rather than a general, you can replace all range calculations with literal values (otherwise replacing them with a variable).</p>\n\n<pre><code>Set the mid-point \"low\"\n\nif key less than value at ( mid-point + largest-mid-point )\n add largest-mid-point to mid-point\nif key less than value at ( mid-point + 2nd-largest-mid-point )\n add 2nd-largest-mid-point to mid-point\nif key less than value at ( mid-point + 3rd-largest-mid-point )\n add 3rd-largest-mid-point to mid-point\netc\n</code></pre>\n\n<p>Developed 31 years ago with Cobol, discovered later in Jon Bentley's Programming Pearls book (and is probably the answer to Exercise 24 in Knuth's Sorting and Searching on binary searches).</p>\n\n<p>Still works, in Cobol, today :-)</p>\n\n<p>Due to the \"powers of two\" it works with even very large tables without vast amounts of extra code.</p>\n\n<p>EDIT: I always used a \"binary\" number of entries in my tables for searching. Bentley shows 1000 entries, \"tying\" the mid-point amendments to the right boundary so as not to go \"outside\" the table. This gives an \"overlap\" using binary mid-points, but implications of that vs actual midpoints I haven't had a chance to look at.</p>\n\n<p>I can get substantial improvements over the \"standard\" with this, as Bentley suggests we should expect. I also used a couple of other \"tweaks\" but these are perhaps related too closely to Cobol.</p>\n\n<p>EDIT: Since \"unwinding\" is no use to a modern language, and bearing in mind I don't know how \"expensive\" these may be for you, or whether they apply to JavaScript and tiny instruction caches, but:</p>\n\n<pre><code>if (this[target] === search) return target;\nelse if (search &gt; this[target]) low = target + 1, high--;\nelse high = target - 1, low++;\n</code></pre>\n\n<ol>\n<li><p>You test for equality first. Equality is the least likely outcome, so this should be re-ordered (you changed the order from your \"normal\" implementation).</p></li>\n<li><p>\"low = target\" I assume would be faster \"than low = target + 1\", similar for the minus. \"high--\" is slower than leaving \"high\" alone altogether, similar for the \"high++\". You rely on the \"crossover\" these cause to terminate the search with failure. If you work out another, simpler, way to terminate the search, you might save a few instructions from the precious cache.</p>\n\n<pre><code>(((search - this[low]) / (this[high] - this[low])) * (high - low))\n</code></pre></li>\n<li><p>\\$\\frac{a - b}{c - b} = \\frac{a}{c} - b\\$</p></li>\n<li><p>Doing two tests for equality on the extremes of the range gives you what? You get more inequality than equality in a binary search, so rather than speeding up, this slows down (subject to cache considerations, maybe).</p></li>\n<li><p>If you let the loop terminate \"naturally\" (meaning you find out how, as mentioned above) you can remove the remaining test for equality from within the loop.</p></li>\n</ol>\n\n<p>Obviously with such a language and cache limitations none of the above may work.</p>\n\n<p>OK, there's a good deal of irony here. These are some things you may investigate to see where they may lead you. They may all be useless to you, but you never know until you try. Or do you? There's that irony again.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-01-28T17:27:19.047", "Id": "33690", "Score": "0", "body": "I would be careful with loop unrolling optimizations like this one, because they can actually have worse performance, especially in a higher-level language like JavaScript. Especially when you consider that more code means that cache misses happen more often (“ancient” Cobol programmers didn't have to worry about caches, I belive)." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-01-28T19:15:51.597", "Id": "33703", "Score": "0", "body": "Wow! Used to be you had to be careful with code size... seems not much progress... I suppose your code is longer than my 698 bytes, for a table with 262144 entries :-) Are you telling me you code to keep as much as possible in \"cache\" and then your programs run like dogs if you're not successful? Very strange. Interesting to know. Usually there will be much more code in our programs than the binary search. Perhaps it still fits in \"our\" caches anyway?" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-01-28T19:23:48.443", "Id": "33705", "Score": "0", "body": "That's not what I'm saying at all. Yes, usually there will be much more code in your program, so the performance of binary search won't matter much (because it's already very fast). I'm just saying you shouldn't be that eager with Cobol-era optimizations (especially if they make your code less maintainable), because it's quite possible they will actually make your code slower." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-01-28T19:45:27.760", "Id": "33709", "Score": "0", "body": "Well, I was just tossing it in the mix. If it's no good for JavaScript, that's OK with me. On \"maintainable\" you have to remember 1) it will not need maintenance (famous last words) and 2) with good naming, comments and documentation, it can be made very clear what is going on. Which bits do you leave out (perhaps you use very short names to ensure the \"language processor\" can make use of the cache?) to make you think it can't be maintained? As I said, it works today, so not sure what the \"Cobol-era\" might mean." } ], "meta_data": { "CommentCount": "4", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-01-28T14:41:34.957", "Id": "20988", "ParentId": "5363", "Score": "2" } }, { "body": "<p>Did you try to execute the algorithm with an array that has only 1 element (e.g. <code>A=[1]</code>)? If you search for the value 1, it'll give <code>false</code>, or in this case <code>-1</code>, because <code>low == high</code> and the loop body is never entered despite the value 1 being part of the array. It might be faster, but will fail to deliver the right answer for at least one case.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-12-03T14:06:31.253", "Id": "36576", "ParentId": "5363", "Score": "0" } }, { "body": "<p>Check this out\n<a href=\"http://en.wikipedia.org/wiki/Interpolation_search\">http://en.wikipedia.org/wiki/Interpolation_search</a></p>\n\n<p>Particularly the paragraph that states:</p>\n\n<p>Each iteration of the above code requires between five and six comparisons (the extra is due to the repetitions needed to distinguish the three states of &lt; > and = via binary comparisons in the absence of a three-way comparison) plus some messy arithmetic, while the binary search algorithm can be written with one comparison per iteration and uses only trivial integer arithmetic. It would thereby search an array of a million elements with no more than twenty comparisons (involving accesses to slow memory where the array elements are stored); \n<strong>* to beat that the interpolation search as written above would be allowed no more than three iterations. *</strong></p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-02-13T13:39:17.547", "Id": "41553", "ParentId": "5363", "Score": "6" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "5", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-10-14T18:05:34.410", "Id": "5363", "Score": "5", "Tags": [ "javascript", "algorithm", "search", "binary-search" ], "Title": "Efficient Binary Search" }
5363
<p>There are a several articles about true data access in MVC. I tried to make the best one according to the architecture flexibility. My way is following:</p> <ol> <li>ADO .NET Entity Data Model (*.edmx from Entity Framework) with default code generation.</li> <li><p>Common repository interface</p> <pre><code> public interface IGenericRepository&lt;T&gt; where T : class { T Get(int id); void Create(T entityToCreate); void Edit(T entityToEdit); void Delete(T entityToDelete); } </code></pre></li> <li><p>Interface (with particular methods of the current class), class with real implementation of methods. For example</p> <pre><code>public interface ITestingRepository: IGenericRepository&lt;Testing&gt; { List&lt;dynamic&gt; GetTestingUser(int id); List&lt;dynamic&gt; GetNotTestingUser(int idTesting, Guid idCompany); List&lt;Testing&gt; List(Guid CompanyId); } public class TestingRepository : ITestingRepository { private TestEverybody _entities = new TestEverybody(); public List&lt;Testing&gt; List(Guid CompanyId) { return _entities.Testing.Where(t =&gt; t.idCompany == CompanyId).ToList(); } public void Edit(Testing productToEdit) { var originalProduct = Get(productToEdit.id); _entities.ApplyCurrentValues(originalProduct.EntityKey.EntitySetName, productToEdit); _entities.SaveChanges(); } public void Create(Testing productToCreate) { _entities.Testing.AddObject(productToCreate); _entities.SaveChanges(); } //other methods } </code></pre></li> <li><p>The following data access method in the controller</p> <pre><code> public class TestingController : Controller { // // GET: /Testing/ private ITestingRepository _repository; public TestingController() : this(new TestingRepository()) { } public TestingController(ITestingRepository repository) { _repository = repository; } [HttpPost] public ActionResult Create(Testing newobject) { _repository.Create(newobject); return RedirectToAction("Index"); } [HttpPost] public ActionResult Edit(Testing item) { _repository.Edit(item); return RedirectToAction("Index"); } } </code></pre></li> </ol> <p>Is it a good one? Have I any mistakes there?</p>
[]
[ { "body": "<p>Your code seems really good, I would change the <code>ITestingRepository</code> methods to return <code>IEnumerable&lt;&gt;</code> instead of <code>List&lt;&gt;</code>. </p>\n\n<p>Also, I suggest you would add a method signature to your generic repository interface that would let you query your DbContext.</p>\n\n<pre><code>public interface IGenericRepository&lt;T&gt; where T : class\n{\n T Get(int id);\n void Create(T entityToCreate);\n void Edit(T entityToEdit);\n void Delete(T entityToDelete);\n IEnumerable&lt;T&gt; Get(Expression&lt;Func&lt;T,bool&gt;&gt; whereClause)\n}\n</code></pre>\n\n<p>Then you can use it this way </p>\n\n<pre><code>//Class example, I don't know what Testing class is\npublic class Testing\n{\n public string PropertyOne { get; set;}\n public string PropertyTwo { get; set;}\n}\n\npublic class TestingRepository\n{\n //Method implementation\n public IEnumerable&lt;Testing&gt; Get(Expression&lt;Func&lt;Testing,bool&gt;&gt; whereClause)\n {\n IQueryable&lt;Testing&gt; result = _entities.Testing;\n\n if(whereClause != null)\n return result.Where(whereClause);\n\n return result.ToList();\n }\n}\n\npublic static void AMethod() //Just to show an example at work!\n{\n List&lt;Testing&gt; testings = new TestingRepository().Get(x =&gt; x.PropertyOne == \"Hello\" &amp;&amp; x.PropertyTwo == \"World\").ToList();\n}\n</code></pre>\n\n<p>Finally, you might want to implement a generic repository class that implements your interface (a <code>public class GenericRepository&lt;T&gt; : IGenericRepository&lt;T&gt;</code>, I won't write it down for you but you could check this <a href=\"http://www.codeproject.com/Articles/640294/Learning-MVC-Part-Generic-Repository-Pattern-in\">http://www.codeproject.com/Articles/640294/Learning-MVC-Part-Generic-Repository-Pattern-in</a></p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-08-19T18:02:13.700", "Id": "60494", "ParentId": "5364", "Score": "8" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-10-14T18:06:34.750", "Id": "5364", "Score": "6", "Tags": [ "c#", "entity-framework", "asp.net-mvc-3" ], "Title": "The way to realise data access" }
5364
<pre><code>I need to insert multiple checkbox text into a column in a mssql database, I could use a single checkbox list and make this thing easier, however, the requirements are to display separate table columns with several checkboxes , kinda like Check all the conditions that apply , but for several criterias, so I am guessing probably a string builder or array? Please help with my code below: code /* Concatenate every checkbox text and textfield that apply! */ /*------------------------------------------------------------------------------------------------------*/ StringBuilder sbSpecificEvents = new StringBuilder(); if (eventdetailsSSI1.Checked) { sbSpecificEvents.Append(eventdetailsSSI1.Text + ","); } if (eventdetailsSSI2.Checked) { sbSpecificEvents.Append(eventdetailsSSI2.Text + ","); } &lt;td&gt; &lt;asp:CheckBox ID="eventCriteria1" runat="server" Text="Purulent drainage or material" /&gt; &lt;br /&gt; &lt;asp:CheckBox ID="eventCriteria2" runat="server" Text="Pain or tenderness"/&gt; &lt;br /&gt; &lt;asp:CheckBox ID="eventCriteria3" runat="server" Text="Localized swelling" /&gt; &lt;br /&gt; &lt;asp:CheckBox ID="eventCriteria4" runat="server" Text="Redness" /&gt; &lt;br /&gt; &lt;asp:CheckBox ID="eventCriteria5" runat="server" Text="Heat" /&gt; &lt;br /&gt; &lt;asp:CheckBox ID="eventCriteria6" runat="server" Text="Fever"/&gt; &lt;br /&gt; &lt;asp:CheckBox ID="eventCriteria7" runat="server" Text="Incision deliberately opened by surgeon"/&gt; &lt;br /&gt; &lt;asp:CheckBox ID="eventCriteria8" runat="server" Text="Wound spontaneously dehisces"/&gt; &lt;br /&gt; &lt;asp:CheckBox ID="eventCriteria9" runat="server" Text="Abscess"/&gt; &lt;br /&gt; &lt;asp:CheckBox ID="eventCriteria10" runat="server" Text="Hypothermia" /&gt; &lt;br /&gt; &lt;asp:CheckBox ID="eventCriteria11" runat="server" Text="Apnea" /&gt; &lt;br /&gt; &lt;asp:CheckBox ID="eventCriteria12" runat="server" Text="Bradycardia" /&gt; &lt;br /&gt; &lt;asp:CheckBox ID="eventCriteria13" runat="server" Text="Lethargy"/&gt; &lt;br /&gt; &lt;asp:CheckBox ID="eventCriteria14" runat="server" Text="Cough"/&gt; &lt;br /&gt; &lt;asp:CheckBox ID="eventCriteria15" runat="server" Text="Nausea"/&gt; &lt;br /&gt; &lt;asp:CheckBox ID="eventCriteria16" runat="server" Text="Vomiting"/&gt; &lt;br /&gt; &lt;asp:CheckBox ID="eventCriteria17" runat="server" Text="Dysuria"/&gt; &lt;br /&gt; &lt;asp:CheckBox ID="eventCriteria18" runat="server" Text="Other evidence of infection found on direct exam, during surgery, or by diagnostic tests"/&gt; &lt;br /&gt; &lt;asp:CheckBox ID="eventCriteria19" runat="server" Text="Other signs &amp; symptoms"/&gt; &lt;/td&gt; &lt;td colspan="2" style="height: 23px; text-decoration: underline; width: 307px;" valign="top"&gt; &lt;br /&gt; Laboratory&lt;br /&gt; &lt;br /&gt; &lt;asp:CheckBox ID="eventCriteria20" runat="server" Text="Positive culture" /&gt; &lt;br /&gt; &lt;asp:CheckBox ID="eventCriteria21" runat="server" Text="Not cultured"/&gt; &lt;br /&gt; &lt;asp:CheckBox ID="eventCriteria22" runat="server" Text="Positive blood culture" /&gt; &lt;br /&gt; &lt;asp:CheckBox ID="eventCriteria23" runat="server" Text="Blood culture not done or no organisms detected in blood" /&gt; &lt;br /&gt; &lt;asp:CheckBox ID="eventCriteria24" runat="server" Text="Positive Gram stain when culture is negative or not done" /&gt; &lt;br /&gt; &lt;asp:CheckBox ID="eventCriteria25" runat="server" Text="Other positive laboratory tests"/&gt; &lt;br /&gt; &lt;asp:CheckBox ID="eventCriteria26" runat="server" Text="Radiographic evidence of infection"/&gt; &lt;br /&gt; &lt;br /&gt; Clinical Diagnosis&lt;br /&gt; &lt;asp:CheckBox ID="eventCriteria27" runat="server" Text="Physician diagnosis of this event type"/&gt; &lt;br /&gt; &lt;asp:CheckBox ID="eventCriteria28" runat="server" Text="Physician institutes appropriate antimicrobial therapy"/&gt; &lt;/td&gt; </code></pre>
[ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-10-14T19:10:54.413", "Id": "8094", "Score": "0", "body": "Not code review, as there is no code... This should go to StackOverflow instead." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-10-14T19:15:39.217", "Id": "8095", "Score": "0", "body": "What do you mean by code?" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-10-14T20:32:06.060", "Id": "8099", "Score": "0", "body": "I mean code. There was no code to get the values from the checkboxes before you edited the question, so there was nothing to review." } ]
[ { "body": "<p>I'm not sure that it's the best choise to store the items as text in the database, and to store them in a single field, but that's a different matter...</p>\n\n<p>You can put the checkboxes in an array and loop over it. Put the selected text in a list, and join it:</p>\n\n<pre><code>Checkbox[] checkboxes = new Checkbox[] { eventCriteria1, eventCriteria2, ... , eventCriteria18 };\nList&lt;string&gt; checked = new List&lt;string&gt;();\nforeach (Checkbox checkbox in checkboxes) {\n if (checkbox.Checked) {\n checked.Add(checkbox.Text);\n }\n}\nstring checkedText = String.Join(\", \", checked);\n</code></pre>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-10-14T20:37:44.730", "Id": "5373", "ParentId": "5366", "Score": "1" } } ]
{ "AcceptedAnswerId": "5373", "CommentCount": "3", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-10-14T18:35:44.913", "Id": "5366", "Score": "3", "Tags": [ "c#", "asp.net" ], "Title": "Inserting multiple single checkbox controls text into a single column in db" }
5366
<p>I'm doing my first major jQuery development. It's a Widget for recurring events, and is as such a fairly complex beast. The full code is available at <a href="https://github.com/collective/jquery.recurrenceinput.js" rel="nofollow">https://github.com/collective/jquery.recurrenceinput.js</a> for those who want to check it out. I appreciate any kind of feedback about any part of the code, so anyone who wants to take a look at it, that would be awesome.</p> <p>I have a couple of specific questions, and it seems best to put them as separate posts, so here is the first one:</p> <p>Does my directory layout fit with what a jQuery developer would expect? Is it "best practice"?</p> <p>The directory structure is this (somewhat simplified):</p> <pre><code>demo // Files to run the demo/tests: delete.png jquery.recurrenceinput.css overlays.css undelete.png input.html jquery.tools.dateinput.css pb_close.png lib // jQuery files: jquery-1.4.2.js jquery.tmpl-beta1.js jquery.tools.dateinput-1.2.5.js jquery.tools.overlay-1.2.5.js jquery.utils.i18n-0.8.5.js src // Actual code jquery.recurrenceinput.display.js jquery.recurrenceinput.form.js jquery.recurrenceinput.js tests // Tests and supporting files jslint.js qunit.css qunit.js test.html tests.js README.rst </code></pre>
[]
[ { "body": "<p><code>lib</code> is not really lib, but your project's dependencies. Normally you'd call it <code>vendor</code></p>\n\n<p><code>tests</code> -> <code>test</code>. This one is just a convention.</p>\n\n<p>I took a quick look at your code and the first thing I saw was snake_case. JS/jQuery convention is to use CamelCase.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-10-27T00:53:17.947", "Id": "5612", "ParentId": "5371", "Score": "2" } }, { "body": "<p>It's close enough. I don't recall noticing a convention for something like a jQuery widget or plugin - maybe because I didn't notice or maybe because there isn't one. As long as you're clearly communicating the separation of the project, which I think the included structure does perfectly well, people will figure it out.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-10-27T13:06:04.063", "Id": "5628", "ParentId": "5371", "Score": "0" } } ]
{ "AcceptedAnswerId": "5612", "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-10-14T19:11:30.793", "Id": "5371", "Score": "5", "Tags": [ "javascript", "jquery" ], "Title": "Writing a jQuery widget: Code layout" }
5371
<p>I'm doing my first major jQuery development. It's a Widget for recurring events, and is as such a fairly complex beast. The full code is available at <a href="https://github.com/collective/jquery.recurrenceinput.js">https://github.com/collective/jquery.recurrenceinput.js</a> for those who want to check it out. I appreciate any kind of feedback about any part of the code, so anyone who wants to take a look at it, that would be awesome.</p> <p>I have a couple of specific questions, and it seems best to put them as separate posts, and here is the second one:</p> <p>I have several big snippets of HTML and I'm using jQuery templating for this. My question is on the best way to include these templates. Currently I'm using two different ways, and none of them are obviously better than any other.</p> <p>In one case I use a string literal:</p> <pre><code>var OCCURRENCE_TMPL = ['&lt;div class="recurrenceinput_occurrences"&gt;&lt;hr/&gt;', '{{each occurrences}}', '&lt;div class="occurrence&gt;', '&lt;span class="date ${occurrences[$index].type}"&gt;', '${occurrences[$index].formatted_date}', '&lt;/span&gt;', '&lt;span class="action"&gt;', '{{if occurrences[$index].type === "rrule"}}', '&lt;a date="${occurrences[$index].date}" href="#"', 'class="${occurrences[$index].type}" &gt;', 'Exclude', '&lt;/a&gt;', '{{/if}}', '{{if occurrences[$index].type === "rdate"}}', '&lt;a date="${occurrences[$index].date}" href="#"', 'class="${occurrences[$index].type}" &gt;', 'Remove', '&lt;/a&gt;', '{{/if}}', '{{if occurrences[$index].type === "exdate"}}', '&lt;a date="${occurrences[$index].date}" href="#"', 'class="${occurrences[$index].type}" &gt;', 'Include', '&lt;/a&gt;', '{{/if}}', '&lt;/span&gt;', '&lt;/div&gt;', '{{/each}}', '&lt;div class="batching"&gt;', '{{each batch.batches}}', '{{if $index === batch.current_batch}}&lt;span class="current"&gt;{{/if}}', '&lt;a href="#" start="${batch.batches[$index][0]}"&gt;[${batch.batches[$index][0]} - ${batch.batches[$index][1]}]&lt;/a&gt;', '{{if $index === batch.current_batch}}&lt;/span&gt;{{/if}}', '{{/each}}', '&lt;/div&gt;&lt;/div&gt;'].join('\n'); $.template('occurrence_tmpl', OCCURRENCE_TMPL); </code></pre> <p>OK, so strictly it's an array of string literals, but that's to make JSLint happy. I then use this:</p> <pre><code>result = $.tmpl('occurrence_tmpl', data); occurrence_div = form.find('.recurrenceinput_occurrences'); occurrence_div.replaceWith(result); </code></pre> <p>This is neat and simple, but the result is a lot of HTML inline. One of the templates is 219 lines long... :-)</p> <p>The other technique I use is to include the template as if it is a script in the HTML:</p> <pre><code>&lt;script id="jquery-recurrenceinput-form-tmpl" type="text/x-jquery-tmpl" src="../src/jquery.recurrenceinput.form.js" &gt;&lt;/script&gt; </code></pre> <p>And I load that HTML via ajax, stick it in a variable and make a template of it:</p> <pre><code> if ($.template.recurrenceinput_form === undefined) { $.ajax({ url: $(conf.template.form)[0].src, async: false, success: function (data) { conf.template.form = data; }, error: function (request, status, error) { alert(error.message + ": " + error.filename); } }); $(conf.template.form).template('recurrenceinput_form'); } </code></pre> <p>And I can then use that:</p> <pre><code>form = $.tmpl('recurrenceinput_form', conf); overlay_conf = $.extend(conf.form_overlay, {}); form.overlay().hide(); </code></pre> <p>This means I don't have the template inline, which is good, but it also means using the Widget is a bit more involved as you need the tag in the HTML, which is bad, and it is a bit of a horrid hack.</p> <p>Opinions on this is welcome, and even more welcome would be a third way that doesn't suck. :-)</p>
[]
[ { "body": "<p>I agree, the string literal in JS is unwieldy. And requesting the HTML via Ajax is more than you need. </p>\n\n<p>The simplest thing is to insert the template on the page as HTML. Can you include the template on your page, not as Javascript, but as HTML? As in,</p>\n\n<pre><code>&lt;div style=\"display: none\"&gt;\n &lt;div class=\"recurrenceinput_occurrences\"&gt;&lt;hr/&gt;\n {{each occurrences}}\n &lt;div class=\"occurrence&gt;\n &lt;span class=\"date ${occurrences[$index].type}\"&gt;\n ...\n&lt;/div&gt;\n</code></pre>\n\n<p>You can either use this as a template, and insert the results of the evaluation into the DOM elsewhere. Or, in some cases, insert it back where it was on the page (and don't use the <code>display: none</code>).</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-10-29T05:22:01.080", "Id": "8591", "Score": "0", "body": "No, I can't ask everybody that uses this widget to paste in several hundred lines of HTML split into three templates into their webpages." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-10-31T02:11:14.753", "Id": "8624", "Score": "2", "body": "Yeah, now that I see it's a plugin, I think your only nice option (for your users) is embed it into your plugin JS code.\n\nYou might want to spike on different ways to embed it. You can include it as a template (as you have done). You might look at what it would take to build the mark up-- or portions of it-- programmatically. Often this can be smaller and easier to test." } ], "meta_data": { "CommentCount": "2", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-10-29T04:55:12.953", "Id": "5680", "ParentId": "5372", "Score": "-1" } }, { "body": "<p>I think loading the templates via AJAX is an elegant solution.</p>\n\n<p>The idea of using a <code>&lt;script&gt;</code>-tag with a non-standard <code>type</code> is also applied in <a href=\"http://yuilibrary.com/yui/docs/app/app-todo.html\" rel=\"nofollow\">this example from the YUI 3 documentation</a>. Your idea to use AJAX to load it is, in my opinion, a much cleaner solution to this dirty problem.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-12-28T18:21:22.183", "Id": "11305", "Score": "0", "body": "It does result in warnings on mismatches of file types on some browsers, so in the end I decided on merging the templates into the main JS file. Those warning probably can be avoided with some fiddling of the web-server config, though." } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-12-28T13:00:46.463", "Id": "7219", "ParentId": "5372", "Score": "2" } }, { "body": "<p>You might want to consider using a toolkit geared towards this sort of thing so you don't have to re-do it yourself. With Dojo it's really easy to create <a href=\"http://dojotoolkit.org/documentation/tutorials/1.6/recipes/custom_widget/\" rel=\"nofollow\">custom widgets</a>, they cache the html, etc (using <a href=\"http://dojotoolkit.org/documentation/tutorials/1.6/templated/\" rel=\"nofollow\">templates</a>). I heard JQuery was going to implement the AMD define/require standard so you could probably mix the toolkits if you wanted to without too much hassle. If not though it'd be worth looking at how they did it.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-12-03T00:55:54.493", "Id": "19241", "ParentId": "5372", "Score": "2" } } ]
{ "AcceptedAnswerId": "7219", "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-10-14T19:24:02.920", "Id": "5372", "Score": "7", "Tags": [ "javascript", "jquery", "ajax" ], "Title": "Writing a jQuery widget: Templating" }
5372
<p>I was given this assignment below and wrote the code below that as the solution. My instructor has been blasting me for writing inefficient code for my last several assignments, and rails at me for using strings as I do. She won't show me why its wrong but just states that it is wrong. I need to know why what I am writing here is so wrong and why. Where am I being so inefficient? I am also being blasted for the use of too many strings, what is wrong with using strings and why?</p> <p><strong>The Assignment:</strong></p> <blockquote> <p>Design a program that will determine based on the temperature and amount of rain whether or not the sprinklers should be turned on.</p> <p>Note: The inputs and outputs below are for the specified data. When I test the program you will be asked to type in different values during program execution.</p> <ul> <li>There are 3 regions in the Garden: F-Flowers V-Vegetable B-Berries. Report an INVALID garden choice if F, V or B is not entered for the garden choice.</li> <li>If the temperature is above 40 degrees then based on the precipitation it can be watered. The Flower Garden it should be watered when the precipitation is less than 0.15 inches. The Vegetable Garden should be watered when less than 0.375 inches and the Berries should be watered when there is less than 0.425 inches. It should state which garden is being watered and or not.</li> </ul> <h3>Example program Outputs</h3> <pre><code>Garden Sprinkler System What is the temperature in degrees(F)? 78 How much precipitation today(in inches)?.1 The Garden Divisions are F-Flowers V-Vegetable B-Berries Which do you choose (FVB)? B Given the temperature is 78 degrees and 0.100 inches of precipitation today. The Berries in the Garden will be watered. </code></pre> <p>OR</p> <pre><code>Garden Sprinkler System What is the temperature in degrees(F) ?32 How much precipitation today(in inches)?0.2 The Garden Divisions are F-Flowers V-Vegetable B-Berries Which do you choose (FVB)? V Given the temperature is 32 degrees and 0.200 inches of precipitation today. The Vegetables in the Garden will NOT be watered. </code></pre> </blockquote> <p><strong>My code answer</strong></p> <pre><code># include &lt;iostream&gt; # include &lt;stdio.h&gt; # include &lt;iomanip&gt; using namespace std; int main() { char Typ; string Bry = "berries"; string Veg = "vegetables"; string Flr = "flowers"; string AllStr; float Tmp1, Precip; int Tmp, FlrW, VegW, BryW, x, Selct; bool Cont = true; AllStr = Flr + ", " + Bry + ", " + "and " + Veg; Selct = 0; x = 0; cout &lt;&lt; setprecision(3)&lt;&lt;fixed; cout&lt;&lt; "Garden Sprinkler System\n\n\n\n"; cout&lt;&lt; "What is the temperature in degrees(F) ? "; cin&gt;&gt;Tmp1; cout&lt;&lt;"How much precipitation today (in inches)? "; cin&gt;&gt;Precip; cout&lt;&lt; "The Garden Divisions are F-Flowers V-Vegetable B-Berries"; cout&lt;&lt;"\nWhich do you choose (FVB)? "; cin&gt;&gt; Typ; Tmp = static_cast&lt;int&gt;(Tmp1); for (x = 1; x &lt;= 4; x++){ if(x == 4 ){ cout&lt;&lt;"\nToo many failed attempts.... exiting program"; cout&lt;&lt;"\n\n\n\n\n\n\n\n\n\n\n\n\n\n(loser)"; Cont = false; break; } if (Typ == 'B' || Typ == 'b'){ Selct = 100; break; } else if (Typ == 'F' || Typ == 'f'){ Selct = 10; break; } else if (Typ == 'V' || Typ == 'v'){ Selct = 1; break; } else { cout&lt;&lt; "\nThe value entered was an INVALID value!"; cout&lt;&lt; "\nThe Garden Divisions are F-Flowers V-Vegetable B-Berries"; cout&lt;&lt;"\nWhich do you choose (FVB)? "; cin&gt;&gt; Typ; } } if (Cont == true){ if (Tmp &gt; 40){ switch(Selct){ case 100: if (Precip &lt; 0.425){ cout&lt;&lt; "\n\n\n\nGiven the temperature is "&lt;&lt; Tmp &lt;&lt;" degrees and "&lt;&lt; Precip&lt;&lt;" inches "; cout&lt;&lt; "of precipitation today."; cout&lt;&lt; "\nThe "&lt;&lt; Bry&lt;&lt;" in the Garden will be watered."; break; } else{ cout&lt;&lt; "\n\n\n\nGiven the temperature is "&lt;&lt; Tmp &lt;&lt;" degrees and "&lt;&lt; Precip &lt;&lt;" inches of"; cout&lt;&lt;" precipitation today.\nThe "&lt;&lt; Bry &lt;&lt;" in the Garden will NOT be watered."; break; } case 10: if (Precip &lt; 0.375){ cout&lt;&lt; "\n\n\n\nGiven the temperature is "&lt;&lt; Tmp &lt;&lt;" degrees and "&lt;&lt; Precip&lt;&lt;" inches "; cout&lt;&lt; "of precipitation today."; cout&lt;&lt; "\nThe "&lt;&lt; Flr &lt;&lt;" in the Garden will be watered."; break; } else{ cout&lt;&lt; "\n\n\n\nGiven the temperature is "&lt;&lt; Tmp &lt;&lt;" degrees and "&lt;&lt; Precip &lt;&lt;" inches of"; cout&lt;&lt;" precipitation today.\nThe "&lt;&lt; Flr &lt;&lt;" in the Garden will NOT be watered."; break; } case 1: if (Precip &lt; 0.15){ cout&lt;&lt; "\n\n\n\nGiven the temperature is "&lt;&lt; Tmp &lt;&lt;" degrees and "&lt;&lt; Precip&lt;&lt;" inches "; cout&lt;&lt; "of precipitation today."; cout&lt;&lt; "\nThe "&lt;&lt; Veg&lt;&lt;" in the Garden will be watered."; break; } else{ cout&lt;&lt; "\n\n\n\nGiven the temperature is "&lt;&lt; Tmp &lt;&lt;" degrees and "&lt;&lt; Precip &lt;&lt;" inches of"; cout&lt;&lt;" precipitation today.\nThe "&lt;&lt; Veg&lt;&lt; " in the Garden will NOT be watered."; break; } default: cout&lt;&lt; "\n\n\n\nThough the temperature is "&lt;&lt; Tmp &lt;&lt;" degrees and "&lt;&lt; Precip &lt;&lt;" inches of"; cout&lt;&lt;" precipitation today.\nThe garden type selection was invalid and the "&lt;&lt; AllStr&lt;&lt;endl; cout&lt;&lt;"in the Garden will NOT be watered."; } } else{ cout&lt;&lt; "\n\n\n\nGiven the temperature is "&lt;&lt; Tmp &lt;&lt;" degrees and "&lt;&lt; Precip &lt;&lt;" inches of"; cout&lt;&lt;" precipitation.\nThe "&lt;&lt; AllStr&lt;&lt; " in the Garden will NOT be watered today."; cout&lt;&lt;"\nBecause it is too cold."; } } getchar(); getchar(); return 0; } </code></pre>
[ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-10-15T19:02:34.847", "Id": "8118", "Score": "3", "body": "Please learn to format your code so it is easier to read." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-10-16T06:24:44.347", "Id": "8128", "Score": "0", "body": "by that do you mean tabing/indenting bracketed items? Or is there another \"formating\" being refered to?" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-10-16T06:28:36.603", "Id": "8129", "Score": "0", "body": "uh....I just realized that is exactly what you meant. Will do." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-10-16T07:41:09.580", "Id": "8132", "Score": "2", "body": "@RSherwin: spacing as well. Just put exactly one space on each side of every operator and between adjacent identifiers. This will do for a start (until you may later want to align similar statements into columns). Right now you seem to randomly use one, two, or no spaces (around `<<`, after `string` etc.)" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-10-16T07:48:07.977", "Id": "8133", "Score": "2", "body": "@RSherwin: ...and please don't do `if (Cont == true) …`. `Cont` is itself already a Boolean variable, there is no need to compare it to one, just use `if (Cont) …`." } ]
[ { "body": "<p>My thoughts:</p>\n\n<ol>\n<li>Your variables are all declared at the beginning of the function: don't do that. Declare variables close to where they are used</li>\n<li>Your variable names are confusing and give little indication of what they are for</li>\n<li>You use magic numbers 100, 10, 1 to denote the different types of plants, that's hard to keep track of</li>\n<li>You have the exact same lines of code over and over again (this is probably what the teacher meant by having too many strings)</li>\n<li>Your code does not have consistent indentation, that makes it hard to read.</li>\n</ol>\n\n<p>Let's look at a small piece of code:</p>\n\n<pre><code> if (Precip &lt; 0.375){\n cout&lt;&lt; \"\\n\\n\\n\\nGiven the temperature is \"&lt;&lt; Tmp &lt;&lt;\" degrees and \"&lt;&lt; Precip&lt;&lt;\" inches \";\n cout&lt;&lt; \"of precipitation today.\";\n cout&lt;&lt; \"\\nThe \"&lt;&lt; Flr &lt;&lt;\" in the Garden will be watered.\";\n break;\n }\n else{\n cout&lt;&lt; \"\\n\\n\\n\\nGiven the temperature is \"&lt;&lt; Tmp &lt;&lt;\" degrees and \"&lt;&lt; Precip &lt;&lt;\" inches of\";\n cout&lt;&lt;\" precipitation today.\\nThe \"&lt;&lt; Flr &lt;&lt;\" in the Garden will NOT be watered.\"; \n break;\n }\n</code></pre>\n\n<p>The first line of code is the same in both cases, we don't need to repeat them, instead we can do:</p>\n\n<pre><code> cout&lt;&lt; \"\\n\\n\\n\\nGiven the temperature is \"&lt;&lt; Tmp &lt;&lt;\" degrees and \"&lt;&lt; Precip&lt;&lt;\" inches \";\n if (Precip &lt; 0.375){\n\n cout&lt;&lt; \"of precipitation today.\";\n cout&lt;&lt; \"\\nThe \"&lt;&lt; Flr &lt;&lt;\" in the Garden will be watered.\";\n break;\n }\n else{\n cout&lt;&lt;\" precipitation today.\\nThe \"&lt;&lt; Flr &lt;&lt;\" in the Garden will NOT be watered.\"; \n break;\n }\n</code></pre>\n\n<p>See that the code is simpler and less repetitive but does the same thing? We can continue. Most of the text inside the code is </p>\n\n<pre><code> cout&lt;&lt; \"\\n\\n\\n\\nGiven the temperature is \"&lt;&lt; Tmp &lt;&lt;\" degrees and \"&lt;&lt; Precip&lt;&lt;\" inches \";\n cout&lt;&lt; \"of precipitation today.\";\n cout&lt;&lt; \"\\nThe \"&lt;&lt; Flr &lt;&lt;\" in the Garden will be watered.\";\n if (Precip &gt;= 0.375){\n cout &lt;&lt; \"NOT\"\n }\n\n cout &lt;&lt; \"be watered.\"; \n break;\n</code></pre>\n\n<p>That way you have less strings, your code is clearer and more \"efficient.\" If you apply this sort of logic several times you should be able to eliminate the same strings appearing multiple times.</p>\n\n<p>Here is what I would for this problem. I may be using techniques you have not learned yet. But, hopefully it will give you some idea of the lack of duplication you should be striving for.</p>\n\n<pre><code>#include &lt;iostream&gt;\n#include &lt;stdio.h&gt;\n#include &lt;iomanip&gt;\n\nusing namespace std;\n\nenum GardenDivision\n{\n BERRIES,\n VEGETABLES,\n FLOWERS\n};\n\nstruct Garden\n{\n GardenDivision division;\n int temperature;\n float percipitation;\n};\n\nbool read_user_input(Garden &amp; garden)\n{\n cout &lt;&lt; setprecision(3) &lt;&lt; fixed;\n cout &lt;&lt; \"Garden Sprinkler System\\n\\n\\n\\n\";\n cout &lt;&lt; \"What is the temperature in degrees(F) ? \";\n cin &gt;&gt; garden.temperature;\n cout &lt;&lt; \"How much precipitation today (in inches)? \";\n cin &gt;&gt; garden.percipitation;\n cout &lt;&lt; \"The Garden Divisions are F-Flowers V-Vegetable B-Berries\";\n cout &lt;&lt; \"\\nWhich do you choose (FVB)? \";\n\n for(int counter = 0; counter &lt; 4;counter++)\n {\n char division_code;\n cin &gt;&gt; division_code;\n switch(division_code)\n {\n case 'F':\n case 'f':\n garden.division = FLOWERS;\n return true;\n case 'V':\n case 'v':\n garden.division = VEGETABLES;\n return true;\n case 'B':\n case 'b':\n garden.division = BERRIES;\n return true;\n }\n\n cout &lt;&lt; \"\\nThe value entered was an INVALID value!\";\n cout &lt;&lt; \"\\nThe Garden Divisions are F-Flowers V-Vegetable B-Berries\";\n cout &lt;&lt; \"\\nWhich do you choose (FVB)? \";\n }\n\n cout &lt;&lt; \"\\nToo many failed attempts.... exiting program\"; \n cout &lt;&lt; \"\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n(loser)\";\n return false;\n}\n\nvoid display_weather(Garden &amp; garden)\n{\n cout &lt;&lt; \"\\n\\n\\n\\nGiven the temperature is \"&lt;&lt; garden.temperature &lt;&lt;\n \" degrees and \" &lt;&lt; garden.percipitation \n &lt;&lt; \" inches of precipitation today.\\n\";\n\n}\n\nvoid water_section(Garden &amp; garden, string name, float max_perciptiation)\n{\n if(garden.percipitation &lt; max_perciptiation)\n {\n cout &lt;&lt; \"\\nThe \"&lt;&lt; name &lt;&lt; \" in the Garden will be watered.\";\n }\n else\n {\n cout &lt;&lt; \"\\nThe \"&lt;&lt; name &lt;&lt; \" in the Garden will NOT be watered.\";\n }\n}\n\nvoid water_by_section(Garden &amp; garden)\n{\n switch(garden.division)\n {\n case FLOWERS:\n water_section(garden, \"Flowers\", 0.375);\n break;\n case VEGETABLES:\n water_section(garden, \"Vegetables\", 0.15);\n break;\n case BERRIES:\n water_section(garden, \"Berries\", 0.425);\n break;\n }\n}\n\nint main()\n{\n Garden garden;\n if(read_user_input(garden))\n {\n display_weather(garden);\n if(garden.temperature &gt; 40)\n {\n water_by_section(garden);\n }\n else\n {\n cout &lt;&lt; \"The berries, vegetables, and flowers in the Garden will NOT be watered today.\";\n cout &lt;&lt; \"\\nBecause it is too cold.\";\n }\n }\n\n getchar();\n getchar();\n\n return 0;\n}\n</code></pre>\n\n<p>Good Luck!</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-10-15T02:45:39.270", "Id": "8108", "Score": "0", "body": "The problem with \"string\" is that I use the string type variable at all, she wants everything typed out. She was upset I used 5 string variables as that was inefficient code. I think she is a c programmer teaching c++. She isn't really thrilled I use cout as opposed to printf either. We have just began for next loops and structs are chapters away right now. And when we get there I'll be able to follow better what it was you entered. But as for \"magic\" numbers I get it, I see your use of case and didn't know it could be used in that fashion that will help alot." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-10-15T02:56:30.750", "Id": "8109", "Score": "0", "body": "@RSherwin, well if the teacher wants you to use printf and not use std::string, there isn't much you can do about that. But all the duplication of having the exact same text over and over again you should reduce." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-10-15T03:55:04.393", "Id": "8110", "Score": "0", "body": "I tried the code posted but it didn't work. The enum looks like what in VB would be a type def, and the \"Void, and bool as functions, so I tried seeing why it didn't work but was unsuccesful thank you very much for the input though I appreciate all and any help I can get." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-10-15T04:16:27.967", "Id": "8111", "Score": "0", "body": "@RSherwin I didn't test the code, so it's probably not quite correct. I just wanted to demonstrate what could be done." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-10-16T08:00:23.537", "Id": "8134", "Score": "0", "body": "@RSherwin: VB has an `enum` statement in both VB6 and VB.NET; see http://msdn.microsoft.com/en-us/library/8h84wky1%28v=vs.80%29.aspx" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-10-16T08:14:35.067", "Id": "8135", "Score": "0", "body": "@RSherwin: I could make the code work with 3 changes: (1) `enum GardenDivison` is missing the last *i*, (2) `cin >> garden.perciptation;` is missing an *i* in the middle, and (3) (although I'm not sure why) my compiler rejects `cout<< \"\\nThe \"<< name <<\" in the Garden will be watered.\";` and instead needs `… name.c_str() …` there. Also, the code is still not formatted very well, for example in `if(garden.percipitation < max_perciptiation )` there should either be spaces on both sides of the condition, or on neither—I recommend to not have spaces there, but instead have one directly after `if`." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-10-16T14:01:13.840", "Id": "8138", "Score": "0", "body": "@FelixDombek, you shouldn't need the .c_str(), because you should be able to cout << std::string. As for spacing, yes in that one case I added an extra space that wasn't necessary by accident. But I don't think that adds up to \"not formatted very well.\"" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-10-16T15:29:22.123", "Id": "8139", "Score": "0", "body": "@WinstonEwert: I was surprised as well, MSVC++2010 told me \"no overload for operator<< and std::string\" (maybe some unicode setting somewhere? I think it usually works correctly, don't want to look into it now). But: why space after cout in `cout << setprecision(3)<<fixed;` and nowhere else? no space before last `counter` in `for`? one `}else{` on 1 line (no linefeeds), one on 3 (linefeeds)? extra spaces before `getchar()` and `return 0` in `main`? That should be all. Not too bad, just not perfect as well. BTW – it's http://en.wiktionary.org/wiki/precipitation, not \"percipitation\"." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-10-16T17:24:05.117", "Id": "8141", "Score": "0", "body": "@FelixDombek, ok. you are right, my spacing was more problematic then I realized. Thanks on precipitation. I think I've been saying that wrong my whole life." } ], "meta_data": { "CommentCount": "9", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-10-15T02:22:07.187", "Id": "5377", "ParentId": "5376", "Score": "11" } }, { "body": "<p>@Winston has already given some good suggestions, but I think I'd go a slightly different direction. I'd start with a data structure something like this:</p>\n\n<pre><code>struct plant {\n char short_name;\n std::string name;\n float min_water;\n};\n</code></pre>\n\n<p>and of course initialize it with your basic data:</p>\n\n<pre><code>plant plants[] = {\n {'b', \"berries\", 0.425},\n {'f', \"flowers\", 0.375},\n {'v', \"vegatables\", 0.15}\n};\n</code></pre>\n\n<p>That lets you consolidate the data about each type of plant in one place. It also means that most of the rest of the program becomes pretty generic, just displaying data from there, comparing inputs to what it say is required, and so on. It's pretty easy to write the rest of the program so that if (for example) you were to add data for a different type of plant, it would get used by the rest of the code without any modification.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-10-15T14:21:27.617", "Id": "8114", "Score": "0", "body": "Jerry's approach is better, but might require more programming experience is appreciate." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-10-16T06:31:17.770", "Id": "8130", "Score": "0", "body": "why the square brackets after plants and not parenthesis? I'm sure that is a dumb question but as I said...structs are still chapters ahead." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-10-16T06:45:12.173", "Id": "8131", "Score": "0", "body": "@RSherwin: Because we're defining an array of structs, and the syntax for an array uses square brackets." } ], "meta_data": { "CommentCount": "3", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-10-15T05:45:30.463", "Id": "5382", "ParentId": "5376", "Score": "11" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "5", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-10-15T00:26:16.510", "Id": "5376", "Score": "6", "Tags": [ "c++", "beginner", "homework" ], "Title": "Garden sprinkler system" }
5376
<p>I have an assignment where I am required to verify if a car is a sports car or not by minimum max speed and minimum horse power. I have finished the program and it works great. I was just wanting to see if you can review my assignment and see if there is room for improvement.</p> <pre><code>using System; using System.Collections.Generic; using System.Linq; using System.Text; namespace Project3 { class sportsCar { public int _maxSpeed = 0; public int _horsepower = 0; private static int _MinimumRequiredSpeed = 150; private static int _MinimumRequiredHorsepower = 250; public bool IsSportsCar() { if ((_maxSpeed &gt;= _MinimumRequiredSpeed) &amp;&amp; (_horsepower &gt;= _MinimumRequiredHorsepower)) return true; else return false; } public void maxSpeed(int newmaxSpeed) { _maxSpeed = newmaxSpeed; } public void horsepower(int newhorsepower) { _horsepower = newhorsepower; } } class Program { static void Main(string[] args) { sportsCar car = new sportsCar(); Console.Write("What is the max speed? "); int newmaxSpeed = int.Parse(Console.ReadLine()); Console.Write("What is the max horsepower? "); int newhorsepower = int.Parse(Console.ReadLine()); car.maxSpeed(newmaxSpeed); car.horsepower(newhorsepower); bool sportCar = car.IsSportsCar(); if (sportCar == true) { Console.WriteLine("This is Definately a Sports Car"); } else { Console.WriteLine("This is NOT a Sports Car"); } } } } </code></pre>
[]
[ { "body": "<p>You code looks reasonable, but I would have couple of relatively minor suggestions:</p>\n\n<ul>\n<li>Did you consider what happens when user enters an invalid number? I.e. a string that contains letters or even a string that can be interpreted as a number but is not in valid range (e.g. is negative or too large to be applicable to any real-life car)? So, you might want to look at handling potential exceptions from <code>int.Parse</code> and also to define some sort of acceptable range of values. If you really want to impress your teacher, make this range configurable (using <code>Properties.Settings</code> mechanism). The <code>maxSpeed</code> method is where you would check the range validity.</li>\n<li>Make <code>_maxSpeed</code> (and <code>_horsepower</code>) private.</li>\n<li>The naming of <code>maxSpeed</code> (and <code>horsepower</code>) is slightly misleading. On the first glance, it looked like it would return the max speed, not set it. Only after visually \"parsing\" the method signature and/or the way it is called, it becomes clear that this is actually a setter - the name alone dos not suggest its purpose. So either change the name to <code>setMaxSpeed</code>, or use a write-only property (and a \"real\" setter).</li>\n<li>Rename <code>sportsCar</code> to just <code>car</code>, since, after all, <code>IsSportsCar</code> is not guaranteed to always return <code>true</code>.</li>\n<li>Not all of your <code>using</code> directives are necessary.</li>\n</ul>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-10-18T07:32:06.467", "Id": "8201", "Score": "0", "body": "-1 (or it would be, if I had the rep): while your answer is useful (though not complete), I find it a very bad suggestion to start the property name with a verb, since it is not a method; also, in `C#` usually class properties and methods start with caps, and local variables start with low caps." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-10-21T02:47:55.583", "Id": "8333", "Score": "2", "body": "@ANeves They aren't properties, they are setter methods." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-10-21T04:15:26.920", "Id": "8334", "Score": "0", "body": "@KirkBroadhurst, I don't understand how \"setter methods\" can mean anything other than [properties](http://msdn.microsoft.com/en-us/library/x9fsa0sw%28v=vs.80%29.aspx). Can you explain?" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-10-21T04:27:32.350", "Id": "8335", "Score": "0", "body": "@ANeves Well, the second sentence of your link explains it somewhat -\"Properties can be used as though they are public data members\". It is were a property, you would be able to assign directly to it like `maxSpeed = value`, rather than `maxSpeed(value)`. See [Using Properties](http://msdn.microsoft.com/en-us/library/w86s7x04(v=vs.80).aspx) - \"To the user of an object, a property appears to be a field, accessing the property requires exactly the same syntax.\"" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-10-21T05:58:21.410", "Id": "8337", "Score": "0", "body": "@KirkBroadhurst ooooh, sorry, I just noticed I've been assuming that OP was using properties!... while OP was actually using \"setter methods\" as you said. But then, my comment would then be something like: `-1: while your answer is useful (though not complete), I find it a very bad suggestion to use \"setter methods\" instead of properties; also, in C# usually class properties and methods are in CamelCase, and local variables in lowCamelCase.`" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-10-21T13:23:45.970", "Id": "8343", "Score": "0", "body": "@ANeves I mentioned \"write-only property\". As for naming convention, this is not set in stone and I simply followed the OP's naming convention." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-10-21T17:03:22.307", "Id": "8354", "Score": "0", "body": "Naming convention is not set in stone but is a [de facto standard](http://en.wikipedia.org/wiki/De_facto_standard). #CodeReview" } ], "meta_data": { "CommentCount": "7", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-10-15T03:49:08.587", "Id": "5379", "ParentId": "5378", "Score": "3" } }, { "body": "<p><code>_maxSpeed</code> and <code>_horsePower</code> should be private.</p>\n\n<p>You have (confusingly named) setter methods for public variables, but no getters. That makes for an odd interface.</p>\n\n<p>In C# you by convention use properties for getters and setters. So instead of</p>\n\n<pre><code>public int _maxSpeed = 0;\npublic int _horsepower = 0;\npublic void maxSpeed(int newmaxSpeed)\n{\n _maxSpeed = newmaxSpeed;\n}\npublic void horsepower(int newhorsepower)\n{\n _horsepower = newhorsepower;\n}\n</code></pre>\n\n<p>You have</p>\n\n<pre><code>public int MaxSpeed { get; set; }\npublic int HorsePower { get; set; } \n</code></pre>\n\n<p>Since these values are unlikely to change, you could make the type immutable:</p>\n\n<pre><code>class Car\n{\n public readonly int MaxSpeed;\n public readonly int HorsePower;\n\n public Car( int maxSpeed, int horsePower )\n {\n MaxSpeed = maxSpeed;\n HorsePower = horsePower;\n }\n}\n</code></pre>\n\n<p>Instead of checking a boolean expression and then returning a literal <code>true</code> or <code>false</code>, just return the expression instead. Booleans are a type just like any other. Also, you don't need the comparison to <code>true</code> or <code>false</code> for the same reason.</p>\n\n<pre><code>if( someCondition == true )\n return true;\nelse\n return false;\n</code></pre>\n\n<p>You have</p>\n\n<pre><code>if( someCondition )\n return true;\nelse\n return false;\n</code></pre>\n\n<p>or better yet</p>\n\n<pre><code>return someCondition;\n</code></pre>\n\n<p>So</p>\n\n<pre><code>return _maxSpeed &gt;= _MinimumRequiredSpeed &amp;&amp; \n _horsepower &gt;= _MinimumRequiredHorsepower;\n</code></pre>\n\n<p>Whenever you take user input you need to check it. Your program will crash if the user enters something that is not a number. You can check this by using <code>TryParse</code> instead of <code>Parse</code>.</p>\n\n<pre><code>int horsePower;\ndo\n{\n string input = Console.ReadLine();\n}\nwhile( !int.TryParse( input, out horsePower ) );\n</code></pre>\n\n<p>Other than that it is fine, keep at it ;)</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-10-15T04:22:25.447", "Id": "5380", "ParentId": "5378", "Score": "15" } }, { "body": "<p>The other answerers caught most of the issues I can see, however here are a couple of small ones:</p>\n\n<ul>\n<li><p>In C# (well, .NET) you should follow the standard <a href=\"http://msdn.microsoft.com/en-us/library/ms229043.aspx\">naming conventions</a>. In particular, classes, properties and methods should be PascalCased.</p></li>\n<li><p>You spelt \"definitely\" wrong ;)</p></li>\n</ul>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-10-17T09:54:18.040", "Id": "5417", "ParentId": "5378", "Score": "5" } }, { "body": "<p>Here's how I would clean it up (explanations below):</p>\n\n<pre><code>namespace Project3\n{\n using System;\n\n internal sealed class SportsCar\n {\n private const int MinimumRequiredSpeed = 150;\n private const int MinimumRequiredHorsepower = 250;\n private readonly int maxSpeed;\n private readonly int horsepower;\n\n public SportsCar(int maxSpeed, int horsepower)\n {\n this.maxSpeed = maxSpeed;\n this.horsepower = horsepower;\n }\n\n public bool IsSportsCar()\n {\n return (this.maxSpeed &gt;= MinimumRequiredSpeed) &amp;&amp; (this.horsepower &gt;= MinimumRequiredHorsepower);\n }\n\n public int MaxSpeed\n {\n get\n {\n return this.maxSpeed;\n }\n }\n\n public int Horsepower\n {\n get\n {\n return this.horsepower;\n }\n }\n }\n\n internal static class Program\n {\n private static void Main()\n {\n Console.Write(\"What is the max speed? \");\n int newmaxSpeed;\n if (!int.TryParse(Console.ReadLine(), out newmaxSpeed))\n {\n Console.WriteLine(\"Invalid max speed!\");\n return;\n }\n\n Console.Write(\"What is the max horsepower? \");\n int newhorsepower;\n if (!int.TryParse(Console.ReadLine(), out newhorsepower))\n {\n Console.WriteLine(\"Invalid max horsepower!\");\n return;\n }\n\n SportsCar car = new SportsCar(newmaxSpeed, newhorsepower);\n bool sportCar = car.IsSportsCar();\n if (sportCar)\n {\n Console.WriteLine(\"This is Definitely a Sports Car\");\n }\n else\n {\n Console.WriteLine(\"This is NOT a Sports Car\");\n }\n }\n }\n}\n</code></pre>\n\n<ul>\n<li>Removed underscores from variable names. I personally don't like them, but that's up to you (or your team standards).</li>\n<li>Changed name of class to 'SportsCar' to meet .NET naming guidelines (classes should be initial caps in a form known as PascalCasing).</li>\n<li>The <code>MinimumRequired</code> variables are constant, so they are declared as <code>const</code>.</li>\n<li>Since the <code>maxSpeed</code> and <code>horsepower</code> should be invariant for a Car, I made them <code>readonly</code> and settable via the constructor.</li>\n<li>Consequently, they are now <code>private</code> but accessible via getter properties.</li>\n<li>The <code>IsSportsCar</code> method is simplified since the evaluation is already a boolean construct (i.e. no need for a <code>return true</code> and <code>return false</code> as it evaluates as such).</li>\n<li>Made the class <code>sealed</code> so no classes can inherit from it. By default, I seal all my classes and only remove the sealant if design dictates it.</li>\n<li>The <code>Program</code> class is now <code>static</code> since it only contains a single static method.</li>\n<li>Employed use of <code>int.TryParse()</code> in place of <code>int.Parse()</code> in order to allow program execution be smoother if an invalid input is typed.</li>\n<li>Removed extraneous 'using' directives.</li>\n<li>Fixed spelling of \"Definitely\".</li>\n</ul>\n\n<p>I'd also add liberal amounts of commenting. .NET has a really good documentation system which allows for \"XML Comments\" at the class, variable, property and method level which would look something like this:</p>\n\n<pre><code> /// &lt;summary&gt;\n /// Determines whether this particular car meets the criteria of being a sports car. Its maximum speed must\n /// be at least MinimumRequiredSpeed AND the horsepower must be at least MinimumRequiredHorsepower.\n /// &lt;/summary&gt;\n /// &lt;returns&gt;\n /// &lt;c&gt;true&lt;/c&gt; if this car is a sports car; otherwise, &lt;c&gt;false&lt;/c&gt;.\n /// &lt;/returns&gt;\n public bool IsSportsCar()\n {\n return (this.maxSpeed &gt;= MinimumRequiredSpeed) &amp;&amp; (this.horsepower &gt;= MinimumRequiredHorsepower);\n }\n</code></pre>\n\n<p>That's just an example, do not underestimate the power of in-code commenting as well.</p>\n\n<p>One last thing I thought of. There's an object oriented principle known as SRP, or Single Responsibility Principle. It means that each class you design should have one and only one purpose which is rather limited in scope. The same thing can be said for methods themselves. You never know when you might need to refactor logic out of a method to use elsewhere. So even though this is a trivial example, you might want to look into rewriting <code>IsSportsCar()</code> into three separate methods:</p>\n\n<pre><code> public bool IsSportsCar()\n {\n return this.MeetsMinimumSpeedRequirements() &amp;&amp; this.MeetsMinimumHorsepowerRequirements();\n }\n\n private bool MeetsMinimumSpeedRequirements()\n {\n return this.maxSpeed &gt;= MinimumRequiredSpeed;\n }\n\n private bool MeetsMinimumHorsepowerRequirements()\n {\n return this.horsepower &gt;= MinimumRequiredHorsepower;\n }\n</code></pre>\n\n<p>Now, if your <code>SportsCar</code> ever needs to do some checks against only speed or horsepower, you have it logically separated out.</p>\n\n<p>Best of luck!</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-10-17T14:28:17.397", "Id": "5423", "ParentId": "5378", "Score": "5" } }, { "body": "<blockquote>\n<pre><code>SportsCar mySportsCar = New Sportscar();\nIf (mySportsCar.IsSportsCar())\n{\n //...\n</code></pre>\n</blockquote>\n\n<p>Well... Doesn't that look odd? I wouldn't expect a <code>SportsCar</code> to be anything <strong><em>but</em></strong> a sportscar. This isn't a <code>SportsCar</code> class. It's a <code>Car</code> class with a <code>IsSportsCar()</code> method. You could either rename the class, or create a constructor that validates the horsepower and speed upon creation. </p>\n\n<p>I'm going to add a slight modification to <a href=\"https://codereview.stackexchange.com/a/5423/41243\">Jesse C. Slicer's answer</a>. If either the speed or horsepower are not sufficient, we'll throw an exception. </p>\n\n<pre><code> private const int MinimumRequiredSpeed = 150;\n private const int MinimumRequiredHorsepower = 250;\n private readonly int maxSpeed;\n private readonly int horsepower;\n\n public SportsCar(int maxSpeed, int horsepower)\n {\n If (maxSpeed &lt; MinimumRequiredSpeed)\n {\n throw New ArgumentException(\"Too slow to be a sportscar\");\n }\n\n If (horsepower &lt; MinimumRequiredHorsepower)\n {\n throw New ArgumentException(\"Not enough horsepower to be a sportscar\");\n }\n\n this.maxSpeed = maxSpeed;\n this.horsepower = horsepower;\n }\n</code></pre>\n\n<p>That's just an example. In reality, I would report back what the minimum speed/horsepower is. </p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-10-10T00:04:37.993", "Id": "65239", "ParentId": "5378", "Score": "1" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-10-15T03:31:51.457", "Id": "5378", "Score": "10", "Tags": [ "c#", "homework", "validation" ], "Title": "Verifying if a car is a sports car based on speed and horse power" }
5378
<p>I have a string of numbers, like <strong>"31654918562314"</strong>, and I want to convert it into an array of integers. The code I've written is:</p> <pre><code>string source = "31654918562314"; int[] numbers = new int[source.Length]; for (int i = 0; i &lt; source.Length; i++) { numbers[i] = Convert.ToInt32(source.Substring(i, 1)); } </code></pre> <p>What improvements can I apply on this code? Is it the best ultimate code I can get to?</p> <p>Note: I'm using C#. However, I also should implement this code in JavaScript.</p>
[ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-10-15T16:47:08.867", "Id": "8115", "Score": "0", "body": "One thing that jumps out at me is that you can just subtract the character value of `0` from each digit, rather than call `Convert.ToInt32()` or `Int32.Parse()`." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-10-15T17:43:33.133", "Id": "8116", "Score": "0", "body": "You've got a point there @Jon, slipped my mind." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-10-18T08:54:54.283", "Id": "8205", "Score": "2", "body": "I wouldn't subtract the character value of 0 from each digit, there is no guarantee that in the future the character values for the digits will be sequential. You might want to look at `Char.GetNumericValue` http://msdn.microsoft.com/en-us/library/e7k33ktz.aspx" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-04-06T18:46:18.610", "Id": "17036", "Score": "0", "body": "@Joey: >.< No! There is a guarantee that the char values will be sequential. It's been this way for 49 years, first in ASCII and now in Unicode, and it isn't going to change." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-04-10T09:04:52.897", "Id": "17144", "Score": "0", "body": "That's no guarantee, that is merely an observation and an assertion. It's akin to saying, \"stocks have risen for the past x years and it isn't going to change\"... Admittedly it is unlikely to change but why take the risk when you can let someone else worry about it, in this case Microsoft." } ]
[ { "body": "<p>I'm partial to using LINQ here. Jon has a point there on the conversion.</p>\n\n<pre><code>var str = \"31654918562314\";\nvar numbers = str.Select(c =&gt; c - '0').ToArray();\n</code></pre>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-10-15T09:35:09.247", "Id": "5384", "ParentId": "5383", "Score": "6" } }, { "body": "<h3>Javascript</h3>\n\n<pre><code>var arr = [];\nvar matches = \"54321\".match(/\\d/g);\nfor (var index = 0; index &lt; matches.length; ++index) {\n arr.push(parseInt(matches[index], 10));\n}\n</code></pre>\n\n<p><a href=\"http://jsbin.com/string-to-integers/2/\" rel=\"nofollow\">live demo</a></p>\n\n<p>Using <code>map()</code> method:</p>\n\n<pre><code>var arr = \"54321\".match(/\\d/g).map(function(m){\n return parseInt(m, 10);\n});\n</code></pre>\n\n<p><a href=\"http://jsbin.com/string-to-integers/3/\" rel=\"nofollow\">live demo</a></p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-10-18T07:45:34.673", "Id": "8202", "Score": "0", "body": "Note that accessing a string like an array doesn't work in some older browsers." } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-10-15T13:28:36.103", "Id": "5387", "ParentId": "5383", "Score": "4" } }, { "body": "<p>The most efficient code would be to use a plain loop and get the numerical value from the character code:</p>\n\n<pre><code>string source = \"31654918562314\";\nint[] numbers = new int[source.Length];\nfor (int i = 0; i &lt; source.Length; i++) {\n numbers[i] = source[i] - '0';\n}\n</code></pre>\n\n<p>In Javascript you would use the <code>charCodeAt</code> method to do the same:</p>\n\n<pre><code>var source = '31654918562314';\nvar numbers = new Array(source.length);\nfor (var i = 0; i &lt; source.length; i++) {\n numbers[i] = source.charCodeAt(i) - 48;\n}\n</code></pre>\n\n<p>A performance test shows that using <code>charCodeAt</code> in a loop is 10-30 times faster than using a regular expression and <code>parseInt</code>: <a href=\"http://jsperf.com/string-to-array-of-numbers\" rel=\"nofollow\">http://jsperf.com/string-to-array-of-numbers</a></p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-12-22T03:34:10.593", "Id": "11007", "Score": "0", "body": "see @Joey's comment above" } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-10-18T07:44:47.573", "Id": "5439", "ParentId": "5383", "Score": "5" } } ]
{ "AcceptedAnswerId": "5384", "CommentCount": "5", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-10-15T09:15:36.430", "Id": "5383", "Score": "4", "Tags": [ "c#", "javascript", "strings", "array" ], "Title": "Improving the code to turn a string into an array of numbers?" }
5383
<p>I am writing a <a href="https://github.com/rahmu/Agros" rel="noreferrer">Unix shell in C</a>, which uses a rather large switch in the main loop.</p> <p>It is used to handle built-in commands like 'cd' or'help'. The way it works is that it parses the user input and return a 'comand_t' struct, with 'name' being the first word of the input.</p> <p>The in order to switch on a string, I translate it into an int by reading this initialized struct:</p> <pre><code>built_in_commands my_commands[CMD_NBR] = { {"" , EMPTY_CMD , ""}, {"cd" , CD_CMD , "change directory"}, {"env" , ENV_CMD , "print enviroment. Can show single variable"}, {"exit" , EXIT_CMD , "exit from AGROS"}, {"help" , HELP_CMD , "print help"}, {"?" , SHORTHELP_CMD , "print short help"} }; </code></pre> <p>The macros are defined in the header file:</p> <pre><code>#define EMPTY_CMD 0 #define CD_CMD 1 #define ENV_CMD 2 #define EXIT_CMD 3 #define HELP_CMD 4 #define SHORTHELP_CMD 5 #define SETENV_CMD 6 #define GETENV_CMD 7 #define OTHER_CMD 8 #define CMD_NBR 9 </code></pre> <p>the main loop of the program is this:</p> <pre><code>while (AG_TRUE){ /* Set the prompt */ get_prompt(prompt, MAX_LINE_LEN, username); /* * Read a line of input * commandline should be deallocated with free() */ commandline = read_input (prompt); parse_command (commandline, &amp;cmd); switch (get_cmd_code (cmd.name)){ //returns an int case EMPTY_CMD: break; case CD_CMD: change_directory (cmd.argv[1], ag_config.loglevel); break; case HELP_CMD: print_help(&amp;ag_config, cmd.argv[1]); break; case SHORTHELP_CMD: print_help(&amp;ag_config, "-s"); break; case ENV_CMD: print_env (cmd.argv[1]); break; case EXIT_CMD: free (commandline); commandline = (char *)NULL; closelog (); return 0; case OTHER_CMD: fork_and_exec(); break; } } </code></pre> <p>Every time I add a new builtin function, I wonder if there isn't a better way to do this. What would it be? How can I call a function dynamically?</p>
[]
[ { "body": "<h3>Function pointers</h3>\n\n<p>You want to use function pointers: <a href=\"http://www.newty.de/fpt/fpt.html\">http://www.newty.de/fpt/fpt.html</a></p>\n\n<pre><code>typedef void (*Command)(char const* args); // Modify as required\n // But something like this\nstruct built_in_commands\n{\n char const* command;\n // int commandID; // Remove this you don't need it.\n char const* man;\n Command function; // Add this: A pointer to a function\n};\n</code></pre>\n\n<p>Then your switch becomes:</p>\n\n<pre><code>parse_command (commandline, &amp;cmd);\nif (cmd != NULL)\n{ (*cmd-&gt;function)(commandline); // Call the function associated with\n} // command (assuming you find it in the list)\n</code></pre>\n\n<h3>Other Notes:</h3>\n\n<p>Basically, all of your function would have the same signature, and then be referred to inside of your struct instead of the number. Then you could call the function pointer from the struct and away you'd go.</p>\n\n<pre><code> case EXIT_CMD:\n free (commandline);\n commandline = (char *)NULL;\n closelog ();\n return 0;\n</code></pre>\n\n<p>This appears to be the only place you free commandline. But you allocate it everytime you get a command. This means that you have a leak. There actually isn't much of a point in freeing the memory here because it will all be free as soon as the process terminates anyways.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-10-15T18:45:34.897", "Id": "8117", "Score": "2", "body": "Seemed pointless writing the same thing as you so just added an example." } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-10-15T14:14:16.300", "Id": "5388", "ParentId": "5386", "Score": "5" } }, { "body": "<p>In addition to @Winston notes on function pointers.</p>\n\n<p>I would not do this:</p>\n\n<pre><code>built_in_commands my_commands[CMD_NBR] = { \n /// ^^^^^^^ This makes mainting the code harder.\n /// If you add commands you now need to modify the code\n /// in multiple places.\n</code></pre>\n\n<p>It is easier to do it like this:</p>\n\n<pre><code>built_in_commands my_commands[] = { \n /// ^^ By leaving it blank the compiler works out the size.\n\n\nint const CMD_NBR = sizeof(my_commands)/sizeof(my_commands[0]);\n /// Now the compiler works out your constant of the size of the array.\n /// Note: This also works for empty arrays as sizeof() \n /// is done at compile time and thus works even if\n /// my_commands[0] is not technically valid at\n /// run-time.\n</code></pre>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-10-15T18:54:12.390", "Id": "5390", "ParentId": "5386", "Score": "5" } } ]
{ "AcceptedAnswerId": "5390", "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-10-15T13:12:07.373", "Id": "5386", "Score": "6", "Tags": [ "c" ], "Title": "Avoiding a large 'switch' call in the main loop" }
5386
<p><strong>Goal</strong></p> <p>Convert the following into an <code>IEnumerable</code> of integers accounting for the <code>x-y</code> ranges:</p> <blockquote> <pre class="lang-none prettyprint-override"><code>"1,2,3,0,7,8,9,10-15" </code></pre> </blockquote> <p>to</p> <blockquote> <pre class="lang-none prettyprint-override"><code>{ 1, 2, 3, 0, 7, 8, 9, 10, 11, 12, 13, 14, 15 } </code></pre> </blockquote> <p><strong>Current implementation</strong></p> <p>I've written this <a href="https://gist.github.com/1282930" rel="nofollow">little function</a> and got something working, but I'm wondering if this can become more efficient or rich in features. My test cases all pass which cover positive and negative ranges.</p> <pre class="lang-c# prettyprint-override"><code>public IEnumerable&lt;int&gt; GetRange(string numbers) { string[] items = numbers.Split(','); foreach (var item in items) { if (!string.IsNullOrWhiteSpace(item)) { //does it contain a -? it's a range then int result; if (item.Contains("-") &amp;&amp; !item.EndsWith("-")) { int start, end; if (int.TryParse(item.Substring(0, item.IndexOf("-")), out start) &amp;&amp; int.TryParse(item.Substring(item.IndexOf("-") + 1), out end)) { int direction = start &lt; end ? 1 : -1; for (result = start; (direction == 1 ? result &lt; end + direction : result &gt; end + direction); result += direction) yield return result; continue; } } if (int.TryParse(item, out result)) { yield return result; continue; } } throw new InvalidCastException(string.Format("Unable to cast \"{0}\" to an int", item)); } } </code></pre>
[ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-10-13T00:31:23.147", "Id": "8119", "Score": "0", "body": "Can there be more than one range? Are non-ranged items sequential?" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-10-13T00:38:52.520", "Id": "8120", "Score": "0", "body": "the ranged items are sequential, by default" } ]
[ { "body": "<p>Ok, some comments:</p>\n\n<ul>\n<li>Code style\n\n<ul>\n<li>While there are no definitive laws about code style, most C# programmers are putting the opening brace <code>{</code> on a separate line. If someone else is going to read your code, they are likely to be annoyed.</li>\n<li>Consider breaking up the method into smaller methods to clarify how it works, which is better than adding comments.</li>\n</ul></li>\n<li><p>Nesting, minimizing nesting makes the code easier to read and in this case you can certainly remove a few levels, namely:</p>\n\n<ul>\n<li><code>if (!string.IsNullOrWhiteSpace(item))</code> can be removed if you instead split the string with the parameter <code>StringSplitOptions.RemoveEmptyEntries</code>.</li>\n<li>If the number cannot be parsed, you could throw the exception when <code>TryParse</code> returns false and keep the \"happy path\" code to run whenever <code>TryParse</code> is successful.</li>\n</ul></li>\n<li><p>Error handling</p>\n\n<ul>\n<li>Since it is <code>TryParse</code> that is failing, you should probably throw a <code>FormatException</code> to indicate invalid format or <code>ArgumentException</code> instead of <code>InvalidCastException</code> to indicate invalid input parameter. Since there is no casting that is failing within the code, this may confuse other developers when debugging the code.</li>\n<li>Stricter validation of input data, for example, to handle the case with the method being invoked with the numbers parameter set to <code>null</code>.</li>\n</ul></li>\n<li><p>Performance</p>\n\n<ul>\n<li>There is always things to improve in this department, however, if the method is fast enough for you, I suggest focusing on readability.</li>\n</ul></li>\n<li>Defect\n\n<ul>\n<li>Invoking the method with a negative range where the first number is negative will not work.</li>\n</ul></li>\n</ul>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2015-12-12T19:42:54.040", "Id": "113758", "ParentId": "5391", "Score": "6" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "2", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-10-13T00:14:41.197", "Id": "5391", "Score": "10", "Tags": [ "c#", "strings", "converting", "integer", "interval" ], "Title": "Converting a range of integers from a string to an IEnumerable" }
5391
<p>The C# code below, using LINQ to Entities, aims to merge all <code>Class</code> entities which have the same <code>SubjectId</code> and the same <code>Students</code>.</p> <pre><code>var sb = new StringBuilder(); var counter = 0; using (var ctx = new Ctx()) { var allClasses = ctx.Classes.Where(o =&gt; o.SubjectId &gt; 0).OrderBy(o =&gt; o.Id).ToList(); foreach (var c in allClasses) ctx.LoadProperty(c, o =&gt; o.Students); // For each class... for (var i = 0; i &lt; allClasses.Count; i++) { var c = allClasses[i]; var duplicates = allClasses .Where(o =&gt; o.SubjectId == c.SubjectId &amp;&amp; o.Id != c.Id &amp;&amp; o.Students.OrderBy(s =&gt; s.Id).Select(s =&gt; s.Id) .SequenceEqual(c.Students.OrderBy(s =&gt; s.Id) .Select(s =&gt; s.Id))) .ToList(); // Does it have any duplicates? if (duplicates.Count == 0) continue; ctx.LoadProperty(c, o =&gt; o.PeriodsTimetable); // For each duplicate... for (var j = 0; j &lt; duplicates.Count; j++) { var d = duplicates[j]; // If the duplicate class has a timetable slot that's not also allocated to // the class we are keeping, then allocate it (otherwise MySql will delete it). ctx.LoadProperty(d, o =&gt; o.PeriodsTimetable); var dt = d.PeriodsTimetable.ToList(); for (var k = 0; k &lt; dt.Count; k++) { var dtp = dt[k]; var tpIsDuplicate = false; foreach (var ctp in c.PeriodsTimetable) { if (dtp.TeacherId == ctp.TeacherId &amp;&amp; dtp.PeriodTime == ctp.PeriodTime) { tpIsDuplicate = true; } } if (!tpIsDuplicate) dtp.ClassId = c.Id; } // Now update all other entities which reference the duplicate to instead // reference the class we are keeping. var dPeriods = ctx.Periods.Where(o =&gt; o.ClassId == d.Id).ToList(); for (var k = 0; k &lt; dPeriods.Count; k++) dPeriods[k].ClassId = c.Id; var dAssessments = ctx.Assessments.Where(o =&gt; o.ClassId == d.Id).ToList(); for (var k = 0; k &lt; dAssessments.Count; k++) dAssessments[k].ClassId = c.Id; var dSeatingPlans = ctx.SeatingPlans.Where(o =&gt; o.ClassId == d.Id).ToList(); for (var k = 0; k &lt; dSeatingPlans.Count; k++) dSeatingPlans[k].ClassId = c.Id; var dMerits = ctx.Merits.Where(o =&gt; o.ClassId == d.Id).ToList(); for (var k = 0; k &lt; dMerits.Count; k++) dMerits[k].ClassId = c.Id; sb.Append(d.LongName).Append(" merged with ").Append(c.LongName).Append(".&lt;br /&gt;"); // Finally, delete the duplicate ctx.Classes.DeleteObject(d); allClasses.Remove(d); counter++; } } ctx.SaveChanges(); lblOutput.Text = "&lt;b&gt;Merged " + counter + " duplicate classes.&lt;/b&gt;&lt;br /&gt;&lt;br /&gt;" + sb.ToString(); } </code></pre> <p>For an idea of scale, there are about 1600 classes with 30 students each, and <code>counter</code> comes out at just over 300.</p> <p>I'd really appreciate any suggestions.</p>
[]
[ { "body": "<p>Your code is <em>very</em> difficult to read. (To give you an idea of <em>how</em> difficult it is, I've been looking at this for the past 2 hours so far)</p>\n\n<ul>\n<li>You are using traditional <code>for</code> loops when you instead should be using <code>foreach</code> loops.</li>\n<li>Your \"loop variables\" are poorly named. Look toward the end of the code. What is a <code>c</code>? What is a <code>d</code>? Leave the shorter names within smaller lambdas, index varialbes and possibly single instances of \"utility\" objects (e.g., <code>StringBuilder</code> or <code>Regex</code>).</li>\n<li>You are trying too hard to write everything within a single line. <code>for</code> loops, <code>if</code> conditions, large queries... all of them should span multiple lines. With perhaps an exception to the <code>if (duplicates.Count == 0) continue;</code> line. I'd be okay with that <em>but</em> you should try to keep those to a minimum (it might be possible that you could code it so that line is not needed).</li>\n<li>You have a long chain of <code>Append()</code>s to the string builder when you really should use a single call to <code>AppendFormat()</code>.</li>\n<li>There are some snippets of your code which would work better either as a separate method or a LINQ query. <em>Use it.</em></li>\n<li>LINQ to Entities should have made associations between your objects so your joins could be replaced by using the navigation properties. If you don't have those set up, you should.</li>\n<li>You also have some useless comments. <code>// For each class...</code> Do we really need a comment to tell us that? Well, maybe since we were using <code>for</code> loops but that should have been avoided in the first place.</li>\n</ul>\n\n<p>You have a lot of performance issues too.</p>\n\n<ul>\n<li>You are calling <code>ToList()</code> on <em>every</em> query when you are simply just enumerating over it most of the time.</li>\n<li>You have a lot of repeated loops on the same collection too. You should be able to do a lot within a single loop.</li>\n<li>Your query for finding duplicates will be a huge hit. I don't have much to say on it right now but it's already making this <code>O(n^2)</code>.</li>\n<li>I have a feeling that you don't need the calls to <code>LoadProperty()</code>. From what I can tell, the majority of your code is filling in data manually when you probably don't need to. Unfortunately I don't know the entity framework enough to know better (though I am looking into it right now).</li>\n</ul>\n\n<p>Applying what I've explained to your code, I'd start with this (hopefully I didn't break anything).</p>\n\n<pre><code>var sb = new StringBuilder();\nvar counter = 0;\nusing (var ctx = new SchoolModel())\n{\n var allClasses = ctx.Classes\n .Where(o =&gt; o.SubjectId &gt; 0)\n .OrderBy(o =&gt; o.Id)\n .ToList(); \n\n foreach (var aClass in allClasses)\n {\n ctx.LoadProperty(aClass, o =&gt; o.Students);\n\n // a properly crafted query could remove this completely and not use LINQ to Objects\n var students = new HashSet&lt;int&gt;(aClass.Students.Select(s =&gt; s.Id));\n var dupClasses = allClasses\n .Where(o =&gt; o.SubjectId == aClass.SubjectId\n &amp;&amp; o.Id != aClass.Id\n &amp;&amp; students.SetEquals(o.Students.Select(s =&gt; s.Id)))\n .ToList();\n\n if (dupClasses.Count == 0) continue;\n\n ctx.LoadProperty(aClass, o =&gt; o.PeriodsTimetable);\n\n foreach (var dupClass in dupClasses)\n {\n // If the duplicate class has a timetable slot that's not also allocated to the\n // class we are keeping, then allocate it (otherwise MySql will delete it).\n ctx.LoadProperty(dupClass, o =&gt; o.PeriodsTimetable);\n\n foreach (var dupTimetable in dupClass.PeriodsTimetable)\n {\n var isDuplicate = aClass.PeriodsTimetable\n .Any(ctp =&gt; dupTimetable.TeacherId == ctp.TeacherId\n &amp;&amp; dupTimetable.PeriodTime == ctp.PeriodTime);\n if (!isDuplicate)\n dupTimetable.ClassId = aClass.Id;\n }\n\n // Now update all other entities which reference the duplicate to instead reference\n // the class we are keeping.\n foreach (var dupPeriod in dupClass.Periods)\n dupPeriod.ClassId = aClass.Id;\n foreach (var dupAssessment in dupClass.Assessments)\n dupAssessment.ClassId = aClass.Id;\n foreach (var dupSeatingPlan in dupClass.SeatingPlans)\n dupSeatingPlan.ClassId = aClass.Id;\n foreach (var dupMerit in dupClass.Merits)\n dupMerit.ClassId = aClass.Id;\n\n sb.AppendFormat(\"{0} merged with {1}.&lt;br /&gt;\", dupClass.LongName, aClass.LongName);\n\n // Finally, delete the duplicate\n ctx.Classes.DeleteObject(dupClass);\n\n // not sure this is really needed\n allClasses.Remove(dupClass);\n counter++;\n }\n }\n ctx.SaveChanges();\n Output = \"&lt;b&gt;Merged \" + counter + \" duplicate classes.&lt;/b&gt;&lt;br /&gt;&lt;br /&gt;\" + sb.ToString();\n}\n</code></pre>\n\n<p>That's my initial analysis so far. I'll update some more once I've gained understanding on what you are doing. As I've said, it is <em>very</em> difficult to read. I'll probably offer more improvements once I've had a chance to look at it more.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-10-16T20:59:07.583", "Id": "8143", "Score": "0", "body": "Thank you very much for looking into this. I like some of your ideas and will implement them. In response to a few of your points: (1) The compiler won't let me use foreach because the enumerable collection is modified in each case (though I'm not sure how in some cases), (2) The variable names made sense to me, e.g. c=class, d=duplicate, and I'm working on this project alone, but I accept that they are unclear - sorry, (3) Without `ToList()` when looping through, for example, `PeriodsTimetable`, an error is thrown about updating references. Again I'm afraid I don't understand why." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-10-16T21:12:48.940", "Id": "8144", "Score": "0", "body": "For points (1) and (3), you probably would be able to use `AsEnumerable()` instead of calling `ToList()`. It would seem that updating objects when enumerating through an entity set is not possible. Using `AsEnumerable()` would force using LINQ to Objects and hopefully allow this to work without being forced to throw them into a list." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-10-16T21:26:11.397", "Id": "8145", "Score": "0", "body": "No luck, I'm afraid. The type is already `IEnumerable<EntityName>` so AsEnumerable() has no effect. I very much like your `HashSet<int>`, `PeriodsTimetable.Any` and `sb.AppendFormat` improvements and am testing them now. Thanks again." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-10-17T02:02:33.003", "Id": "8148", "Score": "0", "body": "Ah, after having thought about it, I could now see why that would cause problems. We're changing the FK so it would alter the collection indirectly since the changes are tracked. I'm still exploring what would be the better way to handle this. I _think_ you might be able to do something like this instead (looking at the period updates): `dupPeriod.Class = aClass;` instead of changing the id's, it will all be handled for you (and no need to use `ToList()`). I hope I just didn't butcher that explanation. :)" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-10-19T18:08:38.217", "Id": "8294", "Score": "0", "body": "I have a few remarks because small parts of the code go back to my answer on StackOverflow: http://stackoverflow.com/questions/7780455/detect-entities-which-have-the-same-children/7780935#7780935 . 1) `LoadProperty` (explicite loading) is ugly ideed and the code is a typical case where one would tend to use `Include` (eager loading). However, it has serious performance problems (see James' comment to my answer about the perf. gain with explicite loading). 2) You cannot move `LoadProperty(aClass, o => o.Students)` into the main loop because the inner query for `dupClasses` will fetch classes..." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-10-19T18:08:55.987", "Id": "8295", "Score": "0", "body": "...which haven't been met yet in the main loop. Therefore the `Students` collection is empty or `null`. So the result would be wrong or the code will crash. Hence `LoadProperty` must be in that separate loop before. 3) I recommended to do the identification for duplicates in memory with LINQ to Objects because LINQ to Entities has many limitations and to find a LINQ query which is translatable into SQL might be hard (see exception in James' question in the SO link above). With your other points I agree, and learning that `HashSet` has a `SetEquals` method was worth alone the look here :)" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-10-19T18:16:40.100", "Id": "8297", "Score": "0", "body": "@Slauma: Thank you for reviewing my review to a Code Review review. :) I'm sure James did the right thing with that `LoadProperty`. I knew L2E has issues with some complex queries, thanks for pointing that out. I was a bit overambitious with some of the changes in my example though." } ], "meta_data": { "CommentCount": "7", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-10-16T20:48:16.893", "Id": "5402", "ParentId": "5396", "Score": "8" } } ]
{ "AcceptedAnswerId": "5402", "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-10-16T07:54:45.283", "Id": "5396", "Score": "3", "Tags": [ "c#", ".net", "linq", "entity-framework" ], "Title": "Merge entities which have the same children" }
5396
<p>I've been teaching myself Python3 for about a week now and I decided to put my skills to the test by writing a simple Tic-Tac-Toe game. Here is what I came up with:</p> <pre><code>#!/usr/bin/env python3 import random board = [0]*9 def resetBoard(): for index, i in enumerate(board): board[index] = 0 def printBoard(): counter = 0 s = "" print("|-----|-----|-----|") for index, i in enumerate(board): s += "| " if(board[index] == 0): s += str(index) if(board[index] == 1): s+= "x" if(board[index] == 2): s += "o" s += " " counter += 1 if(counter == 3): s += "|" print(s) print("|-----|-----|-----|") s = "" counter = 0 def getPlayers(): return input("1 or 2 Players?") def moveSquare(xOro, ai): square = 0 flag = 0 while(board[square] != 0 or flag == 0): if(ai == 0): if(xOro == 1): square = eval(input("Choose a square to place X: ")) if(xOro == 2): square = eval(input("Choose a square to place O: ")) if(ai == 1): square = random.randint(0, 8) flag = 1 board[square] = xOro print("\n\n") def checkForWin(): if(board[0] == board[1] and board[1] == board[2] and board[2] != 0): return 1 if(board[3] == board[4] and board[4] == board[5] and board[5] != 0): return 1 if(board[6] == board[7] and board[7] == board[8] and board[8] != 0): return 1 if(board[0] == board[3] and board[3] == board[6] and board[6] != 0): return 1 if(board[1] == board[4] and board[4] == board[7] and board[7] != 0): return 1 if(board[2] == board[5] and board[5] == board[8] and board[8] != 0): return 1 if(board[0] == board[4] and board[4] == board[8] and board[8] != 0): return 1 if(board[2] == board[4] and board[4] == board[6] and board[6] != 0): return 1 for index, i in enumerate(board): if(i == 0): break if(index == 8): return 2 return 0 def gameOver(): return eval(input("\nPress 0 and then ENTER to play again!")) # Main random.seed() quit = 0 while(quit == 0): players = 0 win = 0 while(players != 1 and players != 2): players = eval(getPlayers()) resetBoard() game = 0 #game = 1 when game is finished while(game == 0): #game loop printBoard() moveSquare(1, 0) game = checkForWin() if(game &gt; 0): win = game break printBoard() if(players == 1): moveSquare(2, 1) if(players == 2): moveSquare(2, 0) game = checkForWin() if(game &gt; 0): win = game + 1 break if(win == 1): print("\nX Wins!") if(win == 2): print("\nO Wins!") if(win == 3): print("\n The game is a draw!") quit = gameOver() exit() </code></pre> <p>I am interested in the following points about my code:</p> <ul> <li>How can I make my code smaller and more optimized?</li> <li>The game displays "O Wins" instead of "The game is a draw!" and I'm not sure why.</li> <li>How can I sanitize input to prevent crashes if a string is entered instead of an integer (for example when choosing a square on the board)?</li> <li>Any additional points to improve my code or general tips that will help me become a better Python programmer.</li> </ul>
[]
[ { "body": "<p>Couple of comments on general style:</p>\n\n<pre><code>while(players != 1 and players != 2):\n players = eval(getPlayers())\n</code></pre>\n\n<p>I would expect getPlayers() to get the player information and do any error handling.\nThus in the main loop this should just be a single call:</p>\n\n<pre><code>players = getPlayers()\n</code></pre>\n\n<p>You have lots of places where you do the same thing in two different ways:</p>\n\n<pre><code> if(players == 1):\n moveSquare(2, 1)\n if(players == 2):\n moveSquare(2, 0)\n</code></pre>\n\n<p>You can simplify this as</p>\n\n<pre><code> moveSquare(2, players - 1)\n</code></pre>\n\n<p>Same sort of thing here:</p>\n\n<pre><code>if(win == 1):\n print(\"\\nX Wins!\")\nif(win == 2):\n print(\"\\nO Wins!\")\nif(win == 3):\n print(\"\\n The game is a draw!\")\n</code></pre>\n\n<p>Can be much neater like this:</p>\n\n<pre><code>print(result[win]) # Now just define the result array.\n</code></pre>\n\n<p>Your problem with printing the wrong thing on a draw is here:</p>\n\n<pre><code> if(game &gt; 0):\n win = game\n break\n</code></pre>\n\n<p>Notice this is different from your second check here</p>\n\n<pre><code> game = checkForWin()\n if(game &gt; 0):\n win = game + 1\n break\n</code></pre>\n\n<p>So checkForWin() returns 0 for no winner 1 for winner and 2 for a draw.\nThe first check above will result in win being 1 or 2 even for a draw, while the second check will result in 2 or 3 (which is probably correct).</p>\n\n<p>What you really want to do is make checkForWin() return the result you are looking for.</p>\n\n<pre><code>0: for no winner\n1: for player one\n2: for player two\n3: for a draw.\n</code></pre>\n\n<p>You can even optimize checkForWin() by passing in the player that made the last move and the position they played in (as the winning move will include their last move).</p>\n\n<pre><code>#!/usr/bin/env python3\n\nimport random\n\n\n# Put the ID of the square in each square for easy printing.\n# We will put 'X' or 'O' in the square as we make each move\ndef resetBoard(board):\n for index, i in enumerate(board):\n board[index] = index\n\n# Print the board\ndef printBoard(board):\n s = \"\"\n for index, i in enumerate(board):\n s += \"| %s \" % i\n if((index % 3) == 2):\n print(\"|-----|-----|-----|\\n%s|\" % s)\n s = \"\"\n print(\"|-----|-----|-----|\")\n\n# Function to get the human mve\ndef humanMove(playerToMove, board):\n\n print \"Human Move (%s)\" % playerToMove\n return eval(raw_input(\"Choose a square to place %s: \" % playerToMove))\n\n# Function to get the AI move\ndef aiMove(playerToMove, board):\n\n print \"AI Move (%s)\" % playerToMove\n return random.randint(0, 8)\n\ndef moveSquare(playerToMove, players, board):\n # Get the move from the cuttrny player\n # Note this passes weather they are an 'X' or an 'O' \n # as a parameter.\n FirstTry = False\n square = 0\n while(board[square] == 'X' or board[square] == 'O' or FirstTry):\n square = players[playerToMove](playerToMove, board)\n FirstTry = False;\n board[square] = playerToMove # Puts an 'X' or an 'O' on the board\n print(\"\\n\\n\")\n\n#\n# This function returns a dictionary with move move functions.\n# So on 'X' move call the result{'X'} function to get a move\n# So we have to decide how to fill the dictionary based on user input.\ndef getPlayers():\n players = 0;\n while players != 1 and players != 2:\n players = input(\"1 or 2 Players?\")\n\n if players == 2:\n # Two players so both elements call the humanMove function\n return {'X': humanMove, 'O': humanMove}\n\n if players == 1:\n human = '?'\n while human != 'X' and human != 'O':\n human = raw_input(\"Do you want to play X or O\");\n if human == 'X':\n # Human is playing X ai is playing O so functions set appropriately.\n return {'X': humanMove, 'O': aiMove}\n else:\n return {'X': aiMove, 'O': humanMove}\n\n\n#\n# Return 'X' for winner is X\n# Return 'O' for winner is O\n# Return 'D' for a draw\n# Return 'R' for game is still running.\ndef checkForWin(board):\n if(board[0] == board[1] and board[1] == board[2] and board[2] != 0):\n return board[0]\n if(board[3] == board[4] and board[4] == board[5] and board[5] != 0):\n return board[3]\n if(board[6] == board[7] and board[7] == board[8] and board[8] != 0):\n return board[6]\n if(board[0] == board[3] and board[3] == board[6] and board[6] != 0):\n return board[0]\n if(board[1] == board[4] and board[4] == board[7] and board[7] != 0):\n return board[1]\n if(board[2] == board[5] and board[5] == board[8] and board[8] != 0):\n return board[2]\n if(board[0] == board[4] and board[4] == board[8] and board[8] != 0):\n return board[0]\n if(board[2] == board[4] and board[4] == board[6] and board[6] != 0):\n return board[2]\n\n # No winner yet\n # decide if the game is still running.\n for index, i in enumerate(board):\n if(i != 'X' or i != 'O'):\n return 'R'\n\n # No empty squares so it must be a draw.\n return 'D'\n\ndef gameOver():\n return raw_input(\"\\nPress 0 and then ENTER to play again!\")\n\n# Main\nrandom.seed()\nquit = \"0\"\nboard = [0]*9\n\nwhile(quit == \"0\"):\n resetBoard(board)\n winner = 'R'\n players = getPlayers()\n playerOrder = ['X', 'O']\n currentPlayer = 0;\n while True:\n printBoard(board)\n\n moveSquare(playerOrder[currentPlayer], players, board)\n winner = checkForWin(board)\n if winner != 'R':\n break\n\n currentPlayer = (currentPlayer + 1) % 2\n\n result = { 'X': \"X Wins!\",'O': \"O Wins!\", 'D': \"The game is a draw!\"}\n print \"\\n%s\\n\" % result[winner];\n\n quit = gameOver()\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-10-16T18:35:40.993", "Id": "8142", "Score": "1", "body": "I think you've misunderstood the second argument to moveSquare. The first argument is the player number. The second number indicates whether or not this is an AI player." } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-10-16T17:54:32.303", "Id": "5398", "ParentId": "5397", "Score": "1" } }, { "body": "<pre><code>#!/usr/bin/env python3\n\nimport random\n\nboard = [0]*9\n</code></pre>\n\n<p>Having global variables that change is considered a bad idea. You'd be better off putting this variable and the methods inside a class.</p>\n\n<pre><code>def resetBoard():\n for index, i in enumerate(board):\n board[index] = 0\n</code></pre>\n\n<p>You could also do <code>board[:] = [0] * 9</code></p>\n\n<pre><code>def printBoard():\n counter = 0\n</code></pre>\n\n<p>In python you rarely need to keep track of counters like this</p>\n\n<pre><code> s = \"\"\n</code></pre>\n\n<p>In python, you should avoid building strings by adding different pieces together</p>\n\n<pre><code> print(\"|-----|-----|-----|\")\n for index, i in enumerate(board):\n s += \"| \"\n if(board[index] == 0):\n</code></pre>\n\n<p>The point of enumerate is that <code>i</code> is the value in board. Use it rather then refetching it here.</p>\n\n<pre><code> s += str(index)\n if(board[index] == 1):\n s+= \"x\"\n if(board[index] == 2):\n s += \"o\"\n s += \" \"\n</code></pre>\n\n<p>By building the string this way its hard to follow exactly what the string is.</p>\n\n<pre><code> counter += 1\n if(counter == 3):\n</code></pre>\n\n<p>Instead of making the counter use `if index % 3 == 2:' Also you don't need the parens</p>\n\n<pre><code> s += \"|\"\n print(s)\n print(\"|-----|-----|-----|\")\n s = \"\"\n counter = 0\n</code></pre>\n\n<p>Your whole algorithm here is rendered more complicated because you are iterating over cells rather the rows. Your algorithm would be much more natural with rows</p>\n\n<pre><code>def getPlayers():\n return input(\"1 or 2 Players?\")\n</code></pre>\n\n<p>Shouldn't this return an int, not a string?</p>\n\n<pre><code>def moveSquare(xOro, ai):\n</code></pre>\n\n<p>variable names are recommended to follow x_or_o as a naming convetion</p>\n\n<pre><code> square = 0\n flag = 0\n</code></pre>\n\n<p>If this is a boolean flag, use False not 0</p>\n\n<pre><code> while(board[square] != 0 or flag == 0):\n</code></pre>\n\n<p>No need for the parens around the while expression</p>\n\n<pre><code> if(ai == 0):\n</code></pre>\n\n<p>Again use True/False for boolean flags. No need for parens</p>\n\n<pre><code> if(xOro == 1):\n square = eval(input(\"Choose a square to place X: \"))\n if(xOro == 2):\n square = eval(input(\"Choose a square to place O: \"))\n</code></pre>\n\n<p>Avoid magic numbers like 1 and 2 to denote X and O. In this case, I'd probably pass 'x' or 'o' strings.</p>\n\n<pre><code> if(ai == 1):\n</code></pre>\n\n<p>Use an else:</p>\n\n<pre><code> square = random.randint(0, 8)\n flag = 1\n</code></pre>\n\n<p>Flag is really terrible variable name because I don't know what it means. Boolean flags are usually an ugly solution</p>\n\n<pre><code> board[square] = xOro\n print(\"\\n\\n\")\n\ndef checkForWin():\n if(board[0] == board[1] and board[1] == board[2] and board[2] != 0):\n return 1\n</code></pre>\n\n<p>Don't use magic numbers like that. Instead create some global constants to return or something</p>\n\n<pre><code> if(board[3] == board[4] and board[4] == board[5] and board[5] != 0):\n return 1\n if(board[6] == board[7] and board[7] == board[8] and board[8] != 0):\n return 1\n if(board[0] == board[3] and board[3] == board[6] and board[6] != 0):\n return 1\n if(board[1] == board[4] and board[4] == board[7] and board[7] != 0):\n return 1\n if(board[2] == board[5] and board[5] == board[8] and board[8] != 0):\n return 1\n if(board[0] == board[4] and board[4] == board[8] and board[8] != 0):\n return 1\n if(board[2] == board[4] and board[4] == board[6] and board[6] != 0):\n return 1\n</code></pre>\n\n<p>A lot duplication here. </p>\n\n<pre><code> for index, i in enumerate(board):\n if(i == 0):\n break\n if(index == 8):\n return 2\n return 0\n\ndef gameOver():\n return eval(input(\"\\nPress 0 and then ENTER to play again!\"))\n</code></pre>\n\n<p>Eval is a bit dangerous because the user can put in anything they want.</p>\n\n<pre><code># Main\n</code></pre>\n\n<p>You should your main logic in a function</p>\n\n<pre><code>random.seed()\nquit = 0\nwhile(quit == 0):\n</code></pre>\n\n<p>Make quite a boolean variable</p>\n\n<pre><code> players = 0\n win = 0\n while(players != 1 and players != 2):\n players = eval(getPlayers())\n resetBoard()\n game = 0 #game = 1 when game is finished\n</code></pre>\n\n<p>Game becoming 1 when the game is finished seems backwards</p>\n\n<pre><code> while(game == 0): #game loop\n printBoard()\n moveSquare(1, 0)\n game = checkForWin()\n if(game &gt; 0):\n win = game\n break\n</code></pre>\n\n<p>Not much point checking game == 0 above if you are just going to break anyways</p>\n\n<pre><code> printBoard()\n if(players == 1):\n moveSquare(2, 1)\n if(players == 2):\n moveSquare(2, 0)\n game = checkForWin()\n if(game &gt; 0):\n win = game + 1\n break\n</code></pre>\n\n<p>See how the two parts of the loop are very similar? Suggests that you should get rid of the duplication.</p>\n\n<pre><code> if(win == 1):\n print(\"\\nX Wins!\")\n if(win == 2):\n print(\"\\nO Wins!\")\n if(win == 3):\n print(\"\\n The game is a draw!\")\n quit = gameOver()\n</code></pre>\n\n<p>Having gameOver() return whether or not you should quit seems confusing. The name doesn't suggest that</p>\n\n<pre><code>exit()\n</code></pre>\n\n<p>Not much point in calling quit, the program is about to terminate anyways</p>\n\n<p>And just to demonstrate how I'd do this:</p>\n\n<pre><code>#!/usr/bin/env python3\nimport random\n\nWINNING_LINES = [\n [0, 1, 2],\n [3, 4, 5],\n [5, 6, 7],\n\n [0, 3, 5],\n [1, 4, 6],\n [2, 5, 7],\n\n [0, 4, 7],\n [2, 4, 5]\n]\n\nSTALEMATE = '!'\n\nclass TicTacToe(object):\n def __init__(self):\n self.board = [' '] * 9\n\n def print(self):\n # make a copy of the board\n cells = self.board[:] \n\n # put a digit in every blank cell\n for index, cell in enumerate(cells):\n if cell == ' ':\n cells[index] = str(index)\n\n # put spaces around the cells\n cells = [' %s ' % cell for cell in cells]\n\n # print the actual board\n print('|---|---|---|')\n for start in range(0, 9, 3):\n row = cells[start:start+3]\n print('|', '|'.join(row), '|', sep = '')\n print('|---|---|---|')\n\n def move_square(self, player, ai):\n square = -1\n while square &lt; 0 or square &gt;= 9 or self.board[square] != ' ':\n if ai:\n square = random.randrange(9)\n else:\n question = \"Choose a square to place {}:\".format(player.upper())\n square_text = input(question)\n print(square_text)\n try:\n square = int(square_text)\n except ValueError:\n # user didn't enter a number\n square = -1\n self.board[square] = player\n print(\"\\n\\n\")\n\n def status(self):\n # check for a win\n for a, b, c in WINNING_LINES:\n if self.board[a] == self.board[b] and self.board[b] == self.board[c] and self.board[a] != ' ':\n return self.board[a]\n\n if not any(cell == ' ' for cell in self.board):\n return STALEMATE\n return ' '\n\ndef get_players():\n while True:\n text = input(\"1 or 2 players\")\n try:\n value = int(text)\n except ValueError:\n pass\n else:\n if 0 &lt; value &lt; 3:\n return value\n\n\n\n\ndef play_again():\n return input(\"\\nPress 0 and then ENTER to play again!\") == '0'\n\nGAME_OVER_MESSAGES = {\n 'X' : 'X wins!',\n 'O' : 'O wins!',\n '!' : 'The game is a draw!'\n}\n\ndef main():\n\n while True:\n\n # create a list to denote whether\n # a player is AI\n ai_players = [False, False]\n if get_players() == 1:\n ai_players[1] = True\n\n\n tic_tac_toe = TicTacToe()\n player_turn = 0\n player_codes = 'XY'\n while tic_tac_toe.status() == ' ':\n tic_tac_toe.print()\n tic_tac_toe.move_square(player_codes[player_turn], ai_players[player_turn])\n player_turn = (player_turn + 1) % 2\n\n print(GAME_OVER_MESSAGES[tic_tac_toe.status()])\n\n if not play_again():\n break\n\n\nif __name__ == '__main__':\n main()\n</code></pre>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-10-16T17:58:43.080", "Id": "5399", "ParentId": "5397", "Score": "5" } } ]
{ "AcceptedAnswerId": "5399", "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-10-16T17:27:43.593", "Id": "5397", "Score": "3", "Tags": [ "python", "optimization", "game", "python-3.x" ], "Title": "Improving and optimizing Tic-Tac-Toe game written in Python 3" }
5397
<p>How can I make the following PHP code better, more efficient, shorter, elegant, etc? While it already works, I am still learning PHP and want to improve upon my current code:</p> <pre><code>&lt;?php $query = 'psoriasis'; $eSearchQueryParameters = array( 'db' =&gt; 'pubmed', 'term' =&gt; $query, 'retmode' =&gt; 'xml', 'retstart' =&gt; '0', 'retmax' =&gt; '500', 'usehistory' =&gt; 'y', ); $eSearchQueryResults = simplexml_load_file('http://eutils.ncbi.nlm.nih.gov/entrez/eutils/esearch.fcgi?' . http_build_query($eSearchQueryParameters)); $eFetchQueryParameters = array( 'db' =&gt; 'pubmed', 'retmax' =&gt; '500', 'query_key' =&gt; (string) $eSearchQueryResults-&gt;QueryKey, 'WebEnv' =&gt; (string) $eSearchQueryResults-&gt;WebEnv, ); $eFetchURL = 'http://eutils.ncbi.nlm.nih.gov/entrez/eutils/efetch.fcgi?' . http_build_query($eFetchQueryParameters); $matches = array(); preg_match_all('/[A-Za-z0-9._%+-]+@[A-Za-z0-9.-]+\.[A-Za-z]{2,4}/', file_get_contents($eFetchURL), $matches); foreach ($matches[0] as $key =&gt; $value) { echo $value . "&lt;br /&gt;"; } ?&gt; </code></pre>
[ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2015-12-15T10:13:53.103", "Id": "211213", "Score": "0", "body": "[Follow-up question](http://codereview.stackexchange.com/q/5485/9357)" } ]
[ { "body": "<p>In my humble opinion, the version below is more elegant, easier to read and to maintain.</p>\n\n<p>It uses a class to keep things more organized.</p>\n\n<p>I would consider the code below as a <strong>starting point</strong> to start being improved, with things like error checking, etc.</p>\n\n<p>I hope you like, and maybe learn something from it.</p>\n\n<pre><code>&lt;?php\n\nclass MyQuery\n{\n public $query = '';\n\n public $search_url = 'http://eutils.ncbi.nlm.nih.gov/entrez/eutils/esearch.fcgi?';\n public $fetch_url = 'http://eutils.ncbi.nlm.nih.gov/entrez/eutils/efetch.fcgi?';\n\n public $search_parameters = array(\n 'db' =&gt; 'pubmed',\n 'term' =&gt; '',\n 'retmode' =&gt; 'xml',\n 'retstart' =&gt; '0',\n 'retmax' =&gt; '500',\n 'usehistory' =&gt; 'y'\n );\n\n public $fetch_parameters = array(\n 'db' =&gt; 'pubmed',\n 'retmax' =&gt; '500',\n 'query_key' =&gt; '',\n 'WebEnv' =&gt; ''\n );\n\n public $search_results;\n public $fetch_results;\n public $matches = array();\n\n public $match_regex = '/[A-Za-z0-9._%+-]+@[A-Za-z0-9.-]+\\.[A-Za-z]{2,4}/';\n\n public __constructor( $query )\n {\n $this-&gt;query = $query;\n }\n\n public search()\n {\n $this-&gt;search_parameters['term'] = $this-&gt;query;\n $url = $this-&gt;search_url . http_build_query( $this-&gt;search_parameters );\n $this-&gt;search_results = simplexml_load_file( $url );\n }\n\n public fetch()\n {\n $this-&gt;fetch_parameters['query_key'] = (string) $this-&gt;search_results-&gt;QueryKey;\n $this-&gt;fetch_parameters['WebEnv'] = (string) $this-&gt;search_results-&gt;WebEnv\n $url = $this-&gt;fetch_url . http_build_query( $this-&gt;fetch_parameters );\n $this-&gt;fetch_results = file_get_contents( $url );\n }\n\n public match()\n {\n $matches = array();\n preg_match_all( $this-&gt;match_regex, $this-&gt;fetch_results, $matches );\n $this-&gt;matches = array_values( $matches[0] );\n }\n\n public get()\n {\n $this-&gt;search();\n $this-&gt;fetch();\n $this-&gt;match();\n return $this-&gt;matches;\n }\n}\n\n$query = new MyQuery( 'psoriasis' );\n$result = $query-&gt;get();\necho implode( '&lt;br /&gt;', $result );\n\n?&gt;\n</code></pre>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-10-17T02:37:36.223", "Id": "5408", "ParentId": "5400", "Score": "2" } } ]
{ "AcceptedAnswerId": "5408", "CommentCount": "1", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-10-16T20:12:45.433", "Id": "5400", "Score": "1", "Tags": [ "php", "web-scraping", "url" ], "Title": "Scraping PubMed query results" }
5400
<p>So I built a little baseball "scouting report" graphic that shows stats for players. As you page through the players, their images slide in and out of the graphic. I worked out a way to do this using a jQuery queue, and it works fairly well.</p> <p>The one hitch is when the graphic is changing from a player on one side of the plate to the other (from a lefty to a righty, for example). Rather than smoothly sliding in, the player just appears there.</p> <p>I can't work out why that is happening. The transitions are always smooth when they are between players who bat on the same side.</p> <p>I have stripped this code down to essentially just the parts that deal with the animation queue/sliding. Could you take a look and show me areas where it could be improved?</p> <p>You can see it in action here: <a href="http://dl.dropbox.com/u/27409695/mlb-scouting/baseball-test.html" rel="nofollow">http://dl.dropbox.com/u/27409695/mlb-scouting/baseball-test.html</a></p> <pre><code>testArray = []; testArray[0] = ['Andrus','XXX','R']; testArray[1] = ['Beltre','XXX','R']; testArray[2] = ['Chavez','XXX','L']; testArray[3] = ['Hamilton','XXX','L']; jQuery(document).ready(function($) { buildSelectList(); $('playerPhoto').hide(); $('#scoutSelect').live('change', function(event) { var userChoice = $(this).val(); if ( userChoice === 'Choose player' ) { return false; } else if (!$('*').is(':animated')) { playerQueue(userChoice); } }); $('.arrow').live('click', function(event) { var player = $(this).attr('player'); if (player !== null &amp;&amp; !$('*').is(':animated') ) { playerQueue(player); } }); jQuery.getScript('http://ajax.googleapis.com/ajax/libs/jqueryui/1.8.16/jquery-ui.min.js', function(){ startUp(); }); }); function buildSelectList() { var playerLength = testArray.length; for (i=0; i &lt; playerLength; i++ ) { jQuery('&lt;option value="'+i+'"&gt;'+testArray[i][1]+' '+testArray[i][0]+'&lt;/option&gt;').appendTo('#scoutSelect'); } } function startUp() { var theQueue = jQuery('#scouting'); var thisPlayerL = jQuery('#playerPhotoL'); var thisPlayerR = jQuery('#playerPhotoR'); var playerHand = testArray[0][2]; theQueue.queue('josh', function() { buildPlayer(0); theQueue.dequeue('josh'); }); theQueue.queue('josh', function() { if (playerHand === 'R') { thisPlayerR.switchClass('offstage','onstage',1500); } else if (playerHand === 'L') { thisPlayerL.switchClass('offstage','onstage',1500); } theQueue.dequeue('josh'); }); theQueue.dequeue('josh'); } function playerQueue(playerID) { var theQueue = jQuery('#scouting'); var thisPlayerL = jQuery('#playerPhotoL'); var thisPlayerR = jQuery('#playerPhotoR'); var playerHand = testArray[playerID][2]; theQueue.queue('josh', function() { if (thisPlayerL.hasClass('onstage') ) { thisPlayerL.switchClass('onstage','offstage',1500); } else if (thisPlayerR.hasClass('onstage') ) { thisPlayerR.switchClass('onstage','offstage',1500); } theQueue.dequeue('josh'); }); theQueue.queue('josh', function() { setTimeout("buildPlayer("+playerID+")",1500); theQueue.dequeue('josh'); }); theQueue.queue('josh', function() { if (playerHand === 'R') { thisPlayerR.switchClass('offstage','onstage',1500); } else if (playerHand === 'L') { thisPlayerL.switchClass('offstage','onstage',1500); } theQueue.dequeue('josh'); }); theQueue.dequeue('josh'); } function buildPlayer(playerID) { var testArraySize = testArray.length; // make sure playerID is an integer not a string playerID = parseInt(playerID,10); // update the arrows' player IDs var prevPlayer = ''; var nextPlayer = ''; if ((playerID &gt; 0) &amp;&amp; (playerID &lt; testArraySize-1)) { prevPlayer = playerID - 1; nextPlayer = playerID + 1; } else if (playerID === 0) { prevPlayer = testArraySize-1; nextPlayer = 1; } else if (playerID === testArraySize-1) { prevPlayer = playerID - 1; nextPlayer = 0; } jQuery('#prevArrow').attr('player',prevPlayer); jQuery('#nextArrow').attr('player',nextPlayer); // player info jQuery('#scouting h1').text(testArray[playerID][0]); showPlayer(playerID); } function showPlayer(playerID) { jQuery('#playerPhotoL img').remove(); jQuery('#playerPhotoR img').remove(); var playerName = testArray[playerID][0]; var playerHand = testArray[playerID][2]; jQuery('&lt;img src="http://dl.dropbox.com/u/27409695/mlb-scouting/lineup/Rangers/'+playerName+'.png" /&gt;') .appendTo('#playerPhoto'+playerHand); } </code></pre>
[]
[ { "body": "<p>I think you need to keep it simple. This seems much more complicated than need be.</p>\n\n<p>For example why are you removing and then creating again?:</p>\n\n<pre><code>jQuery('#playerPhotoL img').remove();\njQuery('#playerPhotoR img').remove();\n\nvar playerName = testArray[playerID][0];\nvar playerHand = testArray[playerID][2];\n\njQuery('&lt;img src=\"http://dl.dropbox.com/u/27409695/mlb-scouting/lineup/Rangers/'+playerName+'.png\" /&gt;')\n .appendTo('#playerPhoto'+playerHand);\n</code></pre>\n\n<p>I would approach this differently. Firstly make your players into literal objects:</p>\n\n<pre><code>var players = [{\n 'name': 'Andrus',\n 'somethingelse': 'XXX',\n 'hand': 'R'\n },\n {\n 'name': 'Beltre',\n 'somethingelse': 'XXX',\n 'hand': 'R'\n },\n {\n 'name': 'Chavez',\n 'somethingelse': 'XXX',\n 'hand': 'L'\n },\n {\n 'name': 'Hamilton',\n 'somethingelse': 'XXX',\n 'hand': 'L'\n }\n];\n</code></pre>\n\n<p>This way you don't have to remember what information is in what element of the list.</p>\n\n<p>Then creat functions: </p>\n\n<ul>\n<li>next arrow click: <code>moveNextPlayer</code></li>\n<li>prev arrow click: <code>movePrevPlayer</code></li>\n<li>Select on change: <code>moveToPlayer</code></li>\n</ul>\n\n<p>and one to animate called <code>_movePlayers(toPlayerIndex)</code></p>\n\n<p>here is a jsfiddle to get you started: <a href=\"http://jsfiddle.net/Skt6F/\" rel=\"nofollow\">http://jsfiddle.net/Skt6F/</a></p>\n\n<p><strong>EDIT:-</strong> further on the objects issue ... you have:</p>\n\n<pre><code>testArray = [];\ntestArray[0] = ['R',0.169,0.311,0.236,0.288,0.436,0.314,0.27,0.35,0.232,20,26,15,27,null,15,26,31,16,0.253,0.443,0.268,0.353,0.473,0.357,0.348,0.447,0.232,28.9,12.4,14.7,9.6,14.3,20.1,0.288,0.283,0.303,0.225,0.229,0.214,0.254,0.241,0.348,0.231,0.242,0.219,59.9,42.2,12.5];\ntestArray[1] = ['Beltre','Adrian','R',];\ntestArray[2] = ...\n</code></pre>\n\n<p>Its still better to have:</p>\n\n<pre><code>var playerData = [{ 'firstName': 'Andrus', 'lastName':'Elvis', 'hand': 'R', 'stats':\n [0.263,0.372,0.285,0.337,0.527,0.302,0.323,0.344,0.329,28,40,31,35,null,38,29,45,34,0.491,0.755,0.416,0.742,1.194,0.55,0.569,0.689,0.519,23.5,7.6,8,22.3,17.8,20.7,0.325,0.323,0.33,0.245,0.267,0.174,0.275,0.269,0.318,0.293,0.205,0.358,38.5,60.4,12.1]\n },\n { 'firstName': etc\n }\n\n];\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-10-18T01:31:24.257", "Id": "8195", "Score": "0", "body": "You have some good ideas here. I am somewhat new to scripting, so the idea of objects didn't occur to me. They make perfect sense here. The only problem I can see is that the actual application involves more than just the players' names and handedness. There are about 30 different statistical categories in each of the player's arrays (as it exists now)." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-10-18T01:34:49.990", "Id": "8196", "Score": "0", "body": "I did embrace your suggestion of not removing and creating the images, and the solution I came up with has eliminated the \"sudden appearance\" problem I described above. Now all the animation is smooth as silk. You can see it here: http://dl.dropbox.com/u/27409695/mlb-scouting/baseball-test.html" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-10-18T02:38:39.880", "Id": "8197", "Score": "0", "body": "@Kirkman14 you still have the data in lists instead of objects. This is going to be a big problem when you need to revise this six months down the track. Its a very good idea to turn them into objects early on. You can even put categories and their stats in a list inside a property. Check out my edit." } ], "meta_data": { "CommentCount": "3", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-10-17T06:46:25.057", "Id": "5412", "ParentId": "5401", "Score": "2" } } ]
{ "AcceptedAnswerId": "5412", "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-10-16T20:42:07.587", "Id": "5401", "Score": "4", "Tags": [ "javascript", "jquery", "queue" ], "Title": "Trying to improve my jQuery animation queue" }
5401
<p>I'm somewhat new to Scala and am not sure if I'm doing things in a very Scala-esque way.</p> <p>In particular, I'm not sure if I'm using <code>Option</code> correctly, since by calling <code>.isDefined</code>, I'm basically just doing ye olde Java null check. Also, the <code>getMethodAndAnnotationFromInfaces</code> method could probably be done better.</p> <p>Please point out ways in which I could better leverage language features in the below code:</p> <pre><code>for (val method &lt;- clazz.getMethods) { val methodAndAnnotation = method.getAnnotation(annotationType) match { case annotation: MessageHandler =&gt; Some((method, annotation)) case _ =&gt; getMethodAndAnnotationFromInterfaces(clazz.getInterfaces, method, annotationType) } if (methodAndAnnotation.isDefined){ // do something } } </code></pre> <p><code>getMethodAndAnnotationFromInterfaces</code> function:</p> <pre><code>def getMethodAndAnnotationFromInterfaces(interfaces: Array[java.lang.Class[_]], method: Method, annotationType: Class[_ &lt;: java.lang.annotation.Annotation]) : Option[(Method, java.lang.annotation.Annotation)] = { @tailrec def getMethodAndAnnotationFromInterfacesInner(interfaces: Array[java.lang.Class[_]], acc: Option[(Method, java.lang.annotation.Annotation)]) : Option[(Method, java.lang.annotation.Annotation)] = { interfaces.length match { case 0 =&gt; acc case _ =&gt; try { interfaces.head.getMethod(method.getName, method.getParameterTypes: _*) match { case newMethod: Method =&gt; val newAnnotation = newMethod.getAnnotation(annotationType) if (newAnnotation != null &amp;&amp; acc.isDefined) { throw new RuntimeException("The annotation is applied to the method in more than one interface of the class.") } getMethodAndAnnotationFromInterfacesInner(interfaces.tail, Some((newMethod, newAnnotation))) case _ =&gt; getMethodAndAnnotationFromInterfacesInner(interfaces.tail, acc) } } catch { case e: NoSuchMethodException =&gt; getMethodAndAnnotationFromInterfacesInner(interfaces.tail, acc) } } } getMethodAndAnnotationFromInterfacesInner(interfaces, None) } </code></pre>
[]
[ { "body": "<p>You could write it like this:</p>\n\n<pre><code>for (val method &lt;- clazz.getMethods) {\n val methodAndAnnotation = method.getAnnotation(annotationType) match {\n case annotation: MessageHandler =&gt; Some((method, annotation))\n case _ =&gt; getMethodAndAnnotationFromInterfaces(clazz.getInterfaces, method, annotationType)\n }\n\n methodAndAnnotation match {\n case Some((method, annotation)) =&gt; // do something\n case None =&gt; //whatever is relevant\n }\n}\n</code></pre>\n\n<p>Or shorter:</p>\n\n<pre><code>for (val method &lt;- clazz.getMethods) {\n method.getAnnotation(annotationType) match {\n case annotation: MessageHandler =&gt; // do something with method and annotation\n case _ =&gt; {\n val v = getMethodAndAnnotationFromInterfaces(clazz.getInterfaces, method, annotationType)\n //whatever is relevant\n }\n }\n}\n</code></pre>\n\n<p>But it depends on what you want to do / if you have something to do when <code>getMethodAndAnnotationFromInterfaces</code> returns <code>None</code>.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-10-19T22:51:39.363", "Id": "8304", "Score": "2", "body": "Noooooooo! Not matching!" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-02-12T22:01:27.913", "Id": "13985", "Score": "0", "body": "@Daniel - Why not matching? I'm a newbie. Odersky's book teaches handing Options with matching." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-02-13T03:42:03.490", "Id": "13991", "Score": "0", "body": "@EdStaub I have to kind of retract that. Matching will give you the most speed in a type-safe way. It's verbose, though, and can get you in the bad habit of matching everything, which leads to less composable code." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-11-12T17:34:11.863", "Id": "57032", "Score": "0", "body": "Good. It was not that bad ;-)" } ], "meta_data": { "CommentCount": "4", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-10-17T06:54:36.443", "Id": "5413", "ParentId": "5404", "Score": "1" } }, { "body": "<p>For a \"scalaesque way\" to deal with <code>Option</code>, study <a href=\"http://blog.tmorris.net/scalaoption-cheat-sheet/\" rel=\"nofollow\">Tony Morris' Option Cheat Sheet</a>. Additionally you can use for comprehensions as well (if you don't want to do anything in case of <code>None</code>):</p>\n\n<pre><code>for (value &lt;- optionValue) {...}\n</code></pre>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-10-17T13:36:24.447", "Id": "5422", "ParentId": "5404", "Score": "1" } }, { "body": "<p>Another improvent is to use Scala Reflection wihch comes in 2.10:</p>\n\n<pre><code>import scala.reflect.runtime.Mirror\nval c = Mirror.classToType(classOf[X])\nval members = c.parents map { _.members filter (_.isMethod) }\nval ann = Mirror.classToSymbol(classOf[Ann])\nval meths = members map { _ filter (_ hasAnnotation ann) }\n</code></pre>\n\n<p>The output is not perfect yet, but the code is short, clear Scala and prints the expected result:</p>\n\n<pre><code>meths: List[List[scala.reflect.runtime.Mirror.Symbol]] = List(List(), List(method c, method a), List())\n</code></pre>\n\n<p>I tested this with following code:</p>\n\n<pre><code>// Java\nimport java.lang.annotation.*;\n\n@Retention(RetentionPolicy.RUNTIME)\n@Target(ElementType.METHOD)\npublic @interface Ann {}\n\n// Scala\ntrait T {\n @Ann\n def a: Int\n def b(i: Int): String\n @Ann\n def c(s: String): String\n}\nclass X extends T {\n def a: Int = 5\n def b(i: Int) = i.toString\n def c(s: String) = \"(\"+s+\")\"\n}\n</code></pre>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-10-17T16:08:44.017", "Id": "5426", "ParentId": "5404", "Score": "0" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-10-16T23:07:20.170", "Id": "5404", "Score": "2", "Tags": [ "beginner", "scala" ], "Title": "Correct use of Option in scala?" }
5404
<p>Wouldn't it be nice to just chain assertions after a method call or is it just me? I was thinking that it'd improve readability.</p> <p>Instead of:</p> <pre><code>var myObject = _objectService.GetRandomObject(); Trace.Assert(myObject!=null); </code></pre> <p>it'll just be this:</p> <pre><code>_objectService.GetRandomObject().NeverNull(); </code></pre> <p>with the extension method defined as</p> <pre><code>namespace System { public static class AssertionExtensions { public static T NeverNull&lt;T&gt;(this T obj) where T : class { Trace.Assert(obj != null); return obj; } } } </code></pre> <p>We could make extensions for some of the most common assertions:</p> <pre><code>public static T Never&lt;T&gt;(this T obj, bool condition) where T : class { Trace.Assert(!condition); return obj; } public static T Always&lt;T&gt;(this T obj, bool condition) where T : class { Trace.Assert(condition); return obj; } </code></pre> <p>If one prefers exceptions over asserts, that's a possibility too.</p>
[ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-10-17T05:40:11.170", "Id": "8151", "Score": "0", "body": "One may overloads != and == operator doing some side effects while comparing, so be careful whe utilizing this operators directly" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-10-17T05:54:19.373", "Id": "8153", "Score": "0", "body": "By providing a meningful name you have to explan what your code is doing insde the function call. this is a good code practice. For the method .NeverNull(), it is uncleat what is going on, is it a constraints, or what? functions call must include action verbs, see the Pattern & Practices books from the GO4. According to these books, you code is bad, because despite great things it is doing beneath the braces, you have to think about the proper utilization of these code again, and again... keeping in memory what these methods like `.NeverDoItAgain()`,`.NeverDoIt()`,`.NeverDo()`,`.No()` means..." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-10-17T07:47:15.387", "Id": "8156", "Score": "0", "body": "I'm not sure I understand the problem with the operators but I do get your point on naming. I considered these names since Asserts imply that a condition should \"never\" be true or that a condition is \"always\" false. Also, the words \"Never\" and \"Always\" are very strong words that I (so far) have rarely encountered in my day to day programming." } ]
[ { "body": "<p>You may found it useful to support both coding techniques, by supplying both versions of a method call, generic and non-generic. One will be using an extension method parameters, mirrored and backed up with method using anonymous function references to as a parameters to static methods.</p>\n\n<p>As an advantge of using this scenario you will get the most from generics and flexiblility of usage for your assertions library of static functions, thus allowed to be used with structures and other value types also. Additionally, i removed the class constraints, because there are already mirrored functions for use by value types in <code>AssertionContracts</code> static class.</p>\n\n<p>I suppose it is better to use <code>Func&lt;T&gt;</code>, <code>Func&lt;T,U&gt;</code> function references where appropriate, just like in this sample (utilizing both extension functions and anonymous functions):</p>\n\n<pre><code> public void ProcessQuery(Query obj, QueryParameter parameter)\n {\n obj\n .AssertNotNull()\n .AssertIsNotNullOrWhitespace((o) =&gt; o.SQLText)\n .AssertNull((o) =&gt; o.QueryResults)\n .AssertNotNull((o) =&gt; o.QueryParameters)\n .AssertPositive((o) =&gt; o.QueryParameters.Length)\n .AssertEquals((o) =&gt; o.QueryParameters[0].Name, parameter.Name);\n\n AssertionContracts.AssertTrue(() =&gt; obj != null);\n AssertionContracts.AssertIsNotNullOrWhitespace(() =&gt; obj.SQLText);\n AssertionContracts.AssertNull(() =&gt; obj.QueryResults);\n AssertionContracts.AssertNotNull(() =&gt; obj.QueryParameters);\n AssertionContracts.AssertPositive(() =&gt; obj.QueryParameters.Length);\n AssertionContracts.AssertEquals(() =&gt; obj.QueryParameters[0].Name, parameter.Name);\n }\n</code></pre>\n\n<p>or this:</p>\n\n<pre><code>public class SmtpServerAddress \n{\n public string UNC { get; set; }\n public long UID { get; set; } \n}\npublic class SmtpClient\n{\n public SmtpServerAddress Server { get; private set; }\n\n public SmtpClient(SmtpServerAddress smtpServer)\n {\n AssertionContracts.ThrowOnTrue&lt;ArgumentNullException&gt;(() =&gt; smtpServer == null);\n Server = smtpServer;\n }\n public SmtpClient(SmtpServerAddress smtpServer, bool dummy1, bool dummy2)\n {\n smtpServer\n .RequireNotNull()\n .RequireIsNullOrWhitespace((obj) =&gt; obj.UNC)\n .RequireEqualsZero((obj) =&gt; obj.UID);\n Server = smtpServer;\n } \n}\n</code></pre>\n\n<p>Source code:</p>\n\n<pre><code>public static class AssertionContracts\n{\n private static class Exceptions&lt;U&gt; where U : Exception, new()\n {\n public static T ThrowOnTrue&lt;T&gt;(T obj, Func&lt;T, bool&gt; function, params object[] args)\n {\n if (function(obj) == true)\n {\n Throw(obj, args);\n }\n return obj;\n }\n public static T ThrowOnFalse&lt;T&gt;(T obj, Func&lt;T, bool&gt; function, params object[] args)\n {\n if (function(obj) == false)\n {\n Throw(obj, args);\n }\n return obj;\n }\n public static void Throw&lt;T&gt;(T obj, params object[] args)\n {\n throw CreateException(obj, args);\n }\n private static U CreateException&lt;T&gt;(T obj, params object[] args)\n {\n return (U)Activator.CreateInstance(typeof(U), args);\n }\n }\n public class ContractException : Exception\n {\n public ContractException() : base() { }\n public ContractException(string message) : base(message) { }\n protected ContractException(SerializationInfo info, StreamingContext context) : base(info, context) { }\n public ContractException(string message, Exception innerException) : base(message, innerException) { }\n }\n public static T ThrowOnTrue&lt;T, U&gt;(this T obj, Func&lt;T, bool&gt; function, params object[] args) where U : Exception, new()\n {\n return AssertionContracts.Exceptions&lt;ContractException&gt;.ThrowOnTrue(obj, function);\n }\n public static T ThrowOnFalse&lt;T, U&gt;(this T obj, Func&lt;T, bool&gt; function, params object[] args) where U : Exception, new()\n {\n return AssertionContracts.Exceptions&lt;ContractException&gt;.ThrowOnFalse(obj, function);\n }\n public static void Throw&lt;T, U&gt;(this T obj, Func&lt;T, bool&gt; function, U ex) where U : Exception\n {\n AssertionContracts.Exceptions&lt;ContractException&gt;.Throw(obj, function);\n }\n public static T NoThrowContractException&lt;T&gt;(this T obj, Func&lt;T, bool&gt; function)\n {\n return AssertionContracts.Exceptions&lt;ContractException&gt;.ThrowOnTrue(obj, function);\n }\n public static T ThrowContractException&lt;T&gt;(this T obj, Func&lt;T, bool&gt; function)\n {\n return AssertionContracts.Exceptions&lt;ContractException&gt;.ThrowOnFalse(obj, function);\n }\n public static T AssertTrue&lt;T&gt;(this T obj, Func&lt;T, bool&gt; function)\n {\n Trace.Assert(function(obj) == true);\n return obj;\n }\n public static T AssertFalse&lt;T&gt;(this T obj, Func&lt;T, bool&gt; function)\n {\n Trace.Assert(function(obj) == false);\n return obj;\n }\n public static T AssertIsNullOrEmpty&lt;T&gt;(this T obj, Func&lt;T, string&gt; function)\n {\n Trace.Assert(string.IsNullOrEmpty(function(obj)));\n return obj;\n }\n public static T AssertIsNullOrWhitespace&lt;T&gt;(this T obj, Func&lt;T, string&gt; function)\n {\n Trace.Assert(string.IsNullOrWhiteSpace(function(obj)));\n return obj;\n }\n public static T AssertIsNotNullOrEmpty&lt;T&gt;(this T obj, Func&lt;T, string&gt; function)\n {\n Trace.Assert(!string.IsNullOrEmpty(function(obj)));\n return obj;\n }\n public static T AssertIsNotNullOrWhitespace&lt;T&gt;(this T obj, Func&lt;T, string&gt; function)\n {\n Trace.Assert(!string.IsNullOrWhiteSpace(function(obj)));\n return obj;\n }\n public static T AssertEquals&lt;T, U&gt;(this T obj, Func&lt;T, U&gt; function, U value)\n {\n Trace.Assert(object.Equals(function(obj), value));\n return obj;\n }\n public static T AssertNotEquals&lt;T, U&gt;(this T obj, Func&lt;T, U&gt; function, U value)\n {\n Trace.Assert(!object.Equals(function(obj), value));\n return obj;\n }\n public static T AssertDefault&lt;T, U&gt;(this T obj, Func&lt;T, U&gt; function)\n {\n Trace.Assert(object.Equals(function(obj), default(U)));\n return obj;\n }\n public static T AssertNonDefault&lt;T, U&gt;(this T obj, Func&lt;T, U&gt; function)\n {\n Trace.Assert(!object.Equals(function(obj), default(U)));\n return obj;\n }\n public static T AssertNotNull&lt;T, U&gt;(this T obj, Func&lt;T, U&gt; function)\n {\n Trace.Assert(!object.Equals(function(obj), default(U)));\n return obj;\n }\n public static T AssertNotNull&lt;T&gt;(this T obj)\n {\n Trace.Assert(!object.Equals(obj, default(T)));\n return obj;\n }\n public static T AssertNull&lt;T, U&gt;(this T obj, Func&lt;T, U&gt; function)\n {\n Trace.Assert(object.Equals(function(obj), default(U)));\n return obj;\n }\n public static T AssertNull&lt;T&gt;(this T obj)\n {\n Trace.Assert(object.Equals(obj, default(T)));\n return obj;\n }\n public static T AssertPositive&lt;T&gt;(this T obj, Func&lt;T, int&gt; function)\n {\n Trace.Assert(function(obj) &gt; 0);\n return obj;\n }\n public static T AssertPositive&lt;T&gt;(this T obj, Func&lt;T, long&gt; function)\n {\n Trace.Assert(function(obj) &gt; 0);\n return obj;\n }\n public static T AssertNegative&lt;T&gt;(this T obj, Func&lt;T, int&gt; function)\n {\n Trace.Assert(function(obj) &lt; 0);\n return obj;\n }\n public static T AssertNegative&lt;T&gt;(this T obj, Func&lt;T, long&gt; function)\n {\n Trace.Assert(function(obj) &lt; 0);\n return obj;\n }\n public static T AssertEqualsZero&lt;T&gt;(this T obj, Func&lt;T, int&gt; function)\n {\n Trace.Assert(function(obj) == 0);\n return obj;\n }\n public static T AssertEqualsZero&lt;T&gt;(this T obj, Func&lt;T, long&gt; function)\n {\n Trace.Assert(function(obj) == 0);\n return obj;\n }\n public static T AssertNotEqualsZero&lt;T&gt;(this T obj, Func&lt;T, int&gt; function)\n {\n Trace.Assert(function(obj) != 0);\n return obj;\n }\n public static T AssertNotEqualsZero&lt;T&gt;(this T obj, Func&lt;T, long&gt; function)\n {\n Trace.Assert(function(obj) != 0);\n return obj;\n }\n public static T AssertGreaterThan&lt;T&gt;(this T obj, Func&lt;T, int&gt; function, int value)\n {\n Trace.Assert(function(obj) &gt; value);\n return obj;\n }\n public static T AssertGreaterThan&lt;T&gt;(this T obj, Func&lt;T, long&gt; function, long value)\n {\n Trace.Assert(function(obj) &gt; value);\n return obj;\n }\n public static T AssertLessThan&lt;T&gt;(this T obj, Func&lt;T, int&gt; function, int value)\n {\n Trace.Assert(function(obj) &lt; value);\n return obj;\n }\n public static T AssertLessThan&lt;T&gt;(this T obj, Func&lt;T, long&gt; function, long value)\n {\n Trace.Assert(function(obj) &lt; value);\n return obj;\n }\n public static T AssertGreaterOrEqualsThan&lt;T&gt;(this T obj, Func&lt;T, int&gt; function, int value)\n {\n Trace.Assert(function(obj) &gt;= value);\n return obj;\n }\n public static T AssertGreaterOrEqualsThan&lt;T&gt;(this T obj, Func&lt;T, long&gt; function, long value)\n {\n Trace.Assert(function(obj) &gt;= value);\n return obj;\n }\n public static T AssertLessOrEqualsThan&lt;T&gt;(this T obj, Func&lt;T, int&gt; function, int value)\n {\n Trace.Assert(function(obj) &lt;= value);\n return obj;\n }\n public static T AssertLessOrEqualsThan&lt;T&gt;(this T obj, Func&lt;T, long&gt; function, long value)\n {\n Trace.Assert(function(obj) &lt;= value);\n return obj;\n }\n public static T AssertGreaterOrEqualsZero&lt;T&gt;(this T obj, Func&lt;T, int&gt; function)\n {\n Trace.Assert(function(obj) &gt;= 0);\n return obj;\n }\n public static T AssertGreaterOrEqualsZero&lt;T&gt;(this T obj, Func&lt;T, long&gt; function, long value)\n {\n Trace.Assert(function(obj) &gt;= 0);\n return obj;\n }\n public static T AssertLessOrEqualsZero&lt;T&gt;(this T obj, Func&lt;T, int&gt; function)\n {\n Trace.Assert(function(obj) &lt;= 0);\n return obj;\n }\n public static T AssertLessOrEqualsZero&lt;T&gt;(this T obj, Func&lt;T, long&gt; function)\n {\n Trace.Assert(function(obj) &lt;= 0);\n return obj;\n }\n public static T RequireTrue&lt;T&gt;(this T obj, Func&lt;T, bool&gt; function)\n {\n return obj.ThrowContractException((o) =&gt; function(obj) == true);\n }\n public static T RequireFalse&lt;T&gt;(this T obj, Func&lt;T, bool&gt; function)\n {\n return obj.ThrowContractException((o) =&gt; function(obj) == false);\n }\n public static T RequireIsNullOrEmpty&lt;T&gt;(this T obj, Func&lt;T, string&gt; function)\n {\n return obj.ThrowContractException((o) =&gt; string.IsNullOrEmpty(function(obj)));\n }\n public static T RequireIsNullOrWhitespace&lt;T&gt;(this T obj, Func&lt;T, string&gt; function)\n {\n return obj.ThrowContractException((o) =&gt; string.IsNullOrWhiteSpace(function(obj)));\n }\n public static T RequireIsNotNullOrEmpty&lt;T&gt;(this T obj, Func&lt;T, string&gt; function)\n {\n return obj.ThrowContractException((o) =&gt; !string.IsNullOrEmpty(function(obj)));\n }\n public static T RequireIsNotNullOrWhitespace&lt;T&gt;(this T obj, Func&lt;T, string&gt; function)\n {\n return obj.ThrowContractException((o) =&gt; !string.IsNullOrWhiteSpace(function(obj)));\n }\n public static T RequireEquals&lt;T, U&gt;(this T obj, Func&lt;T, U&gt; function, U value)\n {\n return obj.ThrowContractException((o) =&gt; object.Equals(function(obj), value));\n }\n public static T RequireEquals&lt;T, U&gt;(this T obj, T value)\n {\n return obj.ThrowContractException((o) =&gt; object.Equals(obj, value));\n }\n public static T RequireNotEquals&lt;T, U&gt;(this T obj, Func&lt;T, U&gt; function, U value)\n {\n return obj.ThrowContractException((o) =&gt; !object.Equals(function(obj), value));\n }\n public static T RequireNotEquals&lt;T, U&gt;(this T obj, T value)\n {\n return obj.ThrowContractException((o) =&gt; !object.Equals(obj, value));\n }\n public static T RequireDefault&lt;T, U&gt;(this T obj, Func&lt;T, U&gt; function)\n {\n return obj.ThrowContractException((o) =&gt; object.Equals(function(obj), default(U)));\n }\n public static T RequireDefault&lt;T&gt;(this T obj)\n {\n return obj.ThrowContractException((o) =&gt; object.Equals(obj, default(T)));\n }\n public static T RequireNonDefault&lt;T, U&gt;(this T obj, Func&lt;T, U&gt; function)\n {\n return obj.ThrowContractException((o) =&gt; !object.Equals(function(obj), default(U)));\n }\n public static T RequireNonDefault&lt;T, U&gt;(this T obj)\n {\n return obj.ThrowContractException((o) =&gt; !object.Equals(obj, default(T)));\n }\n public static T RequireNotNull&lt;T, U&gt;(this T obj, Func&lt;T, U&gt; function)\n {\n return obj.ThrowContractException((o) =&gt; !object.Equals(function(obj), default(U)));\n }\n public static T RequireNotNull&lt;T&gt;(this T obj)\n {\n return obj.ThrowContractException((o) =&gt; !object.Equals(obj, default(T)));\n }\n public static T RequireNull&lt;T, U&gt;(this T obj, Func&lt;T, U&gt; function)\n {\n return obj.ThrowContractException((o) =&gt; object.Equals(function(obj), default(U)));\n }\n public static T RequireNull&lt;T&gt;(this T obj)\n {\n return obj.ThrowContractException((o) =&gt; object.Equals(obj, default(T)));\n }\n public static T RequirePositive&lt;T&gt;(this T obj, Func&lt;T, int&gt; function)\n {\n return obj.ThrowContractException((o) =&gt; function(obj) &gt; 0);\n }\n public static T RequirePositive&lt;T&gt;(this T obj, Func&lt;T, long&gt; function)\n {\n return obj.ThrowContractException((o) =&gt; function(obj) &gt; 0);\n }\n public static T RequireNegative&lt;T&gt;(this T obj, Func&lt;T, int&gt; function)\n {\n return obj.ThrowContractException((o) =&gt; function(obj) &lt; 0);\n }\n public static T RequireNegative&lt;T&gt;(this T obj, Func&lt;T, long&gt; function)\n {\n return obj.ThrowContractException((o) =&gt; function(obj) &lt; 0);\n }\n public static T RequireEqualsZero&lt;T&gt;(this T obj, Func&lt;T, int&gt; function)\n {\n return obj.ThrowContractException((o) =&gt; function(obj) == 0);\n }\n public static T RequireEqualsZero&lt;T&gt;(this T obj, Func&lt;T, long&gt; function)\n {\n return obj.ThrowContractException((o) =&gt; function(obj) == 0);\n }\n public static T RequireNotEqualsZero&lt;T&gt;(this T obj, Func&lt;T, int&gt; function)\n {\n return obj.ThrowContractException((o) =&gt; function(obj) != 0);\n }\n public static T RequireNotEqualsZero&lt;T&gt;(this T obj, Func&lt;T, long&gt; function)\n {\n return obj.ThrowContractException((o) =&gt; function(obj) != 0);\n }\n public static T RequireGreaterThan&lt;T&gt;(this T obj, Func&lt;T, int&gt; function, int value)\n {\n return obj.ThrowContractException((o) =&gt; function(obj) &gt; value);\n }\n public static T RequireGreaterThan&lt;T&gt;(this T obj, Func&lt;T, long&gt; function, long value)\n {\n return obj.ThrowContractException((o) =&gt; function(obj) &gt; value);\n }\n public static T RequireLessThan&lt;T&gt;(this T obj, Func&lt;T, int&gt; function, int value)\n {\n return obj.ThrowContractException((o) =&gt; function(obj) &lt; value);\n }\n public static T RequireLessThan&lt;T&gt;(this T obj, Func&lt;T, long&gt; function, long value)\n {\n return obj.ThrowContractException((o) =&gt; function(obj) &lt; value);\n }\n public static T RequireGreaterOrEqualsThan&lt;T&gt;(this T obj, Func&lt;T, int&gt; function, int value)\n {\n return obj.ThrowContractException((o) =&gt; function(obj) &gt;= value);\n }\n public static T RequireGreaterOrEqualsThan&lt;T&gt;(this T obj, Func&lt;T, long&gt; function, long value)\n {\n return obj.ThrowContractException((o) =&gt; function(obj) &gt;= value);\n }\n public static T RequireLessOrEqualsThan&lt;T&gt;(this T obj, Func&lt;T, int&gt; function, int value)\n {\n return obj.ThrowContractException((o) =&gt; function(obj) &lt;= value);\n }\n public static T RequireLessOrEqualsThan&lt;T&gt;(this T obj, Func&lt;T, long&gt; function, long value)\n {\n return obj.ThrowContractException((o) =&gt; function(obj) &lt;= value);\n }\n public static T RequireGreaterOrEqualsZero&lt;T&gt;(this T obj, Func&lt;T, int&gt; function)\n {\n return obj.ThrowContractException((o) =&gt; function(obj) &gt;= 0);\n }\n public static T RequireGreaterOrEqualsZero&lt;T&gt;(this T obj, Func&lt;T, long&gt; function, long value)\n {\n return obj.ThrowContractException((o) =&gt; function(obj) &gt;= 0);\n }\n public static T RequireLessOrEqualsZero&lt;T&gt;(this T obj, Func&lt;T, int&gt; function)\n {\n return obj.ThrowContractException((o) =&gt; function(obj) &lt;= 0);\n }\n public static T RequireLessOrEqualsZero&lt;T&gt;(this T obj, Func&lt;T, long&gt; function)\n {\n return obj.ThrowContractException((o) =&gt; function(obj) &lt;= 0);\n }\n public static void ThrowOnFalse&lt;U&gt;(Func&lt;bool&gt; function, params object[] args) where U : Exception, new()\n {\n if (function() == false)\n {\n throw (U)Activator.CreateInstance(typeof(U), args);\n }\n }\n public static void ThrowOnTrue&lt;U&gt;(Func&lt;bool&gt; function, params object[] args) where U : Exception, new()\n {\n if (function() == true)\n {\n throw (U)Activator.CreateInstance(typeof(U), args);\n }\n }\n public static void Throw&lt;U&gt;(Func&lt;bool&gt; function, U ex) where U : Exception\n {\n if (function() == false)\n {\n throw ex;\n }\n }\n public static void AssertTrue(Func&lt;bool&gt; function)\n {\n Trace.Assert(function() == true);\n }\n public static void AssertFalse(Func&lt;bool&gt; function)\n {\n Trace.Assert(function() == false);\n }\n public static void AssertIsNullOrEmpty(Func&lt;string&gt; function)\n {\n Trace.Assert(string.IsNullOrEmpty(function()));\n }\n public static void AssertIsNullOrWhitespace(Func&lt;string&gt; function)\n {\n Trace.Assert(string.IsNullOrWhiteSpace(function()));\n }\n public static void AssertIsNotNullOrEmpty(Func&lt;string&gt; function)\n {\n Trace.Assert(!string.IsNullOrEmpty(function()));\n }\n public static void AssertIsNotNullOrWhitespace(Func&lt;string&gt; function)\n {\n Trace.Assert(!string.IsNullOrWhiteSpace(function()));\n }\n public static void AssertEquals&lt;U&gt;(Func&lt;U&gt; function, U value)\n {\n Trace.Assert(object.Equals(function(), value));\n }\n public static void AssertNotEquals&lt;U&gt;(Func&lt;U&gt; function, U value)\n {\n Trace.Assert(!object.Equals(function(), value));\n }\n public static void AssertDefault&lt;U&gt;(Func&lt;U&gt; function)\n {\n Trace.Assert(object.Equals(function(), default(U)));\n }\n public static void AssertNonDefault&lt;U&gt;(Func&lt;U&gt; function)\n {\n Trace.Assert(!object.Equals(function(), default(U)));\n }\n public static void AssertNotNull&lt;U&gt;(Func&lt;U&gt; function)\n {\n Trace.Assert(!object.Equals(function(), default(U)));\n }\n public static void AssertNull&lt;U&gt;(Func&lt;U&gt; function)\n {\n Trace.Assert(object.Equals(function(), default(U)));\n }\n public static void AssertPositive(Func&lt;int&gt; function)\n {\n Trace.Assert(function() &gt; 0);\n }\n public static void AssertPositive(Func&lt;long&gt; function)\n {\n Trace.Assert(function() &gt; 0);\n }\n public static void AssertNegative(Func&lt;int&gt; function)\n {\n Trace.Assert(function() &lt; 0);\n }\n public static void AssertNegative(Func&lt;long&gt; function)\n {\n Trace.Assert(function() &lt; 0);\n }\n public static void AssertEqualsZero(Func&lt;int&gt; function)\n {\n Trace.Assert(function() == 0);\n }\n public static void AssertEqualsZero(Func&lt;long&gt; function)\n {\n Trace.Assert(function() == 0);\n }\n public static void AssertNotEqualsZero(Func&lt;int&gt; function)\n {\n Trace.Assert(function() != 0);\n }\n public static void AssertNotEqualsZero(Func&lt;long&gt; function)\n {\n Trace.Assert(function() != 0);\n }\n public static void AssertGreaterThan(Func&lt;int&gt; function, int value)\n {\n Trace.Assert(function() &gt; value);\n }\n public static void AssertGreaterThan(Func&lt;long&gt; function, long value)\n {\n Trace.Assert(function() &gt; value);\n }\n public static void AssertLessThan(Func&lt;int&gt; function, int value)\n {\n Trace.Assert(function() &lt; value);\n }\n public static void AssertLessThan(Func&lt;long&gt; function, long value)\n {\n Trace.Assert(function() &lt; value);\n }\n public static void AssertGreaterOrEqualsThan(Func&lt;int&gt; function, int value)\n {\n Trace.Assert(function() &gt;= value);\n }\n public static void AssertGreaterOrEqualsThan(Func&lt;long&gt; function, long value)\n {\n Trace.Assert(function() &gt;= value);\n }\n public static void AssertLessOrEqualsThan(Func&lt;int&gt; function, int value)\n {\n Trace.Assert(function() &lt;= value);\n }\n public static void AssertLessOrEqualsThan(Func&lt;long&gt; function, long value)\n {\n Trace.Assert(function() &lt;= value);\n }\n public static void AssertGreaterOrEqualsZero(Func&lt;int&gt; function)\n {\n Trace.Assert(function() &gt;= 0);\n }\n public static void AssertGreaterOrEqualsZero(Func&lt;long&gt; function, long value)\n {\n Trace.Assert(function() &gt;= 0);\n }\n public static void AssertLessOrEqualsZero&lt;T&gt;(Func&lt;int&gt; function)\n {\n Trace.Assert(function() &lt;= 0);\n }\n public static void AssertLessOrEqualsZero(Func&lt;long&gt; function)\n {\n Trace.Assert(function() &lt;= 0);\n }\n}\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-10-17T05:02:36.820", "Id": "8149", "Score": "0", "body": "Is it really necessary to support this? I'm aiming for more readable code (and less typing). Adding the Func delegates seem to make it needlessly complex to the point that one might prefer to just call the original Trace/Debug Assert function." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-10-17T05:37:11.533", "Id": "8150", "Score": "0", "body": "@John: Is this not enougth elegant code for you? : obj \n .AssertTrue((o) => obj != null) \n .AssertIsNotNullOrWhitespace((o) => o.SQLText) \n .AssertNull((o) => o.QueryResults) \n .AssertNotNull((o) => o.QueryParameters) \n .AssertPositive((o) => o.QueryParameters.Length) \n .AssertEquals((o) => o.QueryParameters[0].Name, parameter.Name);" } ], "meta_data": { "CommentCount": "2", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-10-17T04:42:20.310", "Id": "5409", "ParentId": "5407", "Score": "1" } }, { "body": "<p>Sounds like you guys are trying to re-invent the excellent <a href=\"http://fluentassertions.codeplex.com/\" rel=\"nofollow\">FluentAssertions</a> library..</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-10-17T09:05:06.833", "Id": "8161", "Score": "0", "body": "Wow. This lib has everything! Can it do asserts on a regular (not a unit test) project? So far I've read that its mostly used in conjunction with TDD frameworks" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-10-17T09:20:24.330", "Id": "8162", "Score": "0", "body": "It is designed for use in unit testing but there's no reason you couldn't use it to assert your preconditions, if you prefer that kind of syntax over something like CodeContracts :)" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-10-17T14:25:16.847", "Id": "8169", "Score": "0", "body": "If someone is able to write piece of code to cover 100% of the generic use cases (chaining syntax, code contracts style), why not just using it?" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-10-18T00:32:54.530", "Id": "8194", "Score": "0", "body": "Looks like I just might. I didn't know of those before this. Thanks." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-10-18T06:29:31.227", "Id": "8200", "Score": "0", "body": "Another one worth checking out is Shouldly - http://shouldly.github.com/" } ], "meta_data": { "CommentCount": "5", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-10-17T08:48:01.307", "Id": "5415", "ParentId": "5407", "Score": "2" } }, { "body": "<p>I use <a href=\"http://msdn.microsoft.com/en-us/devlabs/dd491992\" rel=\"nofollow\">Code Contracts</a> to take care of my assertions.</p>\n\n<pre><code>Contract.Requires(customer.Age &gt; 0);\nContract.Requires(!string.IsNullOrWhitespace(customer.Name));\nContract.Requires(customer.RegisteredProduct.Any());\nContract.Ensures(Contract.Result&lt;SupportTicket&gt; != null);\n</code></pre>\n\n<p>It can do several things that extension methods can never do:</p>\n\n<ul>\n<li>Show you the source code of the tested expression (although FluentAssertions can approximate that by using expressions, it has the disadvantage of performance and being restricted to using their custom comparison methods (or the more verbose lambdas) as opposed to simple boolean evaluated expressions (like in <code>Debug.Assert(...)</code>)</li>\n<li>Perform assertions on return values, regardless of how many <code>return</code> statements you have in your method.</li>\n<li>Expose additional metadata about the method via tools (so that IntelliSense shows the contracts).</li>\n<li>Apply a contract to an interface, where all implementers automatically inherit the assertions.</li>\n<li>Perform compile-time verifications of the contract, if you're using the Premium or Ultimate versions of Visual Studio. <strong>EDIT:</strong> Version 1.5 now also support the Professional edition.</li>\n</ul>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-10-21T18:56:13.737", "Id": "5507", "ParentId": "5407", "Score": "3" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "3", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-10-17T02:12:40.070", "Id": "5407", "Score": "3", "Tags": [ "c#", "extension-methods" ], "Title": "Chained Assertions" }
5407
<p>I'm new to Clojure. How can I make this more idiomatic Clojure code? Among other things, there are three (do) blocks and I don't think using (def) as many times as I do is a recommended idea.</p> <pre><code>(defn add-phone "Add a phone number to a given service. There are a few steps we have to take: - Validate the service name and token - Validate the phone number - Send a text message to the number - Store the number in the database Arguments: request - an authorized HTTP request Returns: 201 Resource Created - phone number added to a service 400 Bad Request - invalid phone number or bad request" [request auth-type] (do (println "Url requested is " (:request-method request) " " (:uri request)) (println request) (def auth-header ((:headers request) "authorization")) (def auth-map (utils/get-auth-header auth-type auth-header)) (if (model/invalid-user-and-pass auth-map auth-type) {:status 401, :headers {"WWW-Authenticate" "Basic realm=\"smsauth.herokuapp.com\""}} (do (def raw-phone-no (:phone_number (:params request))) (def service-name (:service-name auth-map)) (if raw-phone-no (do (def valid-phone-no (utils/parse-phone-no raw-phone-no)) ; XXX get the service id some other way. (def service-map (model/service-in-db service-name)) (def service-id (service-map :id)) ; XXX check that service doesn't already have phone number (model/store-phone-no :numbers service-id valid-phone-no) (twilio/send-sms-verify twilio/sms-url valid-phone-no service-name) ; XXX jsonify this, send more information, document it. {:status 201, :body (json/json-str { :service_name service-name, :phone_number valid-phone-no, :status "active", :uri (:uri request) ; should have some kind of unique id for the phone number ; here. ; also return the date })}) {:status 400, :body (json/json-str {:error "Please include a phone_number."})}))))) </code></pre>
[]
[ { "body": "<p>There are several errors/bad styles here:</p>\n\n<ul>\n<li>First do isn't necessary, as body of function can contain several expressions</li>\n<li>instead of <code>def</code> inside function it's better to use <code>let</code> that allows to \"define\" several variables in one step, and they will visible only inside this <code>let</code> block. So 2nd &amp; 3rd <code>do</code> could be replaced with corresponding <code>let</code></li>\n<li>if variable is used only once, then you can include function call directly into map</li>\n</ul>\n\n<p>So your code will look like:</p>\n\n<pre><code>(defn add-phone\n [request auth-type]\n (println \"Url requested is \" (:request-method request) \" \" (:uri request))\n (println request)\n (let [auth-header ((:headers request) \"authorization\")\n auth-map (utils/get-auth-header auth-type auth-header)]\n (if (model/invalid-user-and-pass auth-map auth-type)\n {:status 401,\n :headers {\"WWW-Authenticate\" \"Basic realm=\\\"smsauth.herokuapp.com\\\"\"}}\n (let [raw-phone-no (:phone_number (:params request))\n service-name (:service-name auth-map)]\n (if raw-phone-no\n (let [valid-phone-no (utils/parse-phone-no raw-phone-no) ; XXX get the service id some other way.\n service-map (model/service-in-db service-name)\n service-id (service-map :id) ; XXX check that service doesn't already have phone number\n ]\n (model/store-phone-no :numbers service-id valid-phone-no)\n (twilio/send-sms-verify twilio/sms-url valid-phone-no service-name)\n ; XXX jsonify this, send more information, document it.\n {:status 201,\n :body (json/json-str {\n :service_name service-name,\n :phone_number valid-phone-no,\n :status \"active\",\n :uri (:uri request)\n ; should have some kind of unique id for the phone number\n ; here.\n ; also return the date\n })})\n {:status 400,\n :body (json/json-str {:error \"Please include a phone_number.\"})})))))\n</code></pre>\n\n<p>P.S. it's also good idea to check value of <code>service-map</code> - if it will <code>nil</code>, then you'll get NPE. So instead of <code>(service-map :id)</code> you can write <code>(:id service-map)</code> that will correctly work if <code>service-map</code> will <code>nil</code>...</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-10-17T07:34:28.757", "Id": "5414", "ParentId": "5410", "Score": "4" } } ]
{ "AcceptedAnswerId": "5414", "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-10-17T05:58:20.420", "Id": "5410", "Score": "2", "Tags": [ "beginner", "validation", "authentication", "clojure", "web-services" ], "Title": "Web service to add a phone number with SMS validation" }
5410
<p>I am currently exploring the play framework. I'm about to replace the proposed templating system, using the powerful XML processing of the Scala library. Here is what I have come with:</p> <pre><code>import scala.xml._ import play.templates._ import play.mvc.results.ScalaAction object Gui { def asset (file:String) = "/public/"+ file val cssIncludes = "main.css" :: "jquery-ui-1.8.16.custom.css" :: "dynaTree/skin/ui.dynatree.css" :: Nil val jsIncludes = "jquery-1.6.2.min.js" :: "jquery.cookie.js" :: "jquery-ui-1.8.16.custom.min.js":: "jquery.dynatree.min.js" :: Nil def pageBase(title: String = "", jsScript: Option[String])(body: =&gt; Seq[Node]) = { &lt;html&gt; &lt;head&gt;{ val nodes :Seq[Node] = &lt;title&gt;{ title }&lt;/title&gt;:: (for (css &lt;- cssIncludes) yield &lt;link rel="stylesheet" href={ asset("stylesheets/" + css) }&gt;&lt;/link&gt; )::: (for (js &lt;- jsIncludes) yield &lt;script src={asset("javascripts/" + js)} type="text/javascript"&gt;&lt;/script&gt; ):::( &lt;link rel="shortcut icon" type="image/png" href="public/images/favicon.png"&gt;&lt;/link&gt; &lt;script type="text/javascript"&gt;{jsScript getOrElse ""}&lt;/script&gt;).toList nodes }&lt;/head&gt; &lt;body&gt;{ body }&lt;/body&gt; &lt;/html&gt; } } </code></pre> <p>This seems to work well and can be a base for more complex needs.</p> <p>I would be interested in a way to improve the <code>pageBase</code> method. I did not find a clean way to generate the stylesheet and JavaScript inclusion without the <code>:::</code> operator. (I managed to get the code to compile, but only the last for expression would yield a result at execution)</p> <p>Would you share a better way to write it, or show your implementation, if you took a similar path?</p> <p>I'm still searching a better way to handle path creation (for asset and action) that mimics the routing and reverse routing offered in the templates.</p>
[ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-10-17T06:38:58.503", "Id": "8154", "Score": "0", "body": "I would like to add \"playframework\" as a new tag... but don't have the right to do it... Could someone with such power create it for me, or better, give me the right to do it?" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-03-15T19:19:21.797", "Id": "77157", "Score": "0", "body": "have you considered anti-XML? http://anti-xml.org/ I guess no one answered this question yet because the Scala XML standard package is outdated and beyond fixing." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-03-17T10:56:51.603", "Id": "77333", "Score": "0", "body": "Thanks for pointing antiXML... I'll be glad to test it when I have time." } ]
[ { "body": "<p>I'm not that familiar with Play, but overall I can't say that there's anything here I actively dislike. The purpose, layout, variable names and all are quite reasonable and easy to follow. Over all, I would say \"Good job\".</p>\n\n<p>A couple of comments outside of that:</p>\n\n<ol>\n<li><p>It seems strange that you would have to write all this boiler-plate HTML stuff in code. My preference would be to keep a template, but Your Mileage May Vary.</p></li>\n<li><p>I can't say that I'm a huge fan of using concatenation operators to create static lists. I would have, for example, written:</p>\n\n<pre><code>val cssIncludes = List(\"main.css\",\n \"jquery-ui-1.8.16.custom.css\",\n \"dynaTree/skin/ui.dynatree.css\")\n</code></pre>\n\n<p>It isn't that the way you wrote it is wrong, but this form is exactly equivalent and more obvious (and thus more readable).</p></li>\n</ol>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-09-22T12:18:52.417", "Id": "63572", "ParentId": "5411", "Score": "6" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "3", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-10-17T06:38:09.253", "Id": "5411", "Score": "8", "Tags": [ "mvc", "scala", "xml", "template" ], "Title": "Basic XML template" }
5411
<p>I was looking for a simple Event Aggregator to use in my app, but I found people get very complicated very quickly, so I thought this was easy enough to write myself. It seems to work, but I was wondering what you think and if you would change or add anything. (I know some of them raise events back on the same thread that it was registered, but for what I was planning I don't need this.)</p> <pre><code>public class EventAggregator { private Dictionary&lt;Type, List&lt;WeakReference&gt;&gt; _listeners; private object _syncLock; public EventAggregator() { _listeners = new Dictionary&lt;Type, List&lt;WeakReference&gt;&gt;(); _syncLock = new object(); } public EventAggregator Register&lt;TEvent&gt;(Action&lt;TEvent&gt; eventAction) { LockAround(() =&gt; { var listeners = GetListeners(typeof(TEvent)); listeners.RemoveAll(wr =&gt; !wr.IsAlive || (Action&lt;TEvent&gt;)wr.Target == eventAction); listeners.Add(new WeakReference(eventAction)); }); return this; } public void Raise&lt;TEvent&gt;(TEvent ev) { List&lt;WeakReference&gt; targets = null; LockAround(() =&gt; { var listeners = GetListeners(typeof(TEvent)); targets = listeners .Where(wr =&gt; wr.IsAlive) .ToList(); }); targets.ForEach(wr =&gt; ((Action&lt;TEvent&gt;)wr.Target)(ev)); } private void LockAround(Action action) { lock (_syncLock) { action(); } } private List&lt;WeakReference&gt; GetListeners(Type type) { List&lt;WeakReference&gt; result; if (_listeners.TryGetValue(type, out result)) { return result; } result = new List&lt;WeakReference&gt;(); _listeners[type] = result; return result; } } </code></pre> <p>This is how I plan to use it:</p> <pre><code>class Program { static void Main(string[] args) { var ea = new EventAggregator(); var view = new View(ea); var p = new Presenter(ea); view.Name = "Name1"; view.Name = "Name2"; Console.ReadKey(); } } interface INameChangeEvent { string OldName { get; set; } string NewName { get; set; } } public class NameChangeEvent : EventArgs, INameChangeEvent { public NameChangeEvent(string oldName, string newName) { this.OldName = oldName; this.NewName = newName; } public string OldName { get; set; } public string NewName { get; set; } } class View { private string _name; private EventAggregator _ea; public View(EventAggregator ea) { _ea = ea; } public string Name { get { return _name; } set { _ea.Raise&lt;INameChangeEvent&gt;(new NameChangeEvent(_name, value)); _name = value; } } } class Presenter { public Presenter(EventAggregator ea) { ea.Register&lt;INameChangeEvent&gt;((ev) =&gt; Console.WriteLine(string.Format("View name was changed from {0} to {1}", ev.OldName, ev.NewName))); } } </code></pre>
[ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-10-17T15:12:05.573", "Id": "8175", "Score": "0", "body": "I'll embarrassingly admit a bit of TL;DR for the moment, but at a quick glance, I'd make the two `private` variables `readonly` as well." } ]
[ { "body": "<p>I haven't thoroughly looked at it but these are my initial thoughts.</p>\n\n<p><strong>Minor points</strong></p>\n\n<p>I would initialise the private variables inline like this <code>private object _syncLock = new Object();</code> because they don't depend on parameters given to the constructor.</p>\n\n<p>For readability I wouldn't use the <code>LockAround</code> method, I would just lock <code>_syncObject</code>.</p>\n\n<p>In <code>GetListeners</code> is there any reason you are adding a list to the dictionary when no events have been registered for that type? Also, you could make it generic by pulling in the <code>typeof</code> from <code>Raise</code> like so <code>_listeners.TryGetValue(typeof(TEvent), out result)</code>.</p>\n\n<p>In <code>Register&lt;TEvent&gt;</code> what is the purpose of <code>(Action&lt;TEvent&gt;)wr.Target == eventAction</code>? I think if someone wants to register the same event handler twice then they should be able to.</p>\n\n<p>You might want to make your event aggregator a singleton or use a dependency injection framework to ensure there is only ever one instance in existence.</p>\n\n<p><strong>Worries</strong></p>\n\n<p>In <code>Raise&lt;TEvent&gt;</code> the following line worries me <code>targets.ForEach(wr =&gt; ((Action&lt;TEvent&gt;)wr.Target)(ev));</code>. I'm not sure there is any guarantee the weak reference will still be alive at this point. You probably want to solidify the reference and check that it is not null before calling it.</p>\n\n<p><strong>Finally</strong></p>\n\n<p>Have you looked at Microsoft's event aggregator and unity dependency injection framework? I think they probably do what you are looking for and will save you from reinventing the wheel.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-10-18T08:45:22.757", "Id": "8204", "Score": "0", "body": "+1 the LockAround method does not have any advantage atm (in fact it requires 2 more characters)" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-10-18T09:01:22.473", "Id": "8206", "Score": "0", "body": "Thanks, The GetListeners should maybe be called GetOrCreateListeners this is only used in one place and the idea is to create the list if it doesnt exist" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-10-18T09:02:21.177", "Id": "8207", "Score": "0", "body": "I also agree with your observation, i think better would be to inside the foreach (assign the object) (so that its referenced) then check null and isalive?" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-10-18T09:03:17.790", "Id": "8208", "Score": "0", "body": "Finally my reasoning for re inventing the wheel in this case was exactly that is that using one that is frameworked may be really overcomplicating things?, i thought this was really easy to implement" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-10-18T09:05:25.130", "Id": "8209", "Score": "0", "body": "There is no need to use `IsAlive` if you assign the object and check it is not null. In fact checking `IsAlive == true` is not recommended, see: http://msdn.microsoft.com/en-us/library/system.weakreference.isalive.aspx" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-10-18T09:06:41.307", "Id": "8210", "Score": "0", "body": "I think there are potentially many subtleties and edge cases that you have to worry about when implementing it yourself. However provided you test it enough you should be ok." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-10-18T13:49:42.950", "Id": "8216", "Score": "0", "body": "Can i just ask you say that there must be a singleton of EventAggregator, can you tell me why this is, for instance i want to create the interaction between a view and a presenter i dont see why that must be a singleton for the whole app. Can i not create a builder function that constructs it and set it up, i dont like singletons and feel they are overused not to mention hard to test? thanks" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-10-18T13:51:27.633", "Id": "8219", "Score": "0", "body": "PS: the overhead of creating an EventAggregator shouldnt be that much, just a few in memory objects, but id like to know what im not seeing here, thanks" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-10-18T14:04:51.340", "Id": "8223", "Score": "0", "body": "I assumed you wanted it to be a global way of passing messages. As this is not the case you don't need to use a singleton." } ], "meta_data": { "CommentCount": "9", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-10-18T08:14:41.813", "Id": "5440", "ParentId": "5416", "Score": "5" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "1", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-10-17T09:34:35.857", "Id": "5416", "Score": "10", "Tags": [ "c#", "design-patterns" ], "Title": "What do you think of my EventAggregator implementation in C#?" }
5416
<p>I've been wondering about simple collision in C++ for a while now, and I've tried to make up my own code.</p> <p>The code posted below works when walls are placed in a perfect rectangle around the player. However, once you randomly place them in the array, as in the code, weird inconsistencies seem to occur. Sometimes the player collides, sometimes the player doesn't.</p> <p>If anyone would be as kind as to point out what the error is, I'd be much appreciated. In a clear step by step manner, if you would: I'm very new to this and chances are small that I can make the logical steps of thought necessary to successfully implement your suggestions.</p> <pre><code>#include "string.h" #include "surface.h" #include "stdlib.h" #include "template.h" #include "game.h" using namespace Tmpl8; int pacmanPosX = 32; int pacmanPosY = 32; int indexX; int indexY; bool colR; bool colL; bool colU; bool colD; Sprite pacman (new Surface( "assets/pacmanLeft.png"), 1); Surface* tileSet[3]; int levelMap[8][8] = {{1,1,1,1,1,1,1,1}, {1,0,0,0,0,0,0,1}, {1,0,0,0,0,1,0,1}, {1,0,0,1,0,0,0,1}, {1,0,0,0,1,0,0,1}, {1,1,0,0,1,1,1,1}, {1,0,0,0,0,0,1,1}, {1,1,1,1,1,1,1,1}}; void Game::Init() { // put your initialization code here; will be executed once tileSet[0] = new Surface( "assets/pacmanFloor.png" ); // Sets up data for tileSet tileSet[1] = new Surface( "assets/pacmanWall.bmp" ); tileSet[2] = new Surface( "assets/pacmanCookie.png" ); } void Game::Tick( float a_DT ) { m_Screen-&gt;Clear( 0 ); for (indexX = 0; indexX &lt; 8; indexX++) { for (indexY = 0; indexY &lt; 8; indexY++) { int tile = levelMap[indexY][indexX]; tileSet[tile]-&gt;CopyTo( m_Screen, indexX * 32, indexY * 32 ); } } pacman.Draw(pacmanPosX, pacmanPosY, m_Screen); //Defining collision requirements for walls// if(levelMap[(pacmanPosX+32)/32][pacmanPosY/32] == 1) //Right collision { colR = true; }else colR = false; if(levelMap[(pacmanPosX-2)/32][pacmanPosY/32] == 1) //Left collision { colL = true; }else colL = false; if(levelMap[pacmanPosX/32][(pacmanPosY-2)/32] == 1) //Upward collision { colU = true; }else colU = false; if(levelMap[pacmanPosX/32][(pacmanPosY+32)/32] == 1) //Downward collision { colD = true; }else colD = false; //Setting Up Controls// if (GetAsyncKeyState(VK_RIGHT) &amp;&amp; colR == false){pacmanPosX += 2;} if (GetAsyncKeyState(VK_LEFT) &amp;&amp; colL == false){pacmanPosX -= 2;} if (GetAsyncKeyState(VK_UP) &amp;&amp; colU == false){pacmanPosY -= 2;} if (GetAsyncKeyState(VK_DOWN) &amp;&amp; colD == false){pacmanPosY += 2;} Sleep( 10 ); } </code></pre>
[]
[ { "body": "<h3>Bug in your code</h3>\n<p>Here you are accessing the levelMap by 'Y' then 'X'</p>\n<pre><code> int tile = levelMap[indexY][indexX]; \n</code></pre>\n<p>In all other places you are accessing the levelMap by 'X' then 'Y'</p>\n<pre><code>if(levelMap[(pacmanPosX+32)/32][pacmanPosY/32] == 1) //Right collision \n</code></pre>\n<p>So it looks like you are running around a maze that has been printed incorrectly on the screen. and thus it looks like collision detection is not working (it probably is) but the detection does not match the visual cues.</p>\n<h3>Reviewing your code:</h3>\n<p>These expressions</p>\n<pre><code>if(levelMap[(pacmanPosX+32)/32][pacmanPosY/32] == 1) //Right collision \n{ \n colR = true; \n}else colR = false; \n</code></pre>\n<p>Can be simplifies too:</p>\n<pre><code>colR = (levelMap[(pacmanPosX+32)/32][pacmanPosY/32] == 1); //Right collision \n</code></pre>\n<p>While these</p>\n<pre><code>if (GetAsyncKeyState(VK_RIGHT) &amp;&amp; colR == false){pacmanPosX += 2;} \n</code></pre>\n<p>can be simplified to:</p>\n<pre><code>if (GetAsyncKeyState(VK_RIGHT) &amp;&amp; !colR)\n{ pacmanPosX += 2;\n} \n</code></pre>\n<p>Putting the statement on the same line as the test makes it harder to debug (when stepping through with the debugger) as you can not see when then the statements are executed. By putting it on its own line stepping through with the de-bugger does become easier as you will see it skip the statement when the condition fails.</p>\n<p>Global state is the easy way to do things.</p>\n<pre><code>int pacmanPosX = 32; \nint pacmanPosY = 32; \nint indexX; \nint indexY; \n\nbool colR; \nbool colL; \nbool colU; \nbool colD; \n</code></pre>\n<p>But in the long run makes your code more brittle and harder to update. Pass things as parameters to make it easier to maintain and extend your code (or create an object that wraps the information).</p>\n<p>Also it looks like some of these properties would be better held in arrays rather than individual variables.</p>\n<h3>Edit base on comments:</h3>\n<p>This only detects a collision if the top right corner hits a wall.</p>\n<pre><code>colR = (levelMap[(pacmanPosX+32)/32][pacmanPosY/32] == 1); //Right collision \n</code></pre>\n<p>Change too:</p>\n<pre><code>colR = (levelMap[(pacmanPosX+33)/32][(pacmanPosY+00)/32] == 1) // Top right\n || (levelMap[(pacmanPosY+33)/32][(pacmanPosY+31)/32] == 1); // bottom right\n\n// Use +33 because moving left you use -2\n// When you move right +32 puts you in the first pixel of the next block\n// +33 puts you in the second pixel just like move left detection\n\n// Use +31 on the Y access because this is still inside the current sprite.\n</code></pre>\n<p>Note If you have a hole in the wall that is exactly one block wide you need to hit it dead center to pass through the gap. To give you some wiggle room you can move the corners in slightly.</p>\n<pre><code>colR = (levelMap[(pacmanPosX+33)/32][(pacmanPosY+02)/32] == 1) // Top right\n || (levelMap[(pacmanPosY+33)/32][(pacmanPosY+29)/32] == 1); // bottom right\n</code></pre>\n<p>Here you do not need to hit the whole in the wall dead center and you get some wiggle room passing through.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-10-17T13:55:09.603", "Id": "8166", "Score": "0", "body": "Thanks a lot for your useful feed-back. How silly of me to swap the X and the Y! :o It works a lot better now! Something still bothers me, though. Hopefully I can explain it... When you push the 32x32 character against a 32x32 wall which has no wall above or below it, it collides only when the player hits it in the middle. When you rub against the wall and move down, the collision stays okay. When you move up while pushing against the wall, though, you slide through it. This problem goes for every block that isn't surrounded by other blocks. Uhm... Could you follow that?" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-10-17T14:05:40.877", "Id": "8167", "Score": "0", "body": "That's because you are only looking for a collision in the top right or top left corner. In your collision code change it so that when you move right check for a collision in the top and bottom right corners." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-10-17T14:43:56.530", "Id": "8171", "Score": "0", "body": "Hey, I did it, sort of. I used this: if((levelMap[(pacmanPosX+34)/32][pacmanPosY/32] == 1) || (levelMap[(pacmanPosX+34)/32][(pacmanPosY+32)/32] == 1)) //Right collision\n{\n colR = true;\n}else colR = false; You can see I used x+34 instead of x+32. That's because movement gets stuck somehow. This way, though, the character doesn't fit in 'alleys', like in pacman. Suggestions? :)" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-10-17T14:58:53.210", "Id": "8174", "Score": "0", "body": "Sorry, I didn't saw your edit. Thanks again for all your help!" } ], "meta_data": { "CommentCount": "4", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-10-17T13:26:22.887", "Id": "5421", "ParentId": "5420", "Score": "1" } } ]
{ "AcceptedAnswerId": "5421", "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-10-17T13:04:11.497", "Id": "5420", "Score": "2", "Tags": [ "c++", "collision" ], "Title": "Collision detection inconsistencies" }
5420
<p>I have written a (dynamic) <code>TemplateArray</code> class, for purposes to be included as a baseline for a library I am working on, and I would like feedback on any of the following:</p> <ul> <li>How the code can be improved (even if it's just your subjective opinion)?</li> <li>How the code can be made more efficient?</li> <li>How the functions of the class can be made more intuitive and user-friendly (does it operate like how you anticipate it to)?</li> </ul> <p></p> <pre><code>namespace TL { template&lt;typename TemplateItem&gt; class TemplateArray { protected: TemplateItem *Array; SIZE_TYPE Size; void Clear(){Array = NULL; Size = 0;} public: const bool IsEmpty() const { return ((Array == NULL) &amp;&amp; (Size == 0)); } const bool IsValid() const { return ((Array != NULL) &amp;&amp; (Size != 0)); } const bool operator!() const {return IsEmpty();} operator const bool () const {return IsValid();} const SIZE_TYPE GetSize() const {return Size;} const bool SetSize(const SIZE_TYPE S) { ERRORCLASSFUNCTION(TemplateArray,SetSize,S &lt; 1,RETURN_BOOL) if(!IsEmpty()) { Close(); } ERRORCLASSFUNCTION(TemplateArray,SetSize,!CREATEB(Array,S),RETURN_BOOL) Size = S; return true; } const bool CopyArray(const TemplateItem Arr[], const SIZE_TYPE S) { ERRORCLASSFUNCTION(TemplateArray,CopyArray,S &lt; 1,RETURN_BOOL); ERRORCLASSFUNCTION(TemplateArray,CopyArray,S &gt; Size,RETURN_BOOL); SIZE_TYPE Temp = 0; while(Temp &lt; S) { Array[Temp] = Arr[Temp]; Temp++; } return true; } const bool SetArray(const TemplateItem Arr[], const SIZE_TYPE S) { ERRORCLASSFUNCTION(TemplateArray,SetArray,S &lt; 1,RETURN_BOOL) ERRORCLASSFUNCTION(TemplateArray,SetArray,!SetSize(S),RETURN_BOOL) SIZE_TYPE Temp = 0; while(Temp &lt; S) { Array[Temp] = Arr[Temp]; Temp++; } return true; } const bool SetArray(const TemplateArray &amp;ItemCopy) { ERRORCLASSFUNCTION(TemplateArray,SetArray,!ItemCopy,RETURN_BOOL) ERRORCLASSFUNCTION(TemplateArray,SetArray,!SetArray(ItemCopy.Array,ItemCopy.Size),RETURN_BOOL) return true; } const bool SetArray(const std::vector&lt;TemplateItem&gt; &amp;ItemCopy) { ERRORCLASSFUNCTION(TemplateArray,SetArray,ItemCopy.empty(),RETURN_BOOL) ERRORCLASSFUNCTION(TemplateArray,SetArray,!SetArray(&amp;ItemCopy[0],ItemCopy.size()),RETURN_BOOL) return true; } TemplateItem * const GetArray() { return Array; } const TemplateItem * const GetArray() const { return Array; } void TransferFrom(TemplateArray &amp;ItemCopy) { Close(); Array = ItemCopy.Array; Size = ItemCopy.Size; ItemCopy.Array = NULL; ItemCopy.Size = 0; } const bool Reverse() { ERRORCLASSFUNCTION(TemplateArray,Reverse,!IsValid(),RETURN_BOOL) TemplateArray&lt;TemplateItem&gt; Temp; ERRORCLASSFUNCTION(TemplateArray,Reverse,!Temp.SetSize(Size),RETURN_BOOL) TemplateItem *C_Ptr = Array+(Size-1), *C_Ptr_2 = Temp.GetArray(); while(C_Ptr != Array) { *C_Ptr_2 = *C_Ptr; C_Ptr--; C_Ptr_2++; } *C_Ptr_2 = *C_Ptr; TransferFrom(Temp); return true; } const bool Compare(const TemplateItem Arr[], const SIZE_TYPE S) { if(!IsValid()) { return false; } ERRORCLASSFUNCTION(TemplateArray,Compare,S &lt; 1,RETURN_BOOL) SIZE_TYPE Temp = 0; while(Temp &lt; S) { if(Array[Temp] != Arr[Temp]){return false;} Temp++; } return true; } const bool Compare(const TemplateArray &amp;ItemCopy) { if(Size != ItemCopy.Size) { return false; } if(IsEmpty()) { return true; } return Compare(ItemCopy.Array,ItemCopy.Size); } const bool Compare(const std::vector&lt;TemplateItem&gt; &amp;ItemCopy) { if(ItemCopy.size() != Size) { return false; } if(ItemCopy.empty()) { return true; } return Compare(&amp;ItemCopy[0],ItemCopy.size()); } const bool Append(const TemplateItem Data[], const SIZE_TYPE S) { ERRORCLASSFUNCTION(TemplateArray,Append,Data == NULL,RETURN_BOOL) ERRORCLASSFUNCTION(TemplateArray,Append,S &lt; 1,RETURN_BOOL) TemplateArray&lt;TemplateItem&gt; Temp; ERRORCLASSFUNCTION(TemplateArray,Append,!Temp.SetSize(Size+S),RETURN_BOOL) SIZE_TYPE Temp2 = 0; while(Temp2 &lt; Size) { Temp.Array[Temp2] = Array[Temp2]; Temp2++; } Temp2 = 0; while(Temp2 &lt; S) { Temp.Array[Temp2+Size] = Data[Temp2]; Temp2++; } TransferFrom(Temp); return true; } //Tested const bool Append(const TemplateArray &amp;ItemCopy) { ERRORCLASSFUNCTION(TemplateArray,Append,!ItemCopy.IsValid(),RETURN_BOOL) return Append(ItemCopy.GetArray(),ItemCopy.GetSize()); } const bool Append(const std::vector&lt;TemplateItem&gt; &amp;ItemCopy) { ERRORCLASSFUNCTION(TemplateArray,Append,ItemCopy.empty(),RETURN_BOOL) ERRORCLASSFUNCTION(TemplateArray,Append,!Append(&amp;ItemCopy[0],ItemCopy.size()),RETURN_BOOL) return true; } const bool Append(const TemplateItem &amp;ItemCopy) { return Append(&amp;ItemCopy,1); } const bool Remove(const TemplateItem Data[], const SIZE_TYPE S) { ERRORCLASSFUNCTION(TemplateArray,Append,Data == NULL,RETURN_BOOL) ERRORCLASSFUNCTION(TemplateArray,Remove,S &lt; 1,RETURN_BOOL) if(!IsValid()){return false;} if(S &gt; Size){return false;} SIZE_TYPE Temp = 0, Temp2 = 0; do { Temp2 = 0; while(Temp &lt; Size) { if(Array[Temp] == Data[Temp2]) { break; } Temp++; } while(Temp &lt; Size) { if(Array[Temp] != Data[Temp2]) { break; } Temp++; Temp2++; if(Temp2 == S) { break; } } if(Temp2 == S) { TemplateArray&lt;TemplateItem&gt; DataTemp; ERRORCLASSFUNCTION(TemplateArray,operator-=,!DataTemp.SetSize(Size-S),RETURN_BOOL) Temp2 = Temp - S; Temp = 0; while(Temp &lt; Temp2) { DataTemp.Array[Temp] = Array[Temp]; Temp++; } Temp2 += S; while(Temp2 &lt; Size) { DataTemp.Array[Temp] = Array[Temp2]; Temp++; Temp2++; } TransferFrom(DataTemp); return *this; } }while(Temp &lt; Size); return *this; } const bool Remove(const std::vector&lt;TemplateArray&gt; &amp;ItemCopy) { ERRORCLASSFUNCTION(TemplateArray,Remove,ItemCopy.empty(),RETURN_BOOL) ERRORCLASSFUNCTION(TemplateArray,Remove,!Remove(&amp;ItemCopy[0],ItemCopy.size()),RETURN_BOOL) return true; } const bool Remove(const TemplateArray &amp;ItemCopy) { ERRORCLASSFUNCTION(TemplateArray,Remove,!IsValid(),RETURN_BOOL) ERRORCLASSFUNCTION(TemplateArray,Remove,!Remove(ItemCopy.Array,ItemCopy.Size),RETURN_BOOL) return *this; } const bool Remove(const TemplateItem &amp;ItemCopy) { return Remove(&amp;ItemCopy,1); } void Reset() { if(Array != NULL) { DELETEB(Array); } Open(); } void Open(){ Clear(); } void Close() { if(Array != NULL) { DELETEB(Array); } Clear(); } //Tested TemplateArray(){Open();} ~TemplateArray(){Close();} //Tested TemplateArray(const TemplateItem Data[], const SIZE_TYPE S) { Open(); ERRORCLASSFUNCTION(TemplateArray,TemplateArray,!SetArray(Data,S),) } //Tested TemplateArray(const TemplateArray &amp;ItemCopy) { Open(); ERRORCLASSFUNCTION(TemplateArray,TemplateArray,!SetArray(ItemCopy),) } TemplateArray(const std::vector&lt;TemplateItem&gt; &amp;ItemCopy) { ERRORCLASSFUNCTION(TemplateArray,TemplateArray,!SetArray(ItemCopy),RETURN_VOID) } operator const SIZE_TYPE () const {return Size;} operator const std::vector&lt;TemplateItem&gt; () const { std::vector&lt;TemplateItem&gt; Temp; if(!IsValid()) { return Temp; } try { Temp.resize(Size); } catch(...) { std::vector&lt;TemplateItem&gt; Temp2; ERRORCLASSFUNCTION(TemplateArray,std::vector,true,return Temp2;) } SIZE_TYPE Temp2 = 0; while(Temp2 &lt; Size) { Temp[Temp2] = Array[Temp2]; Temp2++; } return Temp; } const bool operator!=(const TemplateArray &amp;ItemCopy){return !((*this) == ItemCopy);} const bool operator==(const TemplateArray &amp;ItemCopy) { return Compare(ItemCopy); } const bool operator==(const std::vector&lt;TemplateItem&gt; &amp;ItemCopy) { return Compare(ItemCopy); } TemplateArray &amp;operator+=(const TemplateItem &amp;ItemCopy) { ERRORCLASSFUNCTION(TemplateArray,operator+=,!Append(ItemCopy),RETURN_THIS) return *this; } //Tested TemplateArray &amp;operator+=(const TemplateArray &amp;ItemCopy) { ERRORCLASSFUNCTION(TemplateArray,operator+=,!Append(ItemCopy),RETURN_THIS) return *this; } //Tested TemplateArray &amp;operator+=(const std::vector&lt;TemplateItem&gt; &amp;ItemCopy) { ERRORCLASSFUNCTION(TemplateArray,operator+=,!Append(ItemCopy),RETURN_THIS) return *this; } TemplateArray &amp;operator-=(const TemplateItem &amp;ItemCopy) { ERRORCLASSFUNCTION(TemplateArray,operator-=,!Remove(ItemCopy),RETURN_THIS) return *this; } TemplateArray &amp;operator-=(const std::vector&lt;TemplateItem&gt; &amp;ItemCopy) { ERRORCLASSFUNCTION(TemplateArray,operator-=,!Remove(ItemCopy),RETURN_THIS) return *this; } TemplateArray &amp;operator-=(const TemplateArray &amp;ItemCopy) { ERRORCLASSFUNCTION(TemplateArray,operator-=,!Remove(ItemCopy),RETURN_THIS) return *this; } TemplateArray &amp;operator=(const std::vector&lt;TemplateItem&gt; &amp;ItemCopy) { ERRORCLASSFUNCTION(TemplateArray,operator=,!SetArray(ItemCopy),RETURN_THIS) return *this; } TemplateArray &amp;operator=(const TemplateArray &amp;ItemCopy) { ERRORCLASSFUNCTION(TemplateArray,operator=,!SetArray(ItemCopy),RETURN_THIS) return *this; } TemplateItem &amp;operator[](const SIZE_TYPE S){ return Array[S]; } const TemplateItem &amp;operator[](const SIZE_TYPE S) const { return Array[S]; } }; } </code></pre> <p>A working example you can paste directly into your compiler is also available <a href="http://ideone.com/mvUcj" rel="nofollow">here</a>.</p> <p>The class has to support the following:</p> <p>To minimise bug tracing times: </p> <ul> <li>Vocal error reporting.</li> <li>Traceable error reporting.</li> <li>Fail-safes (quit on first problem attitude).</li> <li>Functions that primarily return bool where possible.</li> </ul> <p>For compatibility with other classes: </p> <ul> <li>Return and accept a standard data-type (in this case, std::vector).</li> </ul> <p>The class should support the following requirements:</p> <ul> <li>User-friendliness. User should not have to think when using the class.</li> <li>Compatibility with future, potentially unknown classes and sub-classes.</li> </ul> <p>Please ignore the macro, printf usage and the fact the functions are inside the class. It's just my personal preference. <strong>Please <em>avoid</em> suggesting using <code>std::string</code>/<code>std::vector</code> (this is a really old cliche now)</strong>, as standard classes are generic and don't offer the specific functionality a custom built class can (i.e. bool returning, error-reporting/tracing functions), although it does offer compatibility with such classes.</p>
[ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-10-17T15:59:14.587", "Id": "8176", "Score": "2", "body": "Wouldn't it be easier to simply do this as a wrapper around std::vector? And I don't see the point of many of the bool returns? Some are functions that should never fail (and coincide with std::vector). The trace-ability could be easily done as a wrapper arounds std::vector." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-10-17T16:09:19.827", "Id": "8177", "Score": "0", "body": "Whats ERRORCLASSFUNCTION?" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-10-17T16:17:15.273", "Id": "8178", "Score": "0", "body": "@ronag: ERRORCLASSFUNCTION is a macro that both acts as an if escape statement and prints out the information (file, line, class, class method, operation it failed on, information to return). In the link supplied you'll find it included." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-10-17T16:20:09.247", "Id": "8179", "Score": "0", "body": "@ronag: It's not a wrapper because std::vector would require a riddle of try/catch statements. Functions that cannot/must not fail are automatically marked as void (E.G. Clear, Open, Close, Reset), functions that can fail (or have a negative status) return bool. I am not sure which functions you refer to that should never fail?" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-10-17T16:24:24.420", "Id": "8180", "Score": "0", "body": "None of the methods needed to implement this class as a wrapper around std::vector throws... other than std::bad_alloc which probably results in program termination, same as your class." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-10-17T16:44:17.563", "Id": "8183", "Score": "3", "body": "I think you're mistaken about the supposed inability of a generic to provide \"bool returning, error-reporting/tracing functions\". At least from my perspective, the fact that you've failed to provide `begin`, `end`, `rbegin`, `rend`, etc., means your class is essentially unusable. IMO, your class also has an almost incredibly bloated external interface. OTOH, your requirement at the end seem (to me) to be saying: \"Please tell me how to improve this without fixing any of its problems.\"" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-10-17T17:06:30.890", "Id": "8186", "Score": "4", "body": "There is a reason it is a cliche. Its because it works. This on the other hand I am not convinced about." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-10-17T17:15:21.403", "Id": "8187", "Score": "1", "body": "http://en.wikipedia.org/wiki/Not_Invented_Here" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-10-20T12:14:18.810", "Id": "8312", "Score": "0", "body": "@Loki: http://developers.slashdot.org/story/02/04/29/1813208/downsides-to-the-c-stl Really works huh?" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-10-20T12:23:18.717", "Id": "8313", "Score": "0", "body": "@Jerry: Can you justify one valid usage for begin/end/rbegin/rend that cannot already be performed with pointer operations? How exactly is the user interface bloated compared to vector? What features do you consider bloat?" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-10-20T12:25:55.513", "Id": "8314", "Score": "0", "body": "It strikes me with comments like 'where's rend?' etc that all you guys want is effectively a vector duplicate. This isn't trying to duplicate vector (and why on earth would I want it to be?). I'd retort by asking where's vector's -= and Trim function?" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-10-20T13:29:56.817", "Id": "8315", "Score": "1", "body": "@SSight: As far as begin(), end(), etc. go, the answer is simple: many algorithms depend on the standard names for them working. Likewise, programmers don't need to waste time learning your idiosyncrasies. As far as bloat goes, I think (for example) that having `operator==` public is sufficient, and the `Compare`s that it calls should be private. Likewise with `operator=` and `SetArray`. There shouldn't be an `IsValid`, because you should ensure no invalid object ever exists." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-10-20T16:17:37.423", "Id": "8322", "Score": "2", "body": "@SSight3: Your comments are just silly at this point. 2002!!! Accept the criticisms of your class make it better or ignore; then move on. Its not that big of a deal everybody makes a mess now and then." } ]
[ { "body": "<p>All your methods have corresponding functionality with std::vector. I suggest you write your class as a wrapper around std::vector.</p>\n\n<pre><code> template&lt;typename TemplateItem&gt;\nclass TemplateArray\n{\n public:\n // std::vector::empty\n const bool IsEmpty() const { return ((Array == NULL) &amp;&amp; (Size == 0)); }\n\n // unnecessary\n const bool IsValid() const { return ((Array != NULL) &amp;&amp; (Size != 0)); }\n const bool operator!() const {return IsEmpty();}\n operator const bool () const {return IsValid();}\n\n // std::vector::size\n const SIZE_TYPE GetSize() const {return Size;}\n\n // std::vector::resize\n const bool SetSize(const SIZE_TYPE S)\n\n // std::copy\n const bool CopyArray(const TemplateItem Arr[], const SIZE_TYPE S)\n const bool SetArray(const TemplateItem Arr[], const SIZE_TYPE S)\n const bool SetArray(const TemplateArray &amp;ItemCopy)\n const bool SetArray(const std::vector&lt;TemplateItem&gt; &amp;ItemCopy)\n TemplateItem * const GetArray() { return Array; }\n const TemplateItem * const GetArray() const { return Array; }\n\n // move constructor\n void TransferFrom(TemplateArray &amp;ItemCopy)\n\n // std::reverse\n const bool Reverse()\n\n // std::vector::operator==\n const bool Compare(const TemplateItem Arr[], const SIZE_TYPE S)\n const bool Compare(const TemplateArray &amp;ItemCopy)\n const bool Compare(const std::vector&lt;TemplateItem&gt; &amp;ItemCopy)\n\n // std::vector::push_back\n const bool Append(const TemplateItem Data[], const SIZE_TYPE S)\n const bool Append(const TemplateArray &amp;ItemCopy)\n const bool Append(const std::vector&lt;TemplateItem&gt; &amp;ItemCopy)\n const bool Append(const TemplateItem &amp;ItemCopy)\n\n // std::vector::erase + std::remove.\n const bool Remove(const TemplateItem Data[], const SIZE_TYPE S)\n const bool Remove(const std::vector&lt;TemplateArray&gt; &amp;ItemCopy)\n const bool Remove(const TemplateArray &amp;ItemCopy)\n const bool Remove(const TemplateItem &amp;ItemCopy)\n\n // std::vector::clear\n void Clear()\n void Reset()\n\n // A bit wierd, but i guess you want something like std::vector::clear + std::vector::shrink_to_fit\n void Open()\n void Close()\n\n // Nice to have i guess, std::vector::push_back\n TemplateArray &amp;operator+=(const TemplateItem &amp;ItemCopy)\n\n // std::vector::operator[]\n TemplateItem &amp;operator[](const SIZE_TYPE S){ return Array[S]; }\n const TemplateItem &amp;operator[](const SIZE_TYPE S) const { return Array[S]; }\n};\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-10-17T16:31:14.423", "Id": "8181", "Score": "0", "body": "Does vector even support move semantics...? And no low-level trace, and ignoring my request. You are not the first programmer to suggest this, you won't be the last (programmers have a nigh tendency to bleat std::string/std::vector etc etc as if it's a be-all, end-all solution - if I mention it, I already know it). [Appeal to tradition](http://en.wikipedia.org/wiki/Appeal_to_tradition) and [appeal to popularity](http://en.wikipedia.org/wiki/Argumentum_ad_populum). If vector does not support this functionality, I see no reason to expand it's obviously decrepit nature." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-10-17T16:41:08.637", "Id": "8182", "Score": "0", "body": "std::vector supports move semantics. I'm not saying that you should not use this class, I'm saying that you can more easily implement it as a wrapper over std::vector." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-10-17T16:50:41.100", "Id": "8184", "Score": "0", "body": "In some ways it could be more efficient, but I have no idea what vector does under the covers (and it varies from implementation to implementation). I do not see the move semantics from [this list](http://www.cplusplus.com/reference/stl/vector/)." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-10-17T17:02:05.433", "Id": "8185", "Score": "0", "body": "You are looking at the C++03 reference, not C++11 (http://msdn.microsoft.com/en-us/library/zzw4bwhd.aspx). What do you need to know of what it does under the covers? Most (everything?) of the things you should need to know is in the specification. It seems to me the only thing that is interesting for you is what exceptions it can throw, which it says in the reference." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-10-17T17:21:07.010", "Id": "8188", "Score": "0", "body": "I'm using 03 not 11 (11 has lots of nice touches but it's fairly new and not widely supported?). The fact it had to be updated kinda demonstrates my point on it being decrepit in nature." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-10-17T17:26:04.507", "Id": "8189", "Score": "0", "body": "All modern compilers support move semantics, MSCV2010, g++, clang etc..." } ], "meta_data": { "CommentCount": "6", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-10-17T16:08:17.567", "Id": "5425", "ParentId": "5424", "Score": "1" } }, { "body": "<blockquote>\n <p>How the code can be improved (even if it's just your subjective opinion)?</p>\n</blockquote>\n\n<p>Replace the macros with readable code.<br>\nThey make it much harder to read and understand than it needs to be.</p>\n\n<p>Your object does not provide any strong guarantees (which is what I would expect from a container). Either the operation succeeded or the operation fails and the object is left in its original state. Your array does not provide this. If it fails the original state is usually lost.</p>\n\n<p>This breaks your own rule of <code>User-friendliness. User should not have to think when using the class.</code> Now they do have to think. O crap that last operation just lost all my data I can;t even dump my current state for debugging.</p>\n\n<p>You don't seem to check for self assignment (not that I can see I could be wrong but the code is very hard to read). Thus you will break as you delete the array you are copying (yourself) and then read from the now dead array illiciting undefined behavior.</p>\n\n<blockquote>\n <p>How the code can be made more efficient?</p>\n</blockquote>\n\n<p>That will take a long time.<br>\nBut it looks like you have done a basic job of getting it working.</p>\n\n<p>It may improve the use of the swap method which can be useful in a lot of situations and the default implementation of swap is not very efficient for any container.</p>\n\n<p>You do not re-use the array. You always delete and allocate. That can be very in-efficient. It may be nicer to check if the array being copied over this one is smaller and if so re-use the array just move/copy the elements into this array.</p>\n\n<p>You don't pre-allocate memory for possible expansion in the near future and thus fall into the trap of deleting and re-allocating the array for every push onto the back no matter how big it is.</p>\n\n<blockquote>\n <p>How the functions of the class can be made more intuitive and user-friendly (does it operate like how you anticipate it to)?</p>\n</blockquote>\n\n<p>This is where your class is horrible. It is basically the most unfriendly container class I have seen and can <strong>not</strong> be used with any of the standard algorithms, which makes it practically unusable.</p>\n\n<blockquote>\n <p>Generally all-round friendly coder advice to a non-expert.</p>\n</blockquote>\n\n<ul>\n<li>Get rid of the macros replace them with function calls. </li>\n<li>Implement iterators. (so you can use the standard algorithms)</li>\n<li>Provide better protection for your user.\n<ul>\n<li>Operations that fail should leave the object unchanged.</li>\n</ul></li>\n</ul>\n\n<p>I will go to the cliche of saying I don't see any benefit of using this over std::vector (and I do see lots of negatives: Two of the big ones are ease of use and efficiency (Both contradicting your own design goals)).</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-10-19T15:43:49.117", "Id": "8284", "Score": "0", "body": "This is the criticism I was looking for. It will be all taken onboard." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-10-19T16:21:31.787", "Id": "8286", "Score": "0", "body": "`This is where your class is horrible. It is basically the most unfriendly container class I have seen and can not be used with any of the standard algorithms, which makes it practically unusable.` Could you clarify what it is you don't like so I could improve?" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-10-19T17:44:01.170", "Id": "8289", "Score": "0", "body": "in the section: `Generally all-round friendly coder advice`. The line: `Implement iterators` and the second line `Provide better protection for your user.` Both of these are essential. The first is easy the second will be near imposable with your current design (it needs a major re-write)." } ], "meta_data": { "CommentCount": "3", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-10-17T17:28:43.727", "Id": "5428", "ParentId": "5424", "Score": "6" } } ]
{ "AcceptedAnswerId": "5428", "CommentCount": "13", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-10-17T15:03:10.697", "Id": "5424", "Score": "5", "Tags": [ "c++", "template" ], "Title": "C++ TemplateClass" }
5424
<p>PHP doesn't have a built-in functions for <a href="http://en.wikipedia.org/wiki/Advanced_Encryption_Standard" rel="nofollow">AES</a> (specifically, AES-128) encoding/decoding, so I've had to implement my own, and this is what I have come up to (of course, taken from different many sources, mostly not coded by me).</p> <p>My question is, are these correct? Not the code itself, but what they do. The correctness of the algorithm. I have tested them, and they apparently do work. But there might be a subtle error that I'm overlooking... </p> <hr> <p><strong>Encoding algorithm:</strong></p> <pre><code>function aes128_encode($data, $mode) { switch ($mode) { case "ECB": case "CBC": if ($mode === "ECB") { $cipher = mcrypt_module_open(MCRYPT_RIJNDAEL_128, '', MCRYPT_MODE_ECB, ''); } else { $cipher = mcrypt_module_open(MCRYPT_RIJNDAEL_128, '', MCRYPT_MODE_CBC, ''); } $iv = mcrypt_create_iv(mcrypt_enc_get_iv_size($cipher), MCRYPT_RAND); $key = substr(CIPHERKEY, 0, mcrypt_enc_get_key_size($cipher)); if (mcrypt_generic_init($cipher, $key, $iv) != 1) { $cipherData = mcrypt_generic($cipher, $data); mcrypt_generic_deinit($cipher); mcrypt_module_close($cipher); if ($mode === "ECB") { $sanitizedCipherData = trim(base64_encode($cipherData)); } else { $sanitizedCipherData = trim(base64_encode($iv)."_".base64_encode($cipherData)); } return $sanitizedCipherData; } else { return false; } break; default: return false; break; } } </code></pre> <hr> <p><strong>Decoding algorithm:</strong></p> <pre><code>function aes128_decode($data, $mode) { switch ($mode) { case "ECB": $cipher = mcrypt_module_open(MCRYPT_RIJNDAEL_128, '', MCRYPT_MODE_ECB, ''); $key = substr(CIPHERKEY, 0, mcrypt_enc_get_key_size($cipher)); // Fake iv to call mcrypt_generic_init $iv = mcrypt_create_iv(mcrypt_enc_get_iv_size($cipher), MCRYPT_RAND); $cipherData = base64_decode($data); if (mcrypt_generic_init($cipher, $key, $iv) != -1) { $originalData = mdecrypt_generic($cipher, $cipherData); mcrypt_generic_deinit($cipher); mcrypt_module_close($cipher); return $originalData; } else { return false; } break; case "CBC": $cipher = mcrypt_module_open(MCRYPT_RIJNDAEL_128, '', MCRYPT_MODE_CBC, ''); $key = substr(CIPHERKEY, 0, mcrypt_enc_get_key_size($cipher)); $parts = explode("_", $data); $iv = base64_decode($parts[0]); $cipherData = base64_decode($parts[1]); if (mcrypt_generic_init($cipher, $key, $iv) != -1) { $originalData = mdecrypt_generic($cipher, $cipherData); mcrypt_generic_deinit($cipher); mcrypt_module_close($cipher); return $originalData; } else { return false; } break; default: return false; break; } } </code></pre> <hr> <p><strong>NOTE:</strong> The <code>$mode</code> variable indicates which <a href="http://en.wikipedia.org/wiki/Block_cipher_modes_of_operation" rel="nofollow">mode of operation</a> will be used (<code>ECB</code> or <code>CBC</code>). The <code>CIPHERKEY</code> is a constant with a randomized value that should be only known by the admin of the website.</p>
[ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-10-17T18:44:53.563", "Id": "8192", "Score": "2", "body": "It is SO easy to create a broken implementation of encryption that \"some guy on StackOverflow\" doesn't realize is broken. Can you make a native call to a proven implementation on your platform?" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-10-21T13:41:13.470", "Id": "8345", "Score": "0", "body": "Assuming the encryption is happening to store the data securely, I would recommend seeing if your storage platform can manage this task. For example, MySQL offers AES_ENCRYPT() and AES_DECRYPT() methods." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-10-21T18:35:13.067", "Id": "8361", "Score": "0", "body": "Yes, that's precisely what I did. AES encryption is too complex to just \"hope it works\". But I'm not too keen on using external libraries.\nMySQL's AES_ENCRYPT()/AES_DECRYPT() do the job perfectly" } ]
[ { "body": "<p>Implementing AES alone is very risky, mainly because it is very easy to make a mistake. I strongly recommend you use <a href=\"http://phpseclib.sourceforge.net/\">phpseclib</a> for this.</p>\n\n<p>Also you should not use ECB mode unless you are encrypting only 1 block.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-10-17T18:45:40.370", "Id": "5433", "ParentId": "5432", "Score": "10" } }, { "body": "<p>PHP may not have a built-in AES Encryption library but <a href=\"http://www.phpaes.com/\" rel=\"nofollow\">free one exist</a> for ECB or for other type you may check that <a href=\"http://phpseclib.svn.sourceforge.net/viewvc/phpseclib/trunk/phpseclib/Crypt/AES.php?content-type=text/plain\" rel=\"nofollow\">open source</a> project. I strongly suggest to not reinvent the wheel because it can be error prone.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-10-17T18:47:47.137", "Id": "5434", "ParentId": "5432", "Score": "1" } }, { "body": "<p>As I understand it, the only difference between AES and Rijndael is that AES is restricted to a 128-bit block size and can only use key sizes of 128, 192, and 256 bit. So if you are using Rijndael_128 with one of those three key lengths then you <em>are</em> uses AES. </p>\n\n<p>If you must have something that <em>says</em> AES, then, as Chris Smith said, use phpseclib.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-10-17T19:04:50.077", "Id": "5435", "ParentId": "5432", "Score": "4" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "3", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-10-17T18:42:07.423", "Id": "5432", "Score": "3", "Tags": [ "php", "security", "cryptography", "aes" ], "Title": "AES encryption in PHP" }
5432
<p>I am importing XML data to a MySql database using LINQ to Entities. The data represents which students are in which classes, and looks like...</p> <pre><code>&lt;studentClassesData&gt; &lt;studentClassEntry&gt; &lt;upn&gt;W432980573452&lt;/upn&gt; &lt;className&gt;8bcDn4&lt;/className&gt; &lt;/studentClassEntry&gt; &lt;studentClassEntry&gt; &lt;upn&gt;W234525211334&lt;/upn&gt; &lt;className&gt;8bcPe1&lt;/className&gt; &lt;/studentClassEntry&gt; &lt;!-- etc... --&gt; &lt;/studentClassesData&gt; </code></pre> <p>Each entry represents one student in one class. I know it would be better if the format were hierarchical (so each entry gives us all the students in a class), but the XML is generated externally so we have to use it as is.</p> <p>Receiving this information are two entities, <code>Class</code> and <code>Student</code>, which are linked in a many-to-many relationship (e.g. <code>Class.Students</code>). All the students and classes have already been imported to the database.</p> <p>Note that <code>Student.Upn</code> and <code>Class.LongName</code> are unique keys which correspond to the values given in the XML. But the primary keys are <code>Student.Id</code> and <code>Class.Id</code>.</p> <p>Here's my current code, with verbose comments added for explanation.</p> <pre><code>public static string ProcessStudentClasses(string path) { var sb = new StringBuilder(); using (var ctx = new Ctx()) { // Create a dictionary of all classes, to be accessed by their LongName // (attach the classes, but don't bother loading their properties) var classes = ctx.Classes.Select(o =&gt; new { o.LongName, o.Id }) .ToDictionary(o =&gt; o.LongName, o =&gt; new Class { Id = o.Id }); foreach (var cls in classes.Values) ctx.Classes.Attach(cls); // Similarly for students var students = ctx.Students.Select(o =&gt; new { o.Upn, o.Id }) .ToDictionary(o =&gt; o.Upn, o =&gt; new Student { Id = o.Id }); foreach (var stu in students.Values) ctx.Students.Attach(stu); // Create a lookup of which classes already have which students var studentsInClasses = ctx.Classes.SelectMany(c =&gt; c.Students, (c, s) =&gt; new { ClassId = c.Id, StudentId = s.Id } ).ToLookup(o =&gt; o.ClassId, o =&gt; o.StudentId); using (var reader = XmlReader.Create(path)) { var nodeName = String.Empty; var upn = String.Empty; var className = String.Empty; Student thisStudent = null; Class thisClass = null; while (reader.Read()) { switch (reader.NodeType) { case XmlNodeType.Element: // We're reading an XML element; note which element it is nodeName = reader.Name; break; case XmlNodeType.Text: // We're reading text (what's between the &lt;nodeName&gt; and &lt;/nodeName&gt; tags) var trimmed = reader.Value.Trim(); if (trimmed.Length == 0) continue; switch (nodeName) { case "upn": upn = trimmed; students.TryGetValue(upn, out thisStudent); // set 'thisStudent' break; case "className": className = trimmed; classes.TryGetValue(className, out thisClass); // set 'thisClass' break; } break; case XmlNodeType.EndElement: if (reader.Name != "studentClassEntry") continue; // We've got to the end of a studentClassEntry // If the student wasn't set... if (thisStudent == null) { sb.AppendFormat("Skipped: {0} - {1} (unknown UPN)&lt;br /&gt;", upn, className); // If the class wasn't set... } else if (thisClass == null) { sb.AppendFormat("Skipped: {0} - {1} (unknown class)&lt;br /&gt;", upn, className); // If the student's already in the class... // (Note, this only checks against the original list of students in classes; // an error will rightly be thrown if the imported XML contains duplicates) } else if (studentsInClasses[thisClass.Id].Contains(thisStudent.Id)) { sb.AppendFormat("Skipped: {0} - {1} (already exists)&lt;br /&gt;", upn, className); // Otherwise (we're good to add the student to the class)... } else { thisClass.Students.Add(thisStudent); sb.AppendFormat("Imported: {0} - {1}&lt;br /&gt;", upn, className); } // Reset everything, ready for the next entry thisStudent = null; thisClass = null; upn = String.Empty; className = String.Empty; break; } } } ctx.SaveChanges(); } return sb.ToString(); } </code></pre> <p>It takes 13.1 sec to process just over 21,000 student-class entries.</p> <p>I'd very much appreciate any suggestions.</p>
[ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-03-18T17:58:46.203", "Id": "16141", "Score": "0", "body": "What's taking 13 seconds? The parsing or the whole method? How big is your existing database? I suspect a lot of that time is coming from the fact that you're preprocessing the Classes and Students tables twice essentially before you even start reading." } ]
[ { "body": "<p>Hard to say what's causing the extra load here. I had a similiar task which initially took a very long time, but with some adjustments and the use of HashTables, i got it to run within a second (3000 entities created from a 80mb large xml-file).</p>\n\n<p>I did however use XDocument (LINQ-TO-XML) for the task. Have a look at my question regarding performance: <a href=\"https://stackoverflow.com/questions/1629596/xpathselectelement-vs-descendants\">https://stackoverflow.com/questions/1629596/xpathselectelement-vs-descendants</a></p>\n\n<p>Also note that you can take advantage of pre-compilated queries and other useful performance stuff when it comes to LINQ-TO-XML. </p>\n\n<p><a href=\"http://blog.dreamlabsolutions.com/post/2008/12/04/LINQ-to-XML-and-LINQ-to-XML-with-XPath-performance-review.aspx\" rel=\"nofollow noreferrer\">http://blog.dreamlabsolutions.com/post/2008/12/04/LINQ-to-XML-and-LINQ-to-XML-with-XPath-performance-review.aspx</a></p>\n\n<p>Good luck!\nMattias</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-10-27T09:05:48.400", "Id": "5627", "ParentId": "5436", "Score": "1" } }, { "body": "<p>If this were me I'd try commenting out the database insert element of the code, and time just the reading of the XML file.</p>\n\n<p>When you've got performance issues and databases are involved, it is often the database element that is causing it, and in this case I'd suspect the same. Possibly the table has indexes and each insert takes a while to process.</p>\n\n<p>The code looks good - one point I'd note is you try to avoid duplicates with the <em>studentsInClasses</em> lookup, but if you insert a new database value in your code, you should really update the <strong>studentsInClasses</strong> to reflect this, or you may get duplicate values.</p>\n\n<p>LINQ to XML</p>\n\n<p>I'd certainly say give LINQ to XML a try: it will reduce the amount of code, even if it might not solve your performance issues! </p>\n\n<p>This is all the XML reading bit translated for you. You'll need a \"using System.Xml.Linq;\" at the top.</p>\n\n<pre><code> // CHANGED: try LINQ to XML\n var doc = XDocument.Load(path);\n\n // find child elements\n foreach (XElement e in doc.Descendants(\"studentClassEntry\"))\n {\n // get values\n string upn = e.Element(\"upn\").Value;\n string className = e.Element(\"className\").Value;\n</code></pre>\n\n<p>I would echo the warning about large files. See <a href=\"http://mtaulty.com/CommunityServer/blogs/mike_taultys_blog/archive/2007/09/08/9803.aspx\" rel=\"nofollow\">this article</a> by Mike Taulty. He also has an excellent video tutorial <a href=\"http://vimeo.com/1382705\" rel=\"nofollow\">here</a>.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-01-18T14:54:38.333", "Id": "7929", "ParentId": "5436", "Score": "1" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "1", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-10-17T23:43:03.020", "Id": "5436", "Score": "2", "Tags": [ "c#", ".net", "linq", "xml", "entity-framework" ], "Title": "Importing XML to a database using LINQ to Entities" }
5436
<p>I've prepared a small C interface so the rest of my program can access relevant system functions. I am not a C programmer, though - just C++ and D, mainly. I want to make sure that everything here is "C-ish" before committing the rest of my code to this interface.</p> <p>This is just a plain old C file, compiled with a C compiler (as opposed to C++).</p> <pre><code> /* * This file provides functions to interface with * low-level terminal properties such as size and * input modes. Functions meant to be accessible * to external "user" code begin with "Terminal." */ #include &lt;sys/ioctl.h&gt; // For interfacing with the terminal device. #include &lt;termios.h&gt; // Ditto. #include &lt;unistd.h&gt; // For the STDIN_FILENO file descriptor macro. // This is just used internally, and should not be called directly from D code. struct winsize Size() { struct winsize Size; ioctl(STDIN_FILENO, TIOCGWINSZ, &amp;Size); return Size; } unsigned short int TerminalColumnCount() { return Size().ws_col; } unsigned short int TerminalRowCount() { return Size().ws_row; } // Used to reset the terminal properties to their original state. // Again, this is only for internal use. struct termios BackupProperties; // Removes terminal input buffering so programs can see typed characters before Enter is pressed. void TerminalMakeRaw() // I wish I could come up with a better name for this. { tcgetattr(STDIN_FILENO, &amp;BackupProperties); struct termios NewProperties; cfmakeraw(&amp;NewProperties); tcsetattr(STDIN_FILENO, TCSANOW, &amp;NewProperties); } void TerminalReset() { tcsetattr(STDIN_FILENO, TCSANOW, &amp;BackupProperties); } </code></pre>
[ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-10-18T03:07:52.120", "Id": "8198", "Score": "0", "body": "If you're compiling this with a C++ compiler, don't forget to use `extern \"C\"`." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-10-18T03:08:58.530", "Id": "8199", "Score": "0", "body": "@MartinhoFernandes It's just a plain C file, compiled with `gcc`. I'll edit that into the question." } ]
[ { "body": "<p>A few quick comments:</p>\n\n<ul>\n<li>You should declare all internal functions and variables <code>static</code> to avoid polluting the global namespace. (You'd do this in a C++ program as well, but would probably use an unnamed namespace. I'm not sure what the D equivalent is).</li>\n<li>Since you have state (implicitly and explicitly via <code>BackupProperties</code>) I'd recommend using an object oriented approach exposing an <a href=\"http://en.wikipedia.org/wiki/Opaque_pointer#C\" rel=\"nofollow\">opaque pointer</a> to maintain it, even if there is only one <code>Terminal</code> instance it's (IMO) a better approach. Otherwise you should at least ensure that <code>TerminalMakeRaw</code> isn't called twice without corresponding calls to <code>TerminalReset</code>.</li>\n<li>You should also consider that at some point you'll probably want to have callbacks of some sort to notify the users of your library when/if the window size changes and so on. </li>\n</ul>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-10-19T19:45:49.477", "Id": "8301", "Score": "0", "body": "Pertaining to your second suggestion, I ended up going with a global state solution. I'm aware that it's often considered bad practice, but in this case I think it makes sense and I'm not going to overcomplicate things just on principle." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-10-19T19:55:49.627", "Id": "8302", "Score": "0", "body": "@Maxpm: As long as you're making an informed decision it's fine by me :)" } ], "meta_data": { "CommentCount": "2", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-10-18T16:00:50.357", "Id": "5449", "ParentId": "5437", "Score": "2" } } ]
{ "AcceptedAnswerId": "5449", "CommentCount": "2", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-10-18T03:03:25.060", "Id": "5437", "Score": "2", "Tags": [ "c", "console", "unix" ], "Title": "Wrapper functions for terminal capabilities" }
5437
<p>I wrote a quick and dirty program to perform binary search with an ordered array (list) of C style strings. For example:</p> <p><code>{"1", "12", "23", "124"}</code> etc (though my input set is actually much different)</p> <p>NOTE:</p> <ol> <li><p>Apologies for the confusing names - <code>string</code> is not the string, <code>string-&gt;ID</code> is. (Like I said, I cobbled it together very quickly since I was writing into t a larger program). Assume all variables have been declared.</p></li> <li><p>I only care about program (piece) correctness and efficiency of the algorithm (for example - ignore the multiple returns etc) at the moment.</p></li> <li><p>Don't worry about function calls like Log() or macros that I've used. Bottom and top are calculated off of <code>stringEntries</code>.</p></li> <li><p>Think of ways this will break. Don't worry about the rest of the program - just focus on this piece!</p></li> <li><p><code>pID</code> is your input string. We're searching through "string"'s attribute "ID" (which is the string). Assume that "string" is actually something else, like a ptr to a struct or something, with a member "ID" which is a C-style string (null terminated and everything).</p></li> <li><p><code>len</code> is actually <code>strlen(pID)</code>.</p></li> </ol> <p></p> <pre><code> while (TRUE) { *string = &amp;stringEntries[mid = (bottom + top) / 2]; if (*string == NULL) { Log(DEBUG, _ERROR,”*string is NULL\n”); return ERROR; } else if ((*string)-&gt;ID == NULL) { Log(DEBUG, _ERROR,”(*string)-&gt;ID is NULL\n”); return ERROR; } if (!(diff = strcmp(pID, (*string)-&gt;ID))) diff = len - strlen((*string)-&gt;ID); if (!diff) return PRESENT; if (bottom == top) { if (diff &gt; 0) (*string)++; //ignore this bit - i need it later on return NOT_PRESENT; } if (diff &gt; 0){ if (bottom == mid) bottom++; else bottom = mid; } else top = mid; } </code></pre>
[]
[ { "body": "<p>There is not enough information to give a real review.<br>\nIf you fill in all the type information and make it a compilable function I will review your algorithm, but based on the available code the only thing I can review is the style.</p>\n\n<ul>\n<li><p>C and C++ are two completely different languages.</p>\n\n<ul>\n<li>Pick one and learn it.<br>\nThe syntax may be superficially the same but how you use it will not be.<br>\nI will make my comments assuming you are trying to write C++ not C.</li>\n</ul></li>\n<li><p>Your layout is so horrible that it is practically unreadable.</p>\n\n<ul>\n<li>Pick one of the common indenting style<br>\nIf this is a problem with cut and paste then learn how to use your editor so that you can cut/paste without tabs onto a website.</li>\n</ul></li>\n</ul>\n\n<h3>Review</h3>\n\n<pre><code>while (TRUE)\n</code></pre>\n\n<p>C++ has it's own boolean types. true/false</p>\n\n<pre><code> { \n</code></pre>\n\n<p>Horrible formatting. The above '{' is indented way to far especially in relation to the line it is encapsulating.</p>\n\n<pre><code> *string = &amp;stringEntries[mid = (bottom + top) / 2];\n</code></pre>\n\n<p>Assignment inside the [] is allowed but makes the code hard to read.<br>\nPrefer not to do that it is much more readable to split that into two lines.<br>\nYou are not being paid to write compact code you are being paid to write easy to maintain code.</p>\n\n<pre><code> if (!(diff = strcmp(pID, (*string)-&gt;ID))) \n diff = len - strlen((*string)-&gt;ID); \n</code></pre>\n\n<p>Your naming of variables here makes this code unreadable.<br>\nMake your variable names obvious.<br>\nDon't re-use variables. In the above code it looks like diff is being used for two different purposes (or is it not?). Let the compiler optimize out the extra space you should be making the code clear. </p>\n\n<pre><code> if (bottom == top) {\n if (diff &gt; 0) \n (*string)++; //ignore this bit - i need it later on\n return NOT_PRESENT; \n</code></pre>\n\n<p>Absolute fail.<br>\nThe indention suggests that we return when (diff > 0) but the code is not going to do that, as only the first statement after the <code>if statement</code> belongs to the if block. Always prefer to use statement blocks after control structures. Even if they are one liners (some people still use multi-line macro's that will break your code if you don't place it in '{' '}'</p>\n\n<pre><code> if (diff &gt; 0){ \n if (bottom == mid) bottom++; \n else bottom = mid; \n }\n else top = mid; \n</code></pre>\n\n<p>More barely readable code.<br>\nA nice alignment would be good. There are also other constructs that will help:</p>\n\n<pre><code> if (diff &gt; 0)\n {\n bottom = ( bottom == mid) ? bottom + 1 : mid;\n }\n else\n { \n top = mid;\n }\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-10-18T17:35:08.700", "Id": "8230", "Score": "0", "body": "Thanky you very much for taking the time to review. You're right - the indentation is an absolute nightmare, I didn't get the hang of using this editor (after the first few posts when everything seemed misaligned when I copy pasted it out of my editor). But your comments were instructive, thanks again." } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-10-18T15:41:05.807", "Id": "5448", "ParentId": "5438", "Score": "2" } } ]
{ "AcceptedAnswerId": "5448", "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-10-18T03:58:07.560", "Id": "5438", "Score": "3", "Tags": [ "c++", "c", "algorithm", "strings", "binary-search" ], "Title": "Binary search with strings" }
5438
<p>I have piece of code in C which removes any duplicate characters in a string. But I am doing it in two loops and would like it to optimize it to one loop. </p> <pre><code>void removeDuplicates(char* ptr) { int end = 1; int length = strlen(ptr); int current; int i; current = 1; for(end=1; end&lt;length; end++) { for(i=0; i&lt;end; i++) { if(ptr[end] == ptr[i]) break; } if(i == end) { ptr[current] = ptr[i]; current++; } } ptr[current] = 0; } int main(int argc, char** argv) { char str[256] = {0,}; gets(str); removeDuplicates(str); printf("%s\n", str); return 1; } </code></pre>
[ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-10-20T03:53:31.353", "Id": "8309", "Score": "3", "body": "Don't use `gets()` even in test code. Forget it exists; use `fgets()` instead." } ]
[ { "body": "<p>If you're optimizing for time, you could waste some memory and use an array of length <code>sizeof(char)</code> -- let's call it <code>seen</code> -- initialized with zeros.</p>\n\n<p>In the loop you'd a few things:</p>\n\n<ol>\n<li>if the <code>seen</code> count is greater than zero, increment an <code>offset</code> variable (the value of this offset is equal to how many duplicates of all characters have been found so far)</li>\n<li>copy the current character to a new position <code>offset</code> characters behind, if it was not previously seen -- meaning, if <code>seen[current_char]</code> is zero (possibly only if offset is non-zero, otherwise \"from\" and \"to\" position are the same)</li>\n<li>Increment <code>seen[current_char]</code> at the end of the loop</li>\n</ol>\n\n<p>Note that <code>current_char</code> is really the value of the character, not the index of the character in the input string.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-10-18T12:53:00.820", "Id": "5443", "ParentId": "5441", "Score": "0" } }, { "body": "<p>I believe this should turn out to be faster and more efficient:</p>\n\n<pre><code>#include &lt;stdio.h&gt;\n\nvoid removeDuplicates(char* ptr);\n\nvoid removeDuplicates(char* ptr) {\n int seen[(sizeof(char) &lt;&lt; 8) / (sizeof(int) * 8)] = {0,};\n\n char* source = ptr;\n char* dest = ptr;\n\n while (*source != '\\0') {\n\n int destIndex = (*source) / (sizeof(int) * 8);\n int destBit = 1 &lt;&lt; (*source) % (sizeof(int) * 8);\n\n if (!(seen[destIndex] &amp; destBit)) {\n *dest = *source;\n ++dest;\n\n seen[destIndex] |= destBit;\n }\n\n ++source;\n }\n\n *dest = '\\0';\n}\n\nint main (int argc, const char * argv[])\n{\n char str[256] = {0,};\n gets(str);\n removeDuplicates(str);\n printf(\"%s\\n\", str);\n return 0;\n}\n</code></pre>\n\n<p>It uses an array of ints as an array of booleans, each of which indicates whether a character has been seen. It eliminates the <code>strlen()</code> call (which iterates over the entire string) and replaces it with a NULL check. It uses two pointers into the string, <code>source</code> and <code>dest</code>, which track the current read location (iterating over the original string) and the current write location (the destination for in-place copying of the next non-duplicate character).</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-12-04T05:00:25.220", "Id": "130884", "Score": "0", "body": "Sorry you deserve the credit here." } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-10-18T14:23:57.490", "Id": "5446", "ParentId": "5441", "Score": "2" } }, { "body": "<p>Remove Duplicates: (Re-Write Ant's code so it is readable).</p>\n\n<pre><code>#include &lt;stdio.h&gt;\n\nvoid removeDuplicates(char* ptr);\n\nvoid removeDuplicates(char* ptr) \n{\n char seen[UCHAR_MAX+1] = {0};\n\n //\n // Smallest data type is a char (unless you want to bit\n // twiddle, and that has been shown to be not worth it\n // see the complaints about std::vector&lt;bool&gt; in C++).\n // 256 bytes is not much.\n // \n // By using char as they type it prevents all the complex\n // multiplication/division an bit twiddling that Ant was doing.\n\n unsigned char* source = (unsigned char*)ptr;\n unsigned char* dest = (unsigned char*)ptr;\n unsigned char next;\n\n do\n {\n next = *source; // Get next character.\n if (!seen[next]) // Only enter the `if block` if we have not seen it.\n {\n seen[next] = 1; // Mark it as seen\n *dest = next; // Move it to destination.\n // Note: source will change faster than dest when we\n // start seeing dupes, this acts as the copy back\n // over the duplicates.\n ++dest;\n }\n ++source;\n }\n while (next != '\\0'); // Once we have copied the null terminator quit.\n}\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-10-18T15:35:18.563", "Id": "8225", "Score": "0", "body": "That's about 100x more readable, but about 100x less fun... ;) If you're making assumptions about the size of a char you should be able to get away with `char seen[127]`. ASCII is only 7-bit." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-10-18T15:52:20.287", "Id": "8227", "Score": "0", "body": "No. Its 50x less fun. Still lots of fun left." } ], "meta_data": { "CommentCount": "2", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-10-18T15:08:03.647", "Id": "5447", "ParentId": "5441", "Score": "7" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "1", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-10-18T09:12:08.240", "Id": "5441", "Score": "5", "Tags": [ "c", "strings" ], "Title": "Removing any duplicate characters in a string" }
5441
<p>It's long, repetitive, and hard to follow.</p> <pre><code> private void Map(object x, JToken json) { var objType = x.GetType(); var props = objType.GetProperties().Where(p =&gt; p.CanWrite).ToList(); foreach (var prop in props) { var type = prop.PropertyType; var name = prop.Name; var value = json[name]; var actualName = name; if (value == null) { // try camel cased name actualName = name.ToCamelCase(Culture); value = json[actualName]; } if (value == null) { // try lower cased name actualName = name.ToLower(Culture); value = json[actualName]; } if (value == null) { // try name with underscores actualName = name.AddUnderscores(); value = json[actualName]; } if (value == null) { // try name with underscores with lower case actualName = name.AddUnderscores().ToLower(Culture); value = json[actualName]; } if (value == null) { // try name with dashes actualName = name.AddDashes(); value = json[actualName]; } if (value == null) { // try name with dashes with lower case actualName = name.AddDashes().ToLower(Culture); value = json[actualName]; } if (value == null || value.Type == JTokenType.Null) { continue; } // check for nullable and extract underlying type if (type.IsGenericType &amp;&amp; type.GetGenericTypeDefinition() == typeof(Nullable&lt;&gt;)) { type = type.GetGenericArguments()[0]; } if (type.IsPrimitive) { // no primitives can contain quotes so we can safely remove them // allows converting a json value like {"index": "1"} to an int var tmpVal = value.AsString().Replace("\"", string.Empty); prop.SetValue(x, tmpVal.ChangeType(type), null); } else if (type.IsEnum) { string raw = value.AsString(); var converted = Enum.Parse(type, raw, false); prop.SetValue(x, converted, null); } else if (type == typeof(Uri)) { string raw = value.AsString(); var uri = new Uri(raw, UriKind.RelativeOrAbsolute); prop.SetValue(x, uri, null); } else if (type == typeof(string)) { string raw = value.AsString(); prop.SetValue(x, raw, null); } else if (type == typeof(DateTime) || type == typeof(DateTimeOffset)) { DateTime dt; if (DateFormat.HasValue()) { var clean = value.AsString(); dt = DateTime.ParseExact(clean, DateFormat, Culture); } else if (value.Type == JTokenType.Date) { dt = value.Value&lt;DateTime&gt;().ToUniversalTime(); } else { // try parsing instead dt = value.AsString().ParseJsonDate(Culture); } if (type == typeof(DateTime)) prop.SetValue(x, dt, null); else if (type == typeof(DateTimeOffset)) prop.SetValue(x, (DateTimeOffset)dt, null); } else if (type == typeof(Decimal)) { var dec = Decimal.Parse(value.AsString(), Culture); prop.SetValue(x, dec, null); } else if (type == typeof(Guid)) { string raw = value.AsString(); var guid = string.IsNullOrEmpty(raw) ? Guid.Empty : new Guid(raw); prop.SetValue(x, guid, null); } else if (type.IsGenericType) { var genericTypeDef = type.GetGenericTypeDefinition(); if (genericTypeDef == typeof(List&lt;&gt;)) { var list = BuildList(type, value.Children()); prop.SetValue(x, list, null); } else if (genericTypeDef == typeof(Dictionary&lt;,&gt;)) { var keyType = type.GetGenericArguments()[0]; // only supports Dict&lt;string, T&gt;() if (keyType == typeof(string)) { var dict = BuildDictionary(type, value.Children()); prop.SetValue(x, dict, null); } } else { // nested property classes var item = CreateAndMap(type, json[actualName]); prop.SetValue(x, item, null); } } else { // nested property classes var item = CreateAndMap(type, json[actualName]); prop.SetValue(x, item, null); } } } </code></pre>
[ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-01-18T18:48:02.133", "Id": "66316", "Score": "2", "body": "I am downvoting this because there's no description of what the code does, it is basically a \"copy-paste\" question. Please at least include a short description of what the code does." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2016-02-12T06:16:37.940", "Id": "222926", "Score": "0", "body": "I'm not a c# programmer. However, one thing I noticed is that you have multiple if statements who all share the condition value == null. Why do you need like 4 if statements with the same condition? Why not simple take all the blocks from the 4 statements and put them into one?" } ]
[ { "body": "<p>Step 1: extract the body of the loop into its own method that takes prop as a parameter. Now your primary method looks like</p>\n\n<pre><code>private void Map(object x, JToken json)\n {\n var objType = x.GetType();\n var props = objType.GetProperties().Where(p =&gt; p.CanWrite).ToList();\n\n foreach (var prop in props)\n {\n process(prop);\n }\n }\n</code></pre>\n\n<p>and that's a good start.</p>\n\n<p>Now we spend a good amount of code getting the value from the name. Extract that:</p>\n\n<pre><code>private var toValue(var name)\n {\n var value = json[name];\n if (value != null) return value;\n\n value = json[name.ToCamelCase(Culture)];\n if (value != null) return value;\n\n value = json[name.ToLower(Culture)];\n if (value != null) return value;\n\n value = json[name.AddUnderscores()];\n if (value != null) return value;\n\n value = json[name.AddUnderscores().ToLower(Culture)];\n if (value != null) return value;\n\n value = json[name.AddDashes()];\n if (value != null) return value;\n\n value = json[name.AddDashes().ToLower(Culture)];\n if (value != null) return value;\n\n value = json[name.ToCamelCase(Culture)];\n if (value != null) return value;\n\n return null;\n }\n</code></pre>\n\n<p>Notice how much cleaner this section can be, because we've extracted it. We simply return the value when it's non-null, rather than checking over and over again whether it's null. And this extracted method has a clear single purpose; if you came up with another variant of how to process the name to make it a valid key, it would be clear where to put it. Smaller methods pay off in many ways.</p>\n\n<p>I think that is a good start and you should be able to see where to go from here.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-10-19T01:55:44.460", "Id": "8247", "Score": "0", "body": "I like it. I just think there's something more to be done from here. For example : http://sourcemaking.com/refactoring/replace-conditional-with-polymorphism" } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-10-18T17:40:19.490", "Id": "5452", "ParentId": "5450", "Score": "11" } }, { "body": "<p>To expand on Carl's answer a little more, this would be a good candidate for the <a href=\"http://en.wikipedia.org/wiki/Strategy_pattern\">strategy pattern</a>. You could add each case as a strategy callback:</p>\n\n<pre><code>private var toValue(var name, params Func&lt;var, var&gt;[] matchingStrategies)\n{\n foreach(var strategy in matchingStrategies)\n {\n value = json[strategy(name)];\n\n if (value != null)\n return value;\n }\n\n return null;\n}\n\n// usage:\n\nvar name = prop.Name;\n\nvar value = toValue(name,\n (n) =&gt; n.ToCamelCase(Culture),\n (n) =&gt; n.ToLower(Culture),\n (n) =&gt; n.AddUnderscores(),\n (n) =&gt; n.AddUnderscores().ToLower(Culture),\n (n) =&gt; n.AddDashes(),\n (n) =&gt; n.AddDashes().ToLower(),\n (n) =&gt; n.ToCamelCase(Culture));\n</code></pre>\n\n<p>So you're passing a list of matching strategies in order of execution, with the function returning the result of the first successful matching strategy.</p>\n\n<p>Or you could encapsulate each strategy into its own class - which would enable you to unit test them individually.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-10-21T13:35:34.670", "Id": "8344", "Score": "0", "body": "I'm pretty sure C# doesn't support `var` as a return type, or as part of a `Func` declaration." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-10-21T16:19:41.860", "Id": "8350", "Score": "4", "body": "Fair enough, if you're feeling particularly ambitious you could also probably replace the `foreach` loop with a `where` and `FirstOrDefault` linq query. Would make the intent of the code a bit clearer." } ], "meta_data": { "CommentCount": "2", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-10-19T09:31:14.790", "Id": "5467", "ParentId": "5450", "Score": "19" } }, { "body": "<p>I'd also drop the <code>.ToList()</code> on this line:</p>\n\n<pre><code>var props = objType.GetProperties().Where(p =&gt; p.CanWrite).ToList();\n</code></pre>\n\n<p>because props is only used in one place, to be enumerated over in the <code>foreach</code> loop. </p>\n\n<p>Calling <code>ToList</code> forces the computer to loop all the way through the collection, just to convert it into a list. </p>\n\n<p>Then on the very next line it loops all the way through a second time. Why do all that work just to get a list? </p>\n\n<p>The code would behave the same, only faster, if we just loop over the collection once</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-11-02T22:28:54.287", "Id": "28977", "Score": "0", "body": "Why would you drop the .ToList()?" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-02-26T23:06:50.297", "Id": "35774", "Score": "0", "body": "@JeffVanzella, because `props` is only used in one place, to be enumerated over in the foreach loop. Calling `ToList` forces the computer to loop all the way through the collection, just to convert it into a list. Then on the very next like it loops all the way through a second time. Why do all that work just to get a list? The code would behave the same, only faster, if we just loop over the collection once." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-01-15T22:34:58.940", "Id": "65848", "Score": "1", "body": "Just wanted you to elaborate :)" } ], "meta_data": { "CommentCount": "3", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-02-01T12:42:58.647", "Id": "8542", "ParentId": "5450", "Score": "5" } }, { "body": "<p>I personally try to stay away from using the <code>var</code> keyword, as sometimes it tends to make code unreadable for example <code>var result = ReturnResult();</code> when reading this I don't really know what the type it is at a glance. And try to initialize your variables outside of the <code>foreach</code> loop. I would normally declare all my variables at the top of the method and use them later on if needed.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2016-02-12T05:21:49.923", "Id": "222920", "Score": "0", "body": "the problem is not var, but the naming." } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-01-15T21:38:05.527", "Id": "39334", "ParentId": "5450", "Score": "-4" } } ]
{ "AcceptedAnswerId": "5467", "CommentCount": "2", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-10-18T16:43:29.867", "Id": "5450", "Score": "7", "Tags": [ "c#" ], "Title": "How can I make this method shorter and easier to follow?" }
5450
<p>I need to take a month (defined as a start and end date) and return a set of date ranges for each week in that month. A week is defined as Sunday through Saturday. A good way to visualize it is if you double click on your Windows date in the start bar:</p> <p><img src="https://i.stack.imgur.com/JNusa.png" alt="enter image description here"></p> <p>The month of October 2011 has 6 weeks: </p> <blockquote> <p>10/1-10/1 </p> <p>10/2-10/8 </p> <p>10/9-10/15 </p> <p>10/16-10/22 </p> <p>10/23-10/29 </p> <p>10/30-10/31</p> </blockquote> <p>I can describe each week as a struct:</p> <pre><code> struct Range { public DateTime Start; public DateTime End; public Range(DateTime start, DateTime end) { Start = start; End = end; } } </code></pre> <p>I need to write a function that takes a month and returns an array of ranges within it. Here's my first attempt, which appears to work and addresses the obvious edge cases:</p> <pre><code>public static IEnumerable&lt;Range&gt; GetRange(DateTime start, DateTime end) { DateTime curStart = start; DateTime curPtr = start; do { if (curPtr.DayOfWeek == DayOfWeek.Saturday) { yield return new Range(curStart, curPtr); curStart = curPtr.AddDays(1); } curPtr = curPtr.AddDays(1); } while (curPtr &lt;= end); if(curStart &lt;= end) yield return new Range(curStart, end); } </code></pre> <p>I would like to know if there's a cleaner or more obvious approach to do the same. I'm not overly concerned about performance, but I'd like to improve code readability and make the algorithm a bit more concise. Perhaps there's a very creative solution involving a single LINQ expression or something.</p>
[ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-10-18T18:14:00.327", "Id": "8232", "Score": "3", "body": "What happens when somebody flips the start and the end values? And what do you want when someone inputs dates over more than one month (dates in February and April, for example)? Different years? How do you determine the month the week belongs to - is it the month the starting Saturday is in, or must there be some minimum count in a given month? The final `if` clause isn't necessary if you add an `or` condition to the `if` clause in the loop. `curStart` isn't necessary if you put `curPtr.AddDays(1)` inside the `Range` creation. Your method name should be plural." } ]
[ { "body": "<p>Well, first of all your range only has to store the start date, as the weeks are always the same length:</p>\n\n<pre><code>struct Range {\n\n public DateTime Start { get; private set; }\n\n public DateTime End { get { return Start.AddDays(6); } }\n\n public Range(DateTime start) {\n Start = start;\n }\n\n}\n</code></pre>\n\n<p>Getting the weeks can simply be done by looking for sundays starting six days into the previous month:</p>\n\n<pre><code>public static IEnumerable&lt;Range&gt; GetRange(int year, int month) {\n DateTime start = new DateTime(year, month, 1).AddDays(-6);\n DateTime end = new DateTime(year, month, 1).AddMonths(1).AddDays(-1);\n for (DateTime date = start; date &lt;= end; date = date.AddDays(1)) {\n if (date.DayOfWeek == DayOfWeek.Sunday) {\n yield return new Range(date);\n }\n }\n}\n</code></pre>\n\n<p>To clarify: This returns the whole weeks that have days in the month, not partial weeks created from the days in the month by grouping them by what week they belong to.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-10-19T07:13:21.767", "Id": "8257", "Score": "2", "body": "Actually, I want my +1 back. :p `range only has to store the start date, as the weeks are always the same length`: in OP's example the first week has a single day; for a month to have all its weeks with the same length the 1st must be on the start of week and it must have days multiple of 7 (7,14,21,28,35), which means 1/7 of 3/4 of the Februaries, which means a `3/(4*12*7) = 3/336 = ~0.9%` chance." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-10-19T07:23:01.567", "Id": "8258", "Score": "0", "body": "@ANeves: Well, the confusion is due to the contradictions in the question. The OP starts out by *specifically defining* a week as seven days, then goes on to give an example will \"weeks\" of varying length. This code returns the actual weeks." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-10-19T07:34:39.650", "Id": "8260", "Score": "0", "body": "I feel the OP's intention was to not have weeks spill out of the month (or whatever the start/end range is defined as). But I can't +0 unless you edit; and if you do edit, the answer will become proper and deserve the +1 anyway; so, I guess it does not matter too much." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-12-16T09:10:11.330", "Id": "134115", "Score": "2", "body": "Why the downvote? If you don't explain what it is that you think is wrong, it can't improve the answer." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2015-10-26T16:16:22.807", "Id": "200055", "Score": "0", "body": "Why the downvote? If you don't explain what it is that you think is wrong, it can't improve the answer." } ], "meta_data": { "CommentCount": "5", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-10-18T23:56:35.423", "Id": "5459", "ParentId": "5451", "Score": "8" } }, { "body": "<p><strong>Updated</strong></p>\n\n<p>You can generate the dates for the month and use Linq to group them by the week of the year. I think this should give you a closer more elegant result.</p>\n\n<pre><code> DateTime reference = DateTime.Now;\n Calendar calendar = CultureInfo.CurrentCulture.Calendar;\n\n IEnumerable&lt;int&gt; daysInMonth = Enumerable.Range(1, calendar.GetDaysInMonth(reference.Year, reference.Month));\n\n List&lt;Tuple&lt;DateTime, DateTime&gt;&gt; weeks = daysInMonth.Select(day =&gt; new DateTime(reference.Year, reference.Month, day))\n .GroupBy(d =&gt; calendar.GetWeekOfYear(d, CalendarWeekRule.FirstFourDayWeek, DayOfWeek.Sunday))\n .Select(g =&gt; new Tuple&lt;DateTime, DateTime&gt;(g.First(), g.Last()))\n .ToList();\n\n weeks.ForEach(x =&gt; Console.WriteLine(\"{0:MM/dd/yyyy} - {1:MM/dd/yyyy}\", x.Item1, x.Item2));\n</code></pre>\n\n<p>If you pick any date from October 2015 as a reference, this is the result:</p>\n\n<pre><code>10/01/2015 - 10/03/2015\n10/04/2015 - 10/10/2015\n10/11/2015 - 10/17/2015\n10/18/2015 - 10/24/2015\n10/25/2015 - 10/31/2015\n</code></pre>\n\n<p>... you can play with it in the dotnetfiddle I created: <a href=\"https://dotnetfiddle.net/y4K8D8\" rel=\"nofollow\">.Net Fiddle - Week Ranges</a></p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2015-10-26T13:30:20.700", "Id": "200007", "Score": "3", "body": "What's with the underscore? Why is `reference` named normally but then, all of a sudden, `_cal`. I know it's nitpicking, but hey that's CodeReview ;)" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2015-10-26T14:32:08.883", "Id": "200023", "Score": "0", "body": "What is `day` in `new DateTime(reference.Year, reference.Month, day)`?" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2015-10-26T15:31:05.493", "Id": "200039", "Score": "1", "body": "Hi @KonradMorawski... thanks. You are right, I didn't clean the code enough. I just took it from a project I was working on. On that project `_cal` is a class variable, hence the underscore." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2015-10-26T15:34:03.563", "Id": "200041", "Score": "1", "body": "Hi @200_success, in that line `day` is the control variable in the lambda expression.\n`day => new DateTime(reference.Year, reference.Month, day`" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-05-05T18:09:36.677", "Id": "372495", "Score": "0", "body": "Amazing solution. Just what I needed! to run a script in batches... one week at a time. :-)" } ], "meta_data": { "CommentCount": "5", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2015-10-26T13:15:38.650", "Id": "108782", "ParentId": "5451", "Score": "3" } } ]
{ "AcceptedAnswerId": "5459", "CommentCount": "1", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-10-18T17:33:20.077", "Id": "5451", "Score": "14", "Tags": [ "c#", "algorithm", ".net", "datetime" ], "Title": "Listing the weeks in a given month" }
5451
<p>I have a flow where if a certain condition is true then I should take another approach. That condition can be triggered by different scenarios. But each condition test must be done only if the last one failed. Once a condition is true there is no further logical tests to do. My question is how to do that in an elegant way, the way I'm doing it right now requires an indentation for each condition.</p> <pre><code> StatusCode statusCode = null; boolean invokeService = true; CardPort cardPort = findCardPort(card, port); if (cardPort == null) { statusCode = StatusCode.CARD_PORT_NOT_FOUND; } else { Sim sim = cardPort.getSim(); if (sim == null) { statusCode = StatusCode.CARD_WITHOUT_SIM; } else { User user = sim.getUser(); if (user == null) { statusCode = StatusCode.SIM_WITHOUT_USER; } } } if (statusCode != null) { invokeService = false; } </code></pre>
[ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-10-18T18:24:30.483", "Id": "8234", "Score": "2", "body": "It looks like we're missing critical surrounding code. If not, it should be fairly easy to move the code into a function that can simply return the appropriate status code when an operation fails and not have to nest anything." } ]
[ { "body": "<p>Personally, I would separate this into multiple functions:</p>\n\n<pre><code>public StatusCode GetStatus( ... )\n{\n CardPort cardPort = findCardPort(card, port);\n if (cardPort == null) {\n return StatusCode.CARD_PORT_NOT_FOUND;\n } \n\n Sim sim = cardPort.getSim();\n if (sim == null) {\n return StatusCode.CARD_WITHOUT_SIM;\n } \n\n User user = sim.getUser();\n if (user == null) {\n return StatusCode.SIM_WITHOUT_USER;\n }\n\n return null; /* IMO, should be StatusCode.OK instead of null */\n}\n\npublic bool ShouldInvokeService( ... )\n{\n return GetStatus( ... ) == null;\n}\n</code></pre>\n\n<p>Now you don't need the nested indentations to track the status state -- just check conditions until you either know everything is okay, or you run into a problem. </p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-10-20T15:56:01.703", "Id": "8321", "Score": "1", "body": "Yes. Some people frown upon multiple returns in a method, but I find this approach (on handling error conditions, mostly) much cleaner, indeed." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-10-21T18:32:00.633", "Id": "8360", "Score": "0", "body": "I'd replace `return` with `throw`." } ], "meta_data": { "CommentCount": "2", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-10-18T19:48:56.540", "Id": "5455", "ParentId": "5453", "Score": "10" } } ]
{ "AcceptedAnswerId": "5455", "CommentCount": "1", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-10-18T17:51:11.897", "Id": "5453", "Score": "6", "Tags": [ "java" ], "Title": "Indented if/else approach" }
5453
<p>I am working on an application that reads lots of data from the network and puts it in a grid. I noticed that I could save some memory by reusing existing strings instead of always using the new strings that came off the wire. So here is the class that I wrote to accomplish that. It is simple and it works. But I was wondering if this had a name and, of course, if the code could be improved. One thing that I don't like is that I'm storing two references to each string.</p> <pre><code>public class StringCollection { private Dictionary&lt;string, string&gt; lookup_ = new Dictionary&lt;string, string&gt;(); public string Reuse(string s) { if (s == null) { return null; } string existing; if (lookup_.TryGetValue(s, out existing)) { return existing; } else { lookup_.Add(s, s); return s; } } public void Clear() { lookup_.Clear(); } public int Count { get { return lookup_.Count; } } } </code></pre>
[ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-10-19T02:46:16.987", "Id": "8249", "Score": "0", "body": "Making it generic would only make sense if it's use could be limited to immutable reference types. Plus, I only have a use for it with strings." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-10-19T02:57:17.283", "Id": "8250", "Score": "4", "body": "I question the usefulness of this. You're going to have to create an instance of the string anyway to get the key. What's the point of throwing it in a dictionary as key and value? I think you'll need to come up with a different way to tag the strings to make it more useful." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-10-19T03:07:01.097", "Id": "8251", "Score": "0", "body": "The point is, you can let the input string go out of scope and be collected if it is already found in the Dictionary. As I said, it works." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-10-19T05:44:58.213", "Id": "8252", "Score": "0", "body": "I doubt it would still help. There's no way for the framework to determine whether or not what you are receiving on the wire was already received without stuffing it in a buffer to process it. It would need a little bit of help from the other side. Something like a hash of the data before sending might be a better option. Then you could determine whether or not you could use the previously received value or receive the data." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-10-19T06:53:56.347", "Id": "8253", "Score": "1", "body": "DOH! I get it now... @JeffMercado, what he means is that he reads the string, and has it on a local scope. Then he checks in the dictionary, and re-uses the old copy. The new copy is discarded when local scope \"closes\". Otherwise the new string would be used, and not discarded. So, if he does a million cycles reading equal strings, with his method he will create a million strings but discard them and thus only have max two at a time in memory (the one in the dictionary, and new copy that will be checked and discarded); while otherwise he would have a million copies of similar strings." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-10-19T07:05:17.240", "Id": "8254", "Score": "0", "body": "@ANeves: Ok, so this is a cache. It makes sense now. With that said, it would be better to just throw them into a `HashSet<T>` instead of a dictionary." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-10-19T07:07:16.487", "Id": "8256", "Score": "0", "body": "@JeffMercado: great minds... :) http://codereview.stackexchange.com/questions/5460/reusing-strings-read-from-i-o/5462#5462" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-10-19T08:13:28.440", "Id": "8269", "Score": "0", "body": "Now that I've seen what goes into using the `HashSet<T>`, I think using a dictionary would be the better choice after all. Though, I'd probably use the hash of the string as the key instead of the string itself effectively making it a `Dictionary<int, string>`." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-10-19T09:50:44.753", "Id": "8278", "Score": "0", "body": "@JeffMercado: If you use the hash as key, then it won't work for strings where you get a hash collision. If you for example stored the string `\"Bbu\"` in the dictionary, then you could not also store the string `\"MbZ\"`." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-10-19T11:47:52.357", "Id": "8279", "Score": "1", "body": "Sorry, I should have shown the usage of the class as well. ANeves figured it out. And yes, a HashSet would not work and neither would using the hash of a string as the key." } ]
[ { "body": "<p>You might want to look into <a href=\"http://msdn.microsoft.com/en-us/library/system.string.intern.aspx\">string interning</a>:</p>\n\n<blockquote>\n <p>The common language runtime conserves string storage by maintaining a table, called the intern pool, that contains a single reference to each unique literal string declared or created programmatically in your program. Consequently, an instance of a literal string with a particular value only exists once in the system.</p>\n</blockquote>\n\n<p>While it has some memory-related side-effects, you could avoid having to build up a dictionary like this and throw away allocated strings to keep it updated.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-10-19T07:05:33.850", "Id": "8255", "Score": "0", "body": "+1, perfect! But your remark on side-effects is **very** important: as we can read in the link you provide, `the memory allocated for interned String objects is not likely be released until the common language runtime (CLR) terminates. The reason is that the CLR's reference to the interned String object can persist after your application, or even your application domain, terminates.`" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-10-19T11:49:04.647", "Id": "8280", "Score": "0", "body": "Thanks at least I have a name for the technique now. Yeah, I don't like that side effect. With my implementation, I can control when the strings are eligible for garbage collection." } ], "meta_data": { "CommentCount": "2", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-10-19T04:39:56.650", "Id": "5461", "ParentId": "5460", "Score": "10" } }, { "body": "<p>You can use a <code>HashSet&lt;string&gt;</code> instead of a dictionary to half the number of references that you keep, but getting the reference out of the hash set is a bit more difficult.</p>\n\n<p>I used this method to solve it:</p>\n\n<pre><code>public class LocalIntern {\n\n private HashSet&lt;string&gt; _lookup = new HashSet&lt;string&gt;();\n\n public string Reuse(string s) {\n if (s != null) {\n if (_lookup.Contains(s)) {\n s = _lookup.Where(i =&gt; i == s).First();\n } else {\n _lookup.Add(s);\n }\n }\n return s;\n }\n\n public void Clear() {\n _lookup.Clear();\n }\n\n public int Count { get { return _lookup.Count; } }\n\n}\n</code></pre>\n\n<p>Basic function verification:</p>\n\n<pre><code>LocalIntern intern = new LocalIntern();\n\n// store a string \nstring data = \"asdf\";\nintern.Reuse(data);\n\n// create another string instance with the same value \nstring data2 = String.Concat(\"as\", \"df\");\n// verify that they are in fact separate instances\nDebug.Assert(!Object.ReferenceEquals(data, data2));\n\n// look for the string\nstring d = intern.Reuse(data2);\n// verify that the string was replaced\nDebug.Assert(Object.ReferenceEquals(data, d));\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-10-19T08:03:59.487", "Id": "8266", "Score": "0", "body": "Hmm, I thought it would have been a simple index into the set to grab the value. I never realized that we couldn't do that. On second thought, using the dictionary might have been the best thing to do to keep it `O(1)`." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-10-19T09:40:39.180", "Id": "8276", "Score": "1", "body": "@ANeves: Well, not perfect as you get a nasty O(n) lookup when you get the reference from the hash set, so that's a trade-off for the reduced memory use. That could be solved by implementing the hashing yourself instead of using `HashSet`, but that's a lot more code..." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-10-19T23:14:40.613", "Id": "8305", "Score": "0", "body": "This trade-off was not acceptable for me, which is why I went with the Dictionary. It seems like there should be a way to only store one reference and also keep the speed of the Dictionary." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-10-19T23:18:32.787", "Id": "8306", "Score": "0", "body": "In most cases, the memory used by the duplicate references will only be a small fraction of the memory used by the strings themselves." } ], "meta_data": { "CommentCount": "4", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-10-19T07:50:21.380", "Id": "5465", "ParentId": "5460", "Score": "1" } }, { "body": "<p>The ideal thing here would be a <code>WeakDictionary&lt;string,string&gt;</code> (or better yet, a variation of a <code>WeakHashSet&lt;T&gt;</code> which allowed one to retrieve a reference to the stored item which matched a supplied key). Such a data structure would ensure that strings were shared whenever possible (a behavior which would not only reduce memory requirements, but also expedite comparisons among them, since comparing two distinct million-character strings that happen to be equal will take much longer than comparing two references to the same string). If one uses a <code>Dictionary&lt;string,string&gt;</code>, which is the best of the pre-existing classes for the purpose, it may be tricky to ensure that strings get kept as long as they may be useful, without having the dictionary keep them around even after they've become useless (if a string value has been used once before but all references outside the dictionary have been abandoned, having the string remain in the dictionary past the next GC cycle will generally serve no purpose; even if the same sequence of characters gets read again, it would generally be faster to have the old string evaporate and store a new string in the dictionary, than to have to compare all the characters in the new string against the ones in the old string and abandon the new one).</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-10-17T15:26:17.383", "Id": "17648", "ParentId": "5460", "Score": "0" } } ]
{ "AcceptedAnswerId": "5461", "CommentCount": "10", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-10-19T02:28:33.747", "Id": "5460", "Score": "11", "Tags": [ "c#", ".net", "strings", "memory-management" ], "Title": "Reusing strings read from I/O" }
5460
<p>Activating jQuery tabs from URL #id is www.somedomain.com/index.php#tab3</p> <p>Given this my best shot, and it does work but I feel it could be far far better.</p> <p>Please tell me if this is totally shockingly bad JS.</p> <pre><code>$(document).ready(function() { //When page loads... $(".tab_content").hide(); //Hide all content //On Click Event $("ul.tabs li").click(function (e) { e.preventDefault(); $("ul.tabs li").removeClass("active"); //Remove any "active" class $(this).addClass("active"); //Add "active" class to selected tab $(".tab_content").hide(); //Hide all tab content var activeTab = $(this).find("a").attr("href"); //Find the href attribute value to identify the active tab + content $(activeTab).fadeIn(); //Fade in the active ID content }); if(document.location.hash!='') { //get the index from URL hash var tabName = window.location.hash; $(tabName).show(); //Show tab from url hash var tabNumber = tabName.substr(4,1); //shorten #tab2 to just last digit "2" $("ul.tabs li:nth-child(tabNumber)").addClass("active").show(); } else { $("ul.tabs li:first").addClass("active").show(); //Activate first tab $(".tab_content:first").show(); //Show first tab content } }); </code></pre> <p>Thank you</p>
[ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-11-18T17:22:06.670", "Id": "62837", "Score": "0", "body": "Have you considered using [jQuery BBQ](http://benalman.com/projects/jquery-bbq-plugin/)?" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2017-08-16T12:09:54.100", "Id": "328404", "Score": "0", "body": "`$(\"ul.tabs li:nth-child(tabNumber)\")` won't work as `tabNumber` is treated as literal string in the selector." } ]
[ { "body": "<p>Well, you could do some refactoring with this code, the only issue I see is that the low level functinality is implemented at the top level of your code. It would be better to extract the logic to separate functions, something like this (I also improved your code formatting a little bit):</p>\n\n<pre><code>$((function() { // Deleted the \"document).ready\" part, that is not necessary.\n // Hide all content.\n $(\".tab_content\").hide();\n\n // If hash is present in the URL, show tab by hash. Otherwise, show the first tab.\n if(document.location.hash!='') {\n showTabByHash();\n }\n else {\n showFirstTab()\n }\n\n // On the click event of a tab.\n $(\"ul.tabs li\").click(function (e) {\n e.preventDefault();\n showTab($this);\n });\n});\n\nfunction showTab(tab) {\n // Remove any \"active\" class.\n $(\"ul.tabs li\").removeClass(\"active\");\n\n // Add \"active\" class to selected tab.\n tab.addClass(\"active\");\n\n // Hide all tab content\n $(\".tab_content\").hide();\n\n // Find the href attribute value to identify the active tab + content\n var activeTab = tab.find(\"a\").attr(\"href\");\n\n // Fade in the active ID content.\n $(activeTab).fadeIn();\n}\n\nfunction showTabByHash() {\n // Get the index from URL hash.\n var tabName = window.location.hash;\n // Shorten #tab2 to just last digit \"2\".\n var tabNumber = tabName.substr(4,1);\n\n // Why are these two lines needed? Don't they work with the same tab element?\n $(tabName).show(); //Show tab from url hash\n $(\"ul.tabs li:nth-child(tabNumber)\").addClass(\"active\").show();\n}\n\nfunction showFirstTab() {\n // Activate first tab.\n $(\"ul.tabs li:first\").addClass(\"active\").show();\n\n // Show first tab content.\n $(\".tab_content:first\").show();\n}\n</code></pre>\n\n<p>I do not see any other problems with the code (of course, it could be generalized a little bit, but that is not your goal if I understand right), apart from your coding style, which was a little bit cluttered in my opinion (I had to read it more than one time to completely understand it).\nAnd if you are developing in Visual Studio, and these functions are going to be used from somewhere else, then adding <a href=\"http://msdn.microsoft.com/en-us/library/bb514138.aspx\" rel=\"nofollow\">XML comments</a> to them would generally be a good idea.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-10-18T18:30:10.330", "Id": "8281", "Score": "0", "body": "Thank you Mark. That's really helpful. I'm using Notepad++ and attempting to get my JS knowledge up to scratch. Thanks again." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-10-18T18:39:46.290", "Id": "8282", "Score": "0", "body": "You're welcome. However, I am not a JS guru either, so maybe some JS guys will come and find something else there, who knows :)." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-08-29T01:33:01.740", "Id": "48336", "Score": "0", "body": "Old question, wouldn't it be better to trigger the tag with a `click` event? That way if you have any functions that get called when the tab is clicked, they would also be executed." } ], "meta_data": { "CommentCount": "3", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-10-18T18:25:42.740", "Id": "5469", "ParentId": "5468", "Score": "2" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "2", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-10-18T18:06:23.053", "Id": "5468", "Score": "2", "Tags": [ "javascript", "jquery", "performance" ], "Title": "jQuery Select Tabs based on URL #ID" }
5468
<p>There is as of .NET 2.0 a generic <code>EventHandler</code> delegate type, which can be used to define an event in terms of the <code>EventArgs</code> type you wish to use, without having to create a redundant delegate type to use in the event declaration.</p> <p>Well, what about the <code>EventArgs</code>? I often find myself having to create one-offs derived from <code>EventArgs</code> to encapsulate extra data I wish to send. Why can't that be declared generically as well? If all I need to pass is a string, or an integer, or a Point, why do I have to create a <code>StringEventArgs</code>, <code>IntEventArgs</code> and/or <code>PointEventArgs</code> class respectively?</p> <p>I roughed up two very basic <code>EventArgs</code> generic types as a proof-of-concept: </p> <pre><code>public class ReadOnlyEventArgs&lt;T&gt;:EventArgs { public T Parameter { get; private set; } public ReadOnlyEventArgs(T input) { Parameter = input; } } public class EventArgs&lt;T&gt;:EventArgs { public T Parameter { get; set; } public EventArgs(T input) { Parameter = input; } } </code></pre> <p>The obvious difference is whether you want event handlers to be able to modify your arguments. Sometimes it's a good idea, most of the time not so good. Usage would simply look like:</p> <pre><code>public event EventHandler&lt;EventArgs&lt;string&gt;&gt; StringValidationRequested; public event EventHandler&lt;ReadOnlyEventArgs&lt;int&gt;&gt; RecordSelectedForRetrieval; public event EventHandler&lt;ReadOnlyEventArgs&lt;Point&gt;&gt; MouseLocationReported; </code></pre> <p>Now, obviously these are for simpler situations, but I've found most situations of event raising to be pretty simple. The only possible thing I'd add would be two more classes derived from <code>CancelEventArgs</code> to add that additional functionality. The fact that the Parameter can be anything including a class makes it flexible enough to pass complex data, and .NET 4's <code>Tuples</code> take care of the remaining situations where you might not want to define your own complex type. The only drawback I can think of is not being able to descriptively name your parameter; it's generic.</p>
[ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-10-19T16:42:58.100", "Id": "8287", "Score": "0", "body": "You've only now just found out about it? It's been there since .NET 2.0. ;)" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-10-19T16:50:32.847", "Id": "8288", "Score": "0", "body": "Well I didn't JUST find out about it but my steady experience with .NET started at 3.5. Editing." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-10-19T19:03:16.530", "Id": "8298", "Score": "0", "body": "You know, I'm thinking in the case of the mutable event args with tuples, _if_ you wanted to support that, it might be useful to add (extension) methods for the EventArgs used to create the new set of arguments. Something like `ChangeItem1()` and so on. Then that would just be another set of overloads." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2015-06-05T20:03:10.383", "Id": "168545", "Score": "0", "body": "Along the same lines as this question, I find myself needing to wire into an event handler on a pop-up form that can pass an object back to the parent. [ItemChangedEventHandler](https://msdn.microsoft.com/en-us/library/system.windows.forms.itemchangedeventhandler.aspx) seems like it would fit my needs, but I do not have a way to set the Index value in the [ItemChangedEventArgs](https://msdn.microsoft.com/en-us/library/system.windows.forms.itemchangedeventargs.aspx) object that I want to pass back to the parent (it is not public)." } ]
[ { "body": "<p>You could make it a little bit more useful if you added some supporting factory methods to create the arguments. That way you don't have to use the constructor and its somewhat awkward syntax (having to supply the types).</p>\n\n<pre><code>public static class EventHandlerExtensions\n{\n public static EventArgs&lt;T&gt; CreateArgs&lt;T&gt;(\n this EventHandler&lt;EventArgs&lt;T&gt;&gt; _,\n T argument)\n {\n return new EventArgs&lt;T&gt;(argument);\n }\n\n public static ReadOnlyEventArgs&lt;T&gt; CreateArgs&lt;T&gt;(\n this EventHandler&lt;ReadOnlyEventArgs&lt;T&gt;&gt; _,\n T argument)\n {\n return new ReadOnlyEventArgs&lt;T&gt;(argument);\n }\n}\n</code></pre>\n\n<p>Then to create the instance of the arguments, you could just do this:</p>\n\n<pre><code>public event EventHandler&lt;EventArgs&lt;SomeArg&gt;&gt; SomeEvent;\npublic event EventHandler&lt;ReadOnlyEventArgs&lt;SomeArg&gt;&gt; SomeOtherEvent;\n\nprotected virtual void OnSomeEvent(SomeArg argument)\n{\n var someEvent = SomeEvent;\n if (someEvent != null)\n {\n var args = someEvent.CreateArgs(argument);\n // instead of:\n //var args = new EventArgs&lt;SomeArg&gt;(argument);\n someEvent(this, args);\n }\n}\n\nprotected virtual void OnSomeOtherEvent(SomeArg argument)\n{\n var someOtherEvent = SomeOtherEvent;\n if (someOtherEvent != null)\n {\n var args = someOtherEvent.CreateArgs(argument);\n // instead of:\n //var args = new ReadOnlyEventArgs&lt;SomeArg&gt;(argument);\n someOtherEvent(this, args);\n }\n}\n</code></pre>\n\n<p>It might be useful to have options for multiple parameters (similar to how the tuple is). Though it might not be feasible to have all combinations of multiple (im)mutable arguments.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-10-19T17:49:36.767", "Id": "8290", "Score": "0", "body": "Love it. As for multiple parameters, yes I could create a separate class for up to 16 generic types like Tuple/Func/Action, but first, it really wouldn't be that much more elegant versus just having you specify a Tuple, and second, just for EventArgs, ReadOnlyEventArgs, CancelEventArgs and ReadOnlyCancelEventArgs, that's 64 class definitions to write, test and sort through in IntelliSense. I think just making you specify a Tuple and access the args with e.Parameter.Value1 etc is saner, through it still requires a generic constructor." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-10-19T18:06:43.720", "Id": "8292", "Score": "0", "body": "Ah, I thought you get the `Handled`/`Cancel` property in the base `EventHandler`. I guess that's a WinForms feature. Having a factory method to handle multiple arguments and pack them into a tuple could make that scenario much more cleaner. Though it might be weird to specifically support a mutable `EvenArgs<Tuple>` as the tuple itself is immutable. It might be ok to omit those overloads." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-10-19T18:06:54.610", "Id": "8293", "Score": "0", "body": "Yes, the (non-generic) CancelEventArgs is in System.ComponentModel and exposes a boolean mutable Cancel argument that the event raiser can examine after each or all of the handlers are done. For the factory method, you'd still have to know what the generic signature of the Tuple needs to be, meaning you'd need 16 overloads of CreateArgs that would each accept a param list for a Tuple of the proper size and return an `EventArgs<Tuple<T1,T2,...>>`. As the parameters would be implied by the event, though, I do believe IntelliSense would be much easier to manage." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-10-19T18:11:36.117", "Id": "8296", "Score": "0", "body": "After further review, there are built-in ways to create a Tuple from a param list. There are 8 such overloads, so you could quite feasibly have only 7 overloads for Tuple-based EventArgs (the single-parameter Tuple is trivial and to be discouraged in this particular case). That's pretty easy to manage, actually. And yes, since the Tuple itself is immutable you really only want the read-only side." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2015-07-23T09:14:38.393", "Id": "178984", "Score": "0", "body": "Why do you feel var args = new EventArgs<SomeArg>(argument); is an Awkward syntax?" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2015-07-24T07:09:19.787", "Id": "179247", "Score": "0", "body": "@IgnacioSolerGarcia: Because you _must_ provide the type arguments. The compiler cannot infer the types in a constructor, but it can for methods. Would you prefer `new EventArgs<Dictionary<string, List<string>>>(argument)` or `someEvent.CreateArgs(argument)`? This is very much the same reason why factory methods like `Tuple.Create()` exists. This approach here takes it a step further and uses the delegate to provide the preferred types." } ], "meta_data": { "CommentCount": "6", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-10-19T17:08:17.607", "Id": "5472", "ParentId": "5470", "Score": "8" } }, { "body": "<p>Do you really need EventArgs concept? As for me, EventArgs is a legacy concept. When MS introduced generic Action and Func delegates I can hardly remember a situation, when I needed to use EventArgs again.</p>\n\n<p>As far as I understand, you are not bounded to .net 2.0, because you are using Tuple. So if you can, consider using Action and Func.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-04-17T21:34:11.977", "Id": "17423", "Score": "2", "body": "Events as a construct are useful in UI classes because they show up as such in the designer, as opposed to delegate properties." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-07-12T20:41:27.077", "Id": "44604", "Score": "0", "body": "Good suggestion. I never thought about using Action and Func for events." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-07-22T07:46:21.667", "Id": "103152", "Score": "1", "body": "It's still recommended to use EventArgs http://msdn.microsoft.com/library/ms182133.aspx If you are talking about event/EventHandler, they natively handle multiple subscription and unsubscription which is harder with Action or Func." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-10-21T22:46:30.240", "Id": "450522", "Score": "0", "body": "@Guillaume Doesn't event/Action or event/Func also natively handle multiple subscription and unsubscription? (If not, I'm not sure what you are referring to.)" } ], "meta_data": { "CommentCount": "4", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-10-21T04:15:15.653", "Id": "5497", "ParentId": "5470", "Score": "1" } } ]
{ "AcceptedAnswerId": "5472", "CommentCount": "4", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-10-19T16:10:24.130", "Id": "5470", "Score": "18", "Tags": [ "c#", "event-handling" ], "Title": "Generic EventArgs to go with generic EventHandler?" }
5470
<p>Empty Textboxes, <strong>class="loc"</strong> display <strong><em>"(City, State \ Country)"</em></strong> using <strong>italics and silver</strong>. Of course, Textboxes that do have data are displayed according to page defaults. <br><br> I noticed chaining and caching could be used. There are inheritances issues, so I am not bothering with using .addClass instead of targeting with .css.</p> <pre><code> $(function () { var loc = $('.loc'); function desc() { var tar = $(this); if (tar.val().length == 0) { tar.val("(City, State \\ Country)").css({ "color": "silver", "fontStyle": "italic" }); }; } function data() { var tar = $(this); if (tar.val() == "(City, State \\ Country)") { tar.val("").css({ "color": "black", "fontStyle": "normal" }); }; } loc.each(desc).blur(desc).click(data); }); </code></pre> <p>How far off base am I on understanding proper formatting in jQuery?</p>
[]
[ { "body": "<p>You should be using <code>input</code>'s <a href=\"http://developers.whatwg.org/common-input-element-attributes.html#the-placeholder-attribute\" rel=\"nofollow noreferrer\">placeholder</a> attribute instead of implementing the functionality by yourself.</p>\n\n<p>I suggest you read this article on stackoverflow: <a href=\"https://stackoverflow.com/questions/7557801/can-i-use-jquery-to-blank-textarea-fields-or-ajax-like-input-boxes\">https://stackoverflow.com/questions/7557801/can-i-use-jquery-to-blank-textarea-fields-or-ajax-like-input-boxes</a></p>\n\n<p>If you want to go the extra mile to ensure that even old browsers will have the functionality, the selected answer in that article explains how.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-10-20T01:31:43.660", "Id": "5482", "ParentId": "5471", "Score": "2" } }, { "body": "<p>A couple of things:</p>\n\n<ul>\n<li>Anytime you compare to 0 (zero) you want to make sure you use the exactly equal operator === instead of ==. What would make your code even more expressive is doing something like <code>if(tar.val().length){}</code> . This way your code is saying is \"if the value of tar is blank then do this\"</li>\n<li>I'd also bring the last line to the top of your function and place it under the var loc statement. The functions will be hoisted above all that so they'll be there even if they are defined after the calls. </li>\n<li>this could prob be re-factored into one function with a simple if/else statement checking the value of the field.</li>\n<li>Instead of using the each to call the data function ,assuming you don't have any other events attached to blur event you could call blur explicitly at the end of your chain to invoke that functionality <code>...click(data).blur()</code>. </li>\n<li>I would look into ANeves suggestions as well. </li>\n</ul>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-10-20T03:43:28.220", "Id": "8308", "Score": "0", "body": "About your second point, doesn't one need to define `desc` before calling `loc.each(desc)`?" } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-10-20T03:37:13.660", "Id": "5483", "ParentId": "5471", "Score": "3" } }, { "body": "<p>Additionally to the answers of bittersweetryan and ANeves, I'd like to suggest:</p>\n\n<p>1) Don't set the styles directly, but instead use a class, so that the styles are not hard coded into the script - especially important if the default font style isn't black and non-italic:</p>\n\n<pre><code>function desc() {\n var tar = $(this);\n if (tar.val().length == 0) {\n tar.val(\"(City, State \\\\ Country)\").addClass(\"placeholder\");\n };\n}\n\nfunction data() {\n var tar = $(this);\n if (tar.val() == \"(City, State \\\\ Country)\") {\n tar.val(\"\").removeClass(\"placeholder\");\n };\n}\n</code></pre>\n\n<p>with</p>\n\n<pre><code>.loc.placeholder {\n color: silver;\n font-style: italic;\n}\n</code></pre>\n\n<p>2) You should call <code>data</code> on <code>focus</code> instead of <code>click</code>, because a input field can obtain focus in other methods other than clicking.</p>\n\n<p>3) Finally you should move the string constants out of the code and make them parameters, so that the code is more flexible, for example, if you want to use it with other inputs.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-10-20T14:34:52.970", "Id": "5486", "ParentId": "5471", "Score": "1" } } ]
{ "AcceptedAnswerId": "5483", "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-10-19T16:21:12.837", "Id": "5471", "Score": "2", "Tags": [ "beginner", "jquery", "css" ], "Title": "Beginner jQuery – Coding Fundamentals / Performance" }
5471
<p>Goal: typesafe PropertyChanged events, minimum effort implementation for PropertyChanged events, runtime reflection of properties.</p> <p>Am I reinventing the wheel or have I created something worthwile? Would you use it in your next project?</p> <pre><code>public interface StaticProperty { public boolean canGet(); /** assert canGet()] */ public boolean canSet(); public boolean isvalid(); /** return rules().areAllMet() */ public boolean supportsPersistence(); /** assert instanceof Serializable &amp;&amp; new T() */ public boolean canReturnNull(); /** assert canReturnNull &amp;&amp; this.property != null */ public boolean canSetToNull(); /** assert canSetToNull() &amp;&amp; value != null */ public boolean firesEvent(); public abstract class AbstractProperty implements StaticProperty { protected boolean canGet = false; /** All false by default: explicitly set true in base */ protected boolean canGetNull = false; protected boolean canSet = false; protected boolean canSetNull = false; protected boolean isValid = false; protected boolean firesEvent = false; protected boolean supportsPersistence; protected AbstractProperty() {} @Override public boolean canSet() { return canSet; } @Override public boolean canSetToNull() { return canSetNull; } @Override public boolean canReturnNull() { return canGetNull; } @Override public boolean firesEvent() { return firesEvent; } @Override public boolean isvalid() { return isValid; } @Override public boolean canGet() { return canGet; } @Override public boolean supportsPersistence() { return supportsPersistence; } } } public class Props { /** * Any class having either getters, setters, or both * With this, you can do: * * for (Property property : someObject.properties()) { * query.select(property.name()) * .from(someObject.name()); * } * * */ public interface HasProperties { public PropertyTypeList properties(); } public interface IsChild&lt;H extends HasSetters&gt; { public void doSet(H hasProperty); /** Dispatch setting to the property itself */ } /** * A readonly property * */ public interface HasGetters extends HasProperties { public IsChild getProp(StaticProperty type); } public interface FakeProperty extends HasGetters { } /** Write only property */ public interface HasSetters extends HasProperties { public void setProp(StaticProperty type, IsChild value); } /** Because each property needs a dispatch method set(HasProperty parent), simple value types * must be wrapped. */ public interface Value { public interface StringValue extends Value { public String value(); } public interface IntValue extends Value { public int value(); } public interface DoubleValue extends Value { public double value(); } public interface DateValue extends Value { public java.util.Date value(); } public interface MultiValue extends Value { public interface ValueList extends ImmutableList&lt;Value&gt; {} public ValueList value(); } } public interface Handler&lt;P extends IsChild&gt; { public void changed(P newProp, P oldProp); public interface Handle { public void remove(); } } public interface NotifiesPropertyChange { // Type-safe property handling public void addHandler(StaticProperty type, Handler handler); // Register handling of any property change public void addHandler(Handler handler); } /** Keeps track of property values, fires events, dispatches to property */ public static interface PropertyList extends ImmutableList&lt;StaticProperty&gt; { public &lt;H extends HasSetters, P extends IsChild&gt; void set(StaticProperty type, P value, H hasProp); public IsChild get(StaticProperty type); public &lt;H extends HasSetters, P extends IsChild&gt; void setWithoutDispatch(StaticProperty type, P value, H hasProp); public PropertyTypeList types(); public void addHandler(StaticProperty type, Handler handler); public void addHandler(Handler handler); public static class PropertyTypeList extends ImmutableListImpl&lt;StaticProperty&gt; { public PropertyTypeList(List&lt;StaticProperty&gt; properties) { super(properties); } public PropertyTypeList(StaticProperty... properties) { super(properties); } @Override public String toString() { return "PropertyTypeList [items=" + items + "]"; } } public static class Impl extends AbstractImmutableList&lt;StaticProperty&gt; implements PropertyList { private final static boolean doDispatch = true; private final static boolean ignoreDispatch = false; private List&lt;StaticProperty&gt; types = new ArrayList&lt;StaticProperty&gt;(); private Map&lt;StaticProperty, IsChild&gt; properties = new HashMap&lt;StaticProperty, IsChild&gt;(); private Map&lt;Class, List&lt;Handler&gt;&gt; handlers = new HashMap&lt;Class, List&lt;Handler&gt;&gt;(); private List&lt;Handler&gt; geenricHandlers = new ArrayList&lt;Handler&gt;(); /** Construct from a list of property types */ public Impl(PropertyTypeList items2) { for (StaticProperty p : items2) { properties.put(p, null); types.add(p); } } /** Returns all the registered property types */ public PropertyTypeList types() { return new PropertyTypeList(types); } @Override protected List&lt;StaticProperty&gt; createList() { return new ArrayList&lt;StaticProperty&gt;(); } /** Asserts given property is present and returns it */ public IsChild get(StaticProperty type) { assert properties.containsKey(type); return properties.get(type); } /** Asserts given type is present and sets the property, dispatching to the property */ @Override public &lt;H extends HasSetters, P extends IsChild&gt; void set(StaticProperty type, P value, H hasProp) { assert properties.containsKey(type.getClass()); doSet(type, value, hasProp, doDispatch); } /** Sets target property _without_ dispatching to the property */ @Override public &lt;H extends HasSetters, P extends IsChild&gt; void setWithoutDispatch(StaticProperty type, P value, H hasProp) { doSet(type, value, hasProp, ignoreDispatch); } /** Sets the new value, dispatches to property and fires event */ private &lt;H extends HasSetters, P extends IsChild&lt;H&gt;&gt; void doSet(StaticProperty type, P value, H hasProp, boolean setParent) { assert value != null &amp;&amp; type.canSetToNull(); properties.put(type, value); if (setParent) value.doSet(hasProp); if (type.firesEvent()) onChanged(type, value, null); } /** Adds handler for target property */ @Override public void addHandler(StaticProperty type, Handler handler) { if (!handlers.containsKey(type.getClass())) handlers.put(type.getClass(), new ArrayList&lt;Handler&gt;()); handlers.get(type.getClass()).add(handler); } /** Adds handler for any property change event */ public void addHandler(Handler handler) { geenricHandlers.add(handler); } /** Fires event for target property and generic event */ public &lt;P extends IsChild&gt; void onChanged(StaticProperty type, P p, P old) { List&lt;Handler&gt; handlersForType = handlers.get(type.getClass()); if (handlersForType != null) for (Handler handler : handlersForType) handler.changed(p, old); for (Handler hanlder : geenricHandlers) hanlder.changed(p, old); } } } } public interface Woei extends HasName, SetsName, HasDescription, SetsDescription, NotifiesPropertyChange { public static WoeiName nameP = new WoeiName(); public static WoeiDescription descriptionP = new WoeiDescription(); /** Extend properties and set rule values after calling the super constructor */ public static class WoeiName extends AbstractProperty { public WoeiName() { canSetNull = false; firesEvent = true; isValid = true; canGetNull = true; } } public static class WoeiDescription extends AbstractProperty { public WoeiDescription() { canSetNull = false; firesEvent = true; isValid = true; canGetNull = true; } } public static class WoeiImpl implements Woei { private static PropertyTypeList propertyTypes = new PropertyTypeList(nameP, descriptionP); private PropertyList properties = new PropertyList.Impl(propertyTypes); private Name name; private Description description; @Override public IsChild getProp(StaticProperty type) { return properties.get(type); } @Override public PropertyTypeList properties() { return properties.types(); } @Override public Name name() { return name; } @Override public void setName(Name name) { this.name = name; properties.setWithoutDispatch(nameP, name, this); } @Override public void setProp(StaticProperty type, IsChild value) { properties.set(type, value, this); } @Override public Description description() { return description; } @Override public void setDescription(Description description) { this.description = description; properties.setWithoutDispatch(descriptionP, description, this); } @Override public void addHandler(StaticProperty type, Handler handler) { properties.addHandler(type, handler); } @Override public void addHandler(Handler handler) { properties.addHandler(handler); } } } </code></pre>
[ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-10-21T09:34:40.497", "Id": "8338", "Score": "0", "body": "I don't quite understand why you have both `canReturnNull` and `canSetNull`. Why not a single `permitsNull` or so?" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-10-25T19:02:44.570", "Id": "8457", "Score": "1", "body": "I'm not sure either. I guess I expect usecases where canGetNull is possible, but not canSetNull." } ]
[ { "body": "<p>I honestly think that your code suffers from over-engineering.</p>\n\n<p>As you can see in your <code>Woei</code> interface and <code>WoeiImpl</code> class, there is <strong>a lot</strong> of code that is required to <strong>use</strong> what you are building here. So to be blunt, I have to answer <code>Would you use it in your next project?</code> with <strong>NO</strong>.</p>\n\n<hr>\n\n<p>Regarding this code:</p>\n\n<pre><code>for (Property property : someObject.properties()) {\n query.select(property.name())\n .from(someObject.name());\n}\n</code></pre>\n\n<p>If you want to create a SQL query to search for properties like you are doing here, I recommend using <a href=\"http://www.hibernate.org\">Hibernate</a> (which simplifies this a lot -- once you actually get the whole system up and running correctly...)</p>\n\n<hr>\n\n<p>If I want to execute an event whenever a property has changed, I override the corresponding <code>set</code>-method in my code to do what I want to be done whenever the property is changing.</p>\n\n<p>There are way too many interfaces that has to be implemented/extended for me to want to use your code. I don't think it is worth all the trouble of your code just to make it a bit more typesafe, I would rather use <a href=\"http://docs.oracle.com/javase/tutorial/reflect/\">the built-in Java Reflection API</a>.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-11-26T13:51:23.927", "Id": "59054", "Score": "0", "body": "Only took 2 years before he got an answer!" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-11-26T13:59:06.890", "Id": "59056", "Score": "0", "body": "@user1021726 That's because [we're on a mission](http://meta.codereview.stackexchange.com/questions/999/call-of-duty-were-on-a-mission) now." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-11-26T14:30:49.437", "Id": "59066", "Score": "0", "body": "Oops didn't know!" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-11-26T14:37:45.007", "Id": "59067", "Score": "0", "body": "@user1021726 To help us on our mission please vote on questions and answers you find good. [There are very few voters around here](http://codereview.stackexchange.com/users?tab=Voters&filter=week)" } ], "meta_data": { "CommentCount": "4", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-11-26T13:07:46.390", "Id": "36133", "ParentId": "5475", "Score": "5" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "2", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-10-19T19:30:30.610", "Id": "5475", "Score": "4", "Tags": [ "java" ], "Title": "Typesafe Java properties with events and runtime reflection" }
5475
<p>I recently posted a question looking for feedback on a script I wrote (see: <a href="https://codereview.stackexchange.com/q/5400">Scraping PubMed query results</a>)</p> <p>Since then I have re-written it into a class, which I have posted below. How does it look? How can I improve upon it?</p> <pre><code>class PubMedQuery { private $query; private $searchParameters; private $searchURL; private $fetchParameters; private $fetchURL; private $searchResults; private $fetchResults; private $matches; private $matchRegex; private $emailAddresses; public function __construct($query) { $this-&gt;query = $query; } public function setSearchParameters() { $this-&gt;searchParameters = array( 'db' =&gt; 'pubmed', 'term' =&gt; $this-&gt;query, 'retmode' =&gt; 'xml', 'retstart' =&gt; '0', 'retmax' =&gt; '1000', 'usehistory' =&gt; 'y' ); } public function getSearchParameters() { return $this-&gt;searchParameters; } public function setFetchParameters() { $this-&gt;fetchParameters = array( 'db' =&gt; 'pubmed', 'retmax' =&gt; '1000', 'query_key' =&gt; (string) $this-&gt;searchResults-&gt;QueryKey, 'WebEnv' =&gt; (string) $this-&gt;searchResults-&gt;WebEnv ); } public function getFetchParameters() { return $this-&gt;fetchParameters; } public function setSearchURL() { $this-&gt;baseSearchURL = 'http://eutils.ncbi.nlm.nih.gov/entrez/eutils/esearch.fcgi?'; $this-&gt;searchURL = $this-&gt;baseSearchURL . http_build_query($this-&gt;getSearchParameters()); } public function getSearchURL() { return $this-&gt;searchURL; } public function setFetchURL() { $this-&gt;baseFetchURL = 'http://eutils.ncbi.nlm.nih.gov/entrez/eutils/efetch.fcgi?'; $this-&gt;fetchURL = $this-&gt;baseFetchURL . http_build_query($this-&gt;getFetchParameters()); } public function getFetchURL() { return $this-&gt;fetchURL; } public function setSearchResults() { $this-&gt;setSearchParameters(); $this-&gt;setSearchURL(); $this-&gt;searchResults = simplexml_load_file($this-&gt;getSearchURL()); } public function getSearchResults() { $this-&gt;setFetchParameters(); $this-&gt;setFetchURL(); return file_get_contents($this-&gt;getFetchURL()); } public function setEmailAddresses() { $this-&gt;matches = array(); $this-&gt;matchRegex = '/[A-Za-z0-9._%+-]+@[A-Za-z0-9.-]+\.[A-Za-z]{2,4}/'; preg_match_all($this-&gt;matchRegex, $this-&gt;getSearchResults(), $this-&gt;matches); $this-&gt;emailAddresses = array_unique(array_values($this-&gt;matches[0])); } public function getEmailAddresses() { $this-&gt;setSearchResults(); $this-&gt;getSearchResults(); $this-&gt;setEmailAddresses(); return $this-&gt;emailAddresses; } } //Example using search term "psoriasis" $query = new PubMedQuery('psoriasis'); echo implode('&lt;br /&gt;', $query-&gt;getEmailAddresses()); </code></pre>
[]
[ { "body": "<p>The first thing I might do is get rid of the email regex matching. PHP has this awesome functionality called <a href=\"http://www.php.net/manual/en/function.filter-var.php\" rel=\"nofollow\"><code>filter_var</code></a> that will take care of a lot of cool things for you, like <a href=\"http://www.php.net/manual/en/filter.filters.validate.php\" rel=\"nofollow\">validating a string as an email address</a>. This is a better solution because you're less likely to get back false positives where the email is valid, but doesn't match the regex.</p>\n\n<p>Next, I'm not sure I like the search/fetch parameters being set at various places throughout the code. This feels like something that should be done in the constructor; setup all the data you need to complete the responsibility of the class in the constructor. If you ever add a new method or make some changes you always have to keep in the back of your mind \"Have I set <code>$x</code> yet?\". Well, do it in <code>__construct()</code> and you'll know you have.</p>\n\n<p>Finally, I noticed you were calling some <code>get*</code> functions but not assigning the return value to any variable. If you don't use the return value you don't need to use the <code>get*</code> function and if you don't use the <code>get*</code> function you don't need it in the class.</p>\n\n<p>Overall I like the API, the method names are fairly self explanatory. I'm not sure that they should all be <code>public</code> as your use case only has one method actually being used from calling code. In addition, I might change the properties from <code>private</code> to <code>protected</code> for extensibility but that is certainly not mandatory and is as much a preference as anything else. I would also prefer to see some kind of documentation, even if it is just the responsibility of the class and your though processes behind why you solved the problem this way.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-03-27T00:44:18.547", "Id": "16527", "Score": "0", "body": "The setter methods don't actually set anything, they are just procedural code wrapped in a method." } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-01-26T23:41:13.803", "Id": "8351", "ParentId": "5485", "Score": "2" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-10-20T12:43:24.287", "Id": "5485", "Score": "2", "Tags": [ "php", "object-oriented", "web-scraping", "url" ], "Title": "Scraping PubMed query results: follow-up" }
5485
<p>Is this useful or is there an obvious other way?</p> <p>The context is solving the problem of bubbling events in an asp.net site built with user controls and nested user controls. I found myself writing a ton of events.</p> <p>So instead of events, i'm using a technique to allow any client to watch an arbitrary session value.</p> <p>A shared context class for Page and UserControl. Updates to session values go through here as well as registrations for session value changes.</p> <pre><code>public class WebSiteContext { private WebSitePage _webSitePage; public WebSiteContext(WebSitePage webSitePage) { _webSitePage = webSitePage; } internal void SetSessionValue&lt;T&gt;(string key, T value) { object current = _webSitePage.Session[key]; if (current != null &amp;&amp; current.Equals(value)) return; _webSitePage.Session[key] = value; if (_dic.ContainsKey(key)) _dic[key](value); } internal Dictionary&lt;string, Action&lt;object&gt;&gt; _dic = new Dictionary&lt;string, Action&lt;object&gt;&gt;(); internal void WhenSessionValueChanges(string key, Action&lt;object&gt; action) { _dic.Add(key, action); } } </code></pre> <p>Base page constructor creates context instance.</p> <pre><code>public class WebSitePage : System.Web.UI.Page { public WebSitePage() { this.WebSiteContext = new WebSiteContext(this); } public WebSiteContext WebSiteContext { get; set; } } </code></pre> <p>Base user control property to get context from parent page.</p> <pre><code>public class WebSiteUserControl : System.Web.UI.UserControl { public WebSiteContext WebContext { get { return (this.Page as WebSitePage).WebSiteContext; } } } </code></pre> <p>A user control makes a change to a session value.</p> <pre><code>public partial class AdvertiserSelector : WebSiteUserControl { protected void ComboBox_SelectedIndexChanged(object sender, EventArgs e) { this.WebContext.SetSessionValue( SessionKeys.current_advertiser_id, (sender as ComboBox).SelectedValue); } } </code></pre> <p>Now in my web page code behind, instead of subscribing to an event, an action is registered for a session value change.</p> <pre><code>namespace WebApplication1.Screens.CampaignSpend { public partial class Default : WebSitePage { protected void Page_Load(object sender, EventArgs e) { this.WebSiteContext.WhenSessionValueChanges(SessionKeys.current_advertiser_id, c =&gt; GridView1.DataBind()); } } } </code></pre>
[]
[ { "body": "<p>What you have implemented is just a change event for the session value, but as you are using a delegate instead of event only one control at a time can register for the event.</p>\n\n<p>Use an event instead of a delegate, and you have a regular change event for session variables.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-10-21T17:33:15.017", "Id": "8358", "Score": "0", "body": "i felt like i was missing somehting... would the client then have to both register which session keys it was interested in as well as subscribing to the event? I'm not saying that's bad - i think it was my tendency to want one step that led me down this road" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-10-21T18:05:59.207", "Id": "8359", "Score": "1", "body": "@Gabriel: You can use most of the code as it looks now, but have a dictionary that contains events instead of delegates. That way you can add multiple event handlers to it. Come to think of it, delegates are multicast too, so you could use the existing dictionary and combine delegates: http://msdn.microsoft.com/en-us/library/ms173175%28VS.80%29.aspx" } ], "meta_data": { "CommentCount": "2", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-10-21T06:54:45.987", "Id": "5498", "ParentId": "5495", "Score": "1" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-10-21T01:08:46.620", "Id": "5495", "Score": "2", "Tags": [ "c#", "asp.net" ], "Title": "observing asp.net session" }
5495
<p>Using cakePHP, I would love to have your point of view about this large source code, i am not sure if its enought secure. <code>sha1()</code> will be removed with another script. I found this large script can be optimized but how ?</p> <p>i have many times </p> <pre><code>$this-&gt;Session-&gt;setFlash("You hav to complete each fiedls", "error"); </code></pre> <p>and</p> <pre><code>$this-&gt;Request-&gt;redirect(SITE . "users/account"); </code></pre> <p>I wonder if I can optmize this also:</p> <pre><code>class UsersController extends Controller { function account($Req){ if(isset($Req-&gt;post-&gt;login)){ $login = addslashes($Req-&gt;post-&gt;login); $password = sha1(addslashes($Req-&gt;post-&gt;password)); $pass_confirm = sha1(addslashes($Req-&gt;post-&gt;pass_confirm)); $email = addslashes($Req-&gt;post-&gt;email); $signature = addslashes($Req-&gt;post-&gt;signature); if(empty($login) || empty($email)){ $this-&gt;Session-&gt;setFlash("You hav to complete each fiedls", "error"); $this-&gt;Request-&gt;redirect(SITE . "users/account"); } elseif($pass_confirm != $password) { $this-&gt;Session-&gt;setFlash("You gave two differents password", "error"); $Req-&gt;redirect(SITE . "users/account"); } $this-&gt;loadModel("Users"); $dispoLogin = $this-&gt;Users-&gt;findCount(array( "login" =&gt; $login )); if($dispoLogin === 0){ $this-&gt;Session-&gt;setFlash("The login is already use by someone else", "error"); $this-&gt;Request-&gt;redirect(SITE . "users/account"); } $dispoEmail = $this-&gt;Users-&gt;findCount(array( "email" =&gt; $email )); if($dispoEmail === 0){ $this-&gt;Session-&gt;setFlash("Email adress already use by someone else", "error"); $this-&gt;Request-&gt;redirect(SITE . "users/account"); } if(empty($password)){ $q = $this-&gt;Users-&gt;findFirst(array( "fields" =&gt; "password", "conditions" =&gt; array( "id" =&gt; $this-&gt;User-&gt;id ) )); $password = sha1($q-&gt;password); } $this-&gt;Users-&gt;save(array( "id" =&gt; $this-&gt;User-&gt;id, "login" =&gt; $login, "password" =&gt; $password, "email" =&gt; $email, "signature" =&gt; $signature )); $this-&gt;user-&gt;setData(array( "login" =&gt; $login, "password" =&gt; $password, "email" =&gt; $email, "signature" =&gt; $signature )); $this-&gt;Session-&gt;setFlash("Your profile page is updated"); $this-&gt;Request-&gt;redirect(SITE); } } } </code></pre>
[]
[ { "body": "<p>I answered you on SO but I'll repeat it here too.</p>\n\n<p>Please read the <a href=\"http://book.cakephp.org/\" rel=\"nofollow\">CakePHP Documentation</a>, preferably from the start because you really are getting a lot wrong here.</p>\n\n<ul>\n<li>There is no need to <code>addslashes()</code> everything, (or anything ever)</li>\n<li>CakePHP has it's own <a href=\"http://book.cakephp.org/view/1250/Authentication\" rel=\"nofollow\">AuthComponent</a>, so no need to roll your own</li>\n<li>It also has a <a href=\"http://book.cakephp.org/view/1143/Data-Validation\" rel=\"nofollow\">validation engine</a>, so no need to validate anything here</li>\n<li>You're also passing some Request object to the method? I don't even want to ask...</li>\n</ul>\n\n<p>This action should basically be about 6 lines long. TL;DR: Read the CakePHP Authentication docs, and start again.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-10-21T12:01:47.037", "Id": "8341", "Score": "0", "body": "Thank you for your answer\ni really see i have a lake on my knowledge. I'll fix that" } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-10-21T11:43:40.783", "Id": "5502", "ParentId": "5501", "Score": "2" } } ]
{ "AcceptedAnswerId": "5502", "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-10-21T11:20:13.690", "Id": "5501", "Score": "0", "Tags": [ "php", "optimization", "object-oriented" ], "Title": "Is my login function secure ? how to improve it?" }
5501
<p>Algorithm that I had to write is a perfect case for while, or do..while loop, however I found out that if I will implement it with a for loop I will save few lines of code and also scope of variables will be more appropriate. Take a look at the following code:</p> <pre><code> for ( var i = 1, offset = -1; currentPosition.top === fakePosition.top &amp;&amp; offset !== 0; i++ ) { fakePosition.top -= i * 10; offset = this.documentView.getOffsetFromPosition( fakePosition ); fakePosition = this.documentView.getRenderedPosition( offset ); } </code></pre> <p>As you can see second parameter is very atypical as for for loops. My mine reason to switch to this loop was fact that I need iterator (i) and offset variables inside loop (and only there).</p> <p>What do you think about this approach?</p>
[ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-10-21T19:16:33.297", "Id": "8362", "Score": "1", "body": "Too much magic in the loop condition." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-10-21T19:36:13.653", "Id": "8363", "Score": "0", "body": "@Raynos What exactly do you mean? I just see two simple conditional statement (for variables, not even method/function calls)." } ]
[ { "body": "<blockquote>\n <p>As you can see second parameter is very atypical as for for loops</p>\n</blockquote>\n\n<p>Which is why it shouldn't be a <code>for</code> loop, because as you write yourself(!) \"[it] is a perfect case for while, or do..while loop\". Saving a few lines of code and variable scope is not a good reason to obscure the code. You will (or should) be losing any perceived time/line benefit in writing the comments necessary to explain your trickery. If you want to limit variable scope, declare a new scope or function. </p>\n\n<p>As @Raynos alludes to in the comments, you should avoid \"magic\", or rather, complicated expressions in your for loops (and other conditional statements). It might not look bad to you now (though it probably will in X months), but consider what happens when your boss/client asks you to add support for a special case. Very quickly it'll look like this:</p>\n\n<pre><code> for ( var i = 1, offset = -1; currentPosition.top === fakePosition.top &amp;&amp; offset !== 0 &amp;&amp; currentPosition.top != -1 /* browser XYZ gives bogus answer */ &amp;&amp; offset &lt; fakePosition.bottom /* handle condition explained in ticket #123 */; i++ ) {\n fakePosition.top -= i * 10;\n offset = this.documentView.getOffsetFromPosition( fakePosition );\n fakePosition = this.documentView.getRenderedPosition( offset );\n }\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-10-21T20:34:08.783", "Id": "8366", "Score": "0", "body": "Thanks! I refactored it to look like this: http://pastebin.ca/2092328 But I'm still not happy with it - especially that it has 'return' inside loop body." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-10-21T20:49:39.353", "Id": "8368", "Score": "0", "body": "Sometimes code just has to stay \"ugly\", but clear, until you figure out the right way of being clever where you actually reduce complexity rather than increase it. In this case I have to say good luck :)" } ], "meta_data": { "CommentCount": "2", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-10-21T20:00:53.627", "Id": "5509", "ParentId": "5508", "Score": "2" } }, { "body": "<p>The <code>for</code> command is great for simple loops, as it makes the code easier to read when the loop follows a common pattern. For more complex loops you lose that advantage, so you should use a construct that better describes what the loop does.</p>\n\n<blockquote>\n <p>scope of variables will be more appropriate</p>\n</blockquote>\n\n<p>No, it won't. It doesn't matter where in a function you declare a variable, the scope is the entire function.</p>\n\n<p>You can even declare variables below the code where you use it, they will actually be created when you enter the function. Example:</p>\n\n<pre><code>function test() {\n alert(x); // shows undefined\n x = 42;\n alert(x); // shows 42\n var x;\n alert(x); // shows 42\n}\n\n// global scope:\nvar x = 1337;\nalert(x); // shows 1337\ntest();\nalert(x); // shows 1337\n</code></pre>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-10-21T21:42:23.197", "Id": "5512", "ParentId": "5508", "Score": "1" } } ]
{ "AcceptedAnswerId": "5509", "CommentCount": "2", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-10-21T19:09:57.367", "Id": "5508", "Score": "2", "Tags": [ "javascript" ], "Title": "What do you think about this usage of for loop in JavaScript?" }
5508
<p>In order to detect run-time integer casting problems, I've created this function*:</p> <pre><code>template&lt;typename TTo, typename TFrom&gt; static inline TTo int_cast(TFrom value) { TTo result = static_cast&lt;TTo&gt;(value); if (static_cast&lt;TFrom&gt;(result) != value || (result &gt;= TTo()) != (value &gt;= TFrom())) { throw std::out_of_range("numeric_cast: value out of range"); } return result; } </code></pre> <p>Two questions:</p> <ol> <li><p>Are there any loopholes in this function I have not accounted for (e.g. undefined behavior)?</p></li> <li><p>What would be the best way to extend this to perform double-to-float and floating-to-integral conversions?</p></li> </ol> <p><sub>*Note: Yes, I realize Boost has a function like this. But I want my own. :)</sub></p>
[ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-10-22T10:36:50.160", "Id": "8375", "Score": "0", "body": "If you are worried about casting problems why not stick to plain `int`s? It would be safer and faster." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2017-05-02T23:25:49.737", "Id": "308306", "Score": "0", "body": "For those arriving from search engines, Boost provides [`boost::numeric_cast`](http://www.boost.org/doc/libs/1_64_0/libs/numeric/conversion/doc/html/boost_numericconversion/improved_numeric_cast__.html)." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-11-14T02:01:40.467", "Id": "400726", "Score": "0", "body": "I don't think it is appropriate to use exceptions in this case and would recommend using assertions instead. If your algorithm is designed correctly then there will be no invalid casts as long as only correct data is supplied. If you are checking your data before using the algorithm then the only reason for a bad cast would be due to a bug in your algorithm. Exceptions are not meant to handle software bugs." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-11-14T02:17:20.673", "Id": "400730", "Score": "0", "body": "@Chris_F: The issue is that overflow is not always a bug, but potentially a limitation. Instead of getting wrong answers you might prefer an error." } ]
[ { "body": "<blockquote>\n <p>Are there any loopholes in this function I have not accounted for (e.g. undefined behavior)?</p>\n</blockquote>\n\n<p>No. Static cast will not result in undefined behavior.<br>\nIf it compiles then the cast is good (assuming integer/float types).</p>\n\n<p>Though some of your cast may potentially result in implementation defined behavior (depending on the sign-dness and size of the types).</p>\n\n<pre><code>signed x = int_cast&lt;signed,unsigned&gt;(-1); // implementation defined behavior.\n</code></pre>\n\n<p>Since this is only supposed to work on int(s). Then I would make it be a compile time error if you tried to use it with other types. You may also be able to do some compile time range checking when the inputs are literals.</p>\n\n<p>In the following:</p>\n\n<pre><code>(result &gt;= TTo()) != (value &gt;= TFrom())\n</code></pre>\n\n<p>I am assuming this is some form of signdness test (to make sure both source and destination have the same sign). If you are going to do this please comment the code explaining exactly how you think it works.</p>\n\n<p>There are integer traits that allow you to pull the signdess and size of the template type from the input/output types. You could potentially look at this to help identify things.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-10-22T07:39:44.260", "Id": "5519", "ParentId": "5515", "Score": "9" } }, { "body": "<p>If you are able to use C++11 in your application, then you can make use of the <code>enable_if</code> template to provide several overloads of your checked narrowing conversion:</p>\n\n<pre><code>#include &lt;limits&gt;\n#include &lt;stdexcept&gt;\n#include &lt;type_traits&gt;\n\ntemplate &lt;typename I, typename J&gt;\nstatic typename std::enable_if&lt;std::is_signed&lt;I&gt;::value &amp;&amp; std::is_signed&lt;J&gt;::value, I&gt;::type narrow_check(J value) {\n if (value &lt; std::numeric_limits&lt;I&gt;::min() || value &gt; std::numeric_limits&lt;I&gt;::max()) {\n throw std::out_of_range(\"out of range\");\n }\n return static_cast&lt;I&gt;(value);\n}\n\ntemplate &lt;typename I, typename J&gt;\nstatic typename std::enable_if&lt;std::is_signed&lt;I&gt;::value &amp;&amp; std::is_unsigned&lt;J&gt;::value, I&gt;::type narrow_check(J value) {\n if (value &gt; static_cast&lt;typename std::make_unsigned&lt;I&gt;::type&gt;(std::numeric_limits&lt;I&gt;::max())) {\n throw std::out_of_range(\"out of range\");\n }\n return static_cast&lt;I&gt;(value);\n}\n\ntemplate &lt;typename I, typename J&gt;\nstatic typename std::enable_if&lt;std::is_unsigned&lt;I&gt;::value &amp;&amp; std::is_signed&lt;J&gt;::value, I&gt;::type narrow_check(J value) {\n if (value &lt; 0 || static_cast&lt;typename std::make_unsigned&lt;J&gt;::type&gt;(value) &gt; std::numeric_limits&lt;I&gt;::max()) {\n throw std::out_of_range(\"out of range\");\n }\n return static_cast&lt;I&gt;(value);\n}\n\ntemplate &lt;typename I, typename J&gt;\nstatic typename std::enable_if&lt;std::is_unsigned&lt;I&gt;::value &amp;&amp; std::is_unsigned&lt;J&gt;::value, I&gt;::type narrow_check(J value) {\n if (value &gt; std::numeric_limits&lt;I&gt;::max()) {\n throw std::out_of_range(\"out of range\");\n }\n return static_cast&lt;I&gt;(value);\n}\n</code></pre>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-05-22T21:42:12.943", "Id": "26496", "ParentId": "5515", "Score": "8" } } ]
{ "AcceptedAnswerId": "5519", "CommentCount": "4", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-10-22T01:25:56.970", "Id": "5515", "Score": "17", "Tags": [ "c++", "casting" ], "Title": "C++ int_cast<> function for checked casts?" }
5515
<p>I have a situation where I have six possible situations which can relate to four different results. Instead of using an extended if/else statement, I was wondering if it would be more pythonic to use a dictionary to call the functions that I would call inside the if/else as a replacement for a "switch" statement, like one might use in C# or php.</p> <p>My switch statement depends on two values which I'm using to build a tuple, which I'll in turn use as the key to the dictionary that will function as my "switch". I will be getting the values for the tuple from two other functions (database calls), which is why I have the example one() and zero() functions.</p> <p>This is the code pattern I'm thinking of using which I stumbled on with playing around in the python shell:</p> <pre><code>def one(): #Simulated database value return 1 def zero(): return 0 def run(): #Shows the correct function ran print "RUN" return 1 def walk(): print "WALK" return 1 def main(): switch_dictionary = {} #These are the values that I will want to use to decide #which functions to use switch_dictionary[(0,0)] = run switch_dictionary[(1,1)] = walk #These are the tuples that I will build from the database zero_tuple = (zero(), zero()) one_tuple = (one(), one()) #These actually run the functions. In practice I will simply #have the one tuple which is dependent on the database information #to run the function that I defined before switch_dictionary[zero_tuple]() switch_dictionary[one_tuple]() </code></pre> <p>I don't have the actual code written or I would post it here, as I would like to know if this method is considered a python best practice. I'm still a python learner in university, and if this is a method that's a bad habit, then I would like to kick it now before I get out into the real world.</p> <p>Note, the result of executing the code above is as expected, simply "RUN" and "WALK".</p>
[ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-10-22T13:27:38.397", "Id": "8377", "Score": "0", "body": "best practice questions are outside of the scope of code review" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-10-27T01:15:56.923", "Id": "8485", "Score": "0", "body": "Please move this to Stack Overflow, where it belongs." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-06-04T09:29:50.903", "Id": "376991", "Score": "0", "body": "The current question title, which states your concerns about the code, is too general to be useful here. Please [edit] to the site standard, which is for the title to simply state **the task accomplished by the code**. Please see [How to get the best value out of Code Review: Asking Questions](//codereview.meta.stackexchange.com/q/2436) for guidance on writing good question titles." } ]
[ { "body": "<p>In short, a dictionary of functions <em>IS</em> the Python equivalent of the switch statement.</p>\n\n<p>However, your implementation is awful. Start by dropping the \"switch\" in your variable names. It is not a switch, it is a dictionary. And there is no point in using \"dictionary\" in the name either. Make a real name like \"act_on_msg\" but even that is weak in my opinion.</p>\n\n<p>And don't even explain that you are using a dictionary as a switch in your comments. At most, mention that <code>actOnMsg[combomsg]()</code> runs the action method just to help those who are not used to seeing parentheses in that context.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-10-22T07:17:09.433", "Id": "8374", "Score": "0", "body": "It was just pattern code, not my real code, hence the odd names and comments but point taken. =)" } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-10-22T07:09:16.983", "Id": "5518", "ParentId": "5517", "Score": "3" } } ]
{ "AcceptedAnswerId": "5518", "CommentCount": "3", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-10-22T06:18:42.037", "Id": "5517", "Score": "1", "Tags": [ "python" ], "Title": "Is this a \"pythonic\" method of executing functions based on the values of a tuple?" }
5517
<p>I am running a math-oriented computation that spends a significant amount of its time doing <code>memcpy</code>, always copying 80 bytes from one location to the next, an array of 20 32-bit <code>int</code>s. The total computation takes around 4-5 days using both cores of my i7, so even a 1% speedup results in about an hour saved.</p> <p>By using the <code>memcpy</code> in <a href="http://software.intel.com/en-us/articles/memcpy-performance/">this paper by Intel</a>, I was able to speed up by about 25%, and also dropping the size argument and simply declaring inside seems to have some small effect. However, I feel I am not utilising the fact that my copying operations are always the same size. That said, I can't come up with a better way.</p> <pre><code>void *memcpyi80(void* __restrict b, const void* __restrict a){ size_t n = 80; char *s1 = b; const char *s2 = a; for(; 0&lt;n; --n)*s1++ = *s2++; return b; } </code></pre> <p>Some other things that may be useful for optimization:</p> <ol> <li><p>I use an Intel Core i7-2620M, based on Sandy Bridge. I don't care about portability at all.</p></li> <li><p>I only care about the 16 least significant bits of every int. The other 16 are useless to me and are permanently zeroed out.</p></li> <li><p>Even though I copy 20 32-bit ints per memcpy invocation, I only care about the first 17. I have added 3 as it helps with alignment and therefore speed.</p></li> <li><p>I use GCC 4.6 on Windows 7.</p></li> </ol> <p>Any ideas?</p> <p><strong>UPDATE:</strong></p> <p>I think this is the assembly output (never done this before, there may be more than you need):</p> <pre><code>memcpyi80: pushq %r12 .seh_pushreg %r12 pushq %rbp .seh_pushreg %rbp pushq %rdi .seh_pushreg %rdi pushq %rsi .seh_pushreg %rsi pushq %rbx .seh_pushreg %rbx .seh_endprologue movq %rdx, %r9 movq %rcx, %rax negq %r9 andl $15, %r9d je .L165 movzbl (%rdx), %ecx leaq -1(%r9), %r10 movl $79, %esi andl $7, %r10d cmpq $1, %r9 movl $79, %ebx leaq 1(%rdx), %r8 movl $1, %r11d movb %cl, (%rax) leaq 1(%rax), %rcx jbe .L159 testq %r10, %r10 je .L160 cmpq $1, %r10 je .L250 cmpq $2, %r10 je .L251 cmpq $3, %r10 je .L252 cmpq $4, %r10 je .L253 cmpq $5, %r10 je .L254 cmpq $6, %r10 je .L255 movzbl (%r8), %r8d movl $2, %r11d movb %r8b, (%rcx) leaq 2(%rax), %rcx leaq 2(%rdx), %r8 .L255: movzbl (%r8), %ebx addq $1, %r11 addq $1, %r8 movb %bl, (%rcx) addq $1, %rcx .L254: movzbl (%r8), %r10d addq $1, %r11 addq $1, %r8 movb %r10b, (%rcx) addq $1, %rcx .L253: movzbl (%r8), %edi addq $1, %r11 addq $1, %r8 movb %dil, (%rcx) addq $1, %rcx .L252: movzbl (%r8), %ebp addq $1, %r11 addq $1, %r8 movb %bpl, (%rcx) addq $1, %rcx .L251: movzbl (%r8), %r12d addq $1, %r11 addq $1, %r8 movb %r12b, (%rcx) addq $1, %rcx .L250: movzbl (%r8), %ebx addq $1, %r8 movb %bl, (%rcx) movq %rsi, %rbx addq $1, %rcx subq %r11, %rbx addq $1, %r11 cmpq %r11, %r9 jbe .L159 .p2align 4,,10 .L160: movzbl (%r8), %r12d movb %r12b, (%rcx) movzbl 1(%r8), %ebp movb %bpl, 1(%rcx) movzbl 2(%r8), %edi movb %dil, 2(%rcx) movzbl 3(%r8), %ebx movb %bl, 3(%rcx) leaq 7(%r11), %rbx addq $8, %r11 movzbl 4(%r8), %r10d movb %r10b, 4(%rcx) movq %rsi, %r10 movzbl 5(%r8), %r12d subq %rbx, %r10 movq %r10, %rbx movb %r12b, 5(%rcx) movzbl 6(%r8), %ebp movb %bpl, 6(%rcx) movzbl 7(%r8), %edi addq $8, %r8 movb %dil, 7(%rcx) addq $8, %rcx cmpq %r11, %r9 ja .L160 .L159: movl $80, %r12d subq %r9, %r12 movq %r12, %rsi shrq $4, %rsi movq %rsi, %rbp salq $4, %rbp testq %rbp, %rbp je .L161 leaq (%rdx,%r9), %r10 addq %rax, %r9 movl $1, %r11d leaq -1(%rsi), %rdi vmovdqa (%r10), %xmm0 movl $16, %edx andl $7, %edi cmpq $1, %rsi vmovdqu %xmm0, (%r9) jbe .L256 testq %rdi, %rdi je .L162 cmpq $1, %rdi je .L244 cmpq $2, %rdi je .L245 cmpq $3, %rdi je .L246 cmpq $4, %rdi je .L247 cmpq $5, %rdi je .L248 cmpq $6, %rdi je .L249 vmovdqa 16(%r10), %xmm3 movl $2, %r11d movl $32, %edx vmovdqu %xmm3, 16(%r9) .L249: vmovdqa (%r10,%rdx), %xmm4 addq $1, %r11 vmovdqu %xmm4, (%r9,%rdx) addq $16, %rdx .L248: vmovdqa (%r10,%rdx), %xmm5 addq $1, %r11 vmovdqu %xmm5, (%r9,%rdx) addq $16, %rdx .L247: vmovdqa (%r10,%rdx), %xmm0 addq $1, %r11 vmovdqu %xmm0, (%r9,%rdx) addq $16, %rdx .L246: vmovdqa (%r10,%rdx), %xmm1 addq $1, %r11 vmovdqu %xmm1, (%r9,%rdx) addq $16, %rdx .L245: vmovdqa (%r10,%rdx), %xmm2 addq $1, %r11 vmovdqu %xmm2, (%r9,%rdx) addq $16, %rdx .L244: vmovdqa (%r10,%rdx), %xmm3 addq $1, %r11 vmovdqu %xmm3, (%r9,%rdx) addq $16, %rdx cmpq %r11, %rsi jbe .L256 .p2align 4,,10 .L162: vmovdqa (%r10,%rdx), %xmm2 addq $8, %r11 vmovdqu %xmm2, (%r9,%rdx) vmovdqa 16(%r10,%rdx), %xmm1 vmovdqu %xmm1, 16(%r9,%rdx) vmovdqa 32(%r10,%rdx), %xmm0 vmovdqu %xmm0, 32(%r9,%rdx) vmovdqa 48(%r10,%rdx), %xmm5 vmovdqu %xmm5, 48(%r9,%rdx) vmovdqa 64(%r10,%rdx), %xmm4 vmovdqu %xmm4, 64(%r9,%rdx) vmovdqa 80(%r10,%rdx), %xmm3 vmovdqu %xmm3, 80(%r9,%rdx) vmovdqa 96(%r10,%rdx), %xmm2 vmovdqu %xmm2, 96(%r9,%rdx) vmovdqa 112(%r10,%rdx), %xmm1 vmovdqu %xmm1, 112(%r9,%rdx) subq $-128, %rdx cmpq %r11, %rsi ja .L162 .L256: addq %rbp, %rcx addq %rbp, %r8 subq %rbp, %rbx cmpq %rbp, %r12 je .L163 .L161: movzbl (%r8), %edx leaq -1(%rbx), %r9 andl $7, %r9d movb %dl, (%rcx) movl $1, %edx cmpq %rbx, %rdx je .L163 testq %r9, %r9 je .L164 cmpq $1, %r9 je .L238 cmpq $2, %r9 je .L239 cmpq $3, %r9 je .L240 cmpq $4, %r9 je .L241 cmpq $5, %r9 je .L242 cmpq $6, %r9 je .L243 movzbl 1(%r8), %edx movb %dl, 1(%rcx) movl $2, %edx .L243: movzbl (%r8,%rdx), %esi movb %sil, (%rcx,%rdx) addq $1, %rdx .L242: movzbl (%r8,%rdx), %r11d movb %r11b, (%rcx,%rdx) addq $1, %rdx .L241: movzbl (%r8,%rdx), %r10d movb %r10b, (%rcx,%rdx) addq $1, %rdx .L240: movzbl (%r8,%rdx), %edi movb %dil, (%rcx,%rdx) addq $1, %rdx .L239: movzbl (%r8,%rdx), %ebp movb %bpl, (%rcx,%rdx) addq $1, %rdx .L238: movzbl (%r8,%rdx), %r12d movb %r12b, (%rcx,%rdx) addq $1, %rdx cmpq %rbx, %rdx je .L163 .p2align 4,,10 .L164: movzbl (%r8,%rdx), %r9d movb %r9b, (%rcx,%rdx) movzbl 1(%r8,%rdx), %r12d movb %r12b, 1(%rcx,%rdx) movzbl 2(%r8,%rdx), %ebp movb %bpl, 2(%rcx,%rdx) movzbl 3(%r8,%rdx), %edi movb %dil, 3(%rcx,%rdx) movzbl 4(%r8,%rdx), %r10d movb %r10b, 4(%rcx,%rdx) movzbl 5(%r8,%rdx), %r11d movb %r11b, 5(%rcx,%rdx) movzbl 6(%r8,%rdx), %esi movb %sil, 6(%rcx,%rdx) movzbl 7(%r8,%rdx), %r9d movb %r9b, 7(%rcx,%rdx) addq $8, %rdx cmpq %rbx, %rdx jne .L164 .L163: popq %rbx popq %rsi popq %rdi popq %rbp popq %r12 ret .L165: movq %rdx, %r8 movl $80, %ebx jmp .L159 .seh_endproc .p2align 4,,15 .globl memcpyi .def memcpyi; .scl 2; .type 32; .endef .seh_proc memcpyi </code></pre> <p><strong>UPDATE:</strong></p> <p>By building on Peter Alexander's solution and combining it with ideas from around the thread, I have produced this:</p> <pre><code>void memcpyi80(void* __restrict b, const void* __restrict a){ __m128 *s1 = b; const __m128 *s2 = a; *s1++ = *s2++; *s1++ = *s2++; *s1++ = *s2++; *s1++ = *s2++; *s1++ = *s2++; } </code></pre> <p>The speedup is small but measurable (about 1%). Now I guess my next temptation is to find how to use __m256 AVX types so I can do it in 3 steps rather than 5.</p> <p><strong>UPDATE:</strong></p> <p>The __m256 type requires alignment on the 32-bit barrier, which makes things slower, so it seems __m128 is a sweet spot.</p>
[ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-10-22T14:43:46.857", "Id": "8378", "Score": "7", "body": "Is it possible something else (other than the `memcpy`) can be optimized? What I see a lot is people think the problem is *here* when it's not. It's *there*." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-10-22T16:29:51.073", "Id": "8388", "Score": "3", "body": "If you only care about the 16 least significant bits why aren't you using shorts?" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-10-23T11:04:26.920", "Id": "8398", "Score": "0", "body": "MikeDunlavey - I have been optimizing this algo for over a year. Could there be a better way? Maybe, but it's not something obvious. I will post other parts of it here for review once I get done with the suggestions in this thread. \n\n\n@qwert - Using shorts apparently is not making the compiler happy - it seems to slow things down. I will try again though, I had tried it a while ago." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-10-22T15:04:44.600", "Id": "58720", "Score": "0", "body": "Have you try unroll the loop? Do 17 instead of 20? You can also take care of condition 2 at the same time because the values are in the registers already. Int should be 4-byte aligned, copy int instead of char?\nSave you look at Intel SSE instructions?" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-08-01T14:55:00.357", "Id": "105647", "Score": "0", "body": "Excellent job commenting on answers with respective improvement/regression!" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2015-09-18T23:52:16.050", "Id": "192326", "Score": "0", "body": "\"both my cores\"? A Sandybridge i7 has 4 physical cores with hyperthreading. 8 logical cores. Anyway, I checked the asm for that memcpy80, and it's optimal. https://goo.gl/nzaOTM. If you're copying things which were *just* written in the last couple clock cycles, you might hit store-forwarding stalls from using vector copies, but otherwise that's as fast as you'll get on SnB. For further gains, you'll have to change your code to do without the padding between `short`s. (load/store of a 16bit memory location to a 32 or 64bit register is just as fast as from a 32bit array on x86.)" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2017-05-08T17:50:37.133", "Id": "309504", "Score": "1", "body": "Can you confirm that you're correctly telling GCC to optimize for your target? Just posting your compilation flags is probably sufficient for that. I'm expecting something like `-O3 -march=sandybridge`." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-07-25T16:47:50.637", "Id": "483335", "Score": "0", "body": "For something this performance-critical, you should consider experimenting with Intel's own C compiler series. It is proprietary and non-free, but you can get free licenses if you are a student or researcher." } ]
[ { "body": "<p>What is the assembly generated?</p>\n\n<p>I remember finding that using structs can speed things up:</p>\n\n<pre><code>typedef struct {\n int x[17] __attribute__ ((packed));\n int padding __attribute__ ((packed, unused));\n} cbytes __attribute__ ((packed));\n\n\nvoid *memcpyi80(cbytes* __restrict b, const cbytes* __restrict a){\n size_t n = 80 / sizeof(cbytes);\n cbytes *s1 = b;\n const cbytes *s2 = a;\n for(; 0&lt;n; --n)*s1++ = *s2++;\n return b;\n}\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-10-22T10:59:14.840", "Id": "8376", "Score": "0", "body": "Thank you. Added asm output. Will try the struct approach and let you know. (Am afk for the next 20h unfortunately)" } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-10-22T10:21:34.133", "Id": "5521", "ParentId": "5520", "Score": "0" } }, { "body": "<p>You know what the size is, and you know it's ints, so do a little insider-trading:</p>\n\n<pre><code>void myCopy(int* dest, int* src){\n dest[ 0] = src[ 0];\n dest[ 1] = src[ 1];\n dest[ 2] = src[ 2];\n ...\n dest[19] = src[19];\n}\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-10-23T18:44:31.977", "Id": "8408", "Score": "1", "body": "This gives approx. 15% slowdown." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-10-23T22:25:39.550", "Id": "8414", "Score": "0", "body": "@Alex: Hmm... Then the next thing I would do is take maybe 20 [stackshots](http://stackoverflow.com/questions/375913/what-can-i-use-to-profile-c-code-in-linux/378024#378024) so I would be confirming / deconfirming any guesses I might have about what's really going on." } ], "meta_data": { "CommentCount": "2", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-10-22T14:51:47.697", "Id": "5523", "ParentId": "5520", "Score": "-1" } }, { "body": "<p>If you really need this part as fast as possible, one obvious route would be to write it in assembly language. The assembly language you've posted looks a bit on the insane side for this task (at least to me). Given a fixed size, the obvious route would be something like:</p>\n\n<pre><code>; warning: I haven't written a lot of assembly code recently -- I could have \n; some of the syntax a bit wrong.\n;\nmemcpyi80 proc dest:ptr byte src:ptr byte\n mov esi, src\n mov edi, dest\n mov ecx, 20 ; 80/4\n rep movsd\nmemcpyi80 endp\n</code></pre>\n\n<p>That <em>is</em> definitely open to improvement by using (for one example) moves through the SSE registers, but I'll leave that for others to play with. The improvement is pretty small though: recent processors have a special path specifically for memory copies, which this will use, so it's pretty competitive despite its simplicity.</p>\n\n<p>@Mike Dunlavey's comment is good though: most of the time people think they need a faster memory copy, they really need to re-think their code to simply avoid needing it.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2015-09-18T23:45:59.357", "Id": "192325", "Score": "1", "body": "really old answer, but it wasn't until IvyBridge that fast string ops were introduced. (smarter microcode for `rep movsb` with lower startup overhead, and I think better handling of misalignment). http://www.intel.com/content/dam/doc/manual/64-ia-32-architectures-optimization-manual.pdf section 3.7.7. Since vector-copy wins for general memcpy sizes under 128 bytes even on IvB, and in this case the size is an exact multiple of the vector width, using vectors is going to be better even on IvB and later with fast `movsb`." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-10-29T22:44:16.117", "Id": "494694", "Score": "0", "body": "Please also consider adding the \"CLD\" instruction to clear the \"direction\" flag, just in case it was not cleared after an eventual previous move with \"STD\"" } ], "meta_data": { "CommentCount": "2", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-10-22T14:54:40.747", "Id": "5524", "ParentId": "5520", "Score": "4" } }, { "body": "<p>The compiler cannot vectorize your version. If you simply change the for loop to be indexed instead of dereferenced, you will see a huge speed improvement. I get >10x speed up for this:</p>\n\n<pre><code>void *memcpyi80(void* __restrict b, const void* __restrict a) {\n size_t n = 80;\n char *s1 = b;\n const char *s2 = a;\n for(; 0 &lt; n; --n) {\n s1[n] = s2[n];\n }\n return b;\n}\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-10-23T16:16:23.487", "Id": "8401", "Score": "0", "body": "This does not appear to copy correctly." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-10-23T18:00:01.843", "Id": "8406", "Score": "1", "body": "-1 : array indices are start at 0, your code assumes they start at 1" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-10-23T18:39:35.727", "Id": "8407", "Score": "1", "body": "With Tom's fix it takes about 80% longer to run than my current implementation." } ], "meta_data": { "CommentCount": "3", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-10-22T15:49:03.367", "Id": "5527", "ParentId": "5520", "Score": "-1" } }, { "body": "<p>You are copying byte by byte, so it would be a lot faster copying int by int instead. Also unrolling the loop should help:</p>\n\n<pre><code>void *memcpyi80(void* __restrict b, const void* __restrict a){\n int* s1 = b;\n int* s2 = a;\n *s1++ = *s2++; *s1++ = *s2++; *s1++ = *s2++; *s1++ = *s2++;\n *s1++ = *s2++; *s1++ = *s2++; *s1++ = *s2++; *s1++ = *s2++;\n *s1++ = *s2++; *s1++ = *s2++; *s1++ = *s2++; *s1++ = *s2++;\n *s1++ = *s2++; *s1++ = *s2++; *s1++ = *s2++; *s1++ = *s2++;\n *s1++ = *s2++;\n // *s1++ = *s2++; *s1++ = *s2++; *s1++ = *s2++;\n return b;\n}\n</code></pre>\n\n<p>In C# I have found that separating the access and incrementation is faster, so that's worth a try:</p>\n\n<pre><code>void *memcpyi80(void* __restrict b, const void* __restrict a){\n int* s1 = b;\n int* s2 = a;\n *s1 = *s2; s1++; s2++; *s1 = *s2; s1++; s2++; *s1 = *s2; s1++; s2++;\n *s1 = *s2; s1++; s2++; *s1 = *s2; s1++; s2++; *s1 = *s2; s1++; s2++;\n *s1 = *s2; s1++; s2++; *s1 = *s2; s1++; s2++; *s1 = *s2; s1++; s2++;\n *s1 = *s2; s1++; s2++; *s1 = *s2; s1++; s2++; *s1 = *s2; s1++; s2++;\n *s1 = *s2; s1++; s2++; *s1 = *s2; s1++; s2++; *s1 = *s2; s1++; s2++;\n *s1 = *s2; s1++; s2++; *s1 = *s2; s1++; s2++;\n // *s1 = *s2; s1++; s2++; *s1 = *s2; s1++; s2++; *s1 = *s2;\n return b;\n}\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-10-23T16:18:21.067", "Id": "8402", "Score": "3", "body": "This slows it down by >13% on mine." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-07-25T16:44:27.820", "Id": "483333", "Score": "1", "body": "Manual unrolling doesn't make sense. The compiler knows how to do this for you." } ], "meta_data": { "CommentCount": "2", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-10-22T18:47:02.317", "Id": "5530", "ParentId": "5520", "Score": "-1" } }, { "body": "<p>Code below is optimized:\n</p>\n\n<pre class=\"lang-cpp prettyprint-override\"><code>void *memcpyi72(void* __restrict b, const void * __restrict a)\n{\n return memcpy(b,a, 18*sizeof(int));\n}\n</code></pre>\n\n<p>GCC with -O3 generates the same assembly for this function as for the <a href=\"https://codereview.stackexchange.com/questions/5520/copying-80-bytes-as-fast-as-possible/5521#5521\">Pubby8 code</a>. There's no need to use structs.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-10-23T16:20:09.863", "Id": "8403", "Score": "3", "body": "Using this slows down my computation by approx. 5%." } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-10-22T19:26:54.257", "Id": "5532", "ParentId": "5520", "Score": "0" } }, { "body": "<p>The fastest way to do this would be to align your data on 16-byte boundaries, then the entire copy just becomes 5 copies through XMM registers.</p>\n\n<p>This is over <strong><em>twice as fast</em></strong> as your version on my machine.</p>\n\n<p>Store your data like this:</p>\n\n<pre><code>#include &lt;xmmintrin.h&gt;\nstruct Data\n{\n union\n {\n int i[20];\n __m128 v[5];\n };\n};\n</code></pre>\n\n<p>Then the copy function is just:</p>\n\n<pre><code>void memcpyv5(__m128* __restrict b, const __m128* __restrict a)\n{\n __m128 t0 = a[0];\n __m128 t1 = a[1];\n __m128 t2 = a[2];\n __m128 t3 = a[3];\n __m128 t4 = a[4];\n b[0] = t0;\n b[1] = t1;\n b[2] = t2;\n b[3] = t3;\n b[4] = t4;\n}\n\n// Example\nData dst, src;\nmemcpyv5(dst.v, src.v);\n</code></pre>\n\n<p>Assembly output:</p>\n\n<pre><code>__Z8memcpyv5PU8__vectorfPKS_:\nLFB493:\n pushq %rbp\nLCFI2:\n movq %rsp, %rbp\nLCFI3:\n movaps 16(%rsi), %xmm3\n movaps 32(%rsi), %xmm2\n movaps 48(%rsi), %xmm1\n movaps 64(%rsi), %xmm0\n movaps (%rsi), %xmm4\n movaps %xmm4, (%rdi)\n movaps %xmm3, 16(%rdi)\n movaps %xmm2, 32(%rdi)\n movaps %xmm1, 48(%rdi)\n movaps %xmm0, 64(%rdi)\n leave\n ret\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-10-23T00:49:24.347", "Id": "8390", "Score": "3", "body": "Great use of the hardware, especially since portability is not a a concern." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-10-23T16:29:40.773", "Id": "8404", "Score": "0", "body": "Not looking good. Simply converting my code to use structs takes it from <15sec to >40sec. Using the new memcpy function takes it to 37.5 sec. So the function is better but using structs kills the program. I will look for a way to use the xmmintrin commands without structs to see if anything changes and get back." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-10-23T16:50:13.523", "Id": "8405", "Score": "4", "body": "You can avoid using structs by manually aligning your data (check your compiler docs) and just casting it to `(__m128*)`." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-10-23T19:43:00.437", "Id": "8410", "Score": "0", "body": "See update, I've made a version that gives a 1% speedup. Thank you very much for the answer. Any idea how to use __m256 vectors? cheers." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-10-23T19:55:24.727", "Id": "8411", "Score": "0", "body": "Nevermind the __m256 question. I found out about immintrin.h, but it doesn't actually give any more speedup." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2015-09-18T23:38:43.793", "Id": "192324", "Score": "4", "body": "@AlexandrosMarinos: Sandybridge does 256b loads / stores in 2 cycles anyway. They're still single-uop instructions, but it's only significantly faster with Haswell, which has 256b data paths to/from L1 cache. If your data is 32B-aligned, it could be a small gain on SnB, but not if you get a store-forwarding stall because it was written very recently with 16B writes. Also, 256b ops are slower than 128b until the CPU stops for thousands of cycles to power up the upper 128b lane in the execution units. It powers down if unused for ~1 ms. http://www.agner.org/optimize/blog/read.php?i=142#378" } ], "meta_data": { "CommentCount": "6", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-10-22T21:53:00.730", "Id": "5536", "ParentId": "5520", "Score": "31" } }, { "body": "<p>There's no way any solution in c or c++ could be better than assembly (unless of course, it was horribly written). The answer with the assembly language from Jerry Coffin above...</p>\n\n<pre><code>memcpyi80 proc dest:ptr byte src:ptr byte\n mov esi, src ; load source address\n mov edi, dest ; load destination address\n mov ecx, 20 ; initialize count register (80/4)\n rep movsd ; perform transfer\nmemcpyi80 endp\n</code></pre>\n\n<p>cannot be improved upon, in my opinion, unless it's possible to use a smaller number larger operands. Naturally the memory addresses need to be aligned properly. The <code>rep movsd</code> instruction is the only part of the code that does any work, automatically incrementing the count register until the operation is complete.</p>\n\n<p>What you might try is to pass the count as a separate parameter and then split the data into as many parts as you have cores, and call the function with a separate thread for each part.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-10-23T09:04:00.273", "Id": "8396", "Score": "0", "body": "oops - the formatting of the assembly got nuked there..." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-10-23T09:12:57.887", "Id": "8397", "Score": "0", "body": "Another thing - if you run on a 64-bit o/s and use 64-bit assembly you should also be able to use 64-bit operands - i.e. 8 bytes at a time instead of just 4 using 32-bt." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2015-09-19T00:00:27.800", "Id": "192328", "Score": "5", "body": "You want to multithread an 80-byte copy??? Even having a different thread do the whole copy would be a huge performance hit, because the cache line would end up in the \"modified\" state in the L1 cache of another core, and would have to be transferred back to the core running the main thread. Not to mention that there'd be no way to send a request to another thread in less time than it takes to just copy 80 bytes. `rep movsd` isn't terrible, but the microcode has high startup overhead. For short copies, fully-unrolled SSE / AVX is faster." } ], "meta_data": { "CommentCount": "3", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-10-23T09:02:55.610", "Id": "5539", "ParentId": "5520", "Score": "-5" } }, { "body": "<h2>Taking Benefits of The Out-of-Order Execution Engine</h2>\n<p>You can also read about The Out-of-Order Execution Engine in the <a href=\"http://www.intel.com/content/dam/www/public/us/en/documents/manuals/64-ia-32-architectures-optimization-manual.pdf\" rel=\"nofollow noreferrer\">&quot;Intel® 64 and IA-32 Architectures Optimization Reference Manual&quot;</a>, section 2.1.2, and take benefits of it.</p>\n<p>For example, in Intel SkyLake processor series (launched in 2015), it has:</p>\n<ul>\n<li>4 execution units for the Arithmetic logic unit (ALU) (add, and, cmp, or, test, xor, movzx, movsx, mov, (v)movdqu, (v)movdqa, (v)movap*, (v)movup),</li>\n<li>3 execution units for Vector ALU ( (v)pand, (v)por, (v)pxor, (v)movq, (v)movq, (v)movap*, (v)movup*, (v)andp*, (v)orp*, (v)paddb/w/d/q, (v)blendv*, (v)blendp*, (v)pblendd)</li>\n</ul>\n<p>So we can occupy the above units (3+4) in parallel if we use register-only operations. We cannot use 3+4 instructions in parallel for memory copy. We can use simultaneously a maximum of up to two 32-bytes instructions to load from memory and one 32-bytes instruction to store from memory, and even if we are working with Level-1 cache.</p>\n<p>Please see the Intel manual again to understand on how to do the fastest memcpy implementation: <a href=\"http://www.intel.com/content/dam/www/public/us/en/documents/manuals/64-ia-32-architectures-optimization-manual.pdf\" rel=\"nofollow noreferrer\">http://www.intel.com/content/dam/www/public/us/en/documents/manuals/64-ia-32-architectures-optimization-manual.pdf</a></p>\n<p>Section 2.2.2 (The Out-of-Order Engine on the Haswell micro-architecture): &quot;The Scheduler controls the dispatch of micro-ops onto the dispatch ports. There are eight dispatch ports to support the out-of-order execution core. Four of the eight ports provided execution resources for computational operations. The other 4 ports support memory operations of up to two 256-bit load and one 256-bit store operation in a cycle.&quot;</p>\n<p>Section 2.2.4 (Cache and Memory Subsystem) has the following note: &quot;First level data cache supports two load micro-ops each cycle; each micro-op can fetch up to 32-bytes of data.&quot;</p>\n<p>Section 2.2.4.1 (Load and Store Operation Enhancements) has the following information: The L1 data cache can handle two 256-bit (32 bytes) load and one 256-bit (32 bytes) store operations each cycle. The unified L2 can service one cache line (64 bytes) each cycle. Additionally, there are 72 load buffers and 42 store buffers available to support micro-ops execution in-flight.</p>\n<p>The other sections (2.3 and so on, dedicated to Sandy Bridge and other microarchitectures) basically reiterate the above information.</p>\n<p>The section 2.3.4 (The Execution Core) gives additional details.</p>\n<p>The scheduler can dispatch up to six micro-ops every cycle, one on each port. The following table summarizes which operations can be dispatched on which port.</p>\n<ul>\n<li>Port 0: ALU, Shift, Mul, STTNI, Int-Div, 128b-Mov, Blend, 256b-Mov</li>\n<li>Port 1: ALU, Fast LEA, Slow LEA, MUL, Shuf, Blend, 128bMov, Add, CVT</li>\n<li>Port 2 &amp; Port 3: Load_Addr, Store_addr</li>\n<li>Port 4: Store_data</li>\n<li>Port 5: ALU, Shift, Branch, Fast LEA, Shuf, Blend, 128b-Mov, 256b-Mov</li>\n</ul>\n<p>The section 2.3.5.1 (Load and Store Operation Overview) may also be useful to understand on how to make fast memory copy, as well as the section 2.4.4.1 (Loads and Stores).</p>\n<p>For the other processor architectures, it is again - two load units and one store unit. Table 2-4 (Cache Parameters of the Skylake Microarchitecture) has the following information:</p>\n<p>Peak Bandwidth (bytes/cycle):</p>\n<ul>\n<li>First Level Data Cache: 96 bytes (2x32B Load + 1*32B Store)</li>\n<li>Second Level Cache: 64 bytes</li>\n<li>Third Level Cache: 32 bytes.</li>\n</ul>\n<p>I have also done speed tests on my Intel Core i5 6600 CPU (Skylake, 14nm, released in September 2015) with DDR4 memory, which confirmed the theory. For example, my tests have shown that using generic 64-bit registers for memory copy, even many registers in parallel, degrades performance, comparing to larger registers (XMM). Also, using just 2 XMM registers is enough - adding the 3rd doesn't add performance.</p>\n<p>If your CPU has AVX CPUID bit, you may benefit from the large, 256-bit (32 byte) YMM registers to copy memory and occupy two whole load units. The AVX support was first introduced by Intel with the Sandy Bridge processors, shipping in Q1 2011 and later on by AMD with the Bulldozer processor shipping in Q3 2011.</p>\n<pre><code>// first cycle - use two load units\nvmovdqa ymm0, ymmword ptr [esi+0] // load first part (32 bytes)\nvmovdqa ymm1, ymmword ptr [esi+32] // load 2nd part (32 bytes)\n\n// second cycle - use one load unit and one store unit\nvmovdqa xmm2, xmmword ptr [esi+64] // load 3rd part (16 bytes)\nvmovdqa ymmword ptr [edi+0], ymm0 // store first part\n\n// third cycle - use one store unit\nvmovdqa ymmword ptr [edi+32], ymm1 // store 2nd part\n\n// fourth cycle - use one store unit\nvmovdqa xmmword ptr [edi+64], xmm2 // store 3rd part\n</code></pre>\n<p>Just make sure your data is aligned by 16 bytes (for the XMM registers), or by 32 bytes (for the YMM registers). Otherwise, there will be an Access Violation error. If the data is not aligned, use unaligned commands: vmovdqu and movups, respectively.</p>\n<p>If you are lucky to have an AVX-512 processor, you can copy 80 bytes in just four instructions:</p>\n<pre><code>vmovdqu64 zmm30, [esi]\nvmovdqu xmm31, [esi+64] \nvmovdqu64 [edi], zmm30\nvmovdqu [edi+64], xmm31 \n</code></pre>\n<p>We are using registers 30 and 31 here to avoid the <em>upper 256 dirty state</em>, which is a global state, which may incur SSE/AVX transitional penalties. Moreover, on some CPU models, <code>vzeroupper</code> or <code>vzeroall</code> is the only way to exit this state or even restore <em>max-turbo</em> after dirtying a ZMM register. The CPU, however, will not enter this state for writes to (x/y/z)mm16-31 - registers which do not exist on SSE/AVX1/AVX2.</p>\n<h2>Further reading - ERMSB (not needed to copy exactly 80 bytes but for much larger blocks)</h2>\n<p>If your CPU has CPUID ERMSB (Enhanced REP MOVSB) bit, then <code>rep movsb</code> command is executed differently than on older processors, and it will be faster than <code>rep movsd</code> (<code>movsq</code>). However, the benefits of <code>rep movsb</code> will only be only noticeable on large blocks.</p>\n<p><code>rep movsb</code> is faster than plain simple &quot;<code>mov rax</code> in a loop&quot; copy only starting from 256-byte blocks, and faster than AVX copy starting from 2048 bytes-blocks.</p>\n<p>So, since your block size is 80 bytes only, ERMSB will not give you any benefit.</p>\n<p>Get Microsoft Visual Studio, and look for memcpy.asm - it has different scenarios for different processors and different block sizes - so you will be able to figure out which method is best to use for your processor and your block size.</p>\n<p>Meanwhile, I can consider Intel ERMSB &quot;half-baked&quot;, because there is a high internal startup in ERMSB - about 35 cycles, and because of the other limitations.</p>\n<p>See the Intel Manual on Optimization, section 3.7.6 Enhanced REP MOVSB and STOSB operation (ERMSB)\n<a href=\"http://www.intel.com/content/dam/www/public/us/en/documents/manuals/64-ia-32-architectures-optimization-manual.pdf\" rel=\"nofollow noreferrer\">http://www.intel.com/content/dam/www/public/us/en/documents/manuals/64-ia-32-architectures-optimization-manual.pdf</a></p>\n<ul>\n<li>startup cost is 35 cycles;</li>\n<li>both the source and destination addresses have to be aligned to a 16-Byte boundary;</li>\n<li>the source region should not overlap with the destination region;</li>\n<li>the length have to be a multiple of 64 to produce higher performance;</li>\n<li>the direction have to be forward (<code>CLD</code>).</li>\n</ul>\n<p>I hope that in future Intel will eliminate such a high startup costs.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2017-05-08T10:04:24.707", "Id": "162820", "ParentId": "5520", "Score": "10" } } ]
{ "AcceptedAnswerId": "5536", "CommentCount": "8", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-10-22T09:35:44.380", "Id": "5520", "Score": "43", "Tags": [ "optimization", "c", "bitwise", "sse" ], "Title": "Copying 80 bytes as fast as possible" }
5520
<p>I find the TagBuilder written in C# little poor without the ability to "host" inside it sub tags (as objects not as strings).</p> <p>So I wrote a simple class that inherits TagBuilder and allow to save sub tags. I can navigate inside it and add things to it while I move across the application. And when I call the Top Tag Object .ToString, it will render the entire html</p> <pre><code>public class MultiLevelHtmlTag : TagBuilder { public MultiLevelHtmlTag(string tagName) : base(tagName) { } public List&lt;MultiLevelHtmlTag&gt; InnerTags = new List&lt;MultiLevelHtmlTag&gt;(); public override string ToString() { if (InnerTags.Count &gt; 0) { foreach (MultiLevelHtmlTag tag in InnerTags) { this.InnerHtml += tag.ToString(); } } return base.ToString(); } } </code></pre> <p>this is how I use it:</p> <pre><code>MultiLevelHtmlTag top = new MultiLevelHtmlTag("div"); top.InnerTags.Add(new MultiLevelHtmlTag("span")); log.Debug(top.ToString()); </code></pre> <p>output:</p> <pre><code>&lt;div&gt;&lt;span&gt;&lt;/span&gt;&lt;/div&gt; </code></pre> <p>What do you think about it? is that a goot pattern?</p>
[ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-10-23T00:44:16.007", "Id": "8389", "Score": "2", "body": "You have some fundamental issues in your code. Your `ToString()` method has some major problems. See what happens if you call it multiple times. It should only return a string representation of the object. It shouldn't be modifying it." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-10-22T21:03:19.840", "Id": "61282", "Score": "0", "body": "I would create a separate class for all valid HTML tags, and apply the Composite pattern." } ]
[ { "body": "<p>I would make sure the list is not exposed publicly - the caller can then do whatever they want with that list, even assign <code>null</code> to it. So I've refactored it a little bit and implemented <code>Add()</code> (you may also want to implement <code>Remove()</code>, etc.):</p>\n\n<pre><code>/// &lt;summary&gt;\n/// Simple class that inherits TagBuilder and allow to save sub tags.\n/// &lt;/summary&gt;\npublic class MultiLevelHtmlTag : TagBuilder\n{\n /// &lt;summary&gt;\n /// List of inner tags.\n /// &lt;/summary&gt;\n private readonly IList&lt;MultiLevelHtmlTag&gt; innerTags = new List&lt;MultiLevelHtmlTag&gt;();\n\n /// &lt;summary&gt;\n /// Initializes a new instance of the &lt;see cref=\"MultiLevelHtmlTag\"/&gt; class.\n /// &lt;/summary&gt;\n /// &lt;param name=\"tagName\"&gt;The name of the tag.&lt;/param&gt;\n public MultiLevelHtmlTag(string tagName) : base(tagName)\n {\n }\n\n /// &lt;summary&gt;\n /// Gets the inner tag list.\n /// &lt;/summary&gt;\n /// &lt;value&gt;The inner tag list.&lt;/value&gt;\n public IEnumerable&lt;MultiLevelHtmlTag&gt; InnerTags\n {\n get\n {\n return new ReadOnlyCollection&lt;MultiLevelHtmlTag&gt;(this.innerTags);\n }\n }\n\n /// &lt;summary&gt;\n /// Adds the specified tag to the inner tag list.\n /// &lt;/summary&gt;\n /// &lt;param name=\"tag\"&gt;The tag to add.&lt;/param&gt;\n public void Add(MultiLevelHtmlTag tag)\n {\n if (tag == null)\n {\n throw new ArgumentNullException(\"tag\");\n }\n\n this.innerTags.Add(tag);\n }\n\n /// &lt;summary&gt;\n /// Returns a &lt;see cref=\"System.String\"/&gt; that represents this instance.\n /// &lt;/summary&gt;\n /// &lt;returns&gt;\n /// A &lt;see cref=\"System.String\"/&gt; that represents this instance.\n /// &lt;/returns&gt;\n public override string ToString()\n {\n var sb = new StringBuilder();\n\n foreach (var tag in this.innerTags)\n {\n sb.Append(tag.ToString());\n }\n\n this.InnerHtml = sb.ToString();\n return base.ToString();\n }\n}\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-07-07T06:39:09.130", "Id": "44084", "Score": "0", "body": "Great response; in my project I've just changed the inner tags to be `TagBuilder` (so that I can add \"regular\" `TagBuilder` objects to it); there's no actual need to have them as `MultiLevelHtmlTag`s." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-06-12T21:57:54.640", "Id": "94283", "Score": "0", "body": "@ANeves - you need to use concat your results to the existing inner text or else you will end up with all empty tags." } ], "meta_data": { "CommentCount": "2", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-10-22T15:55:37.600", "Id": "5528", "ParentId": "5526", "Score": "6" } } ]
{ "AcceptedAnswerId": "5528", "CommentCount": "2", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-10-22T15:19:44.257", "Id": "5526", "Score": "5", "Tags": [ "c#", "design-patterns" ], "Title": "C# Multi level HTML TagBuilder object - Design pattern Review needed" }
5526
<p>I have this timer working already(<a href="http://jsbin.com/udozuk/3/edit" rel="nofollow">jsbin</a>):</p> <p>HTML:</p> <pre><code> &lt;input id="m" type="number" value="0" min="0" max="59"/&gt; &lt;input id="s" type="number" value="2" min="0" max="59"/&gt; &lt;input id="start" type="button" value="Start!" /&gt; &lt;output&gt;00:00&lt;/output&gt; </code></pre> <p>JavaScript:</p> <pre><code>var o = document.querySelector('output'), m = document.querySelector('#m') s = document.querySelector('#s'), start = document.querySelector('#start'); start.addEventListener('click', function(){ var mm = parseInt(m.value), ss = parseInt(s.value); timer = function(){ if(mm&gt;0){ if(ss&gt;0){ ss--; } else{ mm--; ss = 59; } setTimeout("timer()", 1000); o.value = (mm&lt;10 ? '0' + mm : mm) + ":" + (ss&lt;10 ? '0' + ss : ss); } else{ if(ss&gt;0){ ss--; o.value = "00:" + (ss&lt;10 ? '0' + ss : ss); setTimeout("timer()", 1000); } } } timer(); }, false); </code></pre> <p>It seems a lot of code for just a timer. Is it possible to implement this with less code? Maybe with loops, <code>Date</code> object or something else?</p> <p>This code have problem and that is number of items in call stack when the time is big enough. I tried to write same code with <code>while</code> or <code>for</code> but I couldn't get a good result.</p> <p><strong>MY QUESTION</strong> is how to write this countdown with <code>for</code> or <code>while</code>?</p>
[]
[ { "body": "<p><code>document.querySelector(\"#id\")</code> is just a costly version of <code>document.getElementById(\"id\")</code>. <code>document.getElementById</code> is the fastest way to select an element in your page (to the smartasses of you: besides <code>document.head</code>, <code>document.body</code> etc)</p>\n\n<p><code>document.querySelector(\"tagname\")</code> is also just a costly version of <code>document.getElementsByTagName(\"tagname\")[0]</code>. Coincidentally, that's the second fastest way to get an element.</p>\n\n<p><code>document.querySelector</code> and its array-like version are only useful for compound statements that are either too long or too difficult to do with \"regular\" DOM methods. One might argue that if your html is compound and complex, you're doing it wrong, and they'd most likely be right.</p>\n\n<p>If I were you, I'd also do future-you a favor and name your variables in a way that makes sense.</p>\n\n<p>So, what do we have so far?</p>\n\n<pre><code>var output = document.getElementsByTagName(\"output\")[0],\n minutes = document.getElementById(\"m\"),\n seconds = document.getElementsById(\"m\"),\n start = document.getElementById(\"start\");\n</code></pre>\n\n<p>Moving on. The event listener is fine, now about parsing integers...</p>\n\n<p>Try this piece of code: <code>parseInt(\"08\")</code>. The result is 0. Why, you ask? Well, if you don't pass a radix as a second parameter, <code>parseInt</code> will be nice enough to <em>guess</em> what you mean. <code>parseInt</code> sees that your string begins in a 0 and, of course, assumes the number is in octal! Why wouldn't it be?</p>\n\n<p>Point: either pass a radix like this: <code>parseInt(string, 10)</code> or use <code>parseFloat</code>, which will always assume a decimal number. Whichever you like best, though I once heard that <code>parseFloat</code> is faster, dunno if that's true. I personally prefer <code>parseFloat</code>, for no obvious reason</p>\n\n<p>So we get:</p>\n\n<pre><code>var mm = parseFloat(minutes.value),\n ss = parseFloat(seconds.value);\n</code></pre>\n\n<p>Magnificent.</p>\n\n<p>This line:</p>\n\n<pre><code>timer = \n</code></pre>\n\n<p>Contains one of the most widely made errors in javascript. It's called implied global.</p>\n\n<p>Basically, when you omit the <code>var</code> statement, the variable definition list gets appended to the global object (which <code>window</code> refers to). So:</p>\n\n<pre><code>function foo() { answer = 42; }\nfoo();\nwindow.answer === 42;\n</code></pre>\n\n<p>Never omit the <code>var</code> statement. Even if you <em>do</em> wish to append a variable to the global object, do it explicitly (<code>window.answer = 42;</code>). Better that then let someone scratch their head trying to figure out how magic variables appeared from seemingly nowhere.</p>\n\n<p>Besides one more thing, your code is fine. What's that other thing, you ask? <code>setTimeout</code></p>\n\n<p>When you pass a string to <code>setTimeout</code>, it's the same as calling <code>eval</code>. It evaluates the string. That's slow and bad. Instead, pass a function to it:</p>\n\n<pre><code>setTimeout(timer, 1000);\n</code></pre>\n\n<p>Since <code>timer</code> is a function, you can pass it around like any other value.</p>\n\n<p>Now, one might ask: \"How do I call <code>func</code> with parameters?\"</p>\n\n<pre><code>setTimeout(function() {\n func(something, somethingElse);\n}, 1000);\n//or\nsetTimeout(func, 1000, something, somethingElse);\n</code></pre>\n\n<p>About your actual code? it's fine. It's not the best piece of code I've ever, but it's not the worse as well. It's not too long for a timer, since all that's done is decrementing and calling itself again. I'd move the <code>&lt; 10</code> checks to their own function, but maybe that's because I'm insane and not that \"your way\" is worse.</p>\n\n<p><hr/>\n<strong>tl;dr</strong> Your code contains errors, but other than that, it's fine.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-10-22T20:28:22.597", "Id": "8380", "Score": "0", "body": "I don't agree with things you said about `querySelector` because fastness is not a matter here and I just used that selector for ease of code. My main question was how to improve `timer` that is not answered here." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-10-22T20:30:29.667", "Id": "8381", "Score": "1", "body": "@Mohsen Yes I did. Right at the end." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-10-22T20:49:26.803", "Id": "8382", "Score": "0", "body": "How much I'm close to your ideal? http://jsbin.com/udozuk/8/edit" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-10-22T20:55:33.127", "Id": "8383", "Score": "0", "body": "@Mohsen Looks finer. You got rid of two points. However, the `timer` variable is still an implied global. Also, is your life dependent on using `querySelector` and `querySelectorAll`? You made your html structure a little less obvious to make the selectors much less obvious." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-10-22T20:56:56.413", "Id": "8384", "Score": "0", "body": "I hate `id`s! You can see with this code I can have another timer in my page but it's not easy if I had `id` in my code" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-10-22T21:00:30.793", "Id": "8386", "Score": "1", "body": "@Mohsen `id`s represent elements which *must* be unique. If you have several elements which fit under a single, general name, that's a class for you, and there's `document.getElementsByClassName`." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-10-23T01:36:20.813", "Id": "8391", "Score": "1", "body": "`getElementsByClassName` browser support is same as `querySelector` while you can do `queryselector(\"#div .class element[attr]\")` but it's like ten line of code if you do this with other selectors" } ], "meta_data": { "CommentCount": "7", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-10-22T20:17:13.890", "Id": "5533", "ParentId": "5531", "Score": "4" } }, { "body": "<p>You can't use a loop to do something like this, as that would lock up the user interface. There is nothing happening in the browser as long as your function is running, so the change in the output would simply not show up.</p>\n\n<p>Here are some suggestions:</p>\n\n<p>You have different code for counting down when there is minutes involved and when there isn't, but you can use the same code for both.</p>\n\n<p>You can keep track of the time as seconds, and split it into minutes and seconds when you display it, that simplifies the code a bit.</p>\n\n<p>You can use the function name <code>timer</code> in the <code>setTimeout</code> call, that way you don't have to declare the function globally.</p>\n\n<pre><code>document.querySelector('#start').addEventListener('click', function(){\n\n var o = document.querySelector('output');\n var t =\n parseInt(document.querySelector('#m').value, 10) * 60 +\n parseInt(document.querySelector('#s').value, 10);\n\n var timer = function(){\n if (t &gt; 0) {\n t--;\n var m = Math.floor(t \\ 60);\n var s = t % 60;\n o.value = (m &lt; 10 ? '0' : '') + m + \":\" + (s &lt; 10 ? '0' : '') + s;\n window.setTimeout(timer, 1000);\n }\n }\n\n timer();\n}, false);\n</code></pre>\n\n<p>Regarding the call stack: The code is not recursive, so it won't build up calls on the call stack. The <code>timer</code> function adds itself as an event, it doesn't call itself.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-10-22T21:20:55.187", "Id": "8387", "Score": "1", "body": "@Mohsen: Yes, they can be combined, but that's just a matter of preference. It has no impact on performance." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-09-18T13:21:03.297", "Id": "115537", "Score": "0", "body": "@Guffa : Hie there! I was wondering if there is optimized code for countdown showing DD:HH:MM:SS . Can you please help me out for this? Thanks !!" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-09-18T17:32:29.497", "Id": "115593", "Score": "0", "body": "@Dharmraj: For such a long time period you would need to calculate the time as a time difference to get it reasonably accurate, not just using a counter and a timer. Anyway, here are some tips: http://stackoverflow.com/questions/9642777/looking-for-a-easy-way-to-buildt-a-js-countdown-scriptdays-hours-minutes-seco" } ], "meta_data": { "CommentCount": "3", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-10-22T20:54:10.223", "Id": "5534", "ParentId": "5531", "Score": "4" } }, { "body": "<p>If you use seconds instead of a mm:ss to hold your time, everything will be simpler.</p>\n\n<p>Plus, you can encapsulate your reading and writing of values:</p>\n\n<pre><code>function readSeconds() {\n return parseInt(m.value, 10) * 60 + parseInt(s.value, 10);\n}\n\nfunction output(seconds) {\n var mm = seconds / 60, ss = seconds % 60;\n o.value = (mm&lt;10 ? '0' + mm : mm) + \":\" + (ss&lt;10 ? '0' + ss : ss);\n}\n</code></pre>\n\n<p>Then, you can write your start method more easily. Something like:</p>\n\n<pre><code>start.addEventListener('click', function(){\n var seconds = readSeconds();\n function timer(){\n seconds--;\n output(seconds);\n setTimeout(timer, 1000);\n }\n timer();\n}, false);\n</code></pre>\n\n<p>Obviously this isn't all the details, but a little encapsulation helps quite a bit.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-10-29T04:45:03.047", "Id": "5679", "ParentId": "5531", "Score": "1" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-10-22T19:18:47.517", "Id": "5531", "Score": "4", "Tags": [ "javascript" ], "Title": "Most efficient JavaScript countdown timer implementation" }
5531
<p>Convert a decimal number to binary using only loops, strings, <code>if</code>/<code>else</code> statements. </p> <p>This is my first C++ project and it took me a while to do it. Let me know what you think.</p> <pre><code>#include &lt;iostream&gt; #include &lt;string&gt; using namespace std; string ConvertInt(int value); string ConvertDec(double value); void printBinary1(string str1); void printBinary2(string str2); int main() { double number, decValue; int remainder, intValue; string binary1, binary2; cout &lt;&lt; "Enter a deciaml value to be converted to binary. Then press ENTER: "; cin &gt;&gt; number; intValue = (int)number; decValue = number - intValue; binary1 = ConvertInt(intValue); binary2 = ConvertDec(decValue); printBinary1(binary1); cout &lt;&lt; "."; printBinary2(binary2); int pause; cin &gt;&gt; pause; return 0; } string ConvertInt(int value) { int remainder; string binary; while(value != 0) { remainder = value % 2; binary += remainder; value /= 2; } return binary; } string ConvertDec(double value) { string binary; int integer; double decimal; for(int i = 1; i &lt;= 5; i++) { integer = (int)value; binary += integer; decimal = value - integer; value = decimal * 2; } return binary; } void printBinary1(string str1) { string binary1 = str1; for(int i = (binary1.length() - 1); i &lt;= (binary1.length() - 1); i--) { cout &lt;&lt; (int)binary1[i]; } } void printBinary2(string str2) { string binary2 = str2; for(int index = 1; index &lt; binary2.length(); index++) { cout &lt;&lt; (int)binary2[index]; } } </code></pre>
[ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-10-23T20:40:28.040", "Id": "8412", "Score": "1", "body": "First comment learn how to format your code." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-10-23T21:34:56.443", "Id": "8413", "Score": "0", "body": "@DEdesigns What does the assignment say about dealing with digits after the decimal point? Does it have a use case example?" } ]
[ { "body": "<p>It is considered bad practice (by most people) to declare more than one variable on a line.</p>\n\n<pre><code>double number, decValue;\nint remainder, intValue;\nstring binary1, binary2;\n</code></pre>\n\n<p>Though it is not a problem here there are some corner cases where the declaration gets confusing.</p>\n\n<p>Second you declare all your variables at the top of the function.<br>\nThis is a very C like style and in C++ it is usually better to declare the variable as close to the point of usage as possible (no need to invoke a constructor if you are never going to use the variable, also it makes reading the code easier as you can see the type at the fist point of usage).</p>\n\n<p>I know all the books say to use:</p>\n\n<pre><code>using namespace std;\n</code></pre>\n\n<p>But in the long run its not a good idea. Get used to prefix things with their namespace <code>std::string</code>, or importing the specific bits you want <code>using std::string</code> (even then scope as tightly as possible (you would not believe how many time string has been reinvented)).</p>\n\n<p>Variables should be descriptive (and more importantly unique and easy to find in the source).</p>\n\n<pre><code>for(int i = 1; i &lt;= 5; i++)\n</code></pre>\n\n<p>Think about 10 years of maintenance on this code. The code now covers 5 long pages. Try and find and update all usages of <code>i</code>. This becomes a pane as <code>i</code> will appear in nearly every other identifier in all the comments in lots of places etc. So try and use variables that can be easily searched for.</p>\n\n<p>In your ConvertXXX() functions. You are saving integer values into the string. This is fine. But you are then extracting those char values and converting to int for printing. Why not convert the values directly into the characters you want to print.</p>\n\n<pre><code>string ConvertDec(double value)\n{ \n // STUFF\n binary += '0' + integer; // each digit will be the character 0 or 1\n // MORE STUFF\n}\n</code></pre>\n\n<p>When printing:</p>\n\n<pre><code>cout &lt;&lt; (int)binary1[i];\n\n// Can change this too:\n\ncout &lt;&lt; binary1[i];\n</code></pre>\n\n<p>More importantly you can replace the loop:</p>\n\n<pre><code>for(int index = 1; index &lt; binary2.length(); index++)\n{\n cout &lt;&lt; (int)binary2[index];\n}\n\n// Can be changed too:\n\ncout &lt;&lt; binary2\n</code></pre>\n\n<p>Looking at your loops:</p>\n\n<pre><code>for(int i = (binary1.length() - 1); i &lt;= (binary1.length() - 1); i--)\n</code></pre>\n\n<p>Does this even work?\nIt seems that i is getting smaller and smaller then goes negative.</p>\n\n<p>It is easier to loop up and subtract in the range:</p>\n\n<pre><code>for(int loop = 0; loop &lt; bianry1.length(); ++lop)\n{\n std::cout &lt;&lt; bianry1[binary1.length() - 1 - loop];\n}\n</code></pre>\n\n<p>But the std containers (including string) provide iterators (and more importantly reverse iterators)</p>\n\n<pre><code>for(std::string::const_reverse_iterator loop = bianry1.rbegin(); loop != binary1.rend(); ++loop)\n{\n std::cout &lt;&lt; *loop;\n}\n</code></pre>\n\n<p>Second loop:</p>\n\n<pre><code>for(int index = 1; index &lt; binary2.length(); index++)\n</code></pre>\n\n<p>Problem here is that you are starting from 1. arrays/containers nearly everything is indexed from 0 and you can access the elements 0 -> (size() - 1). So here you are starting at the wrong point and going past the end of the string.</p>\n\n<p>But as mentioned above you don't even need this as you can replace the loop.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-10-23T23:46:16.583", "Id": "8416", "Score": "0", "body": "Note that the loop that prints the string `binary2` *intentionally* skips the first character, so you can't simply replace it with printing the entire string." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-10-24T07:02:38.257", "Id": "8431", "Score": "0", "body": "The loop runs from 1 to length-1, so it won't read outside the array. The reason that it runs from 1 and not 0, is that the `ConvertDec` function puts an extra zero at the beginning of the string." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-10-24T17:26:02.230", "Id": "8436", "Score": "0", "body": "@Guffa: Good spot." } ], "meta_data": { "CommentCount": "3", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-10-23T21:03:22.350", "Id": "5544", "ParentId": "5542", "Score": "4" } }, { "body": "<p>There are some issues with the code:</p>\n\n<ul>\n<li>You are (mis)using strings as integer arrays.</li>\n<li>The functions in the code are codependent. The <code>ConvertInt</code> functions returns a string that is unusable unless you use <code>printBinary1</code> to display it. The same for <code>ConvertDec</code> and <code>printBinary2</code>.</li>\n<li>The <code>ConvertDec</code> function produces a result with a unused value (at index 0), which then has to be avoided in the <code>printBinary2</code> function.</li>\n<li>There is a bug in <code>printBinary1</code> where the condition in the loop should be <code>i &gt;= 0</code> rather than <code>i &lt;= (binary1.length() - 1)</code>.</li>\n</ul>\n\n<p>You should either use a different format for storing the intermediate data, or make the <code>ConvertInt</code> and <code>ConvertDec</code> functions return real strings that you can just display without needing separate functions for that.</p>\n\n<p>If you keep the codependent functions, their naming should suggest that they are to be used in pairs.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-10-24T18:11:59.187", "Id": "8437", "Score": "0", "body": "+1: I like the argument on `codependent` functions. I see this all over the place and have not been able to frame that well in words before. Thanks for a new phrase." } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-10-24T07:27:54.550", "Id": "5555", "ParentId": "5542", "Score": "4" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "2", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-10-23T17:33:31.340", "Id": "5542", "Score": "5", "Tags": [ "c++", "homework", "converting" ], "Title": "Decimal To Binary using only the basics" }
5542
<p>So I am working on an x86 Assembly program for Linux using NASM. This program basically asks the user for their name and their favorite color. After doing this and storing the two strings in variables declared in the .bss section, the program prints "No way <em>name of user</em>, <em>favorite color</em> is my favorite color, too!</p> <p>The problem I am having is that there are enormous spaces in the output because I do not know how long the string was that the user entered, only the length that I declared the buffer to be.</p> <pre><code>section .data greet: db 'Hello!', 0Ah, 'What is your name?', 0Ah ;simple greeting greetL: equ $-greet ;greet length colorQ: db 'What is your favorite color?' ;color question colorL: equ $-colorQ ;colorQ length suprise1: db 'No way ' suprise1L equ $-suprise1 suprise3: db ' is my favorite color, too!', 0Ah section .bss name: resb 20 ;user's name color: resb 15 ;user's color section .text global _start _start: greeting: mov eax, 4 mov ebx, 1 mov ecx, greet mov edx, greetL int 80 ;print greet getname: mov eax, 3 mov ebx, 0 mov ecx, name mov edx, 20 int 80 ;get name askcolor: ;asks the user's favorite color using colorQ getcolor: mov eax, 3 mov ebx, 0 mov ecx, name mov edx, 20 int 80 thesuprise: mov eax, 4 mov ebx, 1 mov ecx, suprise1 mov edx, suprise1L int 80 mov eax, 4 mov ebx, 1 mov ecx, name mov edx, 20 int 80 ;write the color ;write the "suprise" 3 mov eax, 1 mov ebx, 0 int 80 </code></pre> <p>The code for what I am doing is above. Does anyone have a good method for finding the length of the entered string, or of taking in a character at a time to find out the length of the string?</p>
[ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-10-23T19:39:58.700", "Id": "8409", "Score": "0", "body": "The thing is, you can't really do that. You would either have to allocate enough memory for what you would expect at most, or you could ask the user for how much space should be allocated. The second option is not very practical nor safe. Just figure out what limit you would want to account for and handle that. Use the appropriate syscalls to ensure you don't exceed that limit. I generally would use `BUFSIZ` (typically 512)." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-10-24T01:37:07.737", "Id": "8418", "Score": "0", "body": "I'm all in favor of doing this sort of thing in assembly as a learning exercise, but interfacing with syscalls via `int 80h` is not the most interesting use of assembly. Things like doing file I/O or maintaining dynamically-resized buffers make a lot more sense in C. What you will have with this approach is an assembly program that calls C functions (either through a software interrupt in the case of syscalls or `call` instruction in the case of `libc`), and that won't really teach you idiomatic x86 assembly." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-10-24T05:51:44.597", "Id": "8430", "Score": "2", "body": "The read system call returns the number of characters read (or the error code negated - you should check for this), save that count and use it when displaying. As @JeffMercado says it's not unreasonable to limit inputting to something like 512 - who has a favorite color with a longer length than that? Alternatively you can read characters in a loop where you do the equivalent of `realloc` each time the buffer is filled, but this requires more care." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-10-24T10:33:24.530", "Id": "123630", "Score": "0", "body": "Bug solving and code requests like this belong on [Stack Overflow](http://stackoverflow.com/)." } ]
[ { "body": "<p>I have an answer in x86 tasm and written under Windows, so I'm not sure if this will help, apologies if it doesn't. Maybe the way its done will give you some ideas.</p>\n\n<pre><code>.model small\n.stack 100h\n.data\n\n\n colour db 00001111b\n input db 10, 0, \" \" ; \n\n.code\n\nmain:\n\n call initsegs\n call readstring\n call printstring\n call exit\n\n\n\nPROC printstring \n\n push bx dx cx ax bp\n mov bx, 1; 1st (after zero) byte of input we are after, the length\n xor dx, dx; make sure dx contains zero before we play with dh and dl\n\n mov dl, input[bx]\n mov cx, dx; cx now has the 2nd byte value in the string, ie the length\n\n mov ah, 13h ; int 13h of 10h, print a string\n mov al, 1 ; write mode: colour on bl \n mov bh, 0 ; video page zero\n mov bl, colour; colour attribute\n\n mov dh, 10; row\n mov dl, 10; column\n mov bp, offset input ; es:bp needs to point at string..this points to string but includes its max and length at the start\n\n add bp, 2 ; skip the first two elements which will be the length and amount used\n int 10h;\n\n\n pop bp ax cx dx bx\n\n ret\n\nENDP printstring\n\n\nPROC readstring \n\n push ax dx\n\n\n mov ah, 0ah ; function a of 21h - read a string\n mov dx, offset input ; reads string into DS:DX so DX needs be offset of string variable\n\n int 21h ; call the interrupt\n\n pop dx ax\n\n ret\n\nENDP readstring\n\n\n\nPROC exit\n\n mov ah, 4ch\n INT 21h\n\n RET\n\nENDP Exit\n\n\nPROC initsegs\n\n push ax\n\n mov ax, @DATA\n mov ds, ax\n mov es, ax\n\n pop ax\n\n RET\n\nENDP initsegs\n\n\n\nend main\n</code></pre>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-08-13T16:08:28.460", "Id": "14617", "ParentId": "5543", "Score": "2" } }, { "body": "<p>To allocate memory without using the clib, you need to adjust the system break. I explain it here: <a href=\"http://www.dreamincode.net/forums/topic/287274-nasm-linux-dynamic-memory-allocationread-file/\" rel=\"nofollow noreferrer\">NASM - Linux Dynamic Memory Allocation/Read file</a></p>\n\n<pre><code>sys_exit equ 1\nsys_read equ 3\nsys_write equ 4\nsys_brk equ 45\nstdin equ 0\nstdout equ 1\n\nsection .data\nszGreet db 'Hello!', 0Ah, 'What is your name? :',0\nGreet_len equ $-szGreet \nszColor db 'What is your favorite color? :',0 \nColor_len equ $ - szColor\nszSpace db \",\", 32, 0\nsuprise1: db 'No way ',0 \nsuprise1L equ $-suprise1\nsuprise3: db ' is my favorite color, too!', 0Ah,0\nsurprise3L equ $-suprise3\n\nsection .bss\nlpName: resb 20 ;user's name\nname_len equ $ - lpName \nlpColor: resb 15 \ncolor_len equ $-lpColor ;user's color\nTempBuf resd 1\n\nsection .text\n global _start\n\n_start:\n\n.greeting:\n mov edx, Greet_len \n mov ecx, szGreet \n call WriteText ; Say hello, ask for name\n\n.getname: \n mov edx, name_len \n mov ecx, lpName\n call ReadText ; Read name into buffer\n\n.getcolor: \n mov edx, Color_len \n mov ecx, szColor\n call WriteText ; Ask for fav color\n\n mov edx, color_len\n mov ecx, lpColor\n call ReadText ; Read color into buffer\n\n.GetLen:\n mov edi, lpName\n call GetStrlen ; length of inputed name\n mov esi, edx\n\n mov edi, lpColor ; length of inputed color\n call GetStrlen\n\n add esi, edx ; Name len + Color len\n add esi, suprise1L ; surprise1 text len\n add esi, surprise3L ; surprise3 text len\n add esi, 2 ; lenght of comma and space\n call Alloc ;\n mov [TempBuf], eax ; address of the end of bss section\n\n.thesuprise:\n push suprise3\n push lpColor\n push szSpace\n push lpName\n push suprise1\n push dword [TempBuf]\n push 5\n call szMultiCat ; concat all strings together\n add esp, 4 * 7 \n\n mov ecx, dword [TempBuf]\n mov edx, esi\n call WriteText ; print to terminal\n\n ;~ \"free\" memory\n mov ebx, [TempBuf]\n mov eax, sys_brk ; restore system break\n int 80H\n\n mov eax, sys_exit\n mov ebx, 0\n int 80H\n\n;~ #########################################\nWriteText: \n mov ebx, stdout\n mov eax, sys_write\n int 80H \n ret\n\n;~ ######################################### \nReadText:\n mov ebx, stdin \n mov eax, sys_read \n int 80H \n ret \n\n;~ ######################################### \nGetStrlen:\n xor ecx, ecx\n not ecx\n xor eax, eax\n cld\n repne scasb\n mov byte [edi - 2], 0 ; null terminate string\n not ecx\n lea edx, [ecx - 1]\n ret\n\n;~ ######################################### \nAlloc:\n ; esi == size to allcocate\n\n ;~ Get end of bss section\n xor ebx, ebx\n mov eax, sys_brk\n int 80H\n push eax\n\n ; extend it by size\n mov ebx, eax\n add ebx, esi\n mov eax, sys_brk\n int 80H\n\n pop eax ; return address of break\n ret\n\n; #####################################################################\n; Name : szMultiCat\n; Arguments : esp + 4 = \n; esp + 8 = \n; esp + 12 = \n; esp + 16 =\n; Description: Concats multiple NULL terminated strings together\n; Returns : Nothing\n;\nszMultiCat: \n push ebx\n push esi\n push edi\n push ebp\n\n mov ebx, 1\n\n mov ebp, [esp + 20]\n mov edi, [esp + 24] ; lpBuffer\n xor ecx, ecx\n lea edx, [esp + 28] ; args\n sub edi, ebx\n\n.B1:\n add edi, ebx\n movzx eax, byte [edi] ; unroll by 2\n test eax, eax\n je .nxtstr\n\n add edi, ebx\n movzx eax, byte [edi]\n test eax, eax\n jne .B1\n\n.nxtstr:\n sub edi, ebx\n mov esi, [edx + ecx * 4]\n.B2:\n add edi, ebx\n movzx eax, byte [esi] ; unroll by 2\n mov [edi], al\n add esi, ebx\n test eax, eax\n jz .F1\n\n add edi, ebx\n movzx eax, byte [esi]\n mov [edi], al\n add esi, ebx\n test eax, eax\n jne .B2\n\n.F1:\n add ecx, ebx\n cmp ecx, ebp ; pcount\n jne .nxtstr\n\n mov eax, [esp + 24] ; lpBuffer\n\n pop ebp\n pop edi\n pop esi\n pop ebx\n ret\n</code></pre>\n\n<p><img src=\"https://i.stack.imgur.com/zyNJ7.png\" alt=\"enter image description here\"></p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-03-03T03:19:57.927", "Id": "23373", "ParentId": "5543", "Score": "1" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "4", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-10-23T17:49:10.750", "Id": "5543", "Score": "3", "Tags": [ "linux", "assembly" ], "Title": "Correct User Input - x86 Linux Assembly" }
5543
<p><em>(Originally posted on <a href="https://stackoverflow.com/questions/7867686/perl-script-to-find-all-unowned-files-and-directories-on-unix-how-can-i-optimi">Stack Overflow</a>)</em></p> <p>Following my findings and suggestions in my other post <a href="https://stackoverflow.com/questions/7854975/how-to-exclude-a-list-of-full-directory-paths-in-find-command-on-solaris">How to exclude a list of full directory paths in find command on Solaris</a>, I have decided to write a Perl version of this script and see how I could optimize it to run faster than a native find command. So far, the results are impressive!</p> <p>The purpose of this script is to report all unowned files and directories on a Unix system for audit compliance. The script has to accept a list of directories and files to exclude (either by full path or wildcard name), and must take as little processing power as possible. It is meant to be run on hundreds of Unix system that we (the company I work for) support, and has be able to run on all those Unix systems (multiple OS, multiple platforms: AIX, HP-UX, Solaris and Linux) without us having to install or upgrade anything first. In other words, it has to run with standard libraries and binaries we can expect on all systems.</p> <p>I have not yet made the script argument-aware, so all arguments are hard-coded in the script. I plan on having the following arguments in the end and will probably use getopts to do it:</p> <pre><code>-d = comma delimited list of directories to exclude by path name -w = comma delimited list of directories to exclude by basename or wildcard -f = comma delimited list of files to exclude by path name -i = comma delimited list of files to exclude by basename or wildcard -t:list|count = Defines the type of output I want to see (list of all findinds, or summary with count per directory) </code></pre> <p>Here is the source I have done so far:</p> <pre><code>#! /usr/bin/perl use strict; use File::Find; # Full paths of directories to prune my @exclude_dirs = ('/dev','/proc','/home'); # Basenames or wildcard names of directories I want to prune my $exclude_dirs_wildcard = '.svn'; # Full paths of files I want to ignore my @exclude_files = ('/tmp/test/dir3/.svn/svn_file1.txt','/tmp/test/dir3/.svn/svn_file2.txt'); # Basenames of wildcard names of files I want to ignore my $exclude_files_wildcard = '*.tmp'; my %dir_globs = (); my %file_globs = (); # Results will be sroted in this hash my %found = (); # Used for storing uid's and gid's present on system my %uids = (); my %gids = (); # Callback function for find sub wanted { my $dir = $File::Find::dir; my $name = $File::Find::name; my $basename = $_; # Ignore symbolic links return if -l $name; # Search for wildcards if dir was never searched before if (!exists($dir_globs{$dir})) { @{$dir_globs{$dir}} = glob($exclude_dirs_wildcard); } if (!exists($file_globs{$dir})) { @{$file_globs{$dir}} = glob($exclude_files_wildcard); } # Prune directory if present in exclude list if (-d $name &amp;&amp; in_array(\@exclude_dirs, $name)) { $File::Find::prune = 1; return; } # Prune directory if present in dir_globs if (-d $name &amp;&amp; in_array(\@{$dir_globs{$dir}},$basename)) { $File::Find::prune = 1; return; } # Ignore excluded files return if (-f $name &amp;&amp; in_array(\@exclude_files, $name)); return if (-f $name &amp;&amp; in_array(\@{$file_globs{$dir}},$basename)); # Check ownership and add to the hash if unowned (uid or gid does not exist on system) my ($dev,$ino,$mode,$nlink,$uid,$gid) = stat($name); if (!exists $uids{$uid} || !exists($gids{$gid})) { push(@{$found{$dir}}, $basename); } else { return } } # Standard in_array perl implementation sub in_array { my ($arr, $search_for) = @_; my %items = map {$_ =&gt; 1} @$arr; return (exists($items{$search_for}))?1:0; } # Get all uid's that exists on system and store in %uids sub get_uids { while (my ($name, $pw, $uid) = getpwent) { $uids{$uid} = 1; } } # Get all gid's that exists on system and store in %gids sub get_gids { while (my ($name, $pw, $gid) = getgrent) { $gids{$gid} = 1; } } # Print a list of unowned files in the format PARENT_DIR,BASENAME sub print_list { foreach my $dir (sort keys %found) { foreach my $child (sort @{$found{$dir}}) { print "$dir,$child\n"; } } } # Prints a list of directories with the count of unowned childs in the format DIR,COUNT sub print_count { foreach my $dir (sort keys %found) { print "$dir,".scalar(@{$found{$dir}})."\n"; } } # Call it all &amp;get_uids(); &amp;get_gids(); find(\&amp;wanted, '/'); print "List:\n"; &amp;print_list(); print "\nCount:\n"; &amp;print_count(); exit(0); </code></pre> <p>If you want to test it on your system, simply create a test directory structure with generic files, chown the whole tree with a test user you create for this purpose, and then delete the user.</p> <p>I'll take any hints, tips or recommendations you could give me.</p>
[]
[ { "body": "<p>Overall it looks clean and simple. Good job. Here are some things I noticed:</p>\n\n<ol>\n<li>You should use \"use warnings\" for production level code. Its odd that you use strict but not warnings.</li>\n<li>List::Util or List::MoreUtils should have a suitable replacement for your in_array() function if you're interested or have it installed on all your systems.</li>\n<li>If you're using a perl version >= 5.10 you can replace in_array with the smart match oeprator ~~.</li>\n<li>Don't let your exclude lists get too big as storing them in an array an iterating through them is an O(n) operation. A hash lookup may be faster for large lists and would de-dup for you automatically.</li>\n<li>Using &amp; before calling a sub is pretty much deprecated. Just call it directly.</li>\n<li>The shebang line '/usr/bin/env perl' is more portable than '/usr/bin/perl'</li>\n<li>You stat your file $name over and over for all your various tests. stat() it once, save the results, then re-use those results for all your tests. Remember that all tests like -d, -l and -f are stat() calls internally. Read up on the perl stat call and all the fields to help determine how to re-create the -d, -l, and -f checks against the returned data.</li>\n</ol>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-10-25T20:25:40.557", "Id": "5574", "ParentId": "5545", "Score": "2" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-10-23T22:37:47.083", "Id": "5545", "Score": "1", "Tags": [ "perl", "file-system", "unix" ], "Title": "How can I further optimize this Perl script for finding all unowned files and directories on Unix?" }
5545
<p>I am a self taught programmer and, while I understand data structures at a theoretical level (as well as through optimizing my own code), I have never actually taken the time to write my own implementation of all the major ones.</p> <p>So, here is my linked list. I would appreciate any feedback you guys can offer to me, especially when it comes to cleaner/faster/more idiomatic way of implementing some of these basic algorithms (for example, <code>insert</code>). I didn't look at any reference material because I wanted to see how close I would get without help. As such, I'm sure there are probably simpler ways of doing some things that I overlooked.</p> <p>Also note that I have not optimized any of this; this is simply a first pass, took about an hour. I will be benchmarking this (and the others) at a later time, but like I said, space and time improvements are welcome.</p> <p>linked_list.h</p> <pre><code>#ifndef LINKED_LIST_H #define LINKED_LIST_H #include &lt;stddef.h&gt; typedef struct _node { int value; struct _node* next; } node; typedef struct _llist { node* head; node* tail; } llist; void init_node( node** new_node, int value ); void init_llist( llist** list ); size_t len( llist* list ); void push_back( llist* list, int value ); void push_front( llist* list, int value ); void insert( llist* list, int index, int value ); node* find( llist* list, int value ); void free_llist( llist* list ); void print_llist( llist* list ); #endif </code></pre> <p>linked_list.c</p> <pre><code>#include "linked_list.h" #include &lt;stdlib.h&gt; #include &lt;stdio.h&gt; void init_node( node** new_node, int value ) { *new_node = (node*)malloc( sizeof(node) ); (*new_node)-&gt;value = value; (*new_node)-&gt;next = NULL; } void init_llist( llist** list ) { *list = (llist*)malloc( sizeof(llist) ); (*list)-&gt;head = NULL; (*list)-&gt;tail = NULL; } void push_back( llist* list, int value ) { node* new_node; init_node( &amp;new_node, value ); if( !list-&gt;head ) { /* empty list */ list-&gt;head = new_node; list-&gt;tail = list-&gt;head; } else { list-&gt;tail-&gt;next = new_node; list-&gt;tail = new_node; } } void push_front( llist* list, int value ) { node* new_head; init_node( &amp;new_head, value ); new_head-&gt;next = list-&gt;head; list-&gt;head = new_head; if( !list-&gt;tail ) { /* was an empty list */ list-&gt;tail = list-&gt;head; } } void insert( llist* list, int index, int value ) { int cur_idx = 0; node* new_node = NULL; node* prev_node = NULL; node* cur_node = list-&gt;head; if( index &lt; 0 ) return; if( index == 0 ) { push_front( list, value ); return; } /* not sure what I should do here. should I hide the 'error' or force an assert to fail if the caller tries to insert into an empty list or an invalid position? */ if( !cur_node ) { init_node( &amp;cur_node, value ); list-&gt;head = list-&gt;tail = cur_node; return; } while( cur_node &amp;&amp; cur_idx &lt; index ) { ++cur_idx; prev_node = cur_node; cur_node = cur_node-&gt;next; } init_node( &amp;new_node, value ); prev_node-&gt;next = new_node; new_node-&gt;next = cur_node; if( !cur_node ) { /* new tail node, end of list */ list-&gt;tail = new_node; } } node* find( llist* list, int value ) { node* tmp = list-&gt;head; while( tmp != NULL &amp;&amp; tmp-&gt;value != value ) { tmp = tmp-&gt;next; } return tmp; } size_t len( llist* list ) { size_t len = 0; node* current = list-&gt;head; while( current ) { ++len; current = current-&gt;next; } return len; } void free_llist( llist* list ) { node* current = list-&gt;head; while( current ) { node* tmp = current-&gt;next; free( current ); current = tmp; } list-&gt;head = list-&gt;tail = NULL; } void print_llist( llist* list ) { node* cur = list-&gt;head; while( cur ) { printf( "%d\r\n", cur-&gt;value ); cur = cur-&gt;next; } } </code></pre> <p>And some trivial unit tests that should all pass, probably should be more comprehensive:</p> <pre><code>#include "linked_list.h" #include &lt;stdio.h&gt; #include &lt;assert.h&gt; void test_push_back(); void test_push_front(); void test_len(); void test_insert(); void test_find(); int main( int argc, char* argv[] ) { test_push_back(); test_push_front(); test_len(); test_insert(); test_find(); puts( "All Passed" ); return 0; } void test_push_back() { llist* list; node* current; int i; int start = 0; int count = 100; init_llist( &amp;list ); for( i = start; i &lt; count; ++i ) { push_back( list, i ); } current = list-&gt;head; for( i = start; current; ++i ) { assert( current-&gt;value == i ); current = current-&gt;next; } free_llist( list ); } void test_push_front() { llist* list; node* current; int i; int start = 0; int count = 100; init_llist( &amp;list ); for( i = start; i &lt; count; ++i ) { push_front( list, i ); } current = list-&gt;head; for( i = count - 1; current; --i ) { assert( current-&gt;value == i ); current = current-&gt;next; } free_llist( list ); } void test_len() { llist* list; init_llist( &amp;list ); assert( len( list ) == 0 ); push_back( list, 1 ); assert( len( list ) == 1 ); free_llist( list ); assert( len( list ) == 0 ); } void test_insert() { llist* list; init_llist( &amp;list ); /* insert into empty list */ insert( list, 0, 1 ); assert( list-&gt;head-&gt;value == 1 &amp;&amp; list-&gt;tail-&gt;value == 1 ); /* insert at the end */ insert( list, 1, 3 ); assert( list-&gt;tail-&gt;value == 3 ); /* insert in the middle */ insert( list, 1, 2 ); assert( list-&gt;head-&gt;next-&gt;value == 2 ); free_llist( list ); init_llist( &amp;list ); push_back( list, 1 ); push_back( list, 2 ); push_back( list, 3 ); /* insert to front of already populated list */ insert( list, 0, -1 ); assert( list-&gt;head-&gt;value == -1 ); assert( list-&gt;tail-&gt;value == 3 ); /* invalid index, too large, place at end */ insert( list, 100, 100 ); assert( list-&gt;tail-&gt;value == 100 ); free_llist( list ); } void test_find() { llist* list; node* found_node; init_llist( &amp;list ); /* not present, shoudl return NULL */ found_node = find( list, 0 ); assert( found_node == NULL ); push_back( list, 1 ); push_back( list, 2 ); push_back( list, 3 ); found_node = find( list, 1 ); assert( found_node == list-&gt;head &amp;&amp; found_node-&gt;value == 1 ); found_node = find( list, 2 ); assert( found_node-&gt;value == 2 ); found_node = find( list, 3 ); assert( found_node == list-&gt;tail &amp;&amp; found_node-&gt;value == 3 ); free_llist( list ); } </code></pre>
[]
[ { "body": "<p>My first bug bear is identifiers should not begin with an underscore:</p>\n\n<pre><code>typedef struct _node {\ntypedef struct _llist {\n</code></pre>\n\n<p>See: <a href=\"https://stackoverflow.com/questions/228783/what-are-the-rules-about-using-an-underscore-in-a-c-identifier/228797#228797\">what-are-the-rules-about-using-an-underscore-in-a-c-identifier</a></p>\n\n<p>Rather than having any output parameters I think it is easier to see behavior by returning results:</p>\n\n<pre><code>node* init_node(int value )\n{\n node* new_node = (node*)malloc( sizeof(node) );\n new_node-&gt;value = value;\n new_node-&gt;next = NULL;\n\n return new_node;\n}\n</code></pre>\n\n<blockquote>\n <p>/* not sure what I should do here.\n should I hide the 'error' or force\n an assert to fail if the caller \n tries to insert into an empty list \n or an invalid position? */</p>\n</blockquote>\n\n<p>I don't think an assert is appropriate as that forces the program to exit.<br>\nBut some form of error indication may be useful. Or you can document the behavior and decide what it done. I personally would say (in the documentation) an insert where index is beyond the end of the array is equivalent to a push_back() and leave it at that. Then inserting into an empty list and beyond the end have the same behavior.</p>\n\n<p>Then length as currently implemented:</p>\n\n<pre><code>size_t len( llist* list ) {\n</code></pre>\n\n<p>Is actually an O(n) operation. It would be a simple to make this O(1) and store the size.</p>\n\n<p>The method that frees the list does not free up the container object:</p>\n\n<pre><code>void free_llist( llist* list ) // frees all the nodes.\n</code></pre>\n\n<p>I would also expect it to free the object allocated by <code>init_llist</code>.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-10-24T02:26:41.250", "Id": "8419", "Score": "0", "body": "Thanks a lot for your input, I appreciate it. I honestly was ignorant at the plethora of problems that may be caused by using a leading underscore for type names. As for the out parameters to functions... I don't know. Return values are more natural for me as well working mostly in C++, but it... felt more C'ish I guess? I don't know, dumb reasoning. I left the length calculation at O(n) for now as I didn't feel like going back and maintaining a count variable at the moment. I initially started with only a node type and later added the list structure." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-10-24T02:26:50.703", "Id": "8420", "Score": "0", "body": "And yeah, I forgot to free the list itself after adding that type. Thanks again! I'll upvote you when I am able to." } ], "meta_data": { "CommentCount": "2", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-10-24T01:02:29.967", "Id": "5547", "ParentId": "5546", "Score": "11" } }, { "body": "<p>Your question is tagged <code>c</code>, and your file ends in <code>.c</code>. So here's some thoughts from that angle:</p>\n\n<ul>\n<li><p>Don't bother casting <code>void *</code> to another pointer type. This is a C++ thing. In C, <code>void *</code> can be implicitly cast to any pointer type.</p></li>\n<li><p>There is no such thing as a namespace, so don't use collision-prone names like <code>node</code> or <code>len()</code>. Add some kind of prefix.</p></li>\n<li><p><code>malloc</code> can fail. You will want to bubble up that error status. All your functions that end up calling <code>malloc</code> further down the stack will need a means to return error status as well. Typically the way to do this is return <code>NULL</code> (if your function returns a pointer type) or make the function return <code>bool</code> (<code>&lt;stdbool.h&gt;</code> in C99) or <code>int</code> and have some convention where a certain value means failure. (In POSIX it's typically <code>int</code> returning 0 on success. Windows will typically have a boolean where nonzero means success. Returning error codes is also popular.)</p></li>\n</ul>\n\n<p>Some other thoughts:</p>\n\n<ul>\n<li><p>Consider an alternate allocation scheme for <code>struct llist</code>. Personally I would prefer the structure itself (not the nodes of course) to be caller-allocated. Is it worth doing a <code>malloc</code> for something only the size of two pointers in <code>llist_init</code>? I would say no. Further, consider the memory layout if you want to include a list inside a structure: why bother having a pointer to it when you can just have the <code>struct llist</code> be a member of the larger structure?</p></li>\n<li><p>The use of whitespace seems inconsistent. At times you put an extra newline between declarations and statements, and at times you don't. It's of course subjective which one of these you choose (I would rather more space personally), but it's important to be consistent.</p></li>\n</ul>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-10-24T02:30:58.263", "Id": "5549", "ParentId": "5546", "Score": "13" } } ]
{ "AcceptedAnswerId": "5549", "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-10-24T00:16:08.250", "Id": "5546", "Score": "7", "Tags": [ "c", "unit-testing", "linked-list" ], "Title": "Singly Linked List" }
5546
<p>I just started playing with Python and was hoping to get some feedback regarding the quality of the following snippet. Does this look like proper Python? What would you change? Is this small script well structured?</p> <p>Quick description of functional goal: reorder list such that each element is followed by the value closest to it, starting from 20 (AKA shortest-seek-first algorithm).</p> <p>example: <code>[15, 24, 12, 13, 48, 56, 2]</code><br> becomes: <code>[24, 15, 13, 12, 2, 48, 56]</code></p> <p>better example: <code>[22, 19, 23, 18, 17, 16]</code><br> becomes: <code>[19, 18, 17, 16, 22, 23]</code></p> <pre><code>fcfs_working = [15, 24, 12, 13, 48, 56, 2] fcfs_track = [] track_number = 20 while len(fcfs_working) &gt; 0: track_number = min(fcfs_working, key=lambda x:abs(x-track_number)) fcfs_working.remove(track_number) fcfs_track.append(track_number) </code></pre>
[]
[ { "body": "<pre><code>while len(fcfs_working) &gt; 0:\n</code></pre>\n\n<p>is the same as</p>\n\n<pre><code>while fcfs_working:\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-11-20T14:58:03.417", "Id": "30048", "Score": "0", "body": "@GarethRees, you're right. I don't recall what I was thinking at the time." } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-10-24T03:39:44.840", "Id": "5554", "ParentId": "5548", "Score": "4" } }, { "body": "<p>I'm not familiar with the shortest-seek-first algorithm. However, it may work to calculate the distances of each number in the list from the current position, sort that and then output the results. Consequently:</p>\n\n<pre><code>working = [15, 24, 12, 13, 48, 56, 2]\nposition = 20\ndistances = [(abs(position-x), x) for x in working]\n&gt;&gt; [(5, 15), (4, 24), (8, 12), (7, 13), (28, 48), (36, 56), (18, 2)]\ndistances.sort()\n&gt;&gt; [(4, 24), (5, 15), (7, 13), (8, 12), (18, 2), (28, 48), (36, 56)]\n[x[1] for x in distances]\n&gt;&gt; [24, 15, 13, 12, 2, 48, 56]\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-11-24T16:42:53.053", "Id": "30255", "Score": "0", "body": "not working as expected, for example: `working = [15, 24, 12, 13, 25, 56, 2]` results with `[24, 15, 25, 13, 12, 2, 56]`" } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-11-20T21:22:58.190", "Id": "18860", "ParentId": "5548", "Score": "0" } }, { "body": "<p>From the algorithmic perspective, I'd like to suggest another solution (regardless to Python as a language).</p>\n\n<p>Here goes:</p>\n\n<p>let's assume that all items in the given array are different. the other case has a similar solution, so let's focus on the algorithm itself.</p>\n\n<ol>\n<li>Find the nearest number, in terms of distance, from the array to the given external number (20).</li>\n<li>sort the given array.</li>\n<li>find the value in (1) in the array. it can be done using a binary search.</li>\n<li>now, to the main point: the next value would be either to the left of the current value or to the right of the current value, since the distance is now between the next value to the current one, and the array is sorted (!).</li>\n<li>so all you have to do is to hold two additional indexes: inner-left and inner-right. these indexes represent the inner boundaries of the \"hole\" that is being created while constructing the new list.</li>\n</ol>\n\n<p>Demonstration:</p>\n\n<p>original array:</p>\n\n<pre>\n[22, 19, 23, 18, 17, 8]\n</pre>\n\n<p>sorted:</p>\n\n<pre>\n[8, 17, 18, 19, 22, 23]\n</pre>\n\n<p>first element is 19, since abs(20-19) = 1 is the nearest distance to 20.<br>\nlet's find 19 in the sorted array:</p>\n\n<pre>\n[8, 17, 18, 19, 22, 23]\n ^\n</pre>\n\n<p>now the next element would be either 18 or 22, since the array is already sorted:</p>\n\n<pre>\n[8, 17, 18, 19, 22, 23]\n ? ^ ?\n</pre>\n\n<p>so now we have those inner-left and inner-right indexes, let's label them as \"il\" and \"ir\".</p>\n\n<pre>\n[8, 17, 18, 19, 22, 23]\n il ^ ir\n\nresult list: [19]\n</pre>\n\n<p>since 18 is closer to 19 than 22, we take it, and shift il to the left:</p>\n\n<pre>\n[8, 17, 18, 19, 22, 23]\n il ^ ir\n\nresult list: [19, 18]\n</pre>\n\n<p>again, now 17 is closer to 18 than 22</p>\n\n<pre>\n[8, 17, 18, 19, 22, 23]\n il ^ ir\n\nresult list: [19, 18, 17]\n</pre>\n\n<p>now 22 is closer to 17 than 8, so we'd shift the right-index:</p>\n\n<pre>\n[8, 17, 18, 19, 22, 23]\n il ^ ir\n\nresult list: [19, 18, 17, 22]\n</pre>\n\n<p>and the rest is obvious.</p>\n\n<p>Again, this has nothing to do with Python in particular. It's purely an algorithm to be implemented in any language.</p>\n\n<p>This algorithm takes O(n log(n)) in time, while the one suggested by the original poster takes O(n^2) in time.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-11-23T09:51:18.787", "Id": "18926", "ParentId": "5548", "Score": "3" } } ]
{ "AcceptedAnswerId": "5554", "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-10-18T05:02:50.907", "Id": "5548", "Score": "10", "Tags": [ "python" ], "Title": "Reorder list such that each element is followed by the value closest to it" }
5548
<p>As an excercise to "<a href="http://www.haskellcraft.com/craft3e/Home.html" rel="nofollow">Haskell: The Craft of Functional Programming</a>", I created some code to convert an Integer to Roman numerals.</p> <p>This is the first version and I think I'm probably not doing it in the "Haskell way" since my background is in imperative programming.</p> <p>Any advice on how to improve this? Sometimes I think I'm missing a obvious way to do it in just one function.</p> <pre><code>convMap = [(1000,"M"), (900,"CM"), (500,"D"), (400,"CD"), (100,"C"), (90,"XC"), (50,"L"), (40,"XL"), (10,"X"), (9,"IX"), (5,"V"), (4,"IV"), (1,"I")] toRoman :: Integer -&gt; String toRoman x | x == 0 = "N" | otherwise = (snd . numToSubtract $ x) ++ toRoman'(nextNum) where nextNum = x - (fst. numToSubtract $ x) -- Auxiliary function just so we treat 0 differently -- (avoids 3 == "IIIN" if not used) toRoman' :: Integer -&gt; String toRoman' x | x == 0 = "" | x &gt; 0 = (snd . numToSubtract $ x) ++ toRoman'(nextNum) where nextNum = x - (fst. numToSubtract $ x) -- Returns which item in the convMap should be subtracted numToSubtract :: Integer -&gt; (Integer, String) numToSubtract x = head (filter (lessThan x) convMap) -- Filter function to work on the tuples in convMap lessThan :: Integer -&gt; (Integer, String) -&gt; Bool lessThan n (a, b) | a &lt;= n = True | otherwise = False </code></pre>
[ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-10-24T04:44:02.637", "Id": "8428", "Score": "1", "body": "Do you know about [hlint](http://community.haskell.org/~ndm/hlint/)?" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-10-25T02:03:56.213", "Id": "8444", "Score": "0", "body": "@MatrixFrog didn't know it until now! just installed and it's giving me tons of hints where to improve the code. Thank you!" } ]
[ { "body": "<p><strong>Booleans are normal values:</strong></p>\n\n<pre><code>lessThan n (a, b)\n | a &lt;= n = True\n | otherwise = False\n</code></pre>\n\n<p>Simply write:</p>\n\n<pre><code>lessThan n (a, _) = a &lt;= n\n</code></pre>\n\n<p><strong>Use pattern matching:</strong></p>\n\n<pre><code>toRoman' :: Integer -&gt; String\ntoRoman' x \n | x == 0 = \"\"\n | x &gt; 0 = (snd . numToSubtract $ x) ++ toRoman'(nextNum)\n where nextNum = x - (fst. numToSubtract $ x)\n</code></pre>\n\n<p>If you want to take <code>fst</code> and <code>snd</code> of the same tuple, think about pattern matching.\nMinor point: brackets in <code>toRoman'(nextNum)</code> are redundant, simply write <code>toRoman' nextNum</code>.</p>\n\n<pre><code>toRoman' :: Integer -&gt; String\ntoRoman' x\n | x == 0 = \"\"\n | x &gt; 0 = b ++ toRoman' (x - a)\n where (a, b) = numToSubtract x\n</code></pre>\n\n<p><strong>Remove duplication:</strong></p>\n\n<p><code>toRoman</code> and <code>toRoman'</code> contain duplicate code. In fact <code>toRoman</code> is only used to treat specially 0, so can be changed:</p>\n\n<pre><code>toRoman :: Integer -&gt; String\ntoRoman 0 = \"N\"\ntoRoman x = toRoman' x\n</code></pre>\n\n<p><strong>Move or remove utility functions:</strong></p>\n\n<p><code>lessThan</code> and <code>numToSubtract</code> are used only once and don't seem to be generally useful, maybe inline them:</p>\n\n<pre><code>toRoman' :: Integer -&gt; String\ntoRoman' x\n | x == 0 = \"\"\n | x &gt; 0 = b ++ toRoman' (x - a)\n where (a, b) = head $ filter (\\(a,_) -&gt; a &lt;= x) convMap\n</code></pre>\n\n<p>As Dan Burton commented, you can write also:</p>\n\n<pre><code> where (a, b) = head $ filter ((&lt;= x) . fst) convMap\n</code></pre>\n\n<p><strong>Final code</strong></p>\n\n<pre><code>convMap = [(1000,\"M\"), (900,\"CM\"), (500,\"D\"), (400,\"CD\"), (100,\"C\"),\n (90,\"XC\"), (50,\"L\"), (40,\"XL\"), (10,\"X\"), (9,\"IX\"), (5,\"V\"),\n (4,\"IV\"), (1,\"I\")]\n\n-- Auxiliary function just so we treat 0 differently\n-- (avoids 3 == \"IIIN\" if not used)\ntoRoman :: Integer -&gt; String\ntoRoman 0 = \"N\"\ntoRoman x = toRoman' x\n\ntoRoman' :: Integer -&gt; String\ntoRoman' x \n | x == 0 = \"\"\n | x &gt; 0 = b ++ toRoman' (x - a)\n where (a, b) = head $ filter ((&lt;= x) . fst) convMap\n</code></pre>\n\n<p><strong>Fold</strong></p>\n\n<p>If you stare a little at the code, it turns out you <em>each entry from <code>convMap</code> only once</em>. First you check how many M's you need. Then CM's. Then D's. And so on. Using \"filter\" function always restarts search from beginning. In fact, toRoman can be written as a fold!</p>\n\n<pre><code>import Data.List (genericReplicate)\n\nconvMap = [(1000,\"M\"), (900,\"CM\"), (500,\"D\"), (400,\"CD\"), (100,\"C\"),\n (90,\"XC\"), (50,\"L\"), (40,\"XL\"), (10,\"X\"), (9,\"IX\"), (5,\"V\"),\n (4,\"IV\"), (1,\"I\")]\n\ntoRoman :: Integer -&gt; String\ntoRoman 0 = \"N\"\ntoRoman x | x &gt; 0 = snd $ foldl f (x,[]) convMap\n where f (n,s) (rn, rs) = (l, s ++ concat (genericReplicate k rs))\n where (k,l) = divMod n rn\n</code></pre>\n\n<p><strong>Going crazy with abstractions</strong></p>\n\n<p>Erik Hilton's nice answer gives a solution using <code>unfoldr</code>. So you can write the code using fold and unfold, and these are two ways of looking at it. I believe that combination of fold and unfold is called \"paramorphism\" or \"apomorphism\" or something like that...</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-10-24T02:11:12.887", "Id": "8423", "Score": "2", "body": "I would write that lambda like this: `((<= x) . fst)`. Also, it might make more sense semantically to use `dropwhile ((> x) . fst)` instead of `filter`; or even use `find` instead. However, in either case, the actual list traversal is identical." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2018-03-31T04:26:21.050", "Id": "366363", "Score": "0", "body": "I referenced this answer [here](https://stackoverflow.com/a/49584216/633183) :D" } ], "meta_data": { "CommentCount": "2", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-10-24T01:57:15.853", "Id": "5551", "ParentId": "5550", "Score": "14" } }, { "body": "<p>Try something like this</p>\n\n<pre><code>import Data.List\nimport Data.Maybe\n\nconvMap = [(1000,\"M\"), (900,\"CM\"), (500,\"D\"), (400,\"CD\"), (100,\"C\"),\n (90,\"XC\"), (50,\"L\"), (40,\"XL\"), (10,\"X\"), (9,\"IX\"), (5,\"V\"),\n (4,\"IV\"), (1,\"I\")]\n\nintToRoman :: Int -&gt; String\nintToRoman = concat . unfoldr findLeast\n where findLeast n = case i of \n Just (x,r) -&gt; Just(r,n-x)\n Nothing -&gt; Nothing\n where i = find (\\(val,_) -&gt; val &lt;= n) convMap\n</code></pre>\n\n<p>Unfoldr is a function that is sadly underused but exactly what you want here. It takes a seed value, the one you are trying to convert and builds up a list (of roman numeral parts). This might be a touch more verbose than absolutely necessary but I believe it is very clear.</p>\n\n<p>A note on how unfoldr works: you pass it a seed value and a function. this function returns either <code>Just(a,b)</code> or <code>Nothing</code>. In the former case, a is added to the accumulator and b is used as the next seed value. This will continue until the function returns <code>Nothing</code>. At this point the unfoldr is complete.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-10-24T02:20:31.980", "Id": "8425", "Score": "2", "body": "You can write `intToRoman = concat . unfoldr findLeast`" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-10-24T02:21:31.903", "Id": "8426", "Score": "0", "body": "Ahh yes! Superb. Changing now. I always forget the point-free way." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-10-24T02:50:19.830", "Id": "8427", "Score": "0", "body": "thank you very much. I'll be studying the Data.* modules." } ], "meta_data": { "CommentCount": "3", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-10-24T02:14:03.280", "Id": "5552", "ParentId": "5550", "Score": "11" } }, { "body": "<p>Here's my take on it. I've changed the algorithm slightly so that it only has to traverse <code>convMap</code> once.</p>\n\n<pre><code>toRoman 0 = \"N\"\ntoRoman x | x &lt; 0 = error \"toRoman: negative number\"\ntoRoman x = loop x convMap\n where loop 0 _ = \"\"\n loop x cs@((a, b):cs') | x &gt;= a = b ++ loop (x - a) cs\n | otherwise = loop x cs'\n</code></pre>\n\n<p>The pattern is perhaps a little ugly, but other than that I think it's both readable and efficient. You could also write it as a fold,</p>\n\n<pre><code>toRoman x = snd $ foldl f (x, []) convMap\n where f (x, s) (a, b) = let (q, r) = quotRem x a in (r, s ++ concat (replicate q b))\n</code></pre>\n\n<p>but that's slightly less efficient due to quadratic appending. Difference lists would work, but that would only make it messier.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-12-19T16:18:59.350", "Id": "10913", "Score": "0", "body": "Nice! What does cs@((a, b):cs' mean? I know what (cs:cs') means - first item and rest of the list. I have never seen it written like that before :)" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-12-19T16:23:04.913", "Id": "10914", "Score": "0", "body": "Guessing I think that cs would be the whole list and cs' is the whole list minus the first 2 elements while a and b being those elements. Was that correct?" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-12-19T16:51:06.397", "Id": "10919", "Score": "0", "body": "@Ancide: Almost. `(a, b)` is a tuple, so the whole pattern matches a list of tuples, where `a` and `b` are the components of the first tuple, `cs'` is the remaining tuples, and `cs` is the entire list. To match the first and second element of a list, you'd use the `:` pattern twice: `a:b:cs'`." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-12-19T18:21:37.433", "Id": "10922", "Score": "0", "body": "@hammer I keep getting amazed all the time of how awesome Haskell is! Thank you for explaining! :)" } ], "meta_data": { "CommentCount": "4", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-10-24T03:07:34.080", "Id": "5553", "ParentId": "5550", "Score": "7" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "2", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-10-24T01:16:45.197", "Id": "5550", "Score": "14", "Tags": [ "haskell", "roman-numerals" ], "Title": "Converting to Roman numerals" }
5550
<p>This is my architecture to EF4 using repository pattern and unit of work pattern with POCO. I believe I made some mistakes.</p> <p>I have a solution with 5 projects:</p> <ul> <li><code>MyApp.Common</code></li> <li><code>MyApp.Data.EF4</code></li> <li><code>MyApp.Domain.Company</code></li> <li><code>MyApp.Domain.Transmission</code></li> <li><code>MyApp.Web</code></li> </ul> <p>In addition, I am using <code>StructureMap</code> in this application in order to inject the data layer.</p> <p>Now I will describe what each project contains - with source:</p> <p><strong><code>MyApp.Common</code></strong> - contains common classes and interfaces</p> <p>Repository interface: </p> <pre><code>public interface IRepository&lt;T&gt; where T : class { IQueryable&lt;T&gt; GetQuery(IEnumerable&lt;Expression&lt;Func&lt;T, object&gt;&gt;&gt; includes); IPaged&lt;T&gt; GetQuery(IQueryable&lt;T&gt; query, Func&lt;IQueryable&lt;T&gt;, IOrderedQueryable&lt;T&gt;&gt; orderBy, int pageNumber, int pageSize); IPaged&lt;T&gt; GetQuery(IEnumerable&lt;T&gt; query, Func&lt;IEnumerable&lt;T&gt;, IOrderedEnumerable&lt;T&gt;&gt; orderBy, int pageNumber, int pageSize); IEnumerable&lt;T&gt; GetObjectStateManagerChanges(); void Insert(T entity); void MarkModified(T entity); void Delete(T entity); void Attach(T entity); void Detach(T entity); T GetOriginalEntity(Func&lt;T, bool&gt; predicate); } </code></pre> <p>Unit of work interface:</p> <pre><code>public interface IUnitOfWork : IDisposable { int Commit(); } </code></pre> <p>Unit of work factory interface:</p> <pre><code>public interface IUnitOfWorkFactory { IUnitOfWork Create(); } </code></pre> <p>Unit of work:</p> <pre><code> public static class UnitOfWork { private const string HTTPCONTEXTKEY = "MyApp.Common.HttpContext.Key"; private static IUnitOfWorkFactory _unitOfWorkFactory; private static readonly Hashtable _threads = new Hashtable(); public static void Commit() { IUnitOfWork unitOfWork = GetUnitOfWork(); if (unitOfWork != null) { unitOfWork.Commit(); } } public static IUnitOfWork Current { get { IUnitOfWork unitOfWork = GetUnitOfWork(); if (unitOfWork == null) { _unitOfWorkFactory = ObjectFactory.GetInstance&lt;IUnitOfWorkFactory&gt;(); unitOfWork = _unitOfWorkFactory.Create(); SaveUnitOfWork(unitOfWork); } return unitOfWork; } } public static void Dispose() { IUnitOfWork unitOfWork = GetUnitOfWork(); if (unitOfWork != null) { unitOfWork.Dispose(); } } private static IUnitOfWork GetUnitOfWork() { if (HttpContext.Current != null) { if (HttpContext.Current.Items.Contains(HTTPCONTEXTKEY)) { return (IUnitOfWork)HttpContext.Current.Items[HTTPCONTEXTKEY]; } return null; } else { Thread thread = Thread.CurrentThread; if (string.IsNullOrEmpty(thread.Name)) { thread.Name = Guid.NewGuid().ToString(); return null; } else { lock (_threads.SyncRoot) { return (IUnitOfWork)_threads[Thread.CurrentThread.Name]; } } } } private static void SaveUnitOfWork(IUnitOfWork unitOfWork) { if (HttpContext.Current != null) { HttpContext.Current.Items[HTTPCONTEXTKEY] = unitOfWork; } else { lock (_threads.SyncRoot) { _threads[Thread.CurrentThread.Name] = unitOfWork; } } } } </code></pre> <p>Base repository for all entities:</p> <pre><code>public abstract class BaseRepository&lt;T&gt; where T : class { protected IRepository&lt;T&gt; Repository { get; set; } public IEnumerable&lt;Expression&lt;Func&lt;T, object&gt;&gt;&gt; Includes { private get; set; } public BaseRepository() { Repository = ObjectFactory.GetInstance&lt;IRepository&lt;T&gt;&gt;(); Includes = null; } protected virtual IQueryable&lt;T&gt; GetQuery() { return Repository.GetQuery(Includes).AsEnumerable().AsQueryable(); } protected virtual IQueryable&lt;T&gt; GetQuery(params Expression&lt;Func&lt;T, object&gt;&gt;[] includes) { return Repository.GetQuery(includes); } protected virtual IPaged&lt;T&gt; GetQuery(IEnumerable&lt;T&gt; query, Func&lt;IEnumerable&lt;T&gt;, IOrderedEnumerable&lt;T&gt;&gt; orderBy, int pageNumber, int pageSize) { return Repository.GetQuery(query, orderBy, pageNumber, pageSize); } protected virtual IPaged&lt;T&gt; GetQuery(IQueryable&lt;T&gt; query, Func&lt;IQueryable&lt;T&gt;, IOrderedQueryable&lt;T&gt;&gt; orderBy, int pageNumber, int pageSize) { return Repository.GetQuery(query, orderBy, pageNumber, pageSize); } protected virtual IEnumerable&lt;T&gt; GetObjectStateManagerChanges() { return Repository.GetObjectStateManagerChanges(); } protected virtual void Insert(T entity) { Repository.Insert(entity); } protected virtual void MarkModified(T entity) { Repository.MarkModified(entity); } protected virtual void Delete(T entity) { Repository.Delete(entity); } protected virtual void Attach(T entity) { Repository.Attach(entity); } protected virtual void Detach(T entity) { Repository.Detach(entity); } protected virtual T GetOriginalEntity(Func&lt;T, bool&gt; predicate) { return Repository.GetOriginalEntity(predicate); } } </code></pre> <p><strong>MyApp.Data.EF4</strong> - Holds reference of <code>MyApp.Common</code> and implements all interfaces using the EF way. It also includes the MyAppModel.edmx that holds models for all the entities in the system. MyAppModel.edmx has "Code Generation Strategy" set to Default. The entity container name is <code>MyAppEntities</code>.</p> <p>Repository implementation:</p> <pre><code>public class Repository&lt;T&gt; : IRepository&lt;T&gt; where T : class { ObjectContext _context; IObjectSet&lt;T&gt; _objectSet; protected ObjectContext Context { get { if (_context == null) { _context = GetCurrentUnitOfWork&lt;EFUnitOfWork&gt;().Context; } return _context; } } protected IObjectSet&lt;T&gt; ObjectSet { get { if (_objectSet == null) { _objectSet = this.Context.CreateObjectSet&lt;T&gt;(); } return _objectSet; } } public TUnitOfWork GetCurrentUnitOfWork&lt;TUnitOfWork&gt;() where TUnitOfWork : IUnitOfWork { return (TUnitOfWork)UnitOfWork.Current; } public virtual IQueryable&lt;T&gt; GetQuery(IEnumerable&lt;Expression&lt;Func&lt;T, object&gt;&gt;&gt; includes) { return ObjectSet.IncludeMultiple(includes); } public virtual IPaged&lt;T&gt; GetQuery(IQueryable&lt;T&gt; query, Func&lt;IQueryable&lt;T&gt;, IOrderedQueryable&lt;T&gt;&gt; orderBy, int pageNumber, int pageSize) { if (orderBy != null) { query = orderBy(query); } IPaged&lt;T&gt; page = new Paged&lt;T&gt;(query, pageNumber, pageSize); return page; } public virtual IPaged&lt;T&gt; GetQuery(IEnumerable&lt;T&gt; query, Func&lt;IEnumerable&lt;T&gt;, IOrderedEnumerable&lt;T&gt;&gt; orderBy, int pageNumber, int pageSize) { if (orderBy != null) { query = orderBy(query); } IPaged&lt;T&gt; page = new Paged&lt;T&gt;(query, pageNumber, pageSize); return page; } public virtual IEnumerable&lt;T&gt; GetObjectStateManagerChanges() { return this.Context.ObjectStateManager. GetObjectStateEntries(EntityState.Added | EntityState.Modified). Select(e =&gt; e.Entity). OfType&lt;T&gt;(); } public virtual void Insert(T entity) { this.ObjectSet.AddObject(entity); } public virtual void Delete(T entity) { this.ObjectSet.DeleteObject(entity); } public virtual void MarkModified(T entity) { this.Context.ObjectStateManager.ChangeObjectState(entity, EntityState.Modified); } public virtual void Attach(T entity) { ObjectStateEntry entry = null; if (this.Context.ObjectStateManager.TryGetObjectStateEntry(entity, out entry) == false) { this.ObjectSet.Attach(entity); } } public virtual void Detach(T entity) { ObjectStateEntry entry = null; if (this.Context.ObjectStateManager.TryGetObjectStateEntry(entity, out entry) == true) { this.ObjectSet.Detach(entity); } } public virtual T GetOriginalEntity(Func&lt;T, bool&gt; predicate) { T originalEntity = null; EFUnitOfWorkFactory factory = new EFUnitOfWorkFactory(); using (EFUnitOfWork uow = (EFUnitOfWork)factory.Create()) { originalEntity = uow.Context.CreateObjectSet&lt;T&gt;().Single(predicate); } return originalEntity; } } </code></pre> <p>Extension that used in the repository implementation:</p> <pre><code>public static class Extensions { public static IQueryable&lt;T&gt; IncludeMultiple&lt;T&gt;(this IQueryable&lt;T&gt; query, IEnumerable&lt;Expression&lt;Func&lt;T, object&gt;&gt;&gt; includes) where T : class { if (includes != null) { query = includes.Aggregate(query, (current, include) =&gt; current.Include(include)); } return query; } } </code></pre> <p>Implementation for <code>IUnitOfWork</code>:</p> <pre><code>public class EFUnitOfWork : IUnitOfWork, IDisposable { public ObjectContext Context { get; private set; } public int Id { get; private set; } public EFUnitOfWork(ObjectContext context, int id) { Id = id; Context = context; Context.ContextOptions.LazyLoadingEnabled = false; } public int Commit() { return Context.SaveChanges(); } public void Dispose() { if (Context != null) { Context.Dispose(); Context = null; } GC.SuppressFinalize(this); } } </code></pre> <p>Implementation of <code>IUnitOfWorkFactory</code>:</p> <pre><code>public class EFUnitOfWorkFactory : IUnitOfWorkFactory { private static int Counter = 0; private static Func&lt;ObjectContext&gt; _objectContextDelegate; private static readonly Object _lockObject = new object(); public static void SetObjectContext(Func&lt;ObjectContext&gt; objectContextDelegate) { _objectContextDelegate = objectContextDelegate; } public IUnitOfWork Create() { ObjectContext context; lock (_lockObject) { Counter++; context = _objectContextDelegate(); } return new EFUnitOfWork(context, Counter); } } </code></pre> <p><strong><code>MyApp.Domain.Company</code> and <code>MyApp.Domain.Transmission</code></strong> - Contains POCO objects that should hold the query results and be the business logic of the solution. Each project reflects other and different need of the system. But, entities from <code>MyApp.Domain.Company</code> have relationships in the DB and in the .edmx with <code>MyApp.Domain.Transmission</code> entities.</p> <p>For example: <code>Vehicle</code> that exists in <code>MyApp.Domain.Company</code> references by <code>VehicleTransmission</code> that exists in <code>MyApp.Domain.Transmission</code>. In addition, <code>VehicleTransmission</code> holds reference of <code>Vehicle</code> and therefore <code>MyApp.Domain.Transmission</code> contains reference of <code>MyApp.Domain.Company</code>. Both projects hold reference to <code>MyApp.Common</code>. It is important to remember that <code>T_TBL_VEHICLE</code> and <code>T_TBL_VEHICLE_TRANSMISSION</code> (and the connections between them) represented in the same .edmx file. Each .cs file under those projects contains the POCO entity and a repository manager.</p> <p>Vehicle.cs (from <code>MyApp.Domain.Company</code>)</p> <pre><code>public class Vehicle { public virtual long Id { get; set; } public virtual string VehicleNumber { get; set; } public virtual DateTime? PurchaseDate { get; set; } public virtual string InsuranceAgency { get; set; } public virtual DateTime? InsuranceValidity { get; set; } public virtual string Comments { get; set; } public virtual IList&lt;Worker&gt; Workers { get; set; } public string GetPhoneNumber() { string phoneNumber = null; if (PhoneId.HasValue) { phoneNumber = Phone.PhoneNumber1; if (string.IsNullOrEmpty(phoneNumber)) { phoneNumber = Phone.PhoneNumber2; } } return phoneNumber; } public string GetManufacturerName() { string name = null; if (ManufacturerId.HasValue) { name = Manufacturer.Name; } return name; } } public class VehicleRepository : BaseRepository&lt;Vehicle&gt; { private bool IsCounterExists(Guid companyId, long counter) { return GetQuery(). Where(x =&gt; x.CompanyId == companyId). Where(x =&gt; x.IsDeleted == false). AsEnumerable(). Any(x =&gt; x.Code.ToNullable&lt;long&gt;() == counter); } public void Attach(Vehicle entity) { base.Attach(entity); } public void MarkModified(Vehicle entity) { base.MarkModified(entity); } public void Delete(Vehicle entity) { base.Delete(entity); } public void Insert(Vehicle entity) { if (entity.VehicleNumber != null) { entity.VehicleNumber.Trim(); } if (entity.VehicleNumber == null || entity.VehicleNumber == string.Empty) { throw new MissingFieldException( CompanyExceptionMessage.MissingFieldException_Vehicle_Number.Message); } if (string.IsNullOrEmpty(entity.Code)) { StaffCounterRepository rep = new StaffCounterRepository(); entity.Code = rep.GetAndAdvanceCounter(entity.CompanyId, StaffCounterEnum.VEHICLE, counter =&gt; IsCounterExists(entity.CompanyId, counter)).ToString(); } int equals = GetQuery(). Where(x =&gt; x.CompanyId == entity.CompanyId). Where(x =&gt; x.IsDeleted == false). Where(x =&gt; (x.Code != null &amp;&amp; x.Code == entity.Code) || (x.VehicleNumber == entity.VehicleNumber) ).Count(); if (equals &gt; 0) { throw new ExistsNameOrCodeException( CompanyExceptionMessage.ExistsNumberOrCodeException_Vehicle); } base.Insert(entity); } public Vehicle Get(Guid companyId, long vehicleId) { return GetQuery().Where(x =&gt; x.CompanyId == companyId). Single(x =&gt; x.Id == vehicleId); } public IQueryable&lt;Vehicle&gt; Get(Guid companyId) { return GetQuery(). Where(x =&gt; x.CompanyId == companyId). Where(x =&gt; x.IsDeleted == false). OrderBy(x =&gt; x.VehicleNumber); } public Vehicle Get(Guid companyId, string code) { return GetQuery(). Where(x =&gt; x.CompanyId == companyId). Where(x =&gt; x.IsDeleted == false). FirstOrDefault(x =&gt; x.Code == code); } public IQueryable&lt;Vehicle&gt; Search(Guid companyId, string vehicleNumber) { var query = GetQuery(). Where(x =&gt; x.CompanyId == companyId). Where(x =&gt; x.IsDeleted == false); if (vehicleNumber != null) { query = query.Where(x =&gt; x.VehicleNumber.Contains(vehicleNumber)); } return query.OrderBy(x =&gt; x.VehicleNumber); } public IEnumerable&lt;Vehicle&gt; Get(Guid companyId, bool? freeVehicles, bool includeContractorVehicles) { IEnumerable&lt;Vehicle&gt; query = GetQuery(). Where(x =&gt; x.CompanyId == companyId). Where(x =&gt; x.IsDeleted == false); if (freeVehicles == true) { query = query.Where(x =&gt; x.Workers.Count == 0); } else if (freeVehicles == false) { query = query.Where(x =&gt; x.Workers.Count &gt; 0); } query = query.AsEnumerable(); if (includeContractorVehicles == true) { WorkerRepository rep = new WorkerRepository(); IEnumerable&lt;Vehicle&gt; contractorsVehicles = rep.Get(companyId). Where(x =&gt; x.ContractorVehicleNumber != null &amp;&amp; x.ContractorVehicleNumber != string.Empty). AsEnumerable().Select(x =&gt; new Vehicle() { VehicleNumber = x.ContractorVehicleNumber }); query = query.Union(contractorsVehicles); } return query; } public IQueryable&lt;Vehicle&gt; Get(Guid companyId, VehicleStatusEnum? status, string code, string vehicleNumber) { var query = GetQuery(). Where(x =&gt; x.CompanyId == companyId). Where(x =&gt; x.IsDeleted == false); if (status.HasValue) { long? statusId = VehicleStatusWrapper.GetId&lt;VehicleStatusWrapper&gt;(status.Value); query = query.Where(x =&gt; x.StatusId == statusId); } if (!string.IsNullOrEmpty(code)) { query = query.Where(x =&gt; x.Code.Contains(code)); } if (!string.IsNullOrEmpty(vehicleNumber)) { query = query.Where(x =&gt; x.VehicleNumber.Contains(vehicleNumber)); } return query; } } </code></pre> <p>VehicleTransmission.cs (from MyApp.Domain.Transmission)</p> <pre><code>public class VehicleTransmission { public long? VehicleId { get; set; } public string VehicleNumber { get; set; } public long? SubcontractorId { get; set; } public bool WorkerOnHold { get; set; } public Vehicle Vehicle { get; set; } public void SetVehicleId(long? vehicleId) { VehicleId = vehicleId; } //Possibility to set vehicle that is not exists on the db public void SetVehicleNumber(string vehicleNumber) { VehicleId = null; VehicleNumber = vehicleNumber; } } public class VehicleTransmissionRepository : BaseRepository&lt;VehicleTransmission&gt; { public IQueryable&lt;VehicleTransmission&gt; Get() { return GetQuery(); } } </code></pre> <p><strong><code>MyApp.Web</code></strong> - Contains the web application. Holds references to all other projects.</p> <p>In the global.asax, in <code>Application_Start</code> I configure <code>StructureMap</code>:</p> <pre><code> ObjectFactory.Configure(x =&gt; { x.For&lt;IUnitOfWorkFactory&gt;().Use&lt;EFUnitOfWorkFactory&gt;(); x.For(typeof(IRepository&lt;&gt;)).Use(typeof(Repository&lt;&gt;)); x.For(typeof(IEnumRepository&lt;,&gt;)).Use(typeof(EnumRepository&lt;,&gt;)); }); EFUnitOfWorkFactory.SetObjectContext(() =&gt; new MyAppEntities()); </code></pre> <p>In addition, in Application_EndRequest I do:</p> <pre><code>UnitOfWork.Dispose(); </code></pre> <p>I also have web services where there I use the repositories and call <code>UnitOfWork.Commit()</code>when needed.</p> <p>So far, this is my architecture. I really want to know if I made things right and where are my pitfalls.</p>
[ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-10-25T01:28:08.013", "Id": "8443", "Score": "1", "body": "Is there any way you can shorten the code snippets and provide links to the larger examples?" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-10-26T08:52:48.707", "Id": "8472", "Score": "0", "body": "@IAbstract: What do you mean by \"links to the larger examples\"?" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-10-27T02:28:09.850", "Id": "8487", "Score": "0", "body": "@Naor If you can just pad every character with additional whitespace and for every line add 5 lines of comments. That should make the code `larger`." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-12-02T16:49:45.157", "Id": "63714", "Score": "0", "body": "Well you can use `UnitOfWorkScope` to manage life cycle of `UnitOfWork` and take different `UnitOfWorkScope` such as `WCFUnitOfWorkScope`, `WebUnitOfWorkScope`. Their functionality are not applicable by dependency injection containers." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2015-02-11T22:26:13.617", "Id": "145392", "Score": "0", "body": "At a client they have something similar. I spend 80% of time writing abstract layers while the real product implementation is taking ages. I cant see the benefits of half the stuff, yet or ever." } ]
[ { "body": "<p>Without understanding too much of your scenario, here are a few pointers:</p>\n\n<p>I'm not that familiar with Entity Framework, but a common interface for UoW usually have the following behaviors:</p>\n\n<pre><code>public interface UnitOfWork : IDisposable {\n bool IsInTransaction { get; }\n bool IsDirty { get; } // Same as your MarkModified()\n void BeginTransaction();\n void Commit();\n void Rollback();\n}\n</code></pre>\n\n<p>Where is the error and logging handling? Below is an example of a simple wrapper you can use. </p>\n\n<pre><code>// Example call\nExceptionHandler.Try(\"Could not load Vechicle\", () =&gt; _vehicleRepository.Insert(vehicle));\n\n // Example class\n public class ExceptionHandler\n public void Try(string errorMessage, Action func)\n {\n try\n {\n func();\n }\n catch (Exception e)\n {\n Handle(e, errorMessage); // handle and log exception\n }\n }\n</code></pre>\n\n<p>And change the name of the Common-project to something less common..;)</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-10-27T08:42:54.123", "Id": "5626", "ParentId": "5556", "Score": "13" } }, { "body": "<p>This is actually very similar to my implementation...one major difference is that I didn't implement the life-cycle management for the UOW. I handle that with dependency injection (Ninject using Request Scope) which produces the same result.</p>\n\n<p>Another major difference in my implementation is that I also have an <code>ObjectContextResolver</code> and an <code>ObjectContextFactory</code>. The Unit Of Work and the Repositories use the <code>ObjectContextResolver</code> to gain access to the current Context where the <code>ObjectContextFactory</code> is used by the <code>ObjectContextResolver</code> to create new instances of the Context when one does not exist. The <code>ObjectContextFactory</code> also uses an <code>ObjectContextActivationInfo</code> which is a wrapper for the connection string and settings, allowing me to easily vary the way the context is created.</p>\n\n<p>I also have two types of repositories...I have an <code>EntityRepository</code> which is much like your implementation and allows me to query and work with specific entities. I also have a <code>ContextRepository</code> which exposes a <code>GetSet&lt;T&gt;</code> method so I can query any entity type in my model.</p>\n\n<p>I also allow my Unit Of Work scope to be a bit more flexible and let the consuming application define the beginning and end of the unit of work. A typical usage looks like this...</p>\n\n<pre><code>using(var unitOfWork = this.UnitOfWorkFactory.NewUnitOfWork())\n{\n try\n {\n var myVehicle = this.VehicleService.GetVehicleById(123);\n myVehicle.VehicleNumber = this.MyExternalWebService.GetNewVehicleNumber();\n myVehicle.DateModified = DateTime.Now();\n\n unitOfWork.Commit();\n }\n catch(Exception ex)\n {\n // The Web Service Call failed, don't save the changes\n unitOfWork.Rollback();\n }\n\n}\n</code></pre>\n\n<p>This also allows separate Units Of Work to occur with a single Request which is important if some things need to get saved before other things can get created...this happens often when external services or legacy data stores are used in conjunction with EF.</p>\n\n<p>Because I've wrapped my code in a using block, once execution is complete, it is automatically disposed.</p>\n\n<p>I also have a Rollback() method on my UnitOfWork that allows changes to be reverted in cases where some code has failed and you don't want to save the changes.</p>\n\n<p>One limitation of this architecture (both yours and mine) is the inability to perform operations using the UnitOfWork in parallel. I recently had a need to execute two EF queries through my framework in parallel and was not able to do so because the code essentially replaces the current UnitOfWork since my architecture is designed around a single Http Request. </p>\n\n<p>I've been pondering ways to extend my current approach to allow that.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-02-11T07:00:06.480", "Id": "34648", "Score": "0", "body": "Update, I resolved the issue of using these units of work in parallel, but only in read only scenarios." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-02-19T15:37:34.867", "Id": "72577", "Score": "0", "body": "Very interesting. I like how it is used in the end. I wonder if you couldn't pass the UOW instance to the methods in the services somehow? That would be flexible enough to handle any scenario, though I admit it would be potentially a lot more clumsy code-wise, since it would need to be passed to every repository method." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-02-24T17:48:03.137", "Id": "73549", "Score": "1", "body": "I think passing the UOW to the service would defeat the purpose since the UOW scope can span multiple service calls. Assume you have a logical UOW that makes three calls to separate services. If you passed the UOW along, any one of those service methods would be able to Commit or Rollback the UOW. This would force you to continually check the state of the UOW so you'd know if the next service call should commence. I've been using the in app UOW scope for some time now, and I find it very simple, straight forward and reasonably flexible." } ], "meta_data": { "CommentCount": "3", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-10-18T05:27:46.067", "Id": "17661", "ParentId": "5556", "Score": "6" } }, { "body": "<p>Entity Framework IS the Unit of Work in the system so you don't have to reinvent the wheel. Only one you should create: a generic repository base:</p>\n\n<pre><code>interface IRepository&lt;TEntity&gt;\n where TEntity : class\n{\n //Add&lt;TEntity&gt;, Remove&lt;TEntity&gt; ...\n}\n\nclass /* don't have to be abstract */ BaseRepository&lt;TObjectContext, TEntity&gt; : IRepository&lt;TEntity&gt;\n where TObjectContext : ObjectContext\n where TEntity : class\n{\n public RepositoryBase(TObjectContext context)\n {\n //... store context\n }\n\n //implementations\n}\n</code></pre>\n\n<p>And then you can create specialized repositories.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-10-18T14:53:08.217", "Id": "28137", "Score": "0", "body": "It is indeed the unit of work, but if you want to allow control of the lifecycle of the unit of work you need to either create a layer on top of EF that is used by the application or you have to work with Contexts directly in your applications." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-10-18T15:06:03.660", "Id": "28139", "Score": "0", "body": "For lifecycle management use some dependency injection container. (For example Ninject can do it.)" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-10-18T19:04:58.073", "Id": "28160", "Score": "0", "body": "My implementation uses Ninject to manage the lifecycle of the some of the lower level components used to build the context, but not the context itself. This way, my app knows nothing of Contexts. It only knows about services which know about repositories which know about context." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-09-26T03:16:39.590", "Id": "50752", "Score": "0", "body": "@PeterKiss it is true EF **is** a UoW but, by default EF will let you do anything with its context, what happens when your objects dont support every method, let's say you dont want to be able to delete logs, for example. You could always do a generic service wrapper with virtual methods and override every not supported method with a `NotSupportedException`, or handle this in another way, but again, how do you hide your not supported methods? I believe, and this is in my honest and humble oppinion, where the combination of Repository pattern and uow shines." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2015-02-11T22:20:16.773", "Id": "145390", "Score": "0", "body": "What if you create Business \"Manangers\" that implement EF on the data side but expose POCO's - and inject the manangers into the controllers. Currently we have UoF,Repos,POCO's,Manangers, all this bloody abstraction for nothing really. Yea I get it closely couples the data with EF but if they wanted to use something else they gotta write new implementation any way, which can be easily swapped out by DI without changing any web/api layer. Just a current client insists on using it ALL and its doing my head in." } ], "meta_data": { "CommentCount": "5", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-10-18T10:52:54.200", "Id": "17667", "ParentId": "5556", "Score": "4" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "5", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-10-24T08:39:57.773", "Id": "5556", "Score": "33", "Tags": [ "c#", ".net", "entity-framework" ], "Title": "Entity framework with repository and Unit Of Work pattern and POCO architecture" }
5556
<p>I am just wondering if this is a correct way to execute multiple query from a text file.</p> <pre><code>Connection conn = Utility.getConnection(); Statement stmt = null; try{ JFileChooser chooser = new JFileChooser(); int returnVal = chooser.showOpenDialog(chooser); if(returnVal == JFileChooser.APPROVE_OPTION) { String fileName=chooser.getCurrentDirectory().toString()+File.separator+chooser.getSelectedFile().getName(); FileInputStream fstream = new FileInputStream(fileName); DataInputStream in = new DataInputStream(fstream); BufferedReader br = new BufferedReader(new InputStreamReader(in)); String strLine; if(conn != null) stmt = conn.createStatement(); while ((strLine = br.readLine()) != null) { if(stmt !=null){ int rc=stmt.executeUpdate(strLine); if(rc == 0) System.out.println("executing: "+strLine); } } stmt.close(); conn.close(); in.close(); } }catch (Exception e){ e.printStackTrace(); } </code></pre>
[ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-10-24T18:11:45.993", "Id": "8439", "Score": "0", "body": "well you should try to execute it, and you will have a first answer." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-10-24T18:18:05.317", "Id": "8440", "Score": "0", "body": "Code it running fine but I wanted to know some expert opinion :)" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-10-24T20:31:53.603", "Id": "8441", "Score": "1", "body": "It really depends on what the requirements are. Is it just to have an easy way to run a few test queries? Then it's probably fine (assuming it works). If it's for something more serious then I'm not too fond of your (lack of) error handling and I might be worried about security (even if not user supplied you might want to think twice about blindly running deletion or update queries) and atomicity." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-10-25T00:18:21.300", "Id": "8442", "Score": "1", "body": "Side note: You might want to add extra try finally blocks around the execute code. There is no guarantee that the connection or stream is closed if an exception is thrown." } ]
[ { "body": "<p>Some ideas:</p>\n\n<ul>\n<li>Separate the GUI code from the logic.</li>\n<li>If you stay with your current mixed code fail fast. If <code>conn</code> is <code>null</code> there no sense to open the file or ask the user to choose one.</li>\n<li><code>JFileChooser.getSelectedFile()</code> returns a <code>File</code> instance, pass it to <code>FileInputStream</code> directly, don't concatenate strings. <code>File</code> contains the absolute path.</li>\n<li>It's a good practice to pass a <code>Charset</code> (or <code>\"UTF-8\"</code>) the the constructor of the <code>InputStreamReader</code>. The default could vary from system to system.</li>\n<li>The <code>DataInputStream</code> looks unnecessary. You can pass the <code>FileInputStream</code> to the <code>InputStreamReader</code> directly.</li>\n<li>Consider using <a href=\"http://guava-libraries.googlecode.com/svn/trunk/javadoc/com/google/common/io/Files.html#readLines%28java.io.File,%20java.nio.charset.Charset,%20com.google.common.io.LineProcessor%29\" rel=\"nofollow\">Guava's <code>readLines</code></a>.</li>\n<li>Maybe you want to report all executed queries, so the <code>if (rc == 0)</code> condition is unnecessary.</li>\n</ul>\n\n<p>Plus it lacks of proper exception/error handling and resource closing as others mentioned in the comments.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-10-26T04:56:29.197", "Id": "5581", "ParentId": "5558", "Score": "4" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "4", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-10-24T18:08:53.097", "Id": "5558", "Score": "4", "Tags": [ "java", "sql", "swing", "file-system", "jdbc" ], "Title": "Execute multiple query from a text file" }
5558
<p>I know close to nothing about jQuery, but I swear I'm trying to learn. The thing is, I've got some code that works, but I know it's repetitive and probably not kosher for a real programmer, which is why I've turned to you all.</p> <p>What I want to do is show/hide (or toggle, whatever you think is best) some informational divs, or so you might call them, on <a href="http://vefmomentum.com/events/" rel="nofollow noreferrer">this page</a>.</p> <p>The show/hide code that I have right now stands at this: </p> <pre><code> $(document).ready(function(){ $('#meet_growlab, #buddy_tv').hide(); $('a#growlab').click(function(){ $('#meet_growlab').show('slow'); }); $('a#growlab_close').click(function(){ $('#meet_growlab').hide('slow'); }) $('a#buddytv').click(function(){ $('#buddy_tv').show('slow'); }); $('a#buddytv_close').click(function(){ $('#buddy_tv').hide('slow'); }) }); </code></pre> <p>With the HTML being:</p> <pre><code>&lt;div id="meet_growlab"&gt;BLAH BLAH BLAH &lt;p&gt;&lt;a href="#" id="growlab_close"&gt;Close&lt;/a&gt;&lt;/p&gt; &lt;/div&gt; &lt;div id="buddy_tv"&gt;BLAH BLAH BLAH &lt;p&gt;&lt;a href="#" id="buddytv_close"&gt;Close&lt;/a&gt;&lt;/p&gt; &lt;/div&gt; &lt;ul&gt; &lt;li&gt;&lt;a href="#" id="growlab" rel="#meet_growlab"&gt;Meet GrowLab - Canada’s Y-Combinator Arrives in Vancouver (June 24, 2011)&lt;/a&gt;&lt;/li&gt; &lt;li&gt;&lt;a href="#" id="buddytv" rel="#buddy_tv"&gt;Building the Web's Best Entertainment-Based Community Site: Andy Liu, CEO and Founder of BuddyTV (April 1, 2011)&lt;/a&gt;&lt;/li&gt; &lt;/ul&gt; </code></pre> <p>It works, but it's not pretty.</p>
[]
[ { "body": "<ol>\n<li>You could have the hide/show divs inside a container, and then on <code>.ready</code> hide all its immediate children;</li>\n<li>You could then target all <code>a.close</code> inside this container, and on click hide the clicked anchor's grand-grandparent;</li>\n<li>And finally target all anchors inside the items list, and on click show the div corresponding to the anchor's <code>rel</code>;</li>\n<li>I would also make the anchor's <code>href</code> the same as its <code>rel</code>, so that if any user has JavaScript disabled the anchor still works.</li>\n</ol>\n\n<p>So, HTML:</p>\n\n<pre><code>&lt;div id=\"eventDescriptions\"&gt;\n &lt;div id=\"meet_growlab\"&gt;BLAH BLAH BLAH\n &lt;p&gt;&lt;a href=\"#growlab\" class=\"close\"&gt;Close&lt;/a&gt;&lt;/p&gt;\n &lt;/div&gt;\n &lt;div id=\"buddy_tv\"&gt;BLAH BLAH BLAH\n &lt;p&gt;&lt;a href=\"#buddytv\" class=\"close\"&gt;Close&lt;/a&gt;&lt;/p&gt;\n &lt;/div&gt;\n&lt;/div&gt;\n&lt;ul id=\"eventTitles\"&gt;\n &lt;li&gt;&lt;a href=\"#\" id=\"growlab\" rel=\"#meet_growlab\"&gt;Meet GrowLab - Canada’s Y-Combinator Arrives in Vancouver (June 24, 2011)&lt;/a&gt;&lt;/li&gt;\n &lt;li&gt;&lt;a href=\"#\" id=\"buddytv\" rel=\"#buddy_tv\"&gt;Building the Web's Best Entertainment-Based Community Site: Andy Liu, CEO and Founder of BuddyTV (April 1, 2011)&lt;/a&gt;&lt;/li&gt;\n&lt;/ul&gt;\n</code></pre>\n\n<p>and a more compact and <code>DRY</code> JQuery:</p>\n\n<pre><code>$(document).ready(function(){\n $('#eventDescriptions&gt;div').hide();\n $('#eventTitles a').click(function(){\n var target = $(this).attr(\"rel\");\n $(target).show('slow');\n });\n\n $('#eventDescriptions .close').click(function(){\n $(this).parent().parent().hide('slow');\n })\n});\n</code></pre>\n\n<p>Here, a JSFiddle: <a href=\"http://jsfiddle.net/QYjLY/\" rel=\"nofollow\">http://jsfiddle.net/QYjLY/</a></p>\n\n<hr>\n\n<p>Other things I quickly noticed:</p>\n\n<ol>\n<li>Good job on using rel;</li>\n<li>Instead of <code>&lt;img border=0 ...</code> you could use CSS - <code>a img { border: 0;}</code>;</li>\n<li><code>#social</code> is a list, so it could be a <code>ul</code> instead of a <code>div</code>.</li>\n</ol>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-10-25T21:50:00.520", "Id": "8464", "Score": "0", "body": "Thanks for the tips ANeves! And as for #social being a list - even when it's not incorporating the li tag to bring about different elements it's still considered a list? I thought it was just a div because it's a bunch of images, and not text..." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-10-25T22:11:34.457", "Id": "8466", "Score": "0", "body": "I should probably be more eloquent in my question, namely if I'm displaying a set of images, one after another in a horizontal line, that's a list? Isn't it just more code to add a ul component? I have to have div anyway for the social media buttons to position it correct relative to the nav menu and sub menu and the news ticker. Plus those images aren't really even a list - just a conglomeration of...well, images." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-10-26T09:44:40.280", "Id": "8474", "Score": "0", "body": "I think I should have used `could` instead of the strong `should`. My thought was that abstractly it is a list of... other presences on the web? So it could be a `ul`, then styled to be shown in a line. Not too important, though." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-10-26T20:12:12.260", "Id": "8482", "Score": "0", "body": "Aha. I get it. Thanks for the clarification and thanks for all the help!" } ], "meta_data": { "CommentCount": "4", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-10-25T09:21:12.650", "Id": "5564", "ParentId": "5563", "Score": "2" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-10-25T07:36:42.640", "Id": "5563", "Score": "3", "Tags": [ "javascript", "jquery" ], "Title": "Show/hide function with multiple div ids" }
5563
<p>I have a private field called <code>individualProfile</code> (camelCase) and I've created a public property called <code>IndividualProfile</code> (PascalCase) on it:</p> <pre><code>private Profile individualProfile; public Profile IndividualProfile { get { if (individualProfile == null) { individualProfile = ProfileFacade.Instance.GetMainProfileByType ( PortalContext.CurrentUserId, ProfileType.IrnicIndividual ); if (individualProfile == null) { individualProfile = new Profile() { FirstName = string.Empty, Family = string.Empty, Details = new IrnicIndividual() { NationalCode = string.Empty } }; } } return individualProfile; } } </code></pre> <p>I have to use this public property in almost 10 places, so I first check the private member to see if it's null and load it only once, so that I load it only once and I cache it and use it 10 times. Also, since <code>GetMainProfileByType</code> can return null value, I check another time to see if the private member is null or not. If it's null, I simply set it to an empty object, so that I won't bother checking null values when I bind this object to my view.</p> <p>Is this code efficient and maintainable? Is there anything I've overlooked?</p>
[]
[ { "body": "<p>Looks perfect to me.</p>\n\n<p>The only comment I have is that, assuming an empty Profile makes sense, the <code>String.Empty</code> default on the properties could be set by the constructor - rather than you setting them explicitly.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-10-25T11:32:23.530", "Id": "5567", "ParentId": "5565", "Score": "2" } }, { "body": "<p>Good thinking about the caching and efficiency. I have two minor suggestions</p>\n\n<p>1 - <strong>Enforce SRP (single responsibility principal)</strong>, which basically states (according to Robert C. Martin) that in the world of \"Clean Code\" classes must have one reason to change for better maintainability, which is one of the concerns you had in your question. So to apply this to your case, the class that contains the <code>Profile</code> property need not be changed if you decide to change the signature of the <code>ProfileFacade.Instance.GetMainProfileByType</code> method, or maybe choose another method to populate the <code>Profile</code>. So maybe refactoring that code out of the class would be a good idea. Here is what I mean by that:</p>\n\n<pre><code>private Profile _individualProfile;\npublic Profile IndividualProfile\n{\n get\n {\n if (_individualProfile != null) return _individualProfile;\n\n return (_individualProfile = ProfileFacade.Instance.GetIrnicProfile() ?? Profile.NullProfile);\n }\n}\n</code></pre>\n\n<p>As you can see in the code snippet I used the short hand null check using the <code>??</code> null-coalescing operator.</p>\n\n<p>2 - <strong>NULL object pattern</strong>. Basically define the neutral state (or NULL state) of your object inside the object itself, benefiting from not changing the calling code if ou decide to redefine what the NULL means for your object. In my code snippet I added <code>Profile.NullProfile</code> which is defined as such:</p>\n\n<pre><code>public class Profile\n{\n public string FirstName { get; set; }\n // Other properties here\n public static Profile NullProfile\n {\n get\n {\n return new Profile\n {\n FirstName = String.Empty,\n // etc...\n };\n }\n }\n}\n</code></pre>\n\n<p>Other than that... Good work!</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-10-25T15:07:51.047", "Id": "8454", "Score": "1", "body": "Your first code block is convoluted and hard to skim, thus bad from a maintainability point of view. This ruins your answer, IMO. I would suggest to keep the original `if null assign; afterwards return` approach." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-10-25T18:15:50.640", "Id": "8456", "Score": "0", "body": "The succinct style I use is orthogonal to the answer, I do not believe it takes away from the validity of the answer. I had similar reaction when I first realized how versatile and multi-paradigm C# can be, after all there's a lot of personal/individual style involved in coding." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-10-26T09:38:37.823", "Id": "8473", "Score": "0", "body": "This being codereview style is not orthogonal to answers :) , and the question also asks whether the code is maintainable. But other than that, I still think your answer is very good." } ], "meta_data": { "CommentCount": "3", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-10-25T14:15:42.897", "Id": "5570", "ParentId": "5565", "Score": "6" } }, { "body": "<p>Do you have .NET 4 at your disposal? If so, you can use the <code>Lazy&lt;T&gt;</code> as such:</p>\n\n<pre><code> private readonly Lazy&lt;Profile&gt; individualProfile =\n new Lazy&lt;Profile&gt;(() =&gt;\n {\n var newProfile = ProfileFacade.Instance.GetMainProfileByType(\n PortalContext.CurrentUserId,\n ProfileType.IrnicIndividual);\n\n return newProfile ?? new Profile\n {\n FirstName = string.Empty,\n Family = string.Empty,\n Details = new IrnicIndividual\n {\n NationalCode = string.Empty\n }\n };\n });\n\n [DebuggerBrowsable(DebuggerBrowsableState.Never)]\n public Profile IndividualProfile\n {\n get\n {\n return individualProfile.Value;\n }\n }\n</code></pre>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-10-25T16:02:17.997", "Id": "5573", "ParentId": "5565", "Score": "2" } } ]
{ "AcceptedAnswerId": "5570", "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-10-25T10:31:32.103", "Id": "5565", "Score": "3", "Tags": [ "c#", "cache" ], "Title": "Public property, backing up by a private field, with caching and null checking inside" }
5565
<p>I'm teaching myself JavaScript and jQuery at the same time by trying to complete little projects that I come up with or my friends come up with. I have no official JavaScript training and am pretty much just OJT (without the job).</p> <p>I created a function below and was hoping I could get some feedback from the experts and professionals at SO. Could you tell me what I could do better or more efficiently? What is unprofessional in my function? I haven't learned any best practices or had any kind of mentor so I'm not sure what's generally 'acceptable' and what's not. I have a feeling you guys wouldn't like the way I use some arrays in my function for one thing, and anything else you could suggest would be great.</p> <p>Basically what I'm trying to create, is a price that will auto update on each click of a menu item (checkboxes). There's a starting price, a quantity textbox, most options have an additional charge, some don't. The options are grouped into similar categories, and sometimes you get "a # of included" options in your price, so maybe you have 1 included option in that group, that means you should be able to add 1 without having the price go up, then the next time you add one, it should go up. </p> <p>The HTML markup for the menu would look something like this:</p> <pre><code>&lt;p id="Tprice" class="price"&gt;10.00&lt;/p&gt; &lt;label for="quantity" class="quantity"&gt;QTY&lt;/label&gt; &lt;input id="hidden1" type="hidden" value="1" class="includeds"&gt; // how many options are included &lt;h3&gt;cool stuff, one included&lt;/h3&gt; &lt;ul class="groups"&gt; &lt;li&gt;&lt;input id="li1" type="checkbox" name="test2_menu" title="1.00" onclick="updatePrice()"&gt;cheese&lt;/li&gt; &lt;li&gt;&lt;input id="li2" type="checkbox" name="test2_menu" title="2.00" onclick="updatePrice()"&gt;bread&lt;/li&gt; &lt;li&gt;&lt;input id="li3" type="checkbox" name="test2_menu" title="3.50" onclick="updatePrice()"&gt;snacks&lt;/li&gt; &lt;/ul&gt; &lt;input id="hidden2" type="hidden" value="0" class="includeds"&gt; &lt;h3&gt;other stuff&lt;/h3&gt; &lt;ul class="groups"&gt; &lt;li&gt;&lt;input id="li4" type="checkbox" name="test1_menu" title="0" onclick="updatePrice()"&gt;cake&lt;/li&gt; &lt;li&gt;&lt;input id="li5" type="checkbox" name="test1_menu" title="0.50" onclick="updatePrice()"&gt;soup&lt;/li&gt; &lt;li&gt;&lt;input id="li6" type="checkbox" name="test1_menu" title="6.25" onclick="updatePrice()"&gt;donut&lt;/li&gt; &lt;/ul&gt; </code></pre> <p>The JavaScript for <code>updatePrice</code> is as follows:</p> <pre><code>var WKoriginal = '10.00', WKlastPrice = WKoriginal; // original "no additional options" price for item set // last price initially set to same as original on page load, updates after each price update to the new price, this way if a free option is selected, we don't do the price update animation unless the number is different function updatePrice() { var priceControlArray = new Array(), priceControlArrayMax = new Array(), priceControlArrayCount = new Array(), WKextras = 0, WKnewPrice = 0, priceControlArrayIndex = 0; // upextras = total amount of additional charges to apply to original price, based on what's checked // arrays keep track of groups that have a number of additional charges included in original price $('.checkbox').each(function() { // for each item with class 'checkbox' if ($(this).is(':checked')) { // if the item is checked, else do nothing if($(this).closest('ul').prevAll('.includeds:first').val() !== '0') { // if the group has a number of included additionals (based on hidden field above each group), else just add the price to upextras var indexofArray = -1; for (i=0; i &lt; priceControlArray.length; i++) { if (priceControlArray[i] === $(this).attr('name').split('_')[0]) { // search array for an entry matching groupname indexofArray = i; break; } } if (indexofArray === -1) { // if group wasnt found in array, add it, else work with existing array entry priceControlArray[priceControlArrayIndex] = $(this).attr('name').split('_')[0]; // create array line with group name priceControlArrayMax[priceControlArrayIndex] = $(this).closest('ul').prevAll('.includeds:first').val(); // create array line with group included value priceControlArrayCount[priceControlArrayIndex] = 1; // create array line for group that says 1 item has been added so far priceControlArrayIndex = parseInt(priceControlArrayIndex) + 1; // bump up array index for next potential new group } else { // work with existing array entry if (parseInt(priceControlArrayMax[indexofArray]) &lt;= parseInt(priceControlArrayCount[indexofArray])) { // if the number of included options for group is less than or equal to the current amount of group's checked options, add price to upextras, else do not add WKextras = parseFloat(WKextras) + parseFloat($(this).attr('title')); // add price to upextras priceControlArrayCount[indexofArray] = parseInt(priceControlArrayCount[indexofArray]) + 1; // bump up number of included options for group by 1 } else { priceControlArrayCount[indexofArray] = parseInt(priceControlArrayCount[indexofArray]) + 1; // bump up number of included options for group by 1 } } } else { WKextras = parseFloat(WKextras) + parseFloat($(this).attr('title')); // add price of checked option to upextras if there wasn't any group with included # &gt; 0 attached to it } } }); WKnewPrice = (parseFloat(WKoriginal) + parseFloat(WKextras)) * parseFloat($('#quantity').val()); // add original price, total extra charges and multiply by quantity count if (parseFloat(WKnewPrice) !== WKlastPrice) { // if new price is different from the last price, animation price change $('#Tprice').fadeOut('fast', function() { // fadeout existing price, after completed, fade in new price $("#Tprice").html(WKnewPrice.toFixed(2).toString()).fadeIn(); // format price to XX.XX }); } WKlastPrice = WKnewPrice; // update last price, for comparison on next run through } </code></pre> <p>The function works as you see it now, but I'm hoping the pros here can point out what I'm doing badly or inefficiently so I can learn good habits early.</p>
[ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-10-25T14:48:46.060", "Id": "8452", "Score": "0", "body": "It's only been 17 minutes, and you posted quite a bit of code." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-10-25T14:49:36.277", "Id": "8453", "Score": "0", "body": "alrighty sorry all" } ]
[ { "body": "<p>here are some code optimization ( had not checked the algorithm , only syntax ).</p>\n\n<p><strong>#1</strong>\nThis : </p>\n\n<pre><code>var priceControlArray = new Array(), \npriceControlArrayMax = new Array(), \npriceControlArrayCount = new Array(), \nWKextras = 0, \nWKnewPrice = 0, \npriceControlArrayIndex = 0;\n</code></pre>\n\n<p>May be replaced with this :</p>\n\n<pre><code>var priceControlArray = priceControlArrayMax = priceControlArrayCount = [] , \nWKextras = WKnewPrice = priceControlArrayIndex = 0;\n</code></pre>\n\n<p><strong>#2</strong>\nDon't call <code>$(this)</code> all the time, like here :</p>\n\n<pre><code> if ($(this).is(':checked')) { // if the item is checked, else do nothing\n if($(this).closest('ul') ...\n</code></pre>\n\n<p>Save it at the start of the function and use cached variable :</p>\n\n<pre><code>var $this = $(this); //and then use $this variable, it much faster\nif ( $this.is(':checked') ) { // if the item is checked, else do nothing\n if( $this.closest('ul') ...\n</code></pre>\n\n<p><strong>#3</strong>\nThe names of you variables are too long , it is kind hard to read, but this is not an issue, it depends on your own code style. I suggest you to read the source code of jquery library - good example of syntax order.</p>\n\n<p><strong>#4</strong>\nDont use <code>onclick=\"updatePrice()</code> remove it from HTML and attach this event from jquery</p>\n\n<pre><code>$(document).ready(function() {\n $(\"#li1 , #li2, #li3, #li4, #li4, #li5, #li6\").bind( \"click\" , updatePrice );\n});\n</code></pre>\n\n<p>Better not to use div's id , I suggest you to add a common class and then bind the event to this class only</p>\n\n<pre><code>$(document).ready(function() {\n $(\".prices\").bind( \"click\" , updatePrice );\n});\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-10-30T22:30:00.740", "Id": "8619", "Score": "0", "body": "`var priceControlArray = priceControlArrayMax = priceControlArrayCount = [] , ` is very bad for objects/lists (or anything that is not a literal value). because they all point to the same list. Change one and they all change." } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-10-30T10:30:12.313", "Id": "5699", "ParentId": "5571", "Score": "1" } }, { "body": "<p>On your markup:</p>\n\n<p>you have id's for all your <code>&lt;input&gt;</code> elements. Seems unnecessary to have id's unless you need them. </p>\n\n<pre><code> &lt;li&gt;&lt;input id=\"li1\" ...\n &lt;li&gt;&lt;input id=\"li2\" ...\n &lt;li&gt;&lt;input id=\"li3\" ...\n\n &lt;li&gt;&lt;input id=\"li4\" ...\n &lt;li&gt;&lt;input id=\"li5\" ...\n &lt;li&gt;&lt;input id=\"li6\"...\n</code></pre>\n\n<p>With your label:</p>\n\n<pre><code>&lt;label for=\"quantity\" class=\"quantity\"&gt;QTY&lt;/label&gt;\n</code></pre>\n\n<p>the 'for=\"\"` attribute should contain the id of an element (probably an input element). You don't seem to have one called quantity. I'm not sure if this was a typo or not.</p>\n\n<p>you are using the <code>title=\"\"</code> attribute for keeping values. Don't. You should use a <code>data-*</code> attribute .</p>\n\n<pre><code>title=\"0\"\n</code></pre>\n\n<p>becomes </p>\n\n<pre><code>data-price=\"0\"\n</code></pre>\n\n<p>then in jQuery you can easily access it by</p>\n\n<pre><code>$(myelement).data(\"price\")\n</code></pre>\n\n<p>also you are using arrays to hold your elements. It would be easier and quicker to put a class on them and access them in code by that class. You can already access them by</p>\n\n<pre><code>$(\".groups input\")\n</code></pre>\n\n<p>put that in a variable instead of making an array.</p>\n\n<hr>\n\n<p>Just as a note I'd suggest you read up on css selectors as that helps a lot with jQuery:</p>\n\n<ul>\n<li><a href=\"http://htmldog.com/guides/cssbeginner/\" rel=\"nofollow\">http://htmldog.com/guides/cssbeginner/</a></li>\n<li><a href=\"http://htmldog.com/guides/cssintermediate/\" rel=\"nofollow\">http://htmldog.com/guides/cssintermediate/</a></li>\n<li><a href=\"http://htmldog.com/guides/cssadvanced/\" rel=\"nofollow\">http://htmldog.com/guides/cssadvanced/</a></li>\n</ul>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-10-30T22:41:30.120", "Id": "5708", "ParentId": "5571", "Score": "3" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "2", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-10-25T14:26:53.250", "Id": "5571", "Score": "2", "Tags": [ "javascript", "jquery" ], "Title": "Menu that updates a total price on option click" }
5571
<p>I am aware of it being frowned upon to do something like write C# in JavaScript. (see <a href="https://blog.codinghorror.com/you-can-write-fortran-in-any-language/" rel="noreferrer">this</a> if you don't know what I'm talking about)</p> <p>But as a judgement call, I think we could stand to have a relatively simple check for values that are <code>null</code> or empty, so I'm looking for feedback on this implementation of <code>String.isNullOrEmpty</code>.</p> <pre><code>String.isNullOrEmpty = function (value) { return (!value || value == undefined || value == "" || value.length == 0); } </code></pre>
[ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-10-25T19:50:38.630", "Id": "8458", "Score": "1", "body": "Aren't the first checks redundant after you've already tried to call `toString` on `value`?" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-10-25T20:04:37.860", "Id": "8459", "Score": "0", "body": "Possibly.... I was thinking if I were to call a \"static\" String.isNullOrEmpty(). Not sure if I need it." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-10-25T20:59:35.197", "Id": "8460", "Score": "0", "body": "That revision is no good, see [this](http://stackoverflow.com/questions/2703102/typeof-undefined-vs-null) and other posts. You've radically changed the meaning of the function." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-10-25T21:13:18.450", "Id": "8461", "Score": "0", "body": "Not following you on that second comment. \"You've radically changed the meaning of the function\" I just removed that first try, catch. I didn't change any comparison operators. Maybe you should give me your thoughts in a full answer form." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-10-25T21:18:06.880", "Id": "8462", "Score": "0", "body": "Come to think of it. Because I am going to use it as such, would it be better if if(String.isNullOrEmpty(51354.toString())){} Or should the isNullOrEmpty handle casting" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-10-25T21:19:22.183", "Id": "8463", "Score": "0", "body": "I'm not really an authoritative source on javascript, I was just trying to comment in general :) I'll try to write something up tomorrow unless someone more knowledgeable turns up. What I meant with my comment was that your two version returns different answers for something like `0` or `false` and undefined variables." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-10-26T01:16:28.753", "Id": "8468", "Score": "3", "body": "Would not a `return !value;` suffice?" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-10-28T11:54:55.913", "Id": "8547", "Score": "0", "body": "@Terrance please take this C# away. `!string` is what you want, `String.isNullOrEmpty(string)` is an abomination" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-10-28T12:50:51.440", "Id": "8551", "Score": "0", "body": "@Raynos Please elaborate. How do you mean? (How would !string check for empty strings for one and how is String.isNullOrEmpty() an abomination for two) As far as abstraction or performance or what?" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-10-28T13:27:24.813", "Id": "8554", "Score": "0", "body": "@Terrance `!\"\" === true` and `!null == true` and `String.isNullOrEmpty` is just bloat that exists for no purpose other then \"C# does it, it must be the best\"" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-10-28T14:47:31.840", "Id": "8560", "Score": "0", "body": "@Raynos If it makes you feel better I can certainly change the name of the method. I just needed something that insures that all checks are made in dealing with string validation. And since we are a microsoft shop it seems to make the most sense to use something that would be considered a familiar construct. I could care less that it is a \".NET\" thing. As long as the code base doesn't have if(val.length==0) sometimes and other times if(val!=undefined&&val!=null&&val!=\"\") other times. We could call it isNil or isNothing if it insures its usage." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-10-28T15:11:10.297", "Id": "8562", "Score": "0", "body": "@Terrance I'm saying what's wrong with `if (!val) {` instead of `if(val === \"\" || val === null) {`" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-09-13T00:53:27.360", "Id": "444948", "Score": "0", "body": "the link does not work anymore" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-09-13T12:21:33.903", "Id": "445003", "Score": "1", "body": "@MuhammadOmerAslam the OG site apears to be dead but, I added a different article discussing the issue. Hope that helps :P" } ]
[ { "body": "<p>There are just a few revisions I would make. </p>\n\n<p>First, <em>always</em> use <code>===</code> instead of <code>==</code> in Javascript. You can read more about that <a href=\"https://stackoverflow.com/questions/523643/difference-between-and-in-javascript\">on Stack Overflow</a>.</p>\n\n<p>Second, since <a href=\"http://wtfjs.com/2010/02/15/undefined-is-mutable\" rel=\"noreferrer\"><code>undefined</code> is mutable</a>, I would reccomend using</p>\n\n<pre><code>typeof value === \"undefined\"\n</code></pre>\n\n<p>instead of </p>\n\n<pre><code>value === undefined\n</code></pre>\n\n<p>Third, I would remove the <code>!value</code> and <code>value === \"\"</code> conditions. They are redundant.</p>\n\n<h2>My Revision</h2>\n\n<p>I would use a slightly different approach than you:</p>\n\n<pre><code>String.isNullOrEmpty = function(value) {\n return !(typeof value === \"string\" &amp;&amp; value.length &gt; 0);\n}\n</code></pre>\n\n<p>This checks if the type of the value is <code>\"string\"</code> (and thus non-null and not undefined), and if it is not empty. If so, it is not null or empty.</p>\n\n<p>Note that this returns <code>true</code> for non-string inputs, which might not be what you want if you wanted to throw an error for an unexpected input type.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-10-26T04:38:35.550", "Id": "5580", "ParentId": "5572", "Score": "15" } }, { "body": "<p>You should use <code>Object.prototype.isNullOrEmpty = function() { alert(this) }</code>. This ties it to the String object in all instances. This would start to give you access to use strings and variables like <code>\"\".isNullOrEmpty</code> or <code>var x = null; x.isNullOrEmpty();</code></p>\n\n<p>If your intent is to use it as a function to pass in variables: <code>String.isNullOrEmpty();</code></p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-10-28T15:17:15.450", "Id": "8564", "Score": "1", "body": "Except some people don't like extending the native prototypes." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-12-11T09:58:15.013", "Id": "133230", "Score": "5", "body": "Additionally, the example with `null` won't work." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-09-13T13:43:22.733", "Id": "445015", "Score": "1", "body": "And it doesn't work with `undefined` either." } ], "meta_data": { "CommentCount": "3", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-10-28T03:54:19.117", "Id": "5643", "ParentId": "5572", "Score": "3" } }, { "body": "<p>Starting with:</p>\n\n<pre><code>return (!value || value == undefined || value == \"\" || value.length == 0);\n</code></pre>\n\n<p>Looking at the last condition, if value == \"\", it's length MUST be 0. Therefore drop it:</p>\n\n<pre><code>return (!value || value == undefined || value == \"\");\n</code></pre>\n\n<p>But wait! In JS, an empty string is false. Therefore, drop <code>value == \"\"</code>:</p>\n\n<pre><code>return (!value || value == undefined);\n</code></pre>\n\n<p>And <code>!undefined</code> is true, so that check isn't needed. So we have:</p>\n\n<pre><code>return (!value);\n</code></pre>\n\n<p>And we don't need parentheses:</p>\n\n<pre><code>return !value\n</code></pre>\n\n<p>Q.E.D.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-10-31T15:43:36.850", "Id": "8632", "Score": "7", "body": "i must say... bravo" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-11-02T20:37:10.967", "Id": "8731", "Score": "1", "body": "@ndp Gotta give it to you. That was complete and concise. Nice." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2015-03-17T07:16:00.137", "Id": "151582", "Score": "0", "body": "@ndp, Great answer! It's bit confusing for a moment tho... Please add a conclusion to your answer stating it's the final solution, for quick reference, thanks." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-09-24T00:01:59.190", "Id": "393795", "Score": "1", "body": "A really Great Answer ndp!\nI added a screen shot in a reply that shows verfies it and shows execution for those who don't immediately get it.\n\n var A;\n var B = null;\n var C = \"test\";\n console.log(\"is A nullOrEmpty %o\", !A);\n console.log(\"is B nullOrEmpty %o\", !B);\n console.log(\"is C nullOrEmpty %o\", !C);" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-04-18T15:33:33.523", "Id": "472294", "Score": "1", "body": "But if someone passes it as a boolean value of false, then it might return the false positive. I think we need to add the check for that as-well." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-09-03T06:55:47.743", "Id": "487621", "Score": "0", "body": "What if the value is not a type of string, e.g. a number?" } ], "meta_data": { "CommentCount": "6", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-10-31T02:28:36.387", "Id": "5710", "ParentId": "5572", "Score": "119" } }, { "body": "<p>Ryan and seand are spot on: This achieves your end.</p>\n\n<pre><code>Object.prototype.isNullOrEmpty = function(value){\n return (!value);\n}\n</code></pre>\n\n<p>This is what I love about <em>JavaScript</em>!</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-11-24T22:53:27.407", "Id": "455045", "Score": "0", "body": "Just make sure nobody else implements a different isNullOrEmpty in Object.prototype and heavily relies on his implementation. Patching Object.prototype is evil." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-12-03T22:35:00.633", "Id": "498759", "Score": "0", "body": "Doesn't work with null and undefined value" } ], "meta_data": { "CommentCount": "2", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-12-11T07:49:33.473", "Id": "73300", "ParentId": "5572", "Score": "3" } }, { "body": "<p>Your function unexpectedly returns <code>true</code> for the following non-string values:</p>\n\n<ul>\n<li><code>false</code></li>\n<li><code>0</code></li>\n<li><code>Number.NaN</code></li>\n<li><code>[[]]</code></li>\n<li><code>[]</code></li>\n</ul>\n\n<p>It's quite possible that <code>!value</code> though it is similarly sloppy, would suffice, in which case you wouldn't need to define this function at all. But if you create a function that is named <code>isNullOrEmpty</code>, then it should do just that.</p>\n\n<pre><code>function String.isNullOrEmpty(value) {\n return value == null || value === \"\";\n}\n</code></pre>\n\n<p>Note that <code>value == null</code> is shorthand for <code>value === null || value === undefined</code>.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2018-03-07T19:04:47.893", "Id": "361400", "Score": "0", "body": "This is clean. Using coercion is not evil as many might suggest. As long as you realize you are doing it and how and WHY it works." } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2015-02-26T02:59:16.400", "Id": "82633", "ParentId": "5572", "Score": "6" } } ]
{ "AcceptedAnswerId": "5710", "CommentCount": "14", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2011-10-25T15:01:45.477", "Id": "5572", "Score": "56", "Tags": [ "javascript", "strings", "null" ], "Title": "String.IsNullOrEmpty in JavaScript" }
5572
<p>Please review this simple code. When I review it I decide to rewrite so that it doesn't write to a template, but instead directly to output since the whole HTML is fetched from the data layer. I used the tool <code>appengine_admin</code> to get editable HTML for simple html capabilities to an appspot project:</p> <pre><code> class Page(db.Model): html = db.TextProperty(required=True) class AdminPage(appengine_admin.ModelAdmin): model = Page listFields = ( 'html', ) editFields = ( 'html', ) application = webapp.WSGIApplication([ ('/page/([0-9]+)', PageHandler), ]) class PageHandler(BaseHandler): def get(self, file_id): page = Page.get_by_id(long(file_id)) if not page: self.error(404) return self.render_template(file_id+'.html', { 'body': page.body, }) </code></pre> <p>My 2 to-dos:</p> <ol> <li>change variable <code>file_id</code> to <code>page_id</code></li> <li>change writing to direct output instead of template</li> </ol>
[]
[ { "body": "<pre><code> application = webapp.WSGIApplication([ ('/page/([0-9]+)', PageHandler), ])\n</code></pre>\n\n<p>I'd put the list of urls as a global constant, I think that would make it easier to read.</p>\n\n<pre><code> class PageHandler(BaseHandler):\n def get(self, file_id):\n page = Page.get_by_id(long(file_id))\n if not page:\n</code></pre>\n\n<p>If you are checking against None here, I'd use <code>if page is None:</code></p>\n\n<pre><code> self.error(404)\n return\n</code></pre>\n\n<p>I'd use else instead of returning here</p>\n\n<pre><code>self.render_template(file_id+'.html', {\n 'body': page.body,\n})\n</code></pre>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-10-26T04:05:09.857", "Id": "5578", "ParentId": "5577", "Score": "3" } } ]
{ "AcceptedAnswerId": "5578", "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-10-26T02:26:09.710", "Id": "5577", "Score": "2", "Tags": [ "python", "google-app-engine" ], "Title": "HTML editor for Google App Engine" }
5577
<p>I say this is right because X might happen and Y modification to the code is possible in the future. More senior guy says the sorta similar thing, except along the lines "I'm right, you're wrong." Then I back off, b/c he is more senior. </p> <p>Here I implement a method <code>playMatingGameA(String)</code>. My more senior coworker provides alternative implementation <code>playMatingGameB(String)</code>. Please, ignore how the main object fits into the grand scheme of things. The point is coding up a <em>single method</em>. </p> <p><strong>Problem description</strong>: an object of class <code>Partner</code> has to play a mating game. The input is a mating call. S/He takes a taxi, goes to a Bar or a Club or whatever, emits a mating call, flirts and mates. The <code>playMatingGame()</code> method isn't supposed to throw an exception or return a value. A string status variable is set instead. </p> <p>String <code>matingCall</code> must be nonempty. The establishment (Bar) must find it appropriate. A few method calls can throw exceptions/return nulls.</p> <p>I'll conclude with my own thoughts, but comments from other engineers would be much appreciated.</p> <pre><code>interface MeatMarket { public Partner findPartner(String matingCall); public boolean isMatingCallAllower(String call) throws PartnerRejectionException; } // e.g., Bar, Club, Church, etc. class TaxiMeatMarketFactory { public static MeatMarket getMeSomePlaceFun() throws RuntimeException; // I know, no need 2 declare } public abstract class Partner { String name; // {get; set; justkiddingthisisjava;} private String morningAfterFeeling; // here B constructorz [skip] // . . . and the methodz public void flirt(Partner p) throws PartnerRejectionException, ParnterNotSoberException; public abstract void mate(Partner p) throws PartnerWrongSpeciesException; // The goal: with your given mating call, take taxi to a meatmarket // find a partner, flirt then mate. // No throwing up! No Exceptions! // // MUST return void and record morningAfterFeeling as a status. public void playMatingGameA(String matingCall) { morningAfterFeeling = "Great"; if (matingCall == null || matingCall.equals("")) { morningAfterFeeling = "No voice"; log.error(morningAfterFeeling); return; } MeatMarket mm = null; try { // might still return null. mm = TaxiMeatMarketFactory.getMeSomePlaceFun(); } catch(RuntimeException e) { log.error(e); } if (mm == null) { // taxi's fault either way. log.error("Bad taxi"); morningAfterFeeling = "Bad taxi"; return; } try { if (!mm.isMatingCallAllowed(matingCall)) { morningAfterFeeling = "Arse kicked &amp; thrown out"; return; } } catch(PartnerRejectionException e) { morningAfterFeeling = "Bad meatmarket"; log.error(e); return; } try { Partner p = mm.findPartner(matingCall); flirt(p); mate(p); } catch(PartnerRejectionException e) { morningAfterFeeling = "partner not responsive"; log.error(e); } catch(PartnerNotSoberException e) { // here and above the partner's choices are very unwise. morningAfterFeeling = "partner not responsive"; log.error(e); } catch(PartnerWrongSpeciesException e) { // and here it's partner's physique, out of their control morningAfterFeeling = "Could not find partner"; log.error(e); } finally { if (!gotHome()) { morningAfterFeeling += "Slept on street"; } } if (!"Good".equals(morningAfterFeeling)) { log.error("Terrible night out"); } } public void playMatingGameB(String matingCall) { try { morningAfterFeeling = "Great"; if (matingCall == null || matingCall.equals("")) { morningAfterFeeling = "No voice"; log.error(morningAfterFeeling); return; } else { MeatMarket mm = TaxiMeatMarketFactory.getMeSomePlaceFun(); if (!mm.isMatingCallAllowed(matingCall)) { morningAfterFeeling = "Ass kicked &amp; thrown out"; return; } else { Partner p = mm.findPartner(matingCall); flirt(p); mate(p); } } } catch(PartnerRejectionException e) { morningAfterFeeling = "Exception: " + e.getMessage(); log.error(e); } catch(PartnerNotSoberException e) { // here and above the partner's choices are very unwise. morningAfterFeeling = "Exception: " + e.getMessage(); log.error(e); } catch(PartnerWrongSpeciesException e) { // and here it's partner's physique, out of their control morningAfterFeeling = "Exception: " + e.getMessage(); log.error(e); } catch (Exception e) { morningAfterFeeling = "Exception: " + e..getMessage(); log.error(e); } finally { if (!makeItHome()) { morningAfterFeeling += "Slept on street"; } // this clause moved here for no particular reason if (!"Good".equals(morningAfterFeeling)) { log.error("Terrible night out"); } } } } </code></pre> <p>Method A provides more detailed info about what goes wrong. And it stays away from null references. I'd rather touch a living rattle snake than a null. I've learned to do away with bad (null, negative, etc) inputs in the very beginning. Then move on to the "meat". which is exactly 3 lines long: <code>findPartner()</code>, <code>flirt()</code>, <code>mate()</code>.</p> <p>His method is definitely shorter and the whole logic fits into one paragraph, followed by catches. Where I check for null reference, he catches the <code>NullPointerException</code> and gains a few lines of code this way. His "meat" includes some error checking logic and nicely fits on a page. But is way longer than 3 lines, and it involves nested <code>if</code>-<code>else</code>s. Also notice how the line <code>morningAfterFeeling="Good"</code> in his method. Its correctness depends on the overall <code>catch(Exception e)</code>.</p> <p>He says that all my returns are jumps in logic. Not a problem to me, I think. If this is bad, return. It's over. If not, assume it's good &amp; move on. By the time you get to the meat, you KNOW what you shouldn't worry about.</p> <p>P.S. I've changed the method/object names, of course, I would't just copy-paste the proprietary code. Recasting the real thing into the mating game setting was an interesting abstraction exercise.</p>
[ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-10-26T04:20:12.860", "Id": "8469", "Score": "0", "body": "Of course, just a tad bit of refactoring on the A-metod wouldn't hurt. Separate helper method to check for bad arguments, and another one -- inside **catch (Exception e)** clause to deal with the exception appropriately. May have to use reflection to determine its exact type." } ]
[ { "body": "<p>I agree explicitly checking for error conditions (instead of a general catching of <code>Exception</code>) and failing fast or returning early are usually good practices, as you have done in your method. Some people don't like the break in logic flow, but there's no reason to continue on and it avoids nesting of conditionals and/or other code blocks. Catching generic <code>Exception</code> is always a red flag for me -- sometime you have to do it, but usually there's a better way.</p>\n\n<p>To simplify the <code>catch</code> blocks, you might want to consider making a superclass (say <code>AbstractRejectionException</code>) for all your custom exceptions that has an abstract <code>getMorningAfterFeeling()</code> method to allow the subclasses to return their own specific feelings. This would simplify many of your <code>catch</code> blocks into just this:</p>\n\n<pre><code>} catch (AbstractRejectionException e) {\n morningAfterFeeling = e.getMorningAfterFeeling();\n log.error(e);\n}\n</code></pre>\n\n<p>Also, you are initially setting <code>morningAfterFeeling</code> to <code>\"Great\"</code>, but checking for <code>Good\".equals(morningAfterFeeling</code>. I'm assuming that was a typo.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-10-28T07:50:24.643", "Id": "5652", "ParentId": "5579", "Score": "2" } }, { "body": "<p>You and your senior handling the <code>NullPointerException</code> with same logic </p>\n\n<pre><code>if ( matingCall == null || matingCall.equals(\"\") )\n</code></pre>\n\n<p>But it gives me a <em>ughhhhh</em> feeling. However you both are right but I would modify your code</p>\n\n<pre><code>if ( matingCall == null || \"\".equals(matingCall) ) {\n // do what you do\n}\n</code></pre>\n\n<p>This is a guarantee that <a href=\"http://en.wikibooks.org/wiki/Java_Programming/Preventing_NullPointerException\" rel=\"nofollow\">NPE will never occur</a>. </p>\n\n<hr>\n\n<p>Now <code>playMatingGameA(String)</code> has a good work-flow logic. As you said <em>\"If this is bad, return. It's over. If not, assume it's good &amp; move on.\"</em>. I also believe in this as the code is good to handle. I always sacrifice LOC to readability and maintainability.</p>\n\n<p>Your explicit exception handling makes it easier to debug the code than <code>playMatingGameA(String)</code> method. Now in case of multiple catch codeblocks, you can easily optimize that. </p>\n\n<p>Onwards Java7 you can catch multiple exception in same catch block. <em><a href=\"http://docs.oracle.com/javase/7/docs/technotes/guides/language/catch-multiple.html\" rel=\"nofollow\">Catching multiple exception FTW</a></em> right?</p>\n\n<p>Now your code or the senior's code looses like, what 8-9 lines of code. Right? So <strong>Enjoy</strong>. </p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-09-01T00:46:06.380", "Id": "48682", "Score": "0", "body": "Doing `matingCall.equals(\"\")` is perfectly fine **here**. `||` operator will not evaluate the second part if `matingCall` is null." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-09-01T07:33:49.930", "Id": "48709", "Score": "0", "body": "@Marc-Andre yes I know but seeing this gives me a *ughhh* feeling that someone is swallowing NPE. that's why I said that, but it's an opinion." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-09-02T01:15:51.710", "Id": "48750", "Score": "0", "body": "There is no swallowing there, they specifically check for the null condition. `matingCall.equals` can't throw a NPE. It can't be a matter of style here since they're doing `\"\".equals` everywhere else. But you don't have to worry about NPE in this case." } ], "meta_data": { "CommentCount": "3", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-08-31T15:11:28.130", "Id": "30567", "ParentId": "5579", "Score": "0" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "1", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-10-26T04:09:10.067", "Id": "5579", "Score": "5", "Tags": [ "java", "comparative-review" ], "Title": "Partner mating game" }
5579
<p>What difference does this make:</p> <pre><code>&lt;script type="text/javascript"&gt; //&lt;![CDATA[ ...code </code></pre> <p>Compared to this</p> <pre><code>&lt;script type="text/javascript"&gt; ...code </code></pre>
[ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-01-25T10:32:16.480", "Id": "67250", "Score": "5", "body": "This question appears to be off-topic because it is a \"What is the best practice regarding X?\" question. See [help/on-topic]." } ]
[ { "body": "<p>You should not use XHTML 1.0 anymore ( which is where you would use CDATA ). What is even more important, you should no have javascript inside your html files. Instead you should include external files via <code>&lt;script src=\"/my/js/file.js\"&gt;&lt;/script&gt;</code>.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-10-26T16:17:13.173", "Id": "8478", "Score": "0", "body": "To not use XHTML is just your personal opinion. The next version would be HTML 5, which is still far from being final: http://ishtml5readyyet.com/" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-10-27T07:00:10.713", "Id": "8490", "Score": "0", "body": "@Guffa , while you should not use all the features of HTML5 , using HTML5 doctype is strongly recommended." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-10-27T09:53:06.490", "Id": "8501", "Score": "0", "body": "And core HTML 5 support is available in most browsers at this point, whether all the fringe features are available or not. The same can't be said for XHTML; most browsers parse XHTML as HTML anyway, or skip all the features of XHTML that make it worthwhile (namely strict validation)." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-10-27T12:55:27.827", "Id": "8505", "Score": "0", "body": "you should not server XHTML as text/html .. it's just wrong." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-10-23T00:17:22.567", "Id": "28371", "Score": "1", "body": "As a side note, while it's true most of the time, it's not *always* a better idea to use external JS. If the file is small enough, placing it inline can reduce server requests for a speed boost." } ], "meta_data": { "CommentCount": "5", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-10-26T07:05:13.683", "Id": "5583", "ParentId": "5582", "Score": "5" } }, { "body": "<p>If you use XHTML it's useful to have CDATA tags in the script to make the page pass validation.</p>\n\n<p>Normally it's not needed for the page to work. Browsers just look for the end tag of the script and assume that everything in the script tag should be used as is, without decoding.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-10-27T09:46:23.253", "Id": "8500", "Score": "1", "body": "If you use XHTML, it's *all but required* to have CDATA tags. (It's definitely required if you have `<` or `&` in your script. Otherwise, i forget.) Any conforming XML parser would choke on the typical script that's not wrapped in a CDATA tag. That it works, when and if it does, is purely due to XHTML being crappily supported and the browser parsing it as HTML. Which defeats the main goals of XHTML in the first place." } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-10-26T11:35:28.177", "Id": "5585", "ParentId": "5582", "Score": "3" } } ]
{ "AcceptedAnswerId": "5583", "CommentCount": "1", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-10-26T06:24:08.197", "Id": "5582", "Score": "1", "Tags": [ "javascript" ], "Title": "Should I use CDATA in javascript?" }
5582
<p>I have created a really simple repository for some simple data retrieval and was wondering if i was going in the right direction. Has anyone got any thoughts on this?</p> <p><strong><code>interface</code></strong></p> <pre><code>public interface IRepository&lt;T&gt; where T : class { IEnumerable&lt;T&gt; GetAll(); T GetById(int id); IEnumerable&lt;T&gt; Filter(Expression&lt;Func&lt;T, bool&gt;&gt; filter); void Dispose(); } </code></pre> <p><strong><code>class</code></strong></p> <pre><code>public class JobRepository : IRepository&lt;Job&gt;, IDisposable{ /// &lt;summary&gt; /// handles all job data retrieval /// crude but will suffice for now /// &lt;/summary&gt; CentralRepositoryContainer _context = null; public JobRepository() { CentralRepositoryContainer context = HttpContext.Current.GetCentralRepositoryContext(); } /// &lt;summary&gt; /// returns all jobs /// &lt;/summary&gt; /// &lt;returns&gt;IEnumerable&lt;Job&gt;&lt;/returns&gt; public IEnumerable&lt;Job&gt; GetAll() { try { return this._context.Jobs; } catch (SqlException ex) { //error so dispose of context this.Dispose(); //wrap and rethrow back to caller throw new CentralRepositoryException("Error getting all jobs", ex); } } /// &lt;summary&gt; /// return job /// &lt;/summary&gt; /// &lt;param name="id"&gt;integer to search on&lt;/param&gt; /// &lt;returns&gt;job&lt;/returns&gt; public Job GetById(int id) { try { return this._context.Jobs.SingleOrDefault(j =&gt; j.JobId == id); } catch (SqlException ex) { //error so dispose of context this.Dispose(); //wrap and rethrow back to caller throw new CentralRepositoryException("Error getting all job by id", ex); } } /// &lt;summary&gt; /// filters based on parsed filter expression /// &lt;/summary&gt; /// &lt;param name="filter"&gt;filter to search on&lt;/param&gt; /// &lt;returns&gt;IQueryable&lt;Job&gt;&lt;/returns&gt; public IEnumerable&lt;Job&gt; Filter(System.Linq.Expressions.Expression&lt;Func&lt;Job, bool&gt;&gt; filter) { try { return this._context.Jobs.Where(filter); } catch (SqlException ex) { //error so dispose of context this.Dispose(); //wrap and rethrow back to caller throw new CentralRepositoryException("Error getting all job by filter", ex); } } public void Dispose() { if (this._context != null) { this._context.Dispose(); } } } </code></pre>
[ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-10-11T13:26:39.200", "Id": "8475", "Score": "1", "body": "Why post the comments? Especially the summaries? 24 lines of comments (40%) in this simple piece of code carry completely redundant information and totally decrease readability." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-10-26T15:10:37.550", "Id": "8476", "Score": "0", "body": "Typo? I think you meant to write `public JobRepository() { _context = httpContext.Current.GetCentralRepositoryContext(); }`" } ]
[ { "body": "<p>Especially in such simple cases you don't want to create a repository over an EF (I assume it's EF -- but the same goes for Linq2SQL) context. </p>\n\n<p>The DbContext basically is an implementation of the repository pattern. Your repository on top just creates another layer of complexity without actually providing any serious benefit.</p>\n\n<p>In more complicated cases wrapping the DbContext with a specific interface may make sense of course.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-10-11T13:32:44.100", "Id": "5587", "ParentId": "5586", "Score": "3" } }, { "body": "<p>I'd expand on the repository a bit with adding a few operations to the interface and implementing them as well as making your <code>GetAll()</code> and <code>Filter()</code> methods return <code>IQueryable</code> instead (as they are queries):</p>\n\n<pre><code>public interface IRepository&lt;T&gt; where T : class {\n IQueryable&lt;T&gt; GetAll();\n T GetById(int id);\n T GetOne(Expression&lt;Func&lt;T, bool&gt;&gt; filter);\n IQueryable&lt;T&gt; Filter(Expression&lt;Func&lt;T, bool&gt;&gt; filter);\n int Add(T instance); // returns a unique integer ID for this entity.\n void Update(T instance);\n void Delete(T instance);\n void DeleteById(int id);\n void Dispose();\n}\n</code></pre>\n\n<p>You might also want to tighten down what you store in your repository, i.e. do not just 'where T : class' - make your classes implement an interface or descent from a base class which has some inherent qualities:</p>\n\n<pre><code>public abstract class BaseEntity {\n private int id;\n\n public int Id\n {\n get\n {\n return this.id;\n }\n\n private set\n {\n this.id = this.SetId(value);\n }\n }\n\n protected abstract int SetId(int id);\n}\n</code></pre>\n\n<p>as a start.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-10-26T14:56:28.487", "Id": "5588", "ParentId": "5586", "Score": "3" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "2", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-10-11T13:11:28.033", "Id": "5586", "Score": "4", "Tags": [ "c#" ], "Title": "Repository for data retrieval" }
5586
<p>I'd like to know if i respect strlcat(3) behiour with my implementation, cause i'm not really sure to understand strlcat particular behaviour</p> <pre><code>int my_strlcat(char *dest, char *src, int size) { int i; int src_len; int dest_len; i = 0; dest_len = strlen(dest); src_len = strlen(src); if (size &lt;= 0) return dest_len; while (dest_len &lt; size) { dest[dest_len] = src[i]; dest_len++; i++; } dest[dest_len] = '\0'; return (strlen(dest)); } </code></pre>
[ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-10-12T13:01:38.993", "Id": "8477", "Score": "2", "body": "In general, using signed types for sizes and anything but size_t for things of arbitrary size is a bad idea." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2017-01-11T20:29:26.030", "Id": "287751", "Score": "0", "body": "If dest does not already contain a nil-terminated string, or contains one that overflows dest (e.g. because someone previously used strcat()), then strlen() could return a value larger than size and you're already boned. You should replace the strlen() call with some code of your own that stops counting when it reaches size." } ]
[ { "body": "<p>You're basically right I think. Checking the man page for <code>strlcpy()</code> shows one discrepancy I can see - the null termination of the destination only happens if there's room in <code>dest</code> after the copying. Although that seems kind of dangerous to me, it depends how well you want to replicate the semantics. Your current implementation always null-terminates, which is nice and safe but might end up diverging from the stock implementation in that edge case.</p>\n\n<p>For performance, you should check <code>size &lt;= 0</code> before you <code>strlen()</code> both of the strings, as in that case you only need to call <code>strlen(dest)</code>. That might seem minor, but <code>strlen</code> runs in O(N) time so you don't want to be calling it if you don't have to. So basically just move the check on <code>size</code> to before the call to <code>strlen(src)</code>.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-10-12T12:42:57.593", "Id": "5590", "ParentId": "5589", "Score": "0" } }, { "body": "<pre><code>while (dest_len &lt; size)\n {\n dest[dest_len] = src[i];\n dest_len++;\n i++;\n }\ndest[dest_len] = '\\0';\n</code></pre>\n\n<p>At the end of the loop dest_len will be equal to size, and the dest[des_len] will write beyond the allowed offset.</p>\n\n<p>UPDATE: this will probably work</p>\n\n<pre><code>size_t my_strlcat(char *dest, char *src, size_t size)\n{\nsize_t src_len, dest_len;\n\n dest_len = strlen(dest);\n src_len = strlen(src);\n\n if (dest_len+src_len&gt;= size) return dest_len+src_len;\n\n memcpy(dest+dest_len, src, src_len+1);\n\n return dest_len+src_len;\n}\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-09-03T17:54:21.713", "Id": "391317", "Score": "1", "body": "This is inefficient, you end up iterating over `src` twice, making this not `O(N + M)` but `O(N + M*2)`." } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-10-12T12:47:57.453", "Id": "5591", "ParentId": "5589", "Score": "0" } }, { "body": "<ul>\n<li><code>src_len</code> is not used..</li>\n<li>the <code>strlen</code> in the return statement is not needed.. you know the length from <code>dest_len</code>.</li>\n</ul>\n\n<p>IMHO very weird implementation :)</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-10-12T13:00:15.610", "Id": "5592", "ParentId": "5589", "Score": "2" } }, { "body": "<p>There are a few things wrong if this is meant to be a implementation of the standard <a href=\"http://www.manpagez.com/man/3/strlcat/\" rel=\"nofollow\"><code>strlcat()</code></a>:</p>\n\n<ul>\n<li>The function definition should be of the form: <code>size_t my_strlcat(char *dst, const char *src, size_t size);</code></li>\n<li>You are always overflowing the destination buffer by one when you NUL terminate.</li>\n<li>You are overflowing the source buffer reads depending on the input. For example, consider if <code>dest_len=1</code>, <code>src_len=2</code> and <code>size=1000</code>.</li>\n<li>While not wrong it is better to try to minimize the use of <code>strlen()</code> unless needed. You probably only need one <code>strlen(dest)</code>. </li>\n</ul>\n\n<p>See <a href=\"http://src.gnu-darwin.org/src/sys/libkern/strlcat.c.html\" rel=\"nofollow\">here</a> for an example implementation of strlcat().</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-10-12T13:36:36.107", "Id": "5593", "ParentId": "5589", "Score": "2" } } ]
{ "AcceptedAnswerId": "5591", "CommentCount": "2", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-10-12T12:36:00.257", "Id": "5589", "Score": "2", "Tags": [ "c", "strings" ], "Title": "is it a good strlcat() implementation?" }
5589
<p>I have simple code, that draw graph of my histogram. But code looks ugly, do you have idea, how can I make it looks better ?</p> <pre><code> for (int i = 0; i &lt; hueCount - 2; ++i) { if( i % 6 == 0) g.DrawLine(borderPen, margin+ (width - 2 * margin) * ((float)i / (float)hueCount), height - margin, margin+ (width - 2 * margin) * ((float)i / (float)hueCount), height - margin - 5); g.DrawLine(redPen, margin + ((float)i / (float)hueCount) * (width - 2 * margin), (-(float)reds[i] / (float)maxRed) * (height - 2 * margin) - margin + height, margin + ((float)(i + 1) / (float)hueCount) * (width - 2 * margin), (-(float)reds[i + 1] / (float)maxRed) * (height - 2 * margin) - margin + height); g.DrawLine(greenPen, margin + ((float)i / (float)hueCount) * (width - 2 * margin), (-(float)greens[i] / (float)maxGreen) * (height - 2 * margin) - margin + height, margin + ((float)(i + 1) / (float)hueCount) * (width - 2 * margin), (-(float)greens[i + 1] / (float)maxGreen) * (height - 2 * margin) - margin + height); g.DrawLine(bluePen, margin + ((float)i / (float)hueCount) * (width - 2 * margin), (-(float)blues[i] / (float)maxBlue) * (height - 2 * margin) - margin + height, margin + ((float)(i + 1) / (float)hueCount) * (width - 2 * margin), (-(float)blues[i + 1] / (float)maxBlue) * (height - 2 * margin) - margin + height); } </code></pre>
[]
[ { "body": "<p>I had to fake a lot of your values but it seems like your DrawLine's is the same except for the color so just create a method to do the real draw line and pass in the colors etc.</p>\n\n<pre><code> for (int i = 0; i &lt; hueCount - 2; ++i)\n {\n if (i % 6 == 0)\n g.DrawLine(borderPen,\n margin + (width - 2 * margin) * ((float)i / (float)hueCount),\n height - margin,\n margin + (width - 2 * margin) * ((float)i / (float)hueCount),\n height - margin - 5);\n\n DrawLine(reds, width, height, maxRed, hueCount, redPen, i, margin);\n DrawLine(greens, width, height, maxGreen, hueCount, redPen, i, margin);\n DrawLine(blues, width, height, maxBlue, hueCount, redPen, i, margin);\n } \n\n private static void DrawLine(Array colors, int width, int height, int max, \n int hueCount, Pen redPen, Graphics g, int i,\n int margin)\n {\n g.DrawLine(redPen,\n margin + ((float) i/(float) hueCount)*(width - 2*margin),\n (-(float) colors[i]/(float) max)*(height - 2*margin) - margin + height,\n margin + ((float) (i + 1)/(float) hueCount)*(width - 2*margin),\n (-(float) colors[i + 1]/(float) max)*(height - 2*margin) - margin + height);\n }\n</code></pre>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-10-26T19:19:53.687", "Id": "5598", "ParentId": "5594", "Score": "1" } }, { "body": "<p>Here's what I came up with using a helper class:</p>\n\n<pre><code> Draw draw = new Draw(g, borderPen, hueCount, margin, width, height);\n\n for (int i = 0; i &lt; hueCount - 2; ++i)\n {\n draw.DrawBorder(i);\n draw.DrawLine(redPen, i, reds, maxRed);\n draw.DrawLine(greenPen, i, greens, maxGreen);\n draw.DrawLine(bluePen, i, blues, maxBlue);\n }\n</code></pre>\n\n<p>...</p>\n\n<pre><code>internal sealed class Draw\n{\n private readonly Graphics g;\n\n private readonly Pen borderPen;\n\n private readonly int hueCount;\n\n private readonly int margin;\n\n private readonly int doubleMargin;\n\n private readonly int width;\n\n private readonly int height;\n\n internal Draw(Graphics g, Pen borderPen, int hueCount, int margin, int width, int height)\n {\n this.g = g;\n this.borderPen = borderPen;\n this.hueCount = hueCount;\n this.margin = margin;\n this.doubleMargin = 2 * this.margin;\n this.width = width;\n this.height = height;\n }\n\n internal void DrawBorder(int i)\n {\n if (i % 6 == 0)\n {\n float x = margin + (width - doubleMargin) * (float)i / hueCount;\n float y = height - margin;\n\n g.DrawLine(borderPen, x, y, x, y - 5);\n }\n }\n\n internal void DrawLine(Pen pen, int i, int[] colors, int maxColor)\n {\n float wm = width - doubleMargin;\n float hm = height - doubleMargin;\n float mh = margin - height;\n\n g.DrawLine(\n pen,\n margin + ((float)i / hueCount) * wm,\n (-(float)colors[i] / maxColor) * hm - mh,\n margin + ((float)(i + 1) / hueCount) * wm,\n (-(float)colors[i + 1] / maxColor) * hm - mh);\n }\n}\n</code></pre>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-10-26T19:33:35.180", "Id": "5600", "ParentId": "5594", "Score": "5" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-10-26T18:09:16.837", "Id": "5594", "Score": "5", "Tags": [ "c#" ], "Title": "Make my draw graph looks better" }
5594
<p>I have the following code (for <code>Country</code> and <code>City</code> classes <code>key_name</code> is numeric id with addition of 'i' at the beginning):</p> <pre><code>def add_country(country, country_name): if country and country_namef and country_name != '': return Country.get_or_insert('i'+str(country), country_name=country_name) else: return None def add_city(city, city_name, country): if country and city and city_name and city_name != '': return City.get_or_insert('i'+str(city), city_name=city_name, parent=country) else: return None </code></pre> <p>Is it correct code or can it be optimized somehow?</p>
[]
[ { "body": "<pre><code>def add_country(country, country_name):\n if country and country_namef and country_name != '':\n</code></pre>\n\n<p>I assume that country_namef is a typo. If so, there is no point in checking <code>country_name != ''</code> because empty strings are already considered False</p>\n\n<pre><code> return Country.get_or_insert('i'+str(country), country_name=country_name)\n else:\n return None \n\ndef add_city(city, city_name, country):\n if country and city and city_name and city_name != '':\n</code></pre>\n\n<p>As before, empty strings are false, so you are checking that twice</p>\n\n<pre><code> return City.get_or_insert('i'+str(city), city_name=city_name, parent=country)\n else:\n return None\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-10-27T17:56:50.780", "Id": "8512", "Score": "0", "body": "So, in case when `country_name` is equal to `None` and when `country_name` is equal to `''`, in both cases `if country_name` returns `False`, right?" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-10-27T17:58:09.233", "Id": "8513", "Score": "0", "body": "@LA_, yes that is correct." } ], "meta_data": { "CommentCount": "2", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-10-26T20:25:39.233", "Id": "5601", "ParentId": "5599", "Score": "2" } } ]
{ "AcceptedAnswerId": "5601", "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-10-26T19:33:35.027", "Id": "5599", "Score": "0", "Tags": [ "python" ], "Title": "How to optimize the code to save data at GAE datastore?" }
5599
<p>I've coded a simple quiz game for Android, and currently Im having troubles with making questions not appear after they've been shown, i.o. I dont want it to ask me the same question twice..</p> <p>This is the method Im using</p> <pre><code> private void QBegin() { /* * Gets a random question */ question = (TextView) findViewById(R.id.question); String[] types = { "Question one", "Question two", "Question three", "Question four", "Question five"}; Random random = new Random(); int qType = random.nextInt(types.length); question.setText(types[qType]); getAnswers(qType); //gets four answers } </code></pre> <p>Im not sure if this will work but, what if I add something like</p> <p>Edit : Doesn't work..</p> <pre><code> int i = 0; ArrayList&lt;Integer&gt; list = new ArrayList&lt;Integer&gt;(); list.add(qType); i++; if(list.contains(qType) &amp;&amp; i != types.length + 1){ return; } else { answerCounter.setText("Hit the bricks pal, you're done.."); } </code></pre> <p>On <a href="http://stackoverflow.com">http://stackoverflow.com</a> got told to , add smth like:</p> <pre><code> ArrayList&lt;Integer&gt; list = new ArrayList&lt;Integer&gt;(); list.add(types.length); Collections.shuffle(list); if(!list.contains(qType)){ // help please, as I have no idea on what I should be doing! } </code></pre>
[ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-10-27T11:34:10.540", "Id": "8503", "Score": "0", "body": "Duplicate over at Stack Overflow: [Creating Random Numbers with No Duplicates](http://stackoverflow.com/questions/4040001/java-creating-random-numbers-with-no-duplicates)" } ]
[ { "body": "<p>The usual way is to start with something like an array of indexes, then shuffle those into (pseudo-) random order with something like the Fisher-Yates shuffle.</p>\n\n<p>Another possibility is to use a random number generator whose range and period are exactly equal to the number of entries you need to shuffle. Offhand I don't remember any algorithms for finding a generator with a specified range and period though.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-10-26T21:42:14.907", "Id": "5603", "ParentId": "5602", "Score": "4" } }, { "body": "<p>There are basically two different ways of doing this efficiently:</p>\n\n<ul>\n<li>Put the questions in a list</li>\n<li>Shuffle the list</li>\n<li>Loop through the list and show the questions</li>\n</ul>\n\n<p>or:</p>\n\n<ul>\n<li>Put the questions in a list</li>\n<li>Pick a question to show by random</li>\n<li>Remove that question from the list</li>\n<li>Repeat until the list is empty</li>\n</ul>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-10-26T22:13:39.610", "Id": "5604", "ParentId": "5602", "Score": "6" } } ]
{ "AcceptedAnswerId": "5604", "CommentCount": "1", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-10-26T21:32:54.177", "Id": "5602", "Score": "2", "Tags": [ "java", "android" ], "Title": "How to make a int not be used twice when it randomly generates them?" }
5602
<p>I need to compare some values of a Javascript object. If they fail to be identical, I want to pretty print to <code>console.log</code> the mismatch.</p> <p>The <a href="https://github.com/kaihendry/Chrome-Webview-experiments/blob/6494ed05f6527cd1c6a0d85f4fc1b765a7eb270a/sample.js" rel="nofollow">initial code I have written</a> which I find fugly after a JS beautify looks like:</p> <pre><code>function assert(a, b, message) { if (a != b) { console.log("Failed to match " + message + " " + a + " != " + b); return false; } return true; } if (!assert(parsedInput.protocol, cu.protocol, "protocol")) { continue; } if (!assert(parsedInput.port, cu.port, "port")) { continue; } if (!assert(parsedInput.hostname, cu.hostname, "hostname")) { continue; } if (!assert(parsedInput.hash, cu.hash, "hash")) { continue; } </code></pre> <p>Please tell me I've missed the plot and I could write this a lot better. Feel free to critique the rest of the code. Thank you!</p>
[ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-10-27T00:22:29.250", "Id": "8484", "Score": "0", "body": "Keep in mind that console.log does not exist in some versions of IE when not running the IE debugger. So, you should not ever be accessing console.log in your regular production code." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-10-27T07:37:12.090", "Id": "8492", "Score": "0", "body": "It's for Chromium, only Chromium" } ]
[ { "body": "<p>You could write it as:</p>\n\n<pre><code>function safeLog(s) {\n if (window.console &amp;&amp; window.console.log) {\n console.log(s);\n }\n}\n\nfunction assert(a, b, message) {\n if (a != b) {\n safeLog(\"Failed to match \" + message + \" \" + a + \" != \" + b);\n return false;\n }\n return true;\n}\n\nif (!assert(parsedInput.protocol, cu.protocol, \"protocol\") ||\n !assert(parsedInput.port, cu.port, \"port\") ||\n !assert(parsedInput.hostname, cu.hostname, \"hostname\") ||\n !assert(parsedInput.hash, cu.hash, \"hash\")) {\n continue;\n}\n</code></pre>\n\n<p>This would condense the comparisons into one logic statement and would protect from the cases in IE where console.log doesn't exist.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-10-27T09:15:49.900", "Id": "8498", "Score": "0", "body": "code is for a Chromium extension. It's safe to assume console.log" } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-10-27T00:27:02.597", "Id": "5611", "ParentId": "5605", "Score": "2" } }, { "body": "<p>I (and many other people) expect certain behavior from a function called \"assert\"...namely that it throws an exception or otherwise halts execution if the asserted condition isn't true. If your assert function did that, you wouldn't have to test the return value.</p>\n\n<pre><code>function assertEqual(a, b, message)\n{\n if (a != b) throw new Error(message + \" mismatch: \" + a + \" != \" + b);\n}\n\nassertEqual(parsedInput.protocol, cu.protocol, \"protocol\");\nassertEqual(parsedInput.port, cu.port, \"port\");\nassertEqual(parsedInput.hostname, cu.hostname, \"hostname\");\nassertEqual(parsedInput.hash, cu.hash, \"hash\");\n</code></pre>\n\n<p>If that's not what you want, then you should seriously consider renaming your function. Maybe <code>check</code> or something, i dunno. Assertions die when they're false.</p>\n\n<hr>\n\n<p>Now, as for your equality tests, you could do something like</p>\n\n<pre><code>function propsEqual(obj1, obj2, propNames) {\n var result = true;\n for (var i = 0; i &lt; propNames.length; ++i) {\n var prop = propNames[i];\n if (obj1[prop] != obj2[prop]) {\n console.log(\"Failed to match \" + prop +\": \" + obj1[prop] + \" != \" + obj2[prop]);\n result = false;\n }\n }\n return result;\n}\n\nif (!propsEqual(parsedInput, cu, [\"protocol\", \"port\", \"hostname\", \"hash\"])) {\n console.log(\"Skipping.\");\n continue;\n}\n</code></pre>\n\n<p>Benefits of this approach being, you get to see all of what doesn't match, rather than stopping at the first thing.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-10-27T09:15:07.700", "Id": "8497", "Score": "0", "body": "Halting execution is not what I want (or anyone else for that matter IMO), I want to continue through to the next loop." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-10-27T09:32:38.420", "Id": "8499", "Score": "3", "body": "Then for other people's sake, rename your function. The name `assert` carries with it some expectations, and what you want apparently doesn't fit with those expectations at all. See http://en.wikipedia.org/wiki/Assertion_(computing) ." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-01-13T16:53:11.553", "Id": "65536", "Score": "0", "body": "`assert` does not mean necessary halting the program. It could also mean just logging the error. By the way this is the default behavior in PHP. A good assert function would allow for configuration and do different things in debug mode (die displaying a backtrace) and in a published application (silently log or send feedback to the server)." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-01-13T20:23:04.663", "Id": "65580", "Score": "0", "body": "@LorenzMeyer: PHP's default behavior is rather broken, IMO, and should not be used or emulated. Fortunately, PHP does let you configure assertions to act as they do in nearly every other environment that supports them. I wish an error or exception were the default behavior, and one had to go out of one's way to misuse them as input validation and other such post-release stuff." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-01-14T05:52:34.780", "Id": "65626", "Score": "0", "body": "@chao I agree, an assertion by it's nature is never intended for validation. A failed assertion means a real bug. It deserves a program to halt. \nBut this can be too a too strong reaction. If you debug or test, this is what you want : a plain crash with a stacktrace. Now, disabling assertions for delivery assumes that you tested your app 100% and that you can put your hand in the fire that there's no bug remaining." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-01-14T05:59:36.687", "Id": "65627", "Score": "0", "body": "@chao To be honest, I would never be 100% sure, because I write too complex programs to test every possible case. Also I rely on buggy external systems ( like Windows :) ). I therefore want to keep assertions in delivered code, but instread of halting the program, I want to log the bug for me. This is even more important in javascript, where I normally don't get informed about an error. An assertion gives me the chance to know that my app crashes in IE 5.5 on Mac and in Opera mobile 13.2 on iOS 6. It could allow me to log via ajax just before it crashes." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-01-14T06:09:45.283", "Id": "65630", "Score": "0", "body": "@LorenzMeyer: Disabling assertions in production simply means that you're using assertions for what they're made for. :) It is a very common practice, for the same reason we don't ship debug versions of compiled code: comprehensive sanity testing is often not cheap. With PHP, for example, `assert` basically means an `eval` each time, if assertions are enabled -- and little more than a function call if they're not. For testing things that should have been caught well before release." } ], "meta_data": { "CommentCount": "7", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-10-27T01:19:25.533", "Id": "5613", "ParentId": "5605", "Score": "8" } } ]
{ "AcceptedAnswerId": "5613", "CommentCount": "2", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-10-26T22:16:57.520", "Id": "5605", "Score": "3", "Tags": [ "javascript" ], "Title": "Javascript assert function" }
5605
<p>I'm attempting to implement a calculator-like application in C#. But the way I've currently implemented it seems a little messy and inefficient. It works, but it's just I'm pretty sure it can be achieved in a more elegant solution.</p> <p>I looked to see if I could factor out any repeating code, such as the switch statement - but without having numerous parameters in the method, I don't think it'll make things much better.</p> <p>Here's the main portion of the code:</p> <pre><code>private double Calculate() { double answer = 0.0; foreach (double number in this.numbers) { int index = this.numbers.IndexOf(number); if (index != this.numbers.Count() - 1) { if (answer != 0.0) { switch ((int)operators[index]) { case (int)Operator.Plus: answer = (double)(answer + numbers[index + 1]); break; case (int)Operator.Minus: answer = (double)answer - numbers[index + 1]; break; case (int)Operator.Divide: answer = (double)answer / numbers[index + 1]; break; case (int)Operator.Multiply: answer = (double)answer * numbers[index + 1]; break; } } else { switch ((int)operators[index]) { case (int)Operator.Plus: answer += (double)(number + numbers[index + 1]); break; case (int)Operator.Minus: answer += (double)number - numbers[index + 1]; break; case (int)Operator.Divide: answer += (double)number / numbers[index + 1]; break; case (int)Operator.Multiply: answer += (double)number * numbers[index + 1]; break; } } } } return answer; } </code></pre> <p>Just for reference, Operators is an ENUM that's defined as:</p> <pre><code>private enum Operator { Plus = 1, Minus = 2, Multiply = 3, Divide = 4, } </code></pre> <p>and the two lists:</p> <pre><code>private List&lt;double&gt; numbers; private List&lt;Operator&gt; operators; </code></pre> <p>Any ideas on how I could improve this?</p>
[]
[ { "body": "<p>You should be able to use the conditional operator to get it down to 1 switch statement. I haven't done C# in a long time so I'm not sure if this will compile.</p>\n\n<pre><code>bool answer_zero = (bool)(answer != zero);\nswitch ((int)operators[index])\n{\n case (int)Operator.Plus:\n answer = (double)((answer_zero ? answer : number) + numbers[index + 1]);\n break;\n\n case (int)Operator.Minus:\n answer = (double)((answer_zero ? answer : number) - numbers[index + 1]);\n break;\n\n case (int)Operator.Divide:\n answer = (double)((answer_zero ? answer : number) / numbers[index + 1]);\n break;\n\n case (int)Operator.Multiply:\n answer = (double)((answer_zero ? answer : number) * numbers[index + 1]);\n break;\n}\n</code></pre>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-10-26T23:26:01.407", "Id": "5607", "ParentId": "5606", "Score": "0" } }, { "body": "<p>Well, first of all there is a bug in the code. You are getting the index of a number by looking for it in the list, but if the number occured earlier in the list you will get the wrong index. You should use the index in the loop instead of using a <code>foreach</code>.</p>\n\n<p>You are using the <code>Count()</code> extension method to get the number of items in the list, but you should use the <code>Count</code> property instead.</p>\n\n<p>You are casting all enum values to integers, but you can just use the enum values directly.</p>\n\n<p>You are casting a lot of values to double, but they are already double values.</p>\n\n<p>You are using the value of <code>answer</code> in the code where you have determined that it's always zero.</p>\n\n<p>You are comparing the <code>answer</code> value to zero to determine if it's the first iteration, but that could occur later in the loop too.</p>\n\n<p>Instead of handling the first iteration differently, you can just put the first number in the <code>answer</code> variable and start the loop from 1.</p>\n\n<p>The code suddenly got a lot simpler. :)</p>\n\n<pre><code>private double Calculate() {\n double answer = numbers[0];\n for (int index = 1; index &lt; numbers.Count; index++) {\n switch (operators[index - 1]) {\n case Operator.Plus:\n answer += numbers[index];\n break;\n case Operator.Minus:\n answer -= numbers[index];\n break;\n case Operator.Divide:\n answer /= numbers[index];\n break;\n case Operator.Multiply:\n answer *= numbers[index];\n break;\n }\n }\n return answer;\n}\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-10-26T23:37:57.860", "Id": "8483", "Score": "0", "body": "Wow, that really is an improvement. Thanks for the advice!" } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-10-26T23:29:58.640", "Id": "5608", "ParentId": "5606", "Score": "12" } }, { "body": "<p>Your first big problem is going to be fighting your design. Multiple <code>case</code> statements like that are asking to be removed either due to polymorphism, or stuck deep in the bowls of some sort of AbstractFactory, and only referred to once (sorry, I've just been going the <code>Clean Code</code> book).<br>\nIn this case, making this setup polymorphic is going to be your friend... Otherwise, you're going to have an interesting time later, trying to add, say modulous (<code>%</code>).</p>\n\n<p>To start with, define an <code>Operation</code> interface. Something like this: </p>\n\n<pre><code>public interface Operation {\n public double Operate(double argA, double argB);\n}\n</code></pre>\n\n<p>You then need to implement each operation seperately:</p>\n\n<pre><code>public struct Division : Operation {\n // For obvious reasons, the proper argument names should be specified\n public double Operate(double quotient, double divisor) {\n return quotient / divisor;\n }\n}\n</code></pre>\n\n<p>This will allow you to add any number of future operations quite simply (including some really complicated stuff) - so long as it only takes 2 arguments... (note - I'm attempting to retain the general concept of your design; there are other possibilities here). And replace the <code>List&lt;Operator&gt;</code> with a <code>List&lt;Operation&gt;</code>.</p>\n\n<p>Your calculate method then becomes, simply: </p>\n\n<pre><code>private double Calculate () {\n double answer = 0.0;\n for(int i = 0; i &lt; numbers.Count(), i &lt; operators.Count(), i++) {\n // Of course, this doesn't check for divide-by-zero...\n answer = operators[i].Operate(answer, numbers[i]); \n }\n return answer;\n }\n</code></pre>\n\n<p>Your current method had the following issues - </p>\n\n<ol>\n<li>Listing multiple copies of the same number, but with different operations, would re-use only <em>one</em> of the operations (probably the first in the list).</li>\n<li>You aren't sufficiently checking for array out-of-bounds errors - if <code>numbers</code> is longer than <code>operators</code>, you'll run out of operators (it's debatable if ignoring numbers on the end is better, as I do...).</li>\n<li>Your <code>if (answer == 0.0)</code> statement really encapsulates the <em>exact</em> same logic. You just need to look at it a little different.</li>\n</ol>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-10-26T23:57:26.577", "Id": "5610", "ParentId": "5606", "Score": "7" } }, { "body": "<p>X-Zero has some good suggestions. Depending on the intended complexity of your program, creating a polymorphic design as X-Zero suggested is definitely a good way to go - and it makes future code much easier. I would just add a few comments on those code suggestions, though:</p>\n<ul>\n<li><p>Especially if this code may be used as some form of public API, it may be a good idea to name the interface and implementations correctly. For example, <code>Operation</code> is an interface, so following standard naming conventions it should be changed to <code>IOperation</code>. Similarly, it might be worth naming the implementations as <code>SomethingOperation</code>. For example; <code>Division</code> would become <code>DivisionOperation</code>. This is not 100% necessary, but makes it easier to identify what the class is an implementation of, without looking into the code.</p>\n</li>\n<li><p>One other point I would make, is that in the <code>for</code> loop, the first operation is executed using the default initial value of zero. If that first operation is a multiplication, this method will result in erroneous results. To resolve this, I would refer to the answer given by Guffa:</p>\n<blockquote>\n<p>You are comparing the answer value to zero to determine if it's the first iteration, but that could occur later in the loop too.</p>\n<p>Instead of handling the first iteration differently, you can just put the first number in the answer variable and start the loop from 1.</p>\n</blockquote>\n</li>\n</ul>\n<p>Note: The point made on the initial value of zero was referring to the answer given by X-Zero, not the code in the question.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-10-27T08:33:35.403", "Id": "8496", "Score": "0", "body": "Eventhough the initial value is zero, it's not used as one of the operands for the first operator, instead the code does `answer + numbers[0] * numbers[1]`, so the result would still be correct." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-10-28T07:07:59.297", "Id": "8525", "Score": "0", "body": "Are you referring to your own answer, or the one given by X-Zero?" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-10-28T07:35:37.967", "Id": "8527", "Score": "0", "body": "Neither. I am referring to the original code, as I am commenting on your point that having an initial value of zero gives an erroneous result if the first operation is a multiplication." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-10-28T08:47:47.737", "Id": "8535", "Score": "0", "body": "I was referring to the answer given by X-Zero, not the question. I have modified my answer to note this." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-10-28T09:12:38.470", "Id": "8537", "Score": "0", "body": "Ok, then it makes a valid point. I'm sorry that I misunderstood you." } ], "meta_data": { "CommentCount": "5", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-10-27T07:21:59.453", "Id": "5619", "ParentId": "5606", "Score": "1" } }, { "body": "<p>How do people feel about replacing enums with classes and moving the logic into Funcs?</p>\n\n<pre><code>public class Operation&lt;T&gt;\n{\n public string Name { get; set; }\n public Func&lt;T, T, T&gt; Calculation { get; set; }\n}\n\nprivate List&lt;double&gt; numbers;\nprivate List&lt;Operation&lt;double&gt;&gt; operations = new List&lt;Operation&lt;double&gt;&gt;\n{\n new Operation&lt;double&gt; {Name = \"Add\", Calculation = (x,y) =&gt; x + y},\n new Operation&lt;double&gt; {Name = \"Subtract\", Calculation = (x,y) =&gt; x - y},\n new Operation&lt;double&gt; {Name = \"Multiply\", Calculation = (x,y) =&gt; x * y},\n new Operation&lt;double&gt; {Name = \"Divide\", Calculation = (x,y) =&gt; x / y}\n\n //,... Add new ones as you like here\n};\n\npublic double Calculate&lt;T&gt;()\n{\n var answers = numbers[0];\n for (int index = 0; index &lt; operations.Count; index++)\n {\n var operation = operations[index];\n operation.Calculation(answers, numbers[index]);\n }\n\n return answers;\n}\n</code></pre>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-11-04T20:22:10.857", "Id": "5811", "ParentId": "5606", "Score": "1" } } ]
{ "AcceptedAnswerId": "5610", "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-10-26T22:58:20.307", "Id": "5606", "Score": "7", "Tags": [ "c#", "calculator" ], "Title": "Calculator-like application" }
5606
<p>I've always wanted to come up with my own algorithm for encryption. Last evening I started writing "TreeShell" encryption algorithm that uses bit shifting and XOR operations on the bit level to do encryption. </p> <p>This algorithm allows arbitrary length of data and protection key. The key is not stored, but hashed together with the random IV. The random IV is generated from TreeShell's own PRNG, which is shown below.</p> <p>The length of the final ciphertext is not affected by the length of the key provided, but is the fixed-length IV prepended to the encrypted plaintext.</p> <pre><code>&lt;?php class TreeShell{ const BLOCK_SIZE = 16; const BYTES = 4; const KEY_LENGTH = 256; public function encrypt($key, $plain){ $iv = $this-&gt;iv(); $ivs = $this-&gt;ivArrToString($iv); $keyHash = $this-&gt;keyHash($key, $ivs, $iv); $kHL = count($keyHash); $l = strlen($plain); $s = ''; for($i = 0; $i &lt; $l; $i+=4){ $k = $i % ($kHL); $m = $this-&gt;stringToBlock($plain, $i); $j = $m ^ $keyHash[$k]; $s .= $this-&gt;blockToString($j); } return $ivs . $s; } public function decrypt($cipher, $key){ $ivsL = self::BLOCK_SIZE * self::BYTES; $ivs = substr($cipher, 0, $ivsL); $iv = $this-&gt;stringToIVArr($ivs); $keyHash = $this-&gt;keyHash($key, $ivs, $iv); $cipher = substr($cipher, $ivsL); $l = strlen($cipher); $kHL = count($keyHash); $s = ''; for($i = 0; $i &lt; $l; $i+=4){ $k = $i % ($kHL); $m = $this-&gt;stringToBlock($cipher, $i); $j = $m ^ $keyHash[$k]; $s .= $this-&gt;blockToString($j); } return rtrim($s); } private function iv(){ $iv = array(); for($i = 0; $i &lt; self::BLOCK_SIZE; $i++){ $iv[] = $this-&gt;prng(286331153, 4294967295); } return $iv; } private function stringToIVArr($ivs){ $a = unpack('C*', $ivs); $l = count($a); $r = array(); for($i = 1; $i &lt;= $l; $i+=4){ $c = 0; if(array_key_exists($i, $a)){ $c += ($a[$i] &lt;&lt; 24); } if(array_key_exists($i + 1, $a)){ $c += ($a[$i + 1] &lt;&lt; 16); } if(array_key_exists($i + 2, $a)){ $c += ($a[$i + 2] &lt;&lt; 8); } if(array_key_exists($i + 3, $a)){ $c += ($a[$i + 3]); } $c = (($c &amp; 0xFFFF) &lt;&lt; 16) | (($c &gt;&gt; 16) &amp; 0xFFFF); $r[] = $c; } return $r; } private function ivArrToString($iv){ $s = ''; foreach($iv as $a){ $s .= $this-&gt;blockToString($a); } return $s; } private function blockToString($block){ $block = (($block &amp; 0xFFFF) &lt;&lt; 16) | (($block &gt;&gt; 16) &amp; 0xFFFF); $a = array( ($block &gt;&gt; 24) &amp; 0xFF, ($block &gt;&gt; 16) &amp; 0xFF, ($block &gt;&gt; 8) &amp; 0xFF, ($block) &amp; 0xFF ); $s = ''; foreach($a as $v){ $s .= chr($v); } return $s; } private function stringToBlock($s, $i){ $s = substr($s, $i, 4); $c = unpack('C*', $s); while(count($c) &lt; 4){ $c[] = 0; } $block = ($c[1] &lt;&lt; 24) | ($c[2] &lt;&lt; 16) | ($c[3] &lt;&lt; 8) | ($c[4] &lt;&lt; 0); $block = (($block &amp; 0xFFFF) &lt;&lt; 16) | (($block &gt;&gt; 16) &amp; 0xFFFF); return $block; } private function keyHash($key, $ivs, $iv){ $a = array(); $l = strlen($key); $r = array(); $y = $l; $o = $key; while($l &lt; self::KEY_LENGTH){ $key .= $o; $l += $y; } $key .= $ivs; $l += strlen($ivs); for($i = 0; $i &lt; $l; $i+=4){ $k = $i % self::BLOCK_SIZE; $m = $this-&gt;stringToBlock($key, $i); $j = $m ^ $iv[$k]; $r[] = $this-&gt;hash32shift($j); } return $r; } private function bitRotate($value, $bits){ if ($bits &gt;0 ) { $bits %= 32; $value = ($value &lt;&lt; $bits) | ($value &gt;&gt; (32 - $bits)); } elseif ($bits &lt; 0) { $bits = -$bits % 32; $value = ($value &gt;&gt; $bits) | ($value &lt;&lt; (32 - $bits)); } return $value; } private function hash32shift($key){ $c2 = 0x27d4eb23; // a prime or an odd constant $key = ($key ^ 61) ^ $this-&gt;bitRotate($key, 16); $key = $key + ($key &lt;&lt; 3); $key = $key ^ $this-&gt;bitRotate($key, 4); $key = $key * $c2; $key = $key ^ $this-&gt;bitRotate($key, 15); return $key; } private function prng($min = null, $max = null){ static $seed = null; if($seed == null){ if($min &amp;&amp; $max){ $seed = 2.14; }elseif($min){ $seed = 1.24; }elseif($max){ $seed = 0.78; }else{ $seed = 0.65; } $i = ceil(time() % 50 * 5) + 10; while($i --&gt; 0){ $f = (sin(5 * pow($seed, 3)) + cos(10 * pow($seed, 2)) + 2) / 4; if($f &gt; 0.5){ $seed += ceil($f * 96); }else{ $seed -= ceil($f * 32); } } } $f = (sin(2 * pow($seed, 2)) + cos(3 * $seed) + sin(3 * $seed) + cos(2 * $seed) + 4) / 8; if($f &gt; 0.5){ $seed -= ceil($f * 1440); }else{ $seed += ceil($f * 512); } if(func_num_args() == 2){ $f = ($f * ($max - $min)) + $min; if(is_int($min) &amp;&amp; is_int($max)){ $f = (int)ceil($f); } } return $f; } } </code></pre> <p>I've tested the randomness of the PRNG as well as the data integrity of the ciphertext generated (by encrypting then decrypting a sample message using the same key). They look good to me. </p> <p>How can I determine if this algorithm can be cracked within a reasonable time? </p> <blockquote> <p>Note: <s>The current problem with this algorithm is that given a plaintext is encrypted with a key "abc", and decrypted with the key "bcd", some of the plain text is decrypted. I am working to fix that. If you were writing the algorithm, what will you change in this algorithm to fix that problem?</s><br> The hash function has been fixed to make it to have more avalanche effect. Previously the avalanche effect was hardly seen, as such a similar passphrase used will reveal the encrypted plaintext partially.</p> </blockquote>
[ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-10-27T17:06:34.113", "Id": "8511", "Score": "3", "body": "Just a note - Code Review can review your implementation of the algorithm, but as Chris Jester-Young says, we aren't cryptography experts. If you would like to discuss specifics of your crypto scheme, you might try [Crypto.SE]. They won't be able to review your whole scheme, but they can help you with techniques for testing, common holes people miss, and other items that can help prove your ideas." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-10-28T01:55:58.563", "Id": "8521", "Score": "0", "body": "Hi Michael. Understood that. Thanks a lot! :D" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-11-10T03:40:10.350", "Id": "56828", "Score": "0", "body": "Eek! First rule of encryption: Do not use your own algorithms in production! First rule of random number generators: Do not use your own algorithms in production! Encryption researchers can break these rules only after publication and extensive peer review. At least use a published, time tested, open source, peer reviewed algorithm! I mean, if this is just for fun, then get as crazy as you like!" } ]
[ { "body": "<p>First, an important disclaimer: <strong>I am not a crypto expert (IANACE).</strong> Because of this, I will not be reviewing your code in specific. I also encourage you to only trust reviews from crypto experts.</p>\n\n<p>As I understand it, the most important thing to decide if your algorithm is strong is to learn about existing techniques for breaking algorithms, then apply those techniques against your own algorithm. Your algorithm must be able to withstand all existing known techniques.</p>\n\n<p>Most homegrown ciphers are easily breakable, because they fail to consider techniques used by seasoned cryptographers. For example, there are many types of known-plaintext attacks, known-ciphertext attacks, and so on. (Many of them are catalogued in Bruce Schneier's excellent <em>Applied Cryptography</em> book.) You need know how to apply them all.</p>\n\n<p>Another class of attacks to consider are side-channel attacks, and in particular timing oracle attacks. Does your function take longer or shorter if the key is invalid? This gives your attacker valuable information, and in the worst case allows them to reconstruct the correct key.</p>\n\n<p>I also can't comment on the strength of your PRNG, but consider where your sources of entropy are, and whether an attacker can manipulate those to achieve less-than-random output.</p>\n\n<p>As for your KDF (key derivation function), consider whether well-chosen ASCII passphrases (the most common case) give good coverage of the possible keyspace. You want good coverage, so that key distribution isn't skewed for the commonest class of passphrases---that would give an attacker valuable information. Also consider whether similar passphrases give rise to similar keys. They should not. Small changes to a passphrase should result in huge changes to the key, so that the passphrase isn't so easy to derive from a working key.</p>\n\n<p>There are other things to consider also, but again, I'm not a crypto expert. But I hope this will get you started. :-)</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-10-27T03:07:10.897", "Id": "5615", "ParentId": "5614", "Score": "1" } }, { "body": "<blockquote>\n <p>They look good to me. </p>\n</blockquote>\n\n<p>Sure, you are human. But what “looks” random to humans doesn't always have to be random. Have you done any tests like the <a href=\"http://www.phy.duke.edu/~rgb/General/dieharder.php\" rel=\"nofollow\">DieHarder suite</a> (provided by Robert Brown of Duke University) to check on the true randomness of you PRNG implementation? You definitely should check for entropy etc. before even thinking your prng is really as random as it seems to be! There are also smaller tools like <a href=\"http://www.fourmilab.ch/random/\" rel=\"nofollow\">fourmilab's ENT</a>, but since you are targetting cryptography, I would go for the <a href=\"http://www.phy.duke.edu/~rgb/General/dieharder.php\" rel=\"nofollow\">DieHarder suite</a> as it covers more tests. </p>\n\n<p>Also…</p>\n\n<p>Your algorithm uses a pseudo-random number generator - which tends to be cryptographically insecure because it is not truly random. Instead a PRNG's output walks along the fixed sequence the PRNG produces. In a worst-case scenario, an attacker would only need to recover a few bits of your prng to recover the whole state of that PRNG … which would be a so-called <em>\"State recovery attack\"</em>.</p>\n\n<hr>\n\n<p>Btw.: Please feel invited to drop by at <a href=\"http://crypto.stackexchange.com\">Crypto.SE</a> and ask some questions if you need more indeep information related to cryptography, cryptographic, and or potential crypto-related security issues.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-11-10T00:07:01.817", "Id": "35108", "ParentId": "5614", "Score": "0" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "3", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-10-27T02:14:34.280", "Id": "5614", "Score": "3", "Tags": [ "php", "algorithm", "cryptography" ], "Title": "TreeShell PRNG and Encryption Algorithm Review" }
5614
<p>I try to replace multiple occurrences of a character with a single character.</p> <p>Input:</p> <blockquote> <p>hhiii!!! hooowww aaareee yyyooou???</p> </blockquote> <p>Output:</p> <blockquote> <p>hi! how are you?</p> </blockquote> <pre><code>public class CharSingleOccurrence { public static void main(String... args){ charSingleOccurrence("hhiii!!! hooowww aaareee yyyooou???"); } public static void charSingleOccurrence(String str){ int i=0; int j=0; char arr[]=new char[50]; while (i&lt;str.length()-1) { if(str.charAt(i)!=str.charAt(i+1)){ arr[j]=str.charAt(i); i++; j++; }else{ i++; } } arr[j]=str.charAt(str.length()-1); for(char c:arr){ System.out.print(c); } } } </code></pre> <p>Here I need review for</p> <ul> <li><code>char arr[]=new char[50];</code></li> <li><code>arr[j]=str.charAt(str.length()-1);</code></li> </ul>
[]
[ { "body": "<p>Maybe I am wrong but I prefers to use the <code>regex</code> for this kind of text manipulation.\nHere is my code, </p>\n\n<pre><code>System.out.println(\"hhiii!!! hooowww aaareee yyyooou???\"\n .replaceAll(\"(.)\\\\1+\",\"$1\"));\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-10-27T07:37:30.920", "Id": "8493", "Score": "0", "body": ":No, you are not wrong but I don't have to do like that.... \nI'd to make my own logic for `regex` or something like that." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-10-27T07:49:14.913", "Id": "8494", "Score": "0", "body": "Agreed always use tools that are there. But it regex is always worth an extra line of comments." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-10-27T10:36:32.190", "Id": "8502", "Score": "4", "body": "regex is definitely the most graceful solution" } ], "meta_data": { "CommentCount": "3", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-10-27T07:31:18.757", "Id": "5620", "ParentId": "5618", "Score": "11" } }, { "body": "<p>I think this is oddly complicated...though, I'm 99% sure this can be done with a single line of RegEx, I don't know how from the top of my head<sup>1</sup>.</p>\n\n<p>This can be shortened to a much simpler and shorter solution, without the need of arrays at all.</p>\n\n<pre><code>String input = \"hhiii!!! hooowww aaareee yyyooou???\";\nStringBuilder output = new StringBuilder();\n\n// Append the first character of the string.\n// We can also let the loop start at 0, but then\n// we'd need an additional if inside the loop, which\n// I'd like to avoid.\noutput.append(input.charAt(0));\n\n// Start the loop at 1, because we already have the first character.\n// We can not \nfor (int idx = 1; idx &lt; input.length(); idx++) {\n // Check the current against the previous character.\n if(input.charAt(idx) != input.charAt(idx-1)) {\n // If it is not the same, append it.\n output.append(input.charAt(idx));\n }\n }\n</code></pre>\n\n<p>Of course you'd need to protect yourself from invalid input (empty or null String), and it will also break words with allowed double-characters: <code>foobar, tool, support etc.</code>.</p>\n\n<p>Some further comments on your code:</p>\n\n<ul>\n<li><strong>Function name:</strong> It's not directly visible what the function does. It should be called something along the lines of <code>removeDoubleChars</code> or <code>removeMultipleCharacters</code>.</li>\n<li><strong>Function type:</strong> The function shouldn't directly output the result to <code>System.out</code> but rather return it.</li>\n<li><strong>Loops:</strong> Use appropriate loops, f.e. your <code>while</code> should be a <code>for</code>.</li>\n<li><strong>Variable names:</strong> I know it's partly taught, but I get the creeps (or become a Creeper) if I see variables which are named <code>i</code>, <code>j</code> or <code>arr</code>. Give your variables meaningful names! In any modern language the name of the variable is neither limited nor does it matter for performance. Write your code primarily for humans, and only secondary for machines...the coder which has to maintain your code after you will thank you.</li>\n<li><strong>Whitespaces:</strong> Use 'em! <code>if(str.charAt(i)!=str.charAt(i+1)){\n</code> is harder to read then <code>if(str.charAt(i) != str.charAt(i + 1)) {</code>.</li>\n<li><strong>Code duplication:</strong> Avoid duplicate code. In this case it's minor, but the <code>i++</code> should be moved outside the <code>if</code>, so that it's not necessary to have an <code>else</code> part.</li>\n</ul>\n\n<p><sup>1</sup>: <a href=\"https://codereview.stackexchange.com/a/5620/2612\">But John does</a>.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-10-28T12:55:48.347", "Id": "8552", "Score": "0", "body": "I'm sorry but the logic I'd to implement is in the same way I wrote my code, but the thing I need is that what can I do with `char arr[]=new char[50];` so that I don't have to predefine the size of array(`char[50]`);" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-10-28T12:58:07.203", "Id": "8553", "Score": "1", "body": "@MohammadFaisal: Use a `List`." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-03-21T05:52:02.353", "Id": "78246", "Score": "0", "body": "The output you get will not be a meaningful word if a word \"happpy\" is given, as it allows two p's in it. But when executed, your code removes all the duplicate characters, so the output will be \"hapy,\" which is not a dictionary word." } ], "meta_data": { "CommentCount": "3", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-10-27T07:37:22.433", "Id": "5621", "ParentId": "5618", "Score": "11" } }, { "body": "<p>A <code>StringBuilder</code> is good for building strings. I suggest that you keep track of the last character that you put in the builder to avoid the repeated characters.</p>\n\n<p>This is C# code, but I think that it should translate to Java easily enough:</p>\n\n<pre><code>public static string CharSingleOccurance(string value) {\n StringBuilder result = new StringBuilder();\n char? last = null;\n foreach (char c in value) {\n if (!last.HasValue || c != last.Value) {\n result.Append(c);\n last = c;\n }\n }\n return result.ToString();\n}\n</code></pre>\n\n<h3>Edit:</h3>\n\n<p>Here is Bobbys suggestion for a Java translation:</p>\n\n<pre><code>public static String charSingleOccurance(String value) {\n StringBuilder result = new StringBuilder();\n char last = '\\u0000';\n\n for (char c : value.toCharArray()) {\n if (last == '\\u0000' || c != last) {\n result.append(c);\n last = c;\n }\n } \n\n return result.toString();\n}\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-10-27T15:35:12.607", "Id": "8507", "Score": "0", "body": "Variable `last` should be `boolean`." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-10-27T16:10:55.013", "Id": "8508", "Score": "0", "body": "@palacsint: It is. The nullable char contains both a char value and a boolean that determines if it's null or not." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-10-27T19:49:06.363", "Id": "8514", "Score": "0", "body": "@palacsint: Why? It's the last appended character, it can't be `boolean`." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-10-27T20:24:46.053", "Id": "8516", "Score": "0", "body": "Sorry guys, you're right. It have to be `char`, I've overlooked the spec/question." } ], "meta_data": { "CommentCount": "4", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-10-27T07:45:47.957", "Id": "5623", "ParentId": "5618", "Score": "7" } } ]
{ "AcceptedAnswerId": "5621", "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-10-27T07:20:24.653", "Id": "5618", "Score": "8", "Tags": [ "java", "strings", "homework" ], "Title": "Replace multiple occurrences of a character" }
5618
<p>I'm running the below script on a WordPress powered site. It's very heavy on the animations and uses AJAX to fetch posts and load them into a <code>div</code>.</p> <p><strong>Three things I wanted to address:</strong></p> <ol> <li><p>Cleaning up the code so that it runs faster/better</p></li> <li><p>Sometimes the AJAX request doesn't get the next post and either keeps showing the same post, or briefly shows the next post then disappears</p></li> <li><p>The animation <code>bubbles()</code> animates in some divs from off screen, and is closed with the <code>closeAggregator()</code> function. Sometimes the <code>closeAggregator()</code> function doesn't trigger the animations to slide the <code>div</code>s out of view, and instead just fades out. Which is problematic because the next time the <code>bubbles()</code> function is triggered, the divs are already in view, thus: no pretty animation.</p></li> </ol> <p>I imagine a lot of this is due to the lack of cleanliness/organization in the script. Just hoping someone can help clean this bit up!</p> <pre><code>//resize feeling font-size if word count is too high function resizeFeeling(){ var $quote = $(".feeling"); var $numWords = $quote.text().split(" ").length; if (($numWords &gt;= 12) &amp;&amp; ($numWords &lt; 40)) { $quote.find('h1').css({ 'font-size' : '46px', 'line-height' : '48px' }); $quote.find('h2').css({ 'font-size' : '40px', 'line-height' : '50px' }); } }; //binding for key navigation var pressedKeys = {}; var wtf = { 'keydown': function (e) { if (pressedKeys[e.which]) return; pressedKeys[e.which] = true; var keyCode = e.keyCode || e.which, key = {left: 37, right: 39, random: 83}; switch (keyCode) { case key.left: if ($('#post-nav .post-next a').length != 0) { $('#keys .left-arrow').toggleClass('pressed'); $('#post-nav .post-next a').click(); } else { //if reach the beginning $('#keys .left-arrow').toggleClass('pressed'); $('.boots').jrumble({rangeX: 5,rangeY: 0, rangeRot: 0, rumbleEvent: 'custom'});$('.boots').trigger('start_rumble'); } break; case key.right: if ($('#post-nav .post-previous a').length != 0) { $('#keys .right-arrow').toggleClass('pressed'); $('#post-nav .post-previous a').click(); } else { //if reach the end $('#keys .right-arrow').toggleClass('pressed'); $('.boots').jrumble({rangeX: 5,rangeY: 0, rangeRot: 0, rumbleEvent: 'custom'});$('.boots').trigger('start_rumble'); } break; //load a random feeling by pressing the 's' key (ie. shuffle) case key.random: $('#keys .shuffle').toggleClass('pressed'); randomizeFeelings(); break; } }, 'keyup': function (e) { delete pressedKeys[e.which]; var keyCode = e.keyCode || e.which, key = {left: 37, right: 39, random: 83 }; switch (keyCode) { case key.left: $('#keys .left-arrow').toggleClass('pressed'); $('.boots').trigger('stop_rumble'); break; case key.right: $('#keys .right-arrow').toggleClass('pressed'); $('.boots').trigger('stop_rumble'); break; case key.random: $('#keys .shuffle').toggleClass('pressed'); break; } } }; //load up the welcome modal with the appropriate welcome message function welcome() { //Get the time of day var currentTime = new Date().getHours(); //late if (0 &lt;= currentTime&amp;&amp;currentTime &lt; 5) { $('#heavyBoots h2').append("Hello my restless insomniac,"); } //morning if (5 &lt;= currentTime&amp;&amp;currentTime &lt; 12) { $('#heavyBoots h2').append("Yawnnnn; good morning baby,"); } //afternoon if (12 &lt;= currentTime&amp;&amp;currentTime &lt; 16) { $('#heavyBoots h2').append("Whatcha doin' dear?,"); } //evening if (16 &lt;= currentTime&amp;&amp;currentTime &lt; 22) { $('#heavyBoots h2').append("Hello there,"); } //late if (23 &lt;= currentTime&amp;&amp;currentTime &lt;= 24) { $('#heavyBoots h2').append("Hey, isn't it your bedtime?"); } //Get the Day var day=new Date().getDay(); switch (day) { case 0: //Sunday $('#heavyBoots p').append("It's a lazy Sunday."); break; case 1: //Monday $('#heavyBoots h2').html("Fuck Mondays."); break; case 5: //Friday $('#heavyBoots p').append("Also, it's Friday!"); break; default: //Any other day $('#heavyBoots h2').append(""); } //fade-in the background &amp; then the welcome modal $('#home-bg').fadeIn(500, function(){ $('#heavyBoots').animate({ bottom: '50%' }, 500, 'easeInOutQuint'); }); //click to hide the welcome modal and load the first post (resize text if needed) $('#heavyBoots a').live('click', function(){ $(this).parent().parent().animate({ bottom: '-150%' }, 500, 'easeInOutQuint', function(){ $('#home-bg').fadeOut(200); }); resizeFeeling(); $('#content').delay(1500).fadeIn(600); $('.heavy h1').delay(1500).animate({ left: '0%' },200, 'easeOutSine'); $('.heavy h2').delay(1500).animate({ right: '0%' },200, 'easeOutSine', function() { // fade-in bg if there $('#custom-bg').fadeIn(500); }); //slide-down date setTimeout(function() { $('#logo').delay(1000).animate({ top: '20px'}, 300, 'easeInOutElastic', function(){ $('.heavy h3 span').animate({ top: '0px' },200, 'easeOutSine', function() { // Animation complete. $('#keys').animate({bottom: '20px'},300, 'easeInOutElastic'); }); }); }, 1000); //call first post, activate feelings &amp; bind keys $(document).bind(wtf); cycleFeelings(); }); }; function relationshipAggregator() { //Remove current feeling from the view &amp; slide out the keyboard legend $('.heavy h1').animate({ left: '-150%' },200, 'easeInBack'); $('.heavy h2').animate({ right: '-150%' },200, 'easeInBack'); $('#custom-bg').fadeOut(100); $('#content').fadeOut(600, function(){ $('.heavy h3 span').animate({top: '-40px'}); }); $('#keys').animate({bottom: '-55px'},300, 'easeInOutElastic'); //remove key binding to prevent user from accidentally changing the current feeling bubbles(); $(document).unbind(wtf); //close the aggregator, bring back the feeling &amp; rebind the keys }; function closeAggregator() { $('#aggregator-close').animate({ top: '-100px' }, 500, 'easeInOutElastic', function() { $('#bubble1').animate({ left: '-150%' }, 1000, 'easeOutBack'); $('#bubble2').animate({ top: '-150%' }, 1000, 'easeOutBack'); $('#bubble3').animate({ bottom: '-150%' }, 1000, 'easeOutBack'); $('#bubble4').animate({ bottom: '-150%' }, 1000, 'easeOutBack'); $('#bubble5').animate({ right: '-150%' }, 1000, 'easeOutBack'); $('#bubble6').animate({ top: '-150%' }, 1000, 'easeOutBack'); $('#reddit').animate({ bottom: '-150%' }, 1000, 'easeOutBack'); }); setTimeout( function() { $('#aggregator').fadeOut(200); $('.heavy h1').animate({ left: '0%' },200, 'easeInBack'); $('.heavy h2').animate({ right: '0%' },200, 'easeInBack'); $('#custom-bg').fadeIn(100); $('#content').fadeIn(600, function(){ $('.heavy h3 span').animate({top: '0px'}); }); $('#keys').animate({bottom: '20px'},300, 'easeInOutElastic'); }, 800); $(document).bind(wtf); }; //NUMBERS &amp; STUFF function relationshipCount() { var visitTime = $('#visit_time').val(); var relationshipTime = $('#relationship_time').val(); var nextDate = new Date(visitTime+':00:00'); var totalTime = new Date(relationshipTime); $("#visit").countdown({ date: nextDate, //Counting down to a date offset: 1, hoursOnly: true, onChange: function(e,settings) { }, onComplete: function( event ) { $(this).html('Right now'); }, leadingZero: true }); $("#relationship").countdown({ date: totalTime, //Counting up to a date offset: 1, htmlTemplate: "%{o} %{d}", hoursOnly: false, onChange: function(e,settings) { }, onComplete: function( event ) { $(this).html('this should never complete'); }, leadingZero: true, direction: 'up' }); }; function bubbles(){ $('#aggregator').fadeIn(200); comicScroll(); $('#bubble1').animate({ left: '50%' }, 1000, 'easeInBack'); $('#bubble2').animate({ top: '50%' }, 1000, 'easeInBack'); $('#bubble3').animate({ bottom: '50%' }, 1000, 'easeInBack'); $('#bubble4').animate({ bottom: '50%' }, 1000, 'easeInBack'); $('#bubble5').animate({ right: '50%' }, 1000, 'easeInBack'); $('#bubble6').animate({ top: '50%' }, 1000, 'easeInBack', function() { $('#aggregator-close').animate({ top: '70px' }, 500, 'easeInOutElastic'); }); $('#reddit').animate({ bottom: '50%' }, 1000, 'easeInBack'); relationshipCount(); }; //the feeling is requested and loaded via AJAX function cycleFeelings() { //grab the next post link and replace default action with ajax load $('#post-nav a').stop().live('click', function(e){ e.preventDefault(); //remove the current feeling from the view $('.heavy h1').animate({ left: '-150%' },200, 'easeInBack'); $('.heavy h2').animate({ right: '-150%' },200, 'easeInBack'); var link = $(this).attr('href'); $('#custom-bg').fadeOut(100); $('#content').fadeOut(600, loadContent); //bring in the loading modal $('#load').remove(); $('body').append('&lt;div id="load"&gt;&lt;span&gt;&lt;h4&gt;Loading&lt;/h4&gt;&lt;h5&gt;feelings...&lt;/h5&gt;&lt;/span&gt;&lt;/div&gt;').fadeIn(100); $('#load').animate({ top: '50%' }, 500, 'easeInOutElastic').fadeIn(400); //load up the feeling div with the new feeling content function loadContent() { $('#content').load(link+' .heavy','',showNewContent()) } //animate in the newly loaded feeling function showNewContent() { setTimeout(function() {$('#content').fadeIn(600,hideLoader()); resizeFeeling(); $('.heavy h1').animate({ left: '0%' },200, 'easeOutSine'); $('.heavy h2').animate({ right: '0%' },200, 'easeOutSine', function() { // fade-in bg if there $('#custom-bg').fadeIn(500); //slide-down date setTimeout(function() { $('.heavy h3 span').animate({ top: '0px' },200, 'easeOutSine'); }, 500); }); }, 1000); } //function to hide the loading modal function hideLoader() { $('#load').animate({ top: '-150%' }, 200, 'easeInBack').fadeOut(200); } return false; }).stop(); }; //random feeling is requested and loaded via AJAX //TODO: merge with cycleFeelings() to remove redundancy in ajax request function function randomizeFeelings(){ //remove the current feeling from the view $('.heavy h1').animate({ left: '-150%' },200, 'easeInBack'); $('.heavy h2').animate({ right: '-150%' },200, 'easeInBack'); var toLoad = "/random-feeling/?cachebuster=" + Math.floor(Math.random()*10001); $('#custom-bg').fadeOut(100); $('#content').fadeOut(600, loadContent); //bring in the loading modal $('#load').remove(); $('body').append('&lt;div id="load"&gt;&lt;span&gt;&lt;h4&gt;Loading&lt;/h4&gt;&lt;h5&gt;feelings...&lt;/h5&gt;&lt;/span&gt;&lt;/div&gt;').fadeIn(100); $('#load').animate({ top: '50%' }, 500, 'easeInOutElastic').fadeIn(400); //load up the random feeling div with the new feeling content function loadContent() { $('#content').load(toLoad,'',showNewContent()) } //animate in the newly loaded random feeling function showNewContent() { setTimeout(function() {$('#content').fadeIn(600,hideLoader()); resizeFeeling(); $('.heavy h1').animate({ left: '0%' },200, 'easeOutSine'); $('.heavy h2').animate({ right: '0%' },200, 'easeOutSine', function() { // Animation complete. $('#custom-bg').fadeIn(500); //slide-down date setTimeout(function() { $('.heavy h3 span').animate({ top: '0px' },200, 'easeOutSine'); }, 500); }); }, 1000); } //function to hide the loading modal function hideLoader() { $('#load').animate({ top: '-150%' }, 200, 'easeInBack').fadeOut(200); } return false; }; //future option to have a physical button run the random feeling function $('.feelings').click(randomizeFeelings); //bind relationship aggregator to the click of the logo $('#logo a').click(relationshipAggregator); //close the aggregator $('#aggregator-close a').click(closeAggregator); /* -------------------------- RAGE COMIC MODAL -------------------------- TODO: add/remove the div so it doesn't have to be hard-coded in header */ $('#reddit a').click(rageComics); //bringing in the reddit rage comics modal function rageComics() { //unbinding the key nav for the feelings $('#ragebox').fadeIn(200); //binding the new key nav for the comics $(document).bind(wtf2); //initializing the first rage comic from reddit nextRage(); }; function closeRage() { //reset the count so that the first rage comic is loaded on next opening of the reddit modal i = -1; //unbind the key nav for the comics $(document).unbind(wtf2); //fadeout the current rage comic so it's not shown on next opening of the reddit modal $('.rage-wrap').fadeOut(400); //fadout the reddit rage comic modal completely $('#ragebox').fadeOut(200); //rebind the key nav for the feelings } //binding for rage comics key navigation var pressedKeys2 = {}; var wtf2 = { 'keydown': function (e) { if (pressedKeys2[e.which]) return; pressedKeys2[e.which] = true; var keyCode = e.keyCode || e.which, key = {left: 37, right: 39}; switch (keyCode) { case key.left: prevRage(); break; case key.right: nextRage(); break; } }, 'keyup': function (e) { delete pressedKeys2[e.which]; var keyCode = e.keyCode || e.which, key = {left: 37, right: 39}; switch (keyCode) { case key.left: //stuff break; case key.right: //stuff break; } } }; /* -------------------------- REDDIT JSON REQUEST -------------------------- TODO: get the image url even if url is to imgur page */ //set the count var i = -1; //parse the json data function rage(data) { var rageURL = data['data']['children'][i]['data']['url']; //the url var rageTitle = data['data']['children'][i]['data']['title']; //the title of the rage comic //the error variable var rageErr = '&lt;div&gt;&lt;h5&gt;Whoops!&lt;/h5&gt;&lt;h6&gt;'+rageTitle+'&lt;/h6&gt;&lt;a href="'+rageURL+'" target="_blank"&gt;try again in a new tab&lt;/a&gt;&lt;/div&gt;'; //append the image to the modal window $('#comic .rage-wrap').html('&lt;img src="'+rageURL+'" /&gt;'); //if the image loads, fade it in $('img').load(function() { $('.rage-wrap').fadeIn(400); comicScroll(); }); //if the image fails to load, show the error message of the link &amp; title $('img').error(function() { $('#comic').removeClass('comic-loader'); $('.rage-wrap').html(rageErr).fadeIn(400); }); }; //JSON request of the next rage comic function nextRage() { if (i&gt;=-1) { //increase the count by 1 i++; //fadeout the current comic $('.rage-wrap').fadeOut(400); $('#comic').addClass('comic-loader'); $.ajax({ type: "GET", url: "http://www.reddit.com/r/fffffffuuuuuuuuuuuu/.json", dataType: "jsonp", jsonp: "jsonp", cache: true, success: rage //run the data^ }); } }; function prevRage() { if (i&gt;0) { //decrease the count by 1 i--; //fadeout the current comic $('#comic').addClass('comic-loader'); $('.rage-wrap').fadeOut(400); $.ajax({ type: "GET", url: "http://www.reddit.com/r/fffffffuuuuuuuuuuuu/.json", dataType: "jsonp", jsonp: "jsonp", cache: true, success: rage //run the data^ }); } }; //binding the previous rage comic button $('.prev-rage a').click(prevRage); //binding the next rage comic button $('.next-rage a').click(nextRage); //bind closing the modal to the close button $('#closerage').click(closeRage); /* -------------------------- LOGO &amp; LOVE HOVER STATES -------------------------- */ function hoverStates() { //Main Logo $('#logo').hover( function () { $(this).stop().animate({opacity : 1}, 100); }, function () { $(this).stop().animate({opacity : .6}, 100); }); //Love Icon (fill up) $('#love a').hover( function () { $(this).find('span').stop().animate({height:'0'},400, 'easeInSine'); }, function () { $(this).find('span').stop().animate({height:'44px'},400, 'easeOutSine'); }); //Aggregator Close $('#aggregator-close').hover( function () { $(this).stop().animate({opacity : 1}, 100); }, function () { $(this).stop().animate({opacity : .6}, 100); }); }; // usage: log('inside coolFunc', this, arguments); // paulirish.com/2009/log-a-lightweight-wrapper-for-consolelog/ window.log = function(){ log.history = log.history || []; // store logs to an array for reference log.history.push(arguments); if(this.console) { arguments.callee = arguments.callee.caller; var newarr = [].slice.call(arguments); (typeof console.log === 'object' ? log.apply.call(console.log, console, newarr) : console.log.apply(console, newarr)); } }; // make it safe to use console.log always (function(b){function c(){}for(var d="assert,count,debug,dir,dirxml,error,exception,group,groupCollapsed,groupEnd,info,log,timeStamp,profile,profileEnd,time,timeEnd,trace,warn".split(","),a;a=d.pop();){b[a]=b[a]||c}})((function(){try {console.log();return window.console;}catch(err){return window.console={};}})()); (function($) { $.fn.prettynumber = function(options) { var opts = $.extend({}, $.fn.prettynumber.defaults, options); return this.each(function() { $this = $(this); var o = $.meta ? $.extend({}, opts, $this.data()) : opts; var str = $this.html(); $this.html($this.html().toString().replace(new RegExp("(^\\d{"+($this.html().toString().length%3||-1)+"})(?=\\d{3})"),"$1"+o.delimiter).replace(/(\d{3})(?=\d)/g,"$1"+o.delimiter)); }); }; $.fn.prettynumber.defaults = { delimiter : ',' }; })(jQuery); </code></pre>
[ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-12-04T23:47:52.057", "Id": "10170", "Score": "0", "body": "This would be much easier to review if it was broken down into bite-sized chunks. Just put an important part of the code here and link to the rest. Or make multiple questions with different parts of the code in it. Hopefully that will help you get some great answers" } ]
[ { "body": "<p>You should always cache your selectors, even if they're used only once.</p>\n\n<p>For example: <code>var $visit = $(\"#visit\");</code> etc.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-10-27T16:39:34.587", "Id": "8509", "Score": "0", "body": "so for example, just like in the first example, which has:\n\n\n`var $quote = $(\".feeling\");`\n\n\nI should do the same thing inside the rest of my functions?" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-10-27T20:58:06.373", "Id": "8517", "Score": "0", "body": "Yes, for example, with a quick glance I see you're using $(\"#heavyBoots h2\") seven times.\n\nEverytime jQuery has to scan your whole DOM to find that specific selector. If you cache it, that process happens only once.\n\nIt can give a pretty good performance boost, especially in complex/long DOMs." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-11-29T13:24:41.153", "Id": "9906", "Score": "1", "body": "Why must he cache it even if they're used only once?" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-12-05T05:39:31.143", "Id": "10185", "Score": "0", "body": "why prefix it with `$` though? I don't get why people do that.. I imagine it's just an indicator that it's a _jQuery object_. But I'm not sure on that." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-12-05T15:16:54.350", "Id": "10194", "Score": "0", "body": "@mmmshuddup That's pretty much why. It's a convention that works for me." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-12-08T03:21:23.813", "Id": "10304", "Score": "0", "body": "I find that prefixing variables with an `$` confuses me, in that it's harder to spot actual jQuery objects when making a quick scan through the code." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-09-06T16:52:46.970", "Id": "24958", "Score": "0", "body": "This answer is probably the BEST SINGLE PIECE of advice I have found in all of my jQuery use. Heeing this advice will speed up your code in MANY places." } ], "meta_data": { "CommentCount": "7", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-10-27T16:31:04.240", "Id": "5631", "ParentId": "5629", "Score": "2" } }, { "body": "<p>I looked at just the first part of your <code>welcome()</code> function:</p>\n\n<p>Firstly You have multiple <code>$('#heavyBoots p').append(</code> type calls, If you need to change it you will have multiple places to alter. I put the greeting /comment in a variable and <code>+=</code> <em>(for <code>.append()</code>)</em> or <code>=</code> <em>(for <code>.html()</code>)</em>. This is cleaner IMHO. </p>\n\n<p>Also I'd have to ask where you put your else if tool. You had multiple \"if\" statements that can be combined into one else if. This means when it finds one it doesn't have to evaluate any more of them and it has the added benefit of only needing one test.</p>\n\n<p>There was a redundant <code>default:</code> case in your switch which seemed to append nothing (<code>\"\"</code>)to the page.</p>\n\n<pre><code>function welcome() {\n //Get the time of day\n var currentTime = new Date().getHours();\n\n var greeting = \"\";\n var comment = \"\";\n\n if (currentTime &lt; 0) {\n greeting = \"Current Time is Negative. The World doesn't exist yet.\";\n }\n else if (currentTime &lt; 5) {\n //late\n greeting = \"Hello my restless insomniac,\";\n }\n else if (currentTime &lt; 12) {\n //morning\n greeting = \"Yawnnnn; good morning baby,\";\n }\n else if (currentTime &lt; 16) {\n //afternoon\n greeting = \"Whatcha doin' dear?,\";\n }\n else if (currentTime &lt; 22) {\n //evening\n greeting = \"Hello there,\";\n }\n else if (currentTime &lt;= 24) {\n //late\n greeting = \"Hey, isn't it your bedtime?\";\n }\n else\n {\n greeting = \"The World has ended or someone added more hours in the day.\";\n }\n\n\n //Get the Day\n var day = new Date().getDay();\n switch (day) {\n case 0:\n //Sunday\n comment = \"It's a lazy Sunday.\";\n break;\n case 1:\n //Monday\n greeting = \"Fuck Mondays.\";\n break;\n case 5:\n //Friday\n comment = \"Also, it's Friday!\";\n break;\n }\n\n\n $('#heavyBoots p').append(comment);\n $('#heavyBoots h2').append(greeting);\n</code></pre>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-12-05T00:08:45.130", "Id": "6535", "ParentId": "5629", "Score": "1" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "1", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-10-27T15:36:45.387", "Id": "5629", "Score": "0", "Tags": [ "javascript", "jquery", "ajax" ], "Title": "Cleaning up & better AJAX response" }
5629
<p>In <a href="https://metacpan.org/module/Test%3a%3aVersion" rel="nofollow"><code>Test::Version</code></a> I want to add configuration settings that allow one to toggle certain features. I'm thinking about passing an anonymous hash to a custom <code>import</code> like so.</p> <pre><code>use Test::Version 1.2 qw( version_ok ), { is_strict =&gt; '1', has_version =&gt; '0' }; </code></pre> <p>other options I've thought of include package variables (though more ugly in my opinion).</p> <pre><code>use Test::Version 1.2 qw( version_ok ); $Test::Version::IS_STRICT = 1; $Test::Version::HAS_VERSION = 0; </code></pre> <p>or maybe using some other kind of operator to denote config settings on import, though I'm not sure exactly how to implement this.</p> <pre><code>use Test::Version 1.2 qw( version_ok ), +is_strict =&gt; '1', +has_version =&gt; '0'; </code></pre> <p>Keep in mind that this has a simple functional interface, so passing objects, or using config files is overkill. Any preferences? or other suggestions?</p>
[ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-12-16T22:03:11.707", "Id": "10822", "Score": "0", "body": "Check out [Sub::Exporter](http://p3rl.org/Sub::Exporter)." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-12-18T08:00:20.040", "Id": "10858", "Score": "0", "body": "@BradGilbert I found Sub::Exporter to be a bit complicated and powerful for what I'm trying to achieve. Also, I wasn't able to actually discern how I would use it for this purpose." } ]
[ { "body": "<p>I would stay away from changing the normal workings of <code>import()</code>. I've never seen a module mix exporting and configuration at the same time (maybe you have, though), so leave those out (options 1 and 3). I think you are right in thinking that option 2 isn't too pretty. That leaves us with none of those options.</p>\n\n<p>I think instead of this you should just allow calling <code>version_ok</code> and <code>version_all_ok</code> with the options hash.</p>\n\n<pre><code>version_ok({ is_string =&gt; 1, has_version =&gt; 0 });\n</code></pre>\n\n<p>Clear and standard, nothing odd going on. From the way it seems like the module is going to be used this isn't a burden on the user (since there will normally only be one call to this in the entire test suite).</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-10-28T21:27:07.563", "Id": "5673", "ParentId": "5630", "Score": "2" } }, { "body": "<p>Besides passing the options to imported functions as aparker42 mentioned you could simply write a function <code>configure</code> within your package and deal with the options there.</p>\n\n<pre><code>package Test::version ;\n\n#use vars qw($is_string $has_version) ;\n# Instead of multiple configuration variables I personally would\n# bundle them in a hash\n# Filling the hash with defaults ... and it also makes the configure easier\nuse vars qw(%options) ;\n%options = ( is_string =&gt; 0 ,\n has_version =&gt; 1 ) ;\n\nsub configure {\n my ( $opthr ) = @_ ;\n foreach my $key ( keys %{ $opthr } ) {\n if( exists $options{$key} ) {\n # Check if the given variable exists in the %options hash\n $options{$key} = $opthr-&gt;{$key} ;\n }\n } \n}\n\n# Rest of the code here ...\n\n1;\n</code></pre>\n\n<p>And using the module with</p>\n\n<pre><code>use Test::version qw(version_ok) ;\nTest::version::configure( { is_string =&gt; 1 } ) ;\n</code></pre>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-04-10T00:08:15.887", "Id": "10734", "ParentId": "5630", "Score": "0" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "2", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-10-27T15:54:37.310", "Id": "5630", "Score": "2", "Tags": [ "perl" ], "Title": "How should I pass settings to a module in Perl that also exports symbols?" }
5630
<p>So this is my first time going over a pretty big nested object, was posting this up to see how I can possibly cut this down. (Some fears I have would be, I currently know the extent of the nesting (4) but could be more in the future. Which I'm not accounting for. ) </p> <p>The code below sits within a function:</p> <pre><code>if (itemLi.items) { var ul = new Element('ul').inject(el) for (var i = 0; i &lt; itemLi.items.length; i++) { var li = new Element('li').inject(ul); lastPgNum = itemLi.items[i].page; //subItem = new Element('a', {'href': itemLi.items[i].href,'html': itemLi.items[i].title}).inject(li); if (itemLi.items[i].items) { subItem = new Element('span', { 'html': itemLi.items[i].title, 'class': 'pgTitle' }).inject(li); var ulsub = new Element('ul', { 'class': 'here1' }).inject(ul) for (var b = 0; b &lt; itemLi.items[i].items.length; b++) { var liSub = new Element('li').inject(ulsub); lastPgNum = itemLi.items[i].items[b].page; countSubSubs++; if (itemLi.items[i].items[b].items) { subItem = new Element('span', { 'html': itemLi.items[i].items[b].title, 'class': 'pgTitle' }).inject(liSub); var ulsubTwo = new Element('ul', { 'class': 'here2' }).inject(ulsub) for (var c = 0; c &lt; itemLi.items[i].items[b].items.length; c++) { var li = new Element('li').inject(ulsubTwo); lastPgNum = itemLi.items[i].items[b].items[c].page; countSubSubsSub++; subSubItem = new Element('a', { 'href': itemLi.items[i].items[b].items[c].href, 'html': itemLi.items[i].items[b].items[c].title }).inject(li); }; var startPgSub = new Element('span', { 'class': 'pgNumbers', 'html': 'pg ' + (lastPgNum - (countSubSubs + countSubSubs + i + 1)) + '-' + lastPgNum }).inject(name); } else { var startPgSub = new Element('span', { 'class': 'pgNumbers', 'html': 'pg ' + (lastPgNum - (countSubSubs)) + '-' + lastPgNum }).inject(name); subItem = new Element('a', { 'href': itemLi.items[i].items[b].href, 'html': itemLi.items[i].items[b].title }).inject(liSub); } }; } else { subItem = new Element('a', { 'href': itemLi.items[i].href, 'html': itemLi.items[i].title }).inject(li); if ((lastPgNum - i) == lastPgNum) { startPg = new Element('span', { 'class': 'pgNumbers', 'html': 'pg ' + lastPgNum }).inject(name); } else { startPg = new Element('span', { 'class': 'pgNumbers', 'html': 'pg ' + (lastPgNum - i) + '-' + lastPgNum }).inject(name); } } }; }; </code></pre>
[ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-10-27T21:45:10.620", "Id": "8518", "Score": "2", "body": "Your spidey-sense should go off whenever you find yourself with a variable named `countSubsSubsSub`. :P" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-10-27T21:46:33.957", "Id": "8519", "Score": "0", "body": "What exactly does this JSON look like? And the HTML you want to generate from it?" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-10-28T02:55:11.997", "Id": "8524", "Score": "0", "body": "Ha, funny you say 'spidey-sense' because when I got to about the third time looping threw this I said to myself 'This is getting a little ridiculous'. I knew there had to be a better way!" } ]
[ { "body": "<p>You could use a recursive function to traverse your object and generate the HTML.</p>\n\n<p>Something like:</p>\n\n<pre><code>function generateList(items, depth) {\n if (!depth) depth = 0;\n var ul = new Element('ul');\n if (depth) { ul.addClass('here' + depth); }\n for (var i = 0; i &lt; items.length; ++i)\n {\n var item = items[i];\n var li = new Element('li').inject(ul);\n if (item.items) {\n li.adopt(new Element('span', {\n 'html' : item.title,\n 'class': 'pgTitle'\n }));\n li.adopt(generateList(item.items, depth + 1));\n } else {\n li.adopt(new Element('a', {\n 'href' : item.href,\n 'title': item.title\n }));\n }\n }\n return ul;\n}\n\nif (itemLi.items) {\n generateList(itemLi.items).inject(el);\n}\n</code></pre>\n\n<p>This doesn't include code to add the page spans, cause i don't understand yet how they should be generated. (The code doesn't include declarations of the variables involved, for starters.) But it should generate a list of links, with sublists for any items that have sub-items. The classes for the sublists are kinda unnecessary -- CSS can select them just fine as <code>ul&gt;li&gt;ul</code> and <code>ul&gt;li&gt;ul&gt;li&gt;ul</code> -- so unless you have some other need to track the amount of nesting, you could get rid of <code>depth</code> and the class on the <code>ul</code>s.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-10-28T00:36:55.447", "Id": "5639", "ParentId": "5633", "Score": "1" } } ]
{ "AcceptedAnswerId": "5639", "CommentCount": "3", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-10-27T19:11:37.677", "Id": "5633", "Score": "2", "Tags": [ "javascript", "json", "mootools" ], "Title": "Best way to iterate over JSON" }
5633
<p>I'm using the Model View Presenter (MVP) pattern in MFC that's not hugely relevant to my question but I mention it for context. I have some code that is designed to populate a list control with data from a list.</p> <p>I have two list boxes which have almost the same code except the type of list is different and the function used to actually put items in the list control is different. So my questions are:</p> <ol> <li>How can I genericize this member function so that I could pass it an arbitrary list of objects, and a population function (i.e., what AddCustomerToListControl is)?</li> <li>Besides genericizing it are there other improvements to be made?</li> </ol> <p>(Note the calls to SetTopIndex are so that the scroll position is remembered.)</p> <pre><code>void MyDialog::SetCustomerList(const std::list&lt;Customer*&gt;&amp; customers) { customersListCtrl_.SetRedraw(FALSE); int selectedItemIndex = customersListCtrl_.GetNextItem(-1, LVNI_SELECTED); int topIndex = customersListCtrl_.GetTopIndex(); customersListCtrl_.DeleteAllItems(); if(customers.size() &gt; 0) { for(std::list&lt;Customer*&gt;::const_iterator it = customers.begin(); it != customers.end() ; it ++) { AddCustomerToListControl(*it); } customersListCtrl_.SetItemState(selectedItemIndex,LVIS_SELECTED, LVIS_SELECTED); } customersListCtrl_.SetTopIndex(topIndex); customersListCtrl_.SetRedraw(TRUE); } </code></pre> <p><strong>UPDATE</strong></p> <p>Another detail is the the function <code>AddCustomerToListControl</code> above needs a reference to the listControl in order to add items to it (e.g., call <code>InsertItem</code> and <code>SetItemText</code>)</p>
[]
[ { "body": "<p>To Generalize it:</p>\n\n<pre><code>class MyDialog\n{\n template&lt;typename T, typename A&gt;\n void SetCustomerList(T const&amp; customers, A action);\n ....\n};\n\n\ntemplate&lt;typename T, typename A&gt;\nvoid MyDialog::SetCustomerList(T const&amp; customers, A action)\n{\n .....\n // AddCustomerToListControl(*it);\n action(*it);\n .....\n}\n\n// At call point:\nSetCustomerList(customers, &amp;AddCustomerToListControl);\n</code></pre>\n\n<p>Other Changes:<br>\nYou can use the standard algorithms:</p>\n\n<pre><code> for(std::list&lt;Customer*&gt;::const_iterator it = customers.begin();\n it != customers.end() ; it ++)\n {\n AddCustomerToListControl(*it);\n }\n</code></pre>\n\n<p>Can be replaced with:</p>\n\n<pre><code> std::for_each(customer.begin(), customer.end(), AddCustomerToListControl);\n // or in the new code:\n std::for_each(customer.begin(), customer.end(), action);\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-10-28T14:16:30.137", "Id": "8558", "Score": "0", "body": "Will I be able to call `size()` or `begin()` and `end()` on customers? How does the compiler know T is a list (or container)?" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-10-28T15:33:22.250", "Id": "8566", "Score": "0", "body": "@User: At the call point (see above). When you pass an object it then checks the types of the parameters and works out what T and A should be and then compiles the function using these types. So T can be anything; but it will fail to compile if T does not have the methods size(), begin(), end() or you can not call A like a function." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-10-28T16:01:52.793", "Id": "8568", "Score": "0", "body": "So is the way you've defined it better than doing it this way: `void MyDialog::SetCustomerList<T,A>(const std::list<T>& customers, A action)`? I guess more flexible?" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-10-28T16:11:43.573", "Id": "8569", "Score": "0", "body": "@User: Its 6 of one half a dozen of the other. The way I define it allows any type to be used. But if you want to restrict the type to std::list then your way works (and it is often good to restrict the type to things you expect (you can always make it more general later))." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-10-28T16:13:00.030", "Id": "8570", "Score": "0", "body": "Thinking about it. It is more customary to pass the iterators: `void MyDialog::SetCustomerList<I,A>(I begin, I end, A action)` but to be honest I would pass the container for this situation." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-10-31T17:37:05.050", "Id": "8637", "Score": "0", "body": "why do you say normally you'd pass the iterators but for this situation you'd pass the container?" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-10-31T18:28:36.530", "Id": "8640", "Score": "0", "body": "@User: If I was building a series library, I would echo the way the STL works (by using iterators) as it would make interactions with the STL easier. But for a simple one off or school project its just as easy to pass the container." } ], "meta_data": { "CommentCount": "7", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-10-27T23:53:54.093", "Id": "5635", "ParentId": "5634", "Score": "3" } } ]
{ "AcceptedAnswerId": "5635", "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-10-27T22:07:52.340", "Id": "5634", "Score": "4", "Tags": [ "c++" ], "Title": "Generalize code that populates MFC list control?" }
5634
<p>I'm a student and I've created this MySQL database schema for my Service Order Management academic project. I want to know if I need to improve it and, if so, how I could do that.</p> <pre><code>/* * Table 'brands' */ CREATE TABLE `brands` ( `brand_id` INTEGER NOT NULL, `equipment_id` INTEGER NOT NULL, `brand` VARCHAR(45) NOT NULL, CONSTRAINT `pk_brand_id` PRIMARY KEY (`brand_id`), CONSTRAINT `fk_equipment_id` FOREIGN KEY (`equipment_id`) REFERENCES `equipments` ); /* * Table 'cities' */ CREATE TABLE `cities` ( `city_id` INTEGER NOT NULL, `state_id` INTEGER NOT NULL, `city` VARCHAR(50) NOT NULL, CONSTRAINT `pk_city_id` PRIMARY KEY (`city_id`), CONSTRAINT `fk_state_id` FOREIGN KEY (`state_id`) REFERENCES `states` ); /* * Table 'customers' */ CREATE TABLE `customers` ( `customer_id` INTEGER NOT NULL, `user_id` INTEGER NOT NULL, CONSTRAINT `pk_customer_id` PRIMARY KEY (`customer_id`), CONSTRAINT `fk_user_id` FOREIGN KEY (`user_id`) REFERENCES `users` ); /* * Table 'employees' */ CREATE TABLE `employees` ( `employee_id` INTEGER NOT NULL, `user_id` INTEGER NOT NULL, `is_admin` INTEGER NOT NULL, CONSTRAINT `pk_employee_id` PRIMARY KEY (`employee_id`), CONSTRAINT `fk_user_id` FOREIGN KEY (`user_id`) REFERENCES `users`, CONSTRAINT `ck_is_admin` CHECK (`is_admin` IN (0, 1)) -- unsupported by MySQL ); /* * Table 'equipments' */ CREATE TABLE `equipments` ( `equipment_id` INTEGER NOT NULL, `equipment` VARCHAR(45) NOT NULL, CONSTRAINT `pk_equipment_id` PRIMARY KEY (`equipment_id`) ); /* * Table 'legal_users' */ CREATE TABLE `legal_users` ( `user_id` INTEGER NOT NULL, `cnpj` CHAR(14) NOT NULL, `company_name` VARCHAR(150) NOT NULL, `trade_name` VARCHAR(100) NULL, `contact_name` VARCHAR(50) NOT NULL, `mobile_phone` CHAR(10) NULL, `work_phone` CHAR(10) NULL, CONSTRAINT `pk_user_id` PRIMARY KEY (`user_id`), CONSTRAINT `fk_user_id` FOREIGN KEY (`user_id`) REFERENCES `users`, CONSTRAINT `uc_cnpj` UNIQUE (cnpj) ); /* * Table 'natural_users' */ CREATE TABLE `natural_users` ( `user_id` INTEGER NOT NULL, `cpf` CHAR(11) NOT NULL, `name` VARCHAR(50) NOT NULL, `nickname` VARCHAR(30) NULL, `sex` CHAR(1) NOT NULL, `birth_date` DATE NOT NULL, `home_phone` CHAR(10) NULL, `mobile_phone` CHAR(10) NULL, `work_phone` CHAR(10) NULL, -- ignored for employees CONSTRAINT `pk_user_id` PRIMARY KEY (`user_id`), CONSTRAINT `fk_user_id` FOREIGN KEY (`user_id`) REFERENCES `users`, CONSTRAINT `uc_cpf` UNIQUE (`cpf`), CONSTRAINT `ck_sex` CHECK (`sex` IN ('M', 'F')) -- unsupported by MySQL ); /* * Table 'service_orders' */ CREATE TABLE `service_orders` ( `order_id` INTEGER NOT NULL, `employee_id` INTEGER NOT NULL, `customer_id` INTEGER NOT NULL, `opening_date` TIMESTAMP NOT NULL, `status` INTEGER NOT NULL, `equipment_id` INTEGER NOT NULL, `brand_id` INTEGER NOT NULL, `model` VARCHAR(20) NOT NULL, `serial_number` VARCHAR(20) NULL, `under_warranty` INTEGER NOT NULL, `defect` TEXT NOT NULL, `diagnosis` TEXT NULL, `solution` TEXT NULL, `maintenance_cost` DECIMAL(6,2) NULL, `closing_date` TIMESTAMP NULL, `remarks` TEXT NULL, CONSTRAINT `pk_order_id` PRIMARY KEY (`order_id`), CONSTRAINT `fk_employee_id` FOREIGN KEY (`employee_id`) REFERENCES `employees`, CONSTRAINT `fk_customer_id` FOREIGN KEY (`customer_id`) REFERENCES `customers`, CONSTRAINT `ck_status` CHECK (`status` IN (0, 5)), -- unsupported by MySQL CONSTRAINT `fk_equipment_id` FOREIGN KEY (`equipment_id`) REFERENCES `equipments`, CONSTRAINT `fk_brand_id` FOREIGN KEY (`brand_id`) REFERENCES `brands`, CONSTRAINT `ck_under_warranty` CHECK (`under_warranty` IN (0, 1)) -- unsupported by MySQL ); /* * Table 'states' */ CREATE TABLE `states` ( `state_id` INTEGER NOT NULL, `state` VARCHAR(20) NOT NULL, `code` CHAR(2) NOT NULL, CONSTRAINT `pk_state_id` PRIMARY KEY (`state_id`), CONSTRAINT `uc_state` UNIQUE (`state`), CONSTRAINT `uc_code` UNIQUE (code) ); /* * Table 'users' */ CREATE TABLE `users` ( `user_id` INTEGER NOT NULL, `person_type` CHAR(1) NOT NULL, `postal_code` CHAR(8) NOT NULL, `address` VARCHAR(60) NOT NULL, `number` INTEGER NULL, `complement` VARCHAR(50) NULL, `neighborhood` VARCHAR(30) NOT NULL, `city_id` INTEGER NOT NULL, `email` VARCHAR(150) NOT NULL, `password` CHAR(40) NOT NULL, `remarks` TEXT NULL, `is_active` INTEGER NOT NULL DEFAULT 1, CONSTRAINT `pk_user_id` PRIMARY KEY (`user_id`), CONSTRAINT `ck_person_type` CHECK (`person_type` IN ('F', 'J')), -- unsupported by MySQL CONSTRAINT `fk_city_id` FOREIGN KEY (`city_id`) REFERENCES `cities`, CONSTRAINT `uc_email` UNIQUE (`email`), CONSTRAINT `ck_is_active` CHECK (`is_active` IN (0, 1)) -- unsupported by MySQL ); </code></pre>
[]
[ { "body": "<p>You could set the integers that act as an ID to 'unsigned'. It doesn't really improve much, it only gives you a wider range of integer values.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-10-28T06:31:30.127", "Id": "5646", "ParentId": "5645", "Score": "1" } }, { "body": "<p>It looks fine. Two things to consider:</p>\n\n<p>1, Distinct table for phone numbers:</p>\n\n<pre><code>phone_number\n id\n user_id\n type (home/work/mobile/etc)\n number\n</code></pre>\n\n<p>It may not worth it, depends on the data.</p>\n\n<p>2, Maybe you want to store some audit information about your data. (Hints: journal table in Oracle, Hibernate Envers)</p>\n\n<p>+1: <code>CHAR(40)</code> for <code>password</code> - it's SHA-1? If you use SHA-256/SHA-512 it will be too short.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-10-28T23:06:06.880", "Id": "5675", "ParentId": "5645", "Score": "4" } }, { "body": "<p>For states, this makes more sense. Adjust foreign keys to match.</p>\n\n<pre><code>CREATE TABLE `states` (\n `code` CHAR(2) NOT NULL,\n `state` VARCHAR(20) NOT NULL,\n CONSTRAINT `pk_states` PRIMARY KEY (`code`),\n CONSTRAINT `uc_state` UNIQUE (`state`)\n);\n</code></pre>\n\n<p>Using an id number for a surrogate key only makes sense if</p>\n\n<ul>\n<li>the thing you're modeling doesn't carry its identity along with it, or</li>\n<li>its identity is impractically long, like varchar(250).</li>\n</ul>\n\n<p>Both state code and state name are fully identifying. (Within the context of a single country.) Using the state code instead of an integer saves space and usually eliminates a join. </p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-11-10T13:00:34.013", "Id": "29400", "Score": "2", "body": "this is extremely bad practice. Never ever use data that gets displayed anywhere as a primary key. The assumption that state codes don't change ignores that: States change, which might result in change of codes. What an enterprise stores in a state table often doesn't map to some standards body notion of state, so you might end up with duplicate codes, changing codes and all kinds of weird stuff happening to your codes. All this is pain full in any case, but it will kill you when your code is actually a primary key." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-11-10T13:05:41.883", "Id": "29401", "Score": "0", "body": "No, it's not a bad practice. There's no relational principle that says candidate keys must be hidden from the user and immutable. In fact, it's obviously impossible to enforce that requirement on all candidate keys. (Above, \"code\" and \"state\" are both candidate keys.) There's no similar SQL restriction, either, unless you use Oracle. (Oracle is the only major dbms that doesn't support ON UPDATE CASCADE.) Both the relational model *and* SQL allow any column(s) having a UNIQUE constraint to be the target of foreign key references." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-11-10T13:11:37.197", "Id": "29403", "Score": "0", "body": "Yes it is bad practice. I'm not saying that candidate key must be hidden. But Primary Keys should. Have fun with an ON UPDATE CASCADE once you have tables of considerable size referencing a mutating Primary Key. Also ON UPDATE CASCADE solves only one of the mentioned problems. Of course every single problem is solvable in some way. I'm just saying you should just avoid it in the first place when it is so simple." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-11-10T15:32:17.380", "Id": "29407", "Score": "0", "body": "A modern dbms handles ON UPDATE CASCADE fine, even with multi-million row tables. (Except Oracle.) This isn't 1985. (Except for Oracle.) There's no theoretical backing for \"primary key\" at all now--all candidate keys are created equal. Again, this isn't 1985." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-11-10T15:47:42.477", "Id": "29409", "Score": "0", "body": "So we should drop all other IDs as well? Last time I checked pretty much every database had a problem with updating every single row in possibly multiple large tables." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-11-10T16:00:11.153", "Id": "29411", "Score": "0", "body": "No. But you *should* think. If one update cascades to *every* row in a table, your design is broken to start with. With addresses (which use state codes in the USA), selectivity would be 1/50. Updating the state code of West Virginia to 'WZ' might cascade to about 1 of 50 rows, or to 1 million of 50 million rows. But let's say it hits 3 million rows out of 50 million. That update, cascading to about 3 million rows, takes 3 seconds on my *home* computer. *And* I eliminate a join on every query that uses a state code. *And* the USPS has changed only one state code in the last 40 years." } ], "meta_data": { "CommentCount": "6", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-11-10T12:41:52.383", "Id": "18447", "ParentId": "5645", "Score": "-2" } }, { "body": "<p>Looks good. Two things to possibly consider, both in regards to self-referencing columns:</p>\n\n<ol>\n<li><p>Manager column if you ever wanted to establish a hierarchy using self-joins:</p>\n\n<pre><code>CREATE TABLE `employees` (\n `employee_id` INTEGER NOT NULL,\n `user_id` INTEGER NOT NULL,\n `is_admin` INTEGER NOT NULL,\n `manager_employee_id` INTEGER NULL\n</code></pre></li>\n<li><p>Kit column in case any of the <code>equipments</code> could be bundled into a kit, for example <code>SELECT * FROM equipments WHERE kit_id = 5;</code> would return all parts of a kit, which would itself be another record in the <code>equipments</code> table. </p>\n\n<pre><code>CREATE TABLE `equipments` (\n `equipment_id` INTEGER NOT NULL,\n `equipment` VARCHAR(45) NOT NULL,\n `kit_id` INTEGER NULL\n</code></pre></li>\n</ol>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-05-19T22:00:32.223", "Id": "51169", "ParentId": "5645", "Score": "2" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-10-28T05:43:34.067", "Id": "5645", "Score": "5", "Tags": [ "sql", "mysql", "homework" ], "Title": "Database schema for Service Order Management project" }
5645
<p>Is there anything that can be done differently for this function? Any way to make it faster?</p> <pre><code>public List&lt;Channel&gt; ChildrenOf(Channel startingChannel) { List&lt;Channel&gt; result = new List&lt;Channel&gt;(); foreach (Channel child in startingChannel.Children) { result.Add(child); result.AddRange(ChildrenOf(child)); } return result; } </code></pre>
[ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-10-28T07:31:05.467", "Id": "8526", "Score": "2", "body": "Looks to me like that's it. But maybe someone else has some other ideas." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-10-28T12:34:20.717", "Id": "8550", "Score": "1", "body": "Your approach has a problem with deeply nested lists. Let's say you have N items at a nesting depth D. Then each item will be copied D times -> O(N*D) time.\nThe \"yield return\" answer has a similar issue: for each item, it has to execute D 'yield return' statements.\nGuffa's answer doesn't have this problem and will run in O(N) time." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-10-28T16:18:24.970", "Id": "8571", "Score": "0", "body": "Is there a way to do this with tail recursion? HRMMM." } ]
[ { "body": "<p>Share your result list would be one way of preventing allocations and esspecially collections to happen</p>\n\n<pre><code> public List&lt;Channel&gt; ChildrenOf(Channel startingChannel, List&lt;Channel&gt; result) \n { \n foreach (Channel child in startingChannel.Children) \n { \n result.Add(child);\n\n // this will internally add to result\n ChildrenOf(child, result);\n } \n\n return result; \n } \n</code></pre>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-10-28T07:31:59.047", "Id": "5649", "ParentId": "5648", "Score": "11" } }, { "body": "<p>I'd separate iteration and adding items to a list:</p>\n\n<pre><code>public IEnumerable&lt;Channel&gt; ChildrenOf(Channel root)\n{\n yield return root;\n foreach(var c in root.Children)\n foreach(var cc in ChildrenOf(c))\n yield return cc;\n}\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-10-28T07:47:44.240", "Id": "8528", "Score": "0", "body": "does this make it better/faster? How does the IL compare?" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-10-28T07:51:34.080", "Id": "8529", "Score": "1", "body": "Almost there, dont forget to yield back first level childs though" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-10-28T07:53:04.640", "Id": "8530", "Score": "2", "body": "@luketorjussen: This method is faster since it doesn't require any allocations on the heap and hence, therefore no deallocations. be aware though that since the data is not cached in a list, manipulation is not possible and multiple iterations will execute the function multiple times" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-10-28T08:47:39.847", "Id": "8534", "Score": "0", "body": "@Polity: Actually, each \"foreach\" loop will create an enumerator object which is still an allocation on the heap (the inner loop creates an enumerator for each iteration of the outer loop)." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-10-28T09:01:25.850", "Id": "8536", "Score": "0", "body": "@BrianReichle - That depends, if root.Children is a BCL .NET collection like a list or Array, it will allocate on the stack" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-10-28T09:16:41.667", "Id": "8538", "Score": "0", "body": "@Polity, I would not be surprised if a foreach loop over an array was optimised to a for loop by the compiler (and hence be on the stack) but the result of the 'ChildrenOf' method in the inner loop is not such a class :)" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-10-28T09:23:35.340", "Id": "8539", "Score": "0", "body": "@BrianReichle - Damn! your right! I was completely looking beyond your point, thank you for having the patience to shake me awake!" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-10-28T10:19:32.287", "Id": "8541", "Score": "0", "body": "i am really interested in your solution, but it returns also the root channel, trying to remove the 'yield return root;' has caused it to not return ANY child channels... can you explain why?" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-10-28T10:34:18.883", "Id": "8542", "Score": "0", "body": "@Dementic: It doesn't return anything because currently, each element is responsible for returning itself -- and that's the statement that does it. What you could do is add `yield return c;` to the outer foreach (and of course, add braces around the two statements!)." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-10-28T10:43:01.427", "Id": "8544", "Score": "0", "body": "k, got it. the function name should be changed to ChildrenOfAndParent :) thx cHao and Anton" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-10-28T11:11:23.747", "Id": "8545", "Score": "0", "body": "Or move the `yield return root;` to inside the first for and change it to `yield return c;`, I guess?" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-10-28T14:49:24.410", "Id": "8561", "Score": "0", "body": "You still end up with it on the heap since using \"yield return\" transforms your method into a class with fields for your local variables." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2015-05-18T10:09:11.643", "Id": "165103", "Score": "1", "body": "You should be careful to avoid `yield return` in recursive functions, the memory usage scales explosively. See http://stackoverflow.com/a/30300257/284795 . Thus Guffa's and Lippert's solutions are preferable." } ], "meta_data": { "CommentCount": "13", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-10-28T07:32:40.950", "Id": "5650", "ParentId": "5648", "Score": "13" } }, { "body": "<p>Put the recursive part in a private method, so that you can add the items directly to the list instead of creating intermediate lists:</p>\n\n<pre><code>public List&lt;Channel&gt; ChildrenOf(Channel startingChannel) {\n List&lt;Channel&gt; result = new List&lt;Channel&gt;();\n AddChildren(startingChannel, result);\n return result;\n}\n\nprivate void AddChildren(Channel channel, List&lt;Channel&gt; list) {\n foreach (Channel child in channel.Children) {\n list.Add(child);\n AddChildren(child, list);\n }\n}\n</code></pre>\n\n<p>(This is basically the same principle as Polity suggested, only it's implemented in two methods so that you don't have to create an empty list to call it.)</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-10-28T07:43:13.200", "Id": "5651", "ParentId": "5648", "Score": "16" } }, { "body": "<p>Just to round out the other answers: I would be inclined to write your solution like this:</p>\n\n<pre><code>static IEnumerable&lt;T&gt; DepthFirstTreeTraversal&lt;T&gt;(T root, Func&lt;T, IEnumerable&lt;T&gt;&gt; children) \n{\n var stack = new Stack&lt;T&gt;();\n stack.Push(root);\n while(stack.Count != 0)\n {\n var current = stack.Pop();\n // If you don't care about maintaining child order then remove the Reverse.\n foreach(var child in children(current).Reverse())\n stack.Push(child);\n yield return current;\n }\n}\n</code></pre>\n\n<p>And now to achieve your aim, you just say:</p>\n\n<pre><code> static List&lt;Channel&gt; AllChildren(Channel start)\n {\n return DepthFirstTreeTraversal(start, c=&gt;c.Children).ToList();\n }\n</code></pre>\n\n<p>Now you have a more general-purpose tool that you can use to get a depth-first traversal of <em>any</em> tree structure, not just your particular structure. </p>\n\n<p>Another nice feature of my solution is that <em>it uses a fixed amount of call stack space</em>. Even if your hierarchy is twenty thousand deep, you never run out of stack space because the method is not recursive to begin with. All the information that would be needed for recursion is stored on the \"stack\" data structure instead of in activation records on the real call stack.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-11-03T04:15:57.790", "Id": "8741", "Score": "0", "body": "Damn. And here I was, coming to answer this with just such a generic stack... :)" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-05-22T13:47:55.867", "Id": "88796", "Score": "0", "body": "+1 for populating a List using this traversal extension. I make a C# Extension for the traversal method and use it on a bunch of stuff. I find it much easier to understand than using a recursive method." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2017-05-27T03:09:57.610", "Id": "312384", "Score": "0", "body": "Micro-optimisation: I would put the `yield` before the `foreach`, to save some cycles and memory in case the iteration of the enumerator is stopped midway." } ], "meta_data": { "CommentCount": "3", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-10-28T13:45:46.213", "Id": "5661", "ParentId": "5648", "Score": "40" } } ]
{ "AcceptedAnswerId": "5650", "CommentCount": "3", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-10-28T07:26:06.660", "Id": "5648", "Score": "21", "Tags": [ "c#", "recursion" ], "Title": "Any way to make this recursive function better/faster?" }
5648
<pre><code> public List&lt;Channel&gt; Children { get { return myChannels.Where(c =&gt; c.ParentChannelId == this.Id).ToList(); } } </code></pre> <p>is this the right way to get children ? it does work, the question is if its the only way.</p> <p>could give me an example for other methods of acheiving the same thing? (if there are any others?)</p>
[]
[ { "body": "<p>Generally, you should return the items as abstract as possible. If you are just going to loop through the items and don't need it to be a list, you should use <code>IEnumerable&lt;Channel&gt;</code> as return type, even if you actually return a <code>List&lt;Channel&gt;</code>.</p>\n\n<p>Instead of returning it as a list, you can return it as an enumerator:</p>\n\n<pre><code>public IEnumerable&lt;Channel&gt; Children {\n get { return myChannels.Where(c =&gt; c.ParentChannelId == this.Id); }\n}\n</code></pre>\n\n<p>Instead of creating a list, this will return an enumerator that can produce the items. The advantages is that there is almost no work done when you call the property, and it doesn't allocate memory for a list. The drawbacks is that there is some overhead for each item that you get from the enumerator as it has to loop through items in the source until it finds one that matches the condition, and you have to hang on to the original source (<code>myChannels</code>) as long as you are using the enumerator.</p>\n\n<p>One big advantage of this approach though is that it's flexible. You can just use <code>.ToList()</code> on the result, and you are back at allocating a list for the items.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-10-28T08:37:58.187", "Id": "5654", "ParentId": "5653", "Score": "6" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-10-28T08:06:36.663", "Id": "5653", "Score": "0", "Tags": [ "c#" ], "Title": "Children property" }
5653
<p>I have a method to compare two byte arrays. The code is Java-style, and there are many <code>if</code>-<code>else</code>s.</p> <pre><code>def assertArray(b1: Array[Byte], b2: Array[Byte]) { if (b1 == null &amp;&amp; b2 == null) return; else if (b1 != null &amp;&amp; b2 != null) { if (b1.length != b2.length) throw new AssertionError("b1.length != b2.length") else { for (i &lt;- b1.indices) { if (b1(i) != b2(i)) throw new AssertionError("b1(%d) != b2(%d)".format(i, i)) } } } else { throw new AssertionError("b1 is null while b2 is not, vice versa") } } </code></pre> <p>I have tried as following, but it's not simplified the code much:</p> <pre><code>(Option(b1), Option(b2)) match { case (Some(b1), Some(b2)) =&gt; if ( b1.length == b2.length ) { for (i &lt;- b1.indices) { if (b1(i) != b2(i)) throw new AssertionError("b1(%d) != b2(%d)".format(i, i)) } } else { throw new AssertionError("b1.length != b2.length") } case (None, None) =&gt; _ case _ =&gt; throw new AssertionError("b1 is null while b2 is not, vice versa") } </code></pre>
[ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-10-28T10:18:27.763", "Id": "8540", "Score": "0", "body": "note : this question was first posted on SO (http://stackoverflow.com/q/7927404/112053). I think it should be migrated instead of copied, but I don't know how to do this." } ]
[ { "body": "<p>I am not fluent in Scala, but Array is just a thin layer over Java, so List might be cleaner.\nIn Java Arrays.equals(b1, b2) would be used, so delegate to java.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-10-28T13:51:09.777", "Id": "5663", "ParentId": "5655", "Score": "4" } }, { "body": "<p>Part of the problem is all the exceptions. There are better ways of handling exceptions, such as Scalaz <a href=\"http://scalaz.googlecode.com/svn/continuous/latest/browse.sxr/scalaz/example/ExampleValidation.scala.html\" rel=\"nofollow\">Validation</a> or Lift's <a href=\"http://www.assembla.com/spaces/liftweb/wiki/Box\" rel=\"nofollow\">Box</a>. Scala itself comes with <code>Either</code>, which isn't particularly flexible.</p>\n\n<p>On the other hand, you are not returning anything, which actually turns the whole code into a reverse <code>Option</code>: you either have <code>Some(exception)</code> or <code>None</code>.</p>\n\n<p>Now, the test itself, except for checking for nulls, has a name in Scala: <code>sameElements</code>. Only it will not tell you what the problem was. </p>\n\n<p>I can think of two ways of handling it. The first is just a small improvement on your pattern matching:</p>\n\n<pre><code>def assertArray(b1: Array[Byte], b2: Array[Byte]) = (Option(b1), Option(b2)) match {\n case (None, None) =&gt;\n case (None, _) | (_, None) =&gt; throw new AssertionError(\"b1 is null while b2 is not, vice versa\")\n case (Some(b1), Some(b2)) if b1.length == b2.length =&gt;\n (b1, b2).zipped.map(_ == _)\n .zipWithIndex.find(!_._1)\n .foreach { \n case (_, i) =&gt; throw new AssertionError(\"b1(%d) != b2(%d)\".format(i, i))\n }\n case _ =&gt; throw new AssertionError(\"b1.length != b2.length\")\n}\n</code></pre>\n\n<p>The other way would be to turn the problem around completely. It would be like this:</p>\n\n<pre><code>def assertArray(b1: Array[Byte], b2: Array[Byte]) = {\n def isOneNull = \n if ((b1 eq null) ^ (b2 eq null)) Some(\"b1 is null while b2 is not, vice versa\")\n else None\n\n def areSizesDifferent =\n if (b1.length != b2.length) Some(\"b1.length != b2.length\")\n else None\n\n def haveDifferentElements =\n (b1, b2).zipped.map(_ == _)\n .zipWithIndex.find(!_._1)\n .map { case (_, i) =&gt; \"b1(%d) != b2(%d)\" format (i, i) }\n\n def areTheyDifferent =\n if ((b1 ne null) &amp;&amp; (b2 ne null)) areSizesDifferent orElse haveDifferentElements\n else isOneNull\n\n areTheyDifferent foreach (msg =&gt; throw new AssertionError(msg))\n}\n</code></pre>\n\n<p>This is longer, and handles nullness in two separate places, and doesn't <em>protect</em> against nullness, but I think it reads much better. To get more than this I need Scalaz:</p>\n\n<pre><code>def assertArray(b1: Array[Byte], b2: Array[Byte]) = {\n def isOneNull = \n (b1 eq null) ^ (b2 eq null) option \"b1 is null while b2 is not, vice versa\"\n\n def areTheyDifferent = \n Option(b1) &lt;|*|&gt; Option(b2) flatMap {\n case (b1, b2) =&gt;\n def areSizesDifferent = b1.length != b2.length option \"b1.length != b2.length\"\n\n def haveDifferentElements =\n (b1, b2).zipped.map(_ == _)\n .zipWithIndex.find(!_._1)\n .map { case (_, i) =&gt; \"b1(%d) != b2(%d)\" format (i, i) }\n\n areSizesDifferent orElse haveDifferentElements\n } orElse isOneNull\n\n areTheyDifferent foreach (msg =&gt; throw new AssertionError(msg))\n}\n</code></pre>\n\n<p>Or, to go more full-blown with Scalaz:</p>\n\n<pre><code>def assertArray(b1: Array[Byte], b2: Array[Byte]) = {\n type Params = (Array[Byte], Array[Byte])\n type Func = Params =&gt; Option[String]\n\n def isOneNull = \n (b1 eq null) ^ (b2 eq null) option \"b1 is null while b2 is not, vice versa\"\n\n def areSizesDifferent: Func = {\n case (b1, b2) =&gt; b1.length != b2.length option \"b1.length != b2.length\"\n }\n\n def haveDifferentElements: Func = {\n case (b1, b2) =&gt;\n (b1, b2).zipped.map(_ == _)\n .zipWithIndex.find(!_._1)\n .map { case (_, i) =&gt; \"b1(%d) != b2(%d)\" format (i, i) }\n }\n\n def areTheyDifferent =\n Option(b1) &lt;|*|&gt; Option(b2) flatMap (\n areSizesDifferent |@| haveDifferentElements\n apply (_ orElse _)\n ) orElse isOneNull\n\n areTheyDifferent foreach (msg =&gt; throw new AssertionError(msg))\n}\n</code></pre>\n\n<p>Scala has an unfortunate overhead compared to Haskell to do these things. Also, Scalaz will be able to do a bit more in the next version, but this works with 6.0.</p>\n\n<p>The gain with Scalaz is not, however, legibility or conciseness (in this code, anyway), but of composition. For instance, in the current Scalaz we can abstract most of the body of <code>areTheyDifferent</code> like this:</p>\n\n<pre><code>def composeFM[M[_]:Plus, F[_]:Applicative, B](f: F[M[B]], g: F[M[B]]): F[M[B]] = \n (f |@| g)(_ &lt;+&gt; _)\ntype FAB[x] = Array[Byte] =&gt; x\ndef areTheyDifferent = (\n Option(b1) &lt;|*|&gt; Option(b2) \n flatMap composeFM[Option, FAB, Int](areSizesDifferent, haveDifferentElements)\n orElse isOneNull\n)\n</code></pre>\n\n<p>Note that <code>composeFM</code> doesn't know a thing about <code>Option</code> or <code>Function1</code> -- it applies to the pattern.</p>\n\n<p>Well, anyway, take your pick. Sometimes a problem just isn't worth the trouble, but it is useful to know how to handle the trouble anyway.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-10-29T14:12:18.243", "Id": "8600", "Score": "0", "body": "@Freewind You're welcome. I revised the Scalaz examples a bit, as it suddenly occured to me that I could do something about the if-statements that were bothering me with Scalaz." } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-10-28T21:07:46.137", "Id": "5672", "ParentId": "5655", "Score": "5" } } ]
{ "AcceptedAnswerId": "5672", "CommentCount": "1", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-10-28T09:37:49.623", "Id": "5655", "Score": "3", "Tags": [ "array", "scala" ], "Title": "Checking if two byte arrays are the same" }
5655
<p>We deliver content for different devices - web, smart tv, tablet and mobile - and I'm trying to provide a common JavaScript interface providing functions like play stream, alert, log etc without thinking of how the device actually do this.</p> <p>My question is: Is there a way to provide this like an interface, that the Device could implement and ensure that all implementations follows this interface signature? </p> <p><strong>Example of implementation of typical functions against web browser on pc:</strong></p> <pre><code> $.extend({ Device : function() { this.play = function(url){ console.log("Play: " + url); } this.alert = function(title, message, buttonText) { alert(title + "\n" + message); } this.log = function(message){ console.log(message); } this.error = function(message){ console.error(message); } } }); </code></pre> <p><strong>The same functions against against samsung tv</strong></p> <pre><code>$.extend({ Device : function() { var that = this; var TV = new $.TV(); TV.init(); this.play = function(url){ TV.play(url); that.log("Play: " + url); } this.alert = function(title, message, buttonText) { alert(title + "\n" + message); } this.log = function(message){ //no console on tv, so have to include on in the html $("#console").append('&lt;div class="console-log"&gt;' + message + '&lt;/div&gt;'); if($("#console").children().size()&gt;=5){ $("#console").children().first().remove(); } } this.error = function(message){ $("#console").append('&lt;div class="console-error"&gt;' + message + '&lt;/div&gt;'); if($("#console").children().size()&gt;=5){ $("#console").children().first().remove(); } } } }); </code></pre>
[]
[ { "body": "<p>Sure there is. They are called prototypes.</p>\n\n<p>You use prototypical inheritance.</p>\n\n<p>(Uses <a href=\"https://github.com/Raynos/pd#pd.new\" rel=\"nofollow\"><code>.new</code></a> and <a href=\"https://github.com/Raynos/pd#pd.make\" rel=\"nofollow\"><code>Object.make</code></a> because prototypes are a bit ugly otherwise)</p>\n\n<pre><code>// Device prototype\nvar Device = {\n play: function(url){\n console.log(\"Play: \" + url);\n },\n alert: function(title, message, buttonText) {\n alert(title + \"\\n\" + message);\n },\n log: function(message){\n console.log(message);\n },\n error: function(message){\n console.error(message);\n }\n};\n\nvar TVDevice = Object.make(Device, {\n constructor: function () {\n this.TV = new $.TV();\n this.TV.init();\n },\n play: function (url) {\n Device.play.apply(this, arguments);\n this.TV.play(url); \n },\n log: function (message) {\n //no console on tv, so have to include on in the html\n $(\"#console\").append('&lt;div class=\"console-log\"&gt;' + message + '&lt;/div&gt;');\n if($(\"#console\").children().size()&gt;=5){\n $(\"#console\").children().first().remove();\n }\n },\n error: function(message){ \n $(\"#console\").append('&lt;div class=\"console-error\"&gt;' + message + '&lt;/div&gt;');\n if($(\"#console\").children().size()&gt;=5){\n $(\"#console\").children().first().remove();\n }\n }\n});\n\nvar tvDevice = TVDevice.new();\n</code></pre>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-10-28T11:38:54.437", "Id": "5657", "ParentId": "5656", "Score": "1" } } ]
{ "AcceptedAnswerId": "5657", "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-10-28T11:28:25.697", "Id": "5656", "Score": "-1", "Tags": [ "javascript", "object-oriented" ], "Title": "Common interface for various devices (web, smart tv, tablet, mobile)" }
5656
<p>After finishing this article : <a href="http://coding.smashingmagazine.com/2011/10/27/lessons-from-a-review-of-javascript-code/" rel="nofollow">Lessons From A Review Of JavaScript Code</a></p> <p>I was wondering if my namespace</p> <pre><code>/** * The primary namespace object * @type {Object} * @alias BDDS */ if(!window['BDDS']) { window['BDDS'] = {}; } </code></pre> <p>if attached to the window, is this snippet invalid, according to the following?</p> <blockquote> <p>Problem 9</p> <p>Problem: The namespacing pattern used is technically invalid.</p> <p>Feedback: While namespacing is implemented correctly across the rest of the application, the initial check for namespace existence is invalid. Here’s what you currently have: 1 if ( !MyNamespace ) { 2<br> MyNamespace = { }; 3 }</p> <p>The problem is that !MyNamespace will throw a ReferenceError, because the MyNamespace variable was never declared. A better pattern would take advantage of boolean conversion with an inner variable declaration, as follows: 01 if ( !MyNamespace ) { 02 var MyNamespace = { }; 03 } 04 05 //or 06 var myNamespace = myNamespace || {}; 07 08 // Although a more efficient way of doing this is: 09 // myNamespace || ( myNamespace = {} ); 10 // jsPerf test: <a href="http://jsperf.com/conditional-assignment" rel="nofollow">http://jsperf.com/conditional-assignment</a> 11 12 //or 13 if ( typeof MyNamespace == ’undefined’ ) { 14 var MyNamespace = { }; 15 }</p> <p>This could, of course, be done in numerous other ways. If you’re interested in reading about more namespacing patterns (as well as some ideas on namespace extension), I recently wrote “Essential JavaScript Namespacing Patterns.” Juriy Zaytsev also has a pretty comprehensive post on namespacing patterns.</p> </blockquote>
[ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-10-28T15:19:04.483", "Id": "8565", "Score": "0", "body": "It won't throw a reference error, if that's what you mean." } ]
[ { "body": "<p>No your code is correct.</p>\n\n<p><code>!reference</code> only throws a reference error if its not defined.</p>\n\n<p><code>window</code> is defined and <code>window[\"not_defined\"]</code> just returns <code>undefined</code> for not defined variables.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-10-28T15:16:54.363", "Id": "5666", "ParentId": "5665", "Score": "3" } }, { "body": "<p>I prefer a one liner but it's just a syntax thing:</p>\n\n<pre><code>window.SomeNamespace = SomeNamespace || {};\n</code></pre>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-10-31T18:29:51.583", "Id": "5717", "ParentId": "5665", "Score": "0" } } ]
{ "AcceptedAnswerId": "5666", "CommentCount": "1", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-10-28T15:06:12.177", "Id": "5665", "Score": "2", "Tags": [ "javascript" ], "Title": "Namespacing patterns" }
5665
<p>Here is the problem:</p> <blockquote> <p>A positive integer is called a palindrome if its representation in the decimal system is the same when read from left to right and from right to left. For a given positive integer <code>K</code> of not more than 1000000 digits, write the value of the smallest palindrome larger than <code>K</code> to output. Numbers are always displayed without leading zeros.</p> <p>Input: The first line contains integer <code>t</code>, the number of test cases. Integers <code>K</code> are given in the next <code>t</code> lines.</p> <p>Output: For each <code>K</code>, output the smallest palindrome larger than <code>K</code>. Example</p> <p>Input:</p> <pre><code>2 808 2133 </code></pre> <p>Output:</p> <pre><code>818 2222 </code></pre> </blockquote> <p>Here is my code:</p> <pre><code>// I know it is bad practice to not cater for erroneous input, // however for the purpose of the execise it is omitted import java.io.BufferedReader; import java.io.InputStreamReader; import java.util.Scanner; import java.lang.Exception; import java.math.BigInteger; public class Main { public static void main(String [] args){ try{ Main instance = new Main(); // create an instance to access non-static // variables // Use java.util.Scanner to scan the get the input and initialise the // variable Scanner sc=null; BufferedReader r = new BufferedReader(new InputStreamReader(System.in)); String input = ""; int numberOfTests = 0; String k; // declare any other variables here if((input = r.readLine()) != null){ sc = new Scanner(input); numberOfTests = sc.nextInt(); } for (int i = 0; i &lt; numberOfTests; i++){ if((input = r.readLine()) != null){ sc = new Scanner(input); k=sc.next(); // initialise the remainder of the variables sc.next() instance.palindrome(k); } //if }// for }// try catch (Exception e) { e.printStackTrace(); } }// main public void palindrome(String number){ StringBuffer theNumber = new StringBuffer(number); int length = theNumber.length(); int left, right, leftPos, rightPos; // if incresing a value to more than 9 the value to left (offset) need incrementing int offset, offsetPos; boolean offsetUpdated; // To update the string with new values String insert; boolean hasAltered = false; for(int i = 0; i &lt; length/2; i++){ leftPos = i; rightPos = (length-1) - i; offsetPos = rightPos -1; offsetUpdated = false; // set values at opposite indices and offset left = Integer.parseInt(String.valueOf(theNumber.charAt(leftPos))); right = Integer.parseInt(String.valueOf(theNumber.charAt(rightPos))); offset = Integer.parseInt(String.valueOf(theNumber.charAt(offsetPos))); if(left != right){ // if r &gt; l then offest needs updating if(right &gt; left){ // update and replace right = left; insert = Integer.toString(right); theNumber.replace(rightPos, rightPos + 1, insert); offset++; if (offset == 10) offset = 0; insert = Integer.toString(offset); theNumber.replace(offsetPos, offsetPos + 1, insert); offsetUpdated = true; // then we need to update the value to left again while (offset == 0 &amp;&amp; offsetUpdated){ offsetPos--; offset = Integer.parseInt(String.valueOf(theNumber.charAt(offsetPos))); offset++; if (offset == 10) offset = 0; // replace insert = Integer.toString(offset); theNumber.replace(offsetPos, offsetPos + 1, insert); } // finally incase right and offset are the two middle values left = Integer.parseInt(String.valueOf(theNumber.charAt(leftPos))); if (right != left){ right = left; insert = Integer.toString(right); theNumber.replace(rightPos, rightPos + 1, insert); } }// if r &gt; l else // update and replace right = left; insert = Integer.toString(right); theNumber.replace(rightPos, rightPos + 1, insert); }// if l != r }// for i System.out.println(theNumber.toString()); }// palindrome } </code></pre> <p>Finally my explanation and question:</p> <blockquote> <pre class="lang-none prettyprint-override"><code> My code compares either end and then moves in if left and right are not equal if right is greater than left (increasing right past 9 should increase the digit to its left i.e 09 ---- &gt; 10) and continue to do so if require as for 89999, increasing the right most 9 makes the value 90000 before updating my string we check that the right and left are equal, because in the middle e.g 78849887 we set the 9 --&gt; 4 and increase 4 --&gt; 5, so we must cater for this. </code></pre> </blockquote> <p>The problem is from <a href="http://spoj.pl/" rel="nofollow">spoj.pl</a>, an online judge system. My code works for all the test can provide but when I submit it, I get a time limit exceeded error and my answer is not accepted.</p> <p>Does anyone have any suggestions as to how I can improve my algorithm? While writing this question, I thought that instead of my <code>while (offset == 0 &amp;&amp; offsetUpdated)</code> loop I could use a <code>boolean</code> to to make sure I increment the <code>offset</code> on my next <code>[i]</code> iteration. Confirmation of my change or any suggestion would be appreciated. Also, let me know if I need to make my question clearer. </p>
[ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-10-28T21:12:07.797", "Id": "8578", "Score": "0", "body": "You could significantly speed it up if you convert the digit to an integer by hand instead of parsing it. e.g. `'5' - '0' == 5`." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-10-28T23:53:09.993", "Id": "8584", "Score": "1", "body": "Could speed it up even more if you stopped trying to think of it as an integer at all." } ]
[ { "body": "<p>Among other things:</p>\n\n<ul>\n<li><p>Knowing the right-side chars has exactly one purpose: it tells you whether the number you're making (when palindromized) can be returned as is, or whether you have to find the \"next\" one. So have a flag <code>needsBump</code> that starts out true. Before you copy each char from the left side to the right, set the flag to <code>(left&lt;right || (needsBump &amp;&amp; left==right))</code>. (<em>Don't</em> do any incrementing yet; do that separately once you've determined you need to. Just copy chars.) Once you've gotten to the middle, <code>needsBump</code> will indicate whether you need to bump the number up. (The most significant digits to determine whether you need to bump are the middle ones. If the left one is bigger than the right, then copying from left to right increases the number (making it unnecessary to bump). If it's smaller, then copying will <em>decrease</em> the resulting number, making it necessary to bump -- however, even the smallest change to the least significant digit of the left side has more value than the entirety of the right side of the number. If the left and right digits are equal, then the last decision made stands.) </p></li>\n<li><p>Once you've determined you need to bump the number, you only have to start at the middle digit(s) and work your way out til you no longer have to carry. If you're at the end of the number and still have to carry, prepend and append a '1'.</p></li>\n<li><p>You're doing <em>way</em> too much parsing and stringifying. <code>Integer.toString(...)</code>, <code>String.valueOf(...)</code>, etc create a new string each time -- which in <code>String.valueOf</code>'s case, you're just throwing away as soon as you parse. You're talking about potentially millions of strings. Stop trying to parse the numbers, and just work with them as chars. You should see a pretty big speed boost. </p>\n\n<ul>\n<li>StringBuffer and StringBuilder both have a <code>setCharAt</code> method, which you should be using (considering your \"strings\" always consist of a single char).</li>\n<li><code>offset++; if (offset == 10) offset = 0;</code> becomes <code>if (++offset &gt; '9') offset = '0';</code>, for example.</li>\n<li><code>Integer.parseInt(String.valueOf(theNumber.charAt(leftPos)))</code> becomes just <code>theNumber.charAt(leftPos)</code></li>\n<li>You may be able to get rid of the string buffer/builder altogether and work with a regular old <code>char[]</code>. All of your operations will be in terms of chars, and you shouldn't have any insertion to do in the general case -- except if K == 99...99, in which case you need to return 100...001. But that's easy enough to do with <code>+</code> when you have to.</li>\n</ul></li>\n<li><p>If you stick with string buffers, <code>StringBuilder</code> is generally faster, and should be preferred if you don't require synchronization (which you don't).</p></li>\n</ul>\n\n<p>Style issues:</p>\n\n<ul>\n<li>Declaring every variable you'll ever use at the top of the function is a very Pascal way to do things. Prefer declaring variables as close as possible to their first use. It reduces scope, and along with that, decreases the number of things someone reading your code has to worry about at one time.</li>\n</ul>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-10-29T09:53:05.103", "Id": "8593", "Score": "0", "body": "doesn't `theNumber.charAt(leftPos)` return ath ASCII and not the integer value?" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-10-29T13:20:07.763", "Id": "8598", "Score": "2", "body": "@Mead3000: Yes. But guess what? You *don't need* the integer value. The only thing you're going to do with the char is bump it up by one, and if it's greater than '9', set it to '0' and repeat with the char to the left. None of this requires that you know the integer value of the char. If you insist on integer values, though, either `Character.digit(ch, 10)` or `ch - '0'` will give you that. In either case, you don't need to stringify or parse." } ], "meta_data": { "CommentCount": "2", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-10-28T23:42:49.000", "Id": "5676", "ParentId": "5671", "Score": "6" } }, { "body": "<p>Actually for any Programming Contest Java is slower(very little) than C/C++. If you don't believe you can <a href=\"http://www.codechef.com/problems/PALIN/\" rel=\"nofollow noreferrer\">see it yourself</a>. So I have seen many people using own defined methods to read and write inputs and outputs respectively. You can get the idea from a <a href=\"https://codereview.stackexchange.com/questions/32302/simple-i-o-class-review-request\">post in CR</a>.</p>\n\n<p>Now come to the code I didn't benchmark your palindrome code(sorry for that) but at first glance it's very big and I'm sure it's also hard to maintain. So as a Java programmer this should be your first concern.</p>\n\n<p><em>Enough talk let's write the code</em></p>\n\n<pre><code>import java.io.BufferedReader;\nimport java.io.InputStreamReader;\nimport java.io.IOException;\n\nclass NextPalNo {\n public static void main (String[] args) throws IOException {\n BufferedReader br = new BufferedReader(new InputStreamReader(System.in));\n\n int i = Integer.parseInt(br.readLine());\n\n // we know 1 to 9 all are palindrome numbers\n if(i &lt; 9)\n System.out.println(i+1);\n\n else {\n while(true) {\n i += 1;\n if(isPalindrome(i))\n break;\n }\n System.out.println(i);\n }\n br.close();\n }\n\n public static boolean isPalindrome(int i) {\n String s = String.valueOf(i);\n // easy way to see if a number is palindrome or not ;)\n return new StringBuilder(s).reverse().toString().equals(s);\n }\n}\n</code></pre>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-10-06T18:57:29.647", "Id": "32339", "ParentId": "5671", "Score": "1" } }, { "body": "<p><strong>Step 1 :</strong> Convert the Number String to int.</p>\n<p><strong>Step 2:</strong> Add the line after the input line.</p>\n<p>public static void main(String[] args) {</p>\n<pre><code> Scanner sc= new Scanner(System.in); //System.in is a standard input stream.\n System.out.print(&quot;Enter the Number : &quot;);\n int num= sc.nextInt();\n String numString=String.valueOf(num);\n int l=numString.length();\n int n=2;\n int nextNumber=num+1;\n \n if(l&gt;=2 &amp;&amp; l&lt;=15){\n while(n!=0){\n int tempNextNumber=nextNumber;\n int reversed = 0;\n while(tempNextNumber != 0) {\n int digit = tempNextNumber % 10;\n reversed = reversed * 10 + digit;\n tempNextNumber /= 10;\n }\n if(reversed==nextNumber) {\n System.out.println(reversed);\n break;\n }\n n++;\n nextNumber++; \n } \n }\n}\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-12-21T11:13:50.707", "Id": "500337", "Score": "2", "body": "It seems to me you provided an alternative solution instead of reviewing and improving the one the OP suggested, which thing is against the community rules here." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-12-23T22:54:27.717", "Id": "500580", "Score": "0", "body": "Welcome to Code Review! You have presented an alternative solution, but haven't reviewed the code. Please explain your reasoning (how your solution works and why it is better than the original) so that the author and other readers can learn from your thought process." } ], "meta_data": { "CommentCount": "2", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-12-21T09:16:52.760", "Id": "253736", "ParentId": "5671", "Score": "-1" } } ]
{ "AcceptedAnswerId": "5676", "CommentCount": "2", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-10-28T20:21:16.253", "Id": "5671", "Score": "6", "Tags": [ "java", "algorithm", "programming-challenge", "palindrome", "time-limit-exceeded" ], "Title": "Finding the next palindrome of a number string" }
5671
<p>I decided to try and implement (a version of) the <a href="http://en.wikipedia.org/wiki/Simulated_annealing" rel="nofollow">simulated annealing</a> algorithm using just LINQ, just to see if I could.</p> <p>I'd love it if anybody could see any ways to improve it, or give advice on any cool tricks for doing this kind of thing.</p> <pre><code>var result = (from res in Enumerable.Range(0, 1) let R = new Random() let initial = Enumerable.Range(0, 10).Select(i =&gt; R.Next(-10, 10)) let iterations = Enumerable.Range(0, 100) let Schedule = (Func&lt;int, float&gt;) (X =&gt; 4 + (float)Math.Sin(X)) from iteration in iterations let temperature = Schedule(iteration) let state = Enumerable.Range(0, 10).Select(i =&gt; R.Next(-10, 10)) let DeltaE = state.Sum() - initial.Sum() where DeltaE &gt; 0 || Math.Pow(Math.E, DeltaE / temperature) &gt; R.NextDouble() select state.ToList() ).OrderBy(S =&gt; S.Sum()).First(); </code></pre>
[]
[ { "body": "<p>You have a lot of small errors here.</p>\n\n<ul>\n<li>What is the purpose of <code>from res in Enumerable.Range(0, 1)</code>? It looks like you did it to force some local variables into 'let' queries, which makes no sense to me.</li>\n<li>Instead of using <code>OrderBy(X).First()</code> you should use <code>MinBy(X)</code> (write it yourself if it doesn't exist). There's a significant performance difference.</li>\n<li>The value of <code>initial</code> changes every time it is enumerated. Confusing. (You can cache the results with <code>ToArray</code> or <code>ToList</code> to prevent re-enumerating from running more <code>Random.Next</code> calls)</li>\n<li>Ensure <code>new Random()</code> is only performed once (do it outside the query). The default seed is the current time, which is highly correlated between calls. You're likely to end up with two instances of <code>Random</code> with the exact same seed.</li>\n<li><code>Random.Next(-10, 10)</code> returns values in <code>[-10, +9]</code>. You probably wanted <code>[-10, +10]</code>.</li>\n</ul>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-11-01T16:11:14.460", "Id": "5740", "ParentId": "5677", "Score": "6" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-10-29T03:15:11.423", "Id": "5677", "Score": "7", "Tags": [ "c#", "linq" ], "Title": "Linq version of the simulated annealing algorithm" }
5677
<p>There are quite a few things I am considering:</p> <ol> <li>I will have to check for <code>null</code> values</li> <li>I will have serious trouble persisting it in the database. </li> </ol> <p>How do I improve this or re-factor this for better results?</p> <pre><code>public class ErrorLog { public static void LogError(Exception e) { var exceptionLog = new Dictionary&lt;String, String&gt; { {"Inner Exception", e.InnerException.Message}, {"Message", e.Message}, {"Source", e.Source}, {"StackTrace", e.StackTrace}, {"MethodName",e.TargetSite.Name} }; foreach (KeyValuePair&lt;String, String&gt; kvp in e.Data) exceptionLog.Add(kvp.Key, kvp.Value); } } </code></pre> <p>Update with the new and simpler class </p> <pre><code> public class ErrorLog { public static void LogError(Exception e) { var innerExcpetionMessage = e.InnerException == null ? "Null" : e.InnerException.Message; using (var connection = new SqlConnection(ConfigurationManager.ConnectionStrings["ConnectionString"].ConnectionString)) { var cmd = new SqlCommand("ApplicationErrorLog", connection) { CommandType = System.Data.CommandType.StoredProcedure }; cmd.Parameters.AddWithValue("@Type", e.GetType().Name); cmd.Parameters.AddWithValue("@InnerException", innerExcpetionMessage); cmd.Parameters.AddWithValue("@Message", e.Message); cmd.Parameters.AddWithValue("@Source", e.Source); cmd.Parameters.AddWithValue("@StackTrace", e.StackTrace); cmd.Parameters.AddWithValue("@MethodName", e.TargetSite.Name); connection.Open(); cmd.ExecuteNonQuery(); connection.Close(); } } } } </code></pre> <p>Now what if there is an error in updating this log, how will I log that?</p>
[ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-10-29T12:28:09.667", "Id": "8596", "Score": "1", "body": "I dont know if there is any good way to log logging errors. Interesting question." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-10-29T12:31:33.207", "Id": "8597", "Score": "0", "body": "yes this stumped me as well..if i re-log this it will be an infinite loop and yes it was fun trying that too :P .." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-10-29T22:18:03.780", "Id": "8607", "Score": "1", "body": "I would perhaps log to a file, or to the event log on critical log failure?" } ]
[ { "body": "<p>Why would you have serious trouble with persistance?</p>\n\n<p>Just do null checks for InnerException and TargetSite, rest will be inserted as null or string empty depending on your db setup.</p>\n\n<p>And why not just simplify it as:</p>\n\n<pre><code>var innerExceptionMessage = e.InnerException == null ? string.Empty : e.InnerException.Message;\nvar targetSiteMessage = e.TargetSite == null ? string.Empty : e.TargetSite.Message;\n\nexceptionLog.Add(\"Inner Exception\", innerExceptionMessage);\nexceptionLog.Add(\"Message\", e.Message);\nexceptionLog.Add(\"Source\", e.Source);\nexceptionLog.Add(\"StackTrace\", e.StackTrace);\nexceptionLog.Add(\"MethodName\",targetSiteMessage);\n</code></pre>\n\n<p>Keep it simple :)</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-10-29T12:19:42.923", "Id": "8595", "Score": "0", "body": "upvote for thinkiing like me i have updated the question.." } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-10-29T12:08:05.010", "Id": "5683", "ParentId": "5682", "Score": "5" } }, { "body": "<p>I would pose several suggestions:</p>\n\n<ol>\n<li>First, you should add exception handling code to your logging.\nYou may not want your logging code raising unhandled exceptions (which, depending where it happens in your code, could try to recursively log again). At the very least, it would give you the opportunity to write something out about why it failed and perhaps include the original exception to some backup log destination like system event logs, console output, or a file.</li>\n<li>Second, I would implement your database logging as a listener class for a separate logging class. As this is C#, you may take a look at the <a href=\"http://msdn.microsoft.com/en-us/library/system.diagnostics.tracesource.aspx\" rel=\"nofollow\">TraceSource</a> class. Your database logger would be written to extend TraceListener and then attached to the Listeners collection on the trace object. This gives you the freedom to attach multiple types of listeners that can log to various different outputs, each potentially having different filtering. This can even be done via app.config file.</li>\n<li>You may also want to use <a href=\"http://msdn.microsoft.com/en-us/library/system.dbnull.aspx\" rel=\"nofollow\">DBNull</a> instead of \"Null\" or string.Empty for values which are unavailable, assuming your stored procedure and logging schema support it.</li>\n</ol>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-11-01T05:40:44.583", "Id": "8660", "Score": "0", "body": "the exception handling for my logging code is also a concern , I have mentioned in the comments for the question above that I did face this situation and a suggested alternative was to log the exception in the logging mechanism to a file." } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-10-31T17:47:42.493", "Id": "5716", "ParentId": "5682", "Score": "2" } }, { "body": "<p>You're doing ugly things here. The \"new and simpler class\" tightly couples you to SQL and persistence concerns. A dictionary of String String is an implementation concern, and more likely the basis for a Class. </p>\n\n<p>A better approach would be to go with your original approach, then define a separate method to do the database write that takes in the dictionary/class as a parameter. </p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-11-01T05:34:24.000", "Id": "8659", "Score": "0", "body": "if I am understanding it right you would like me to have one class whose instance would be populated with the exception details I wish to log and then have another method to which I pass the instance and then have it persisted to the database." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-11-02T12:24:35.080", "Id": "8707", "Score": "0", "body": "correct. This would be a cleaner approach that would provide the most adaptability down the line." } ], "meta_data": { "CommentCount": "2", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-10-31T19:28:49.413", "Id": "5719", "ParentId": "5682", "Score": "2" } }, { "body": "<p>Just a quick comment on @Mattias's answer. I think you would want to capture the original exception message if the InnerException is null. If so, you could write:</p>\n\n<pre><code>var innerExceptionMessage = e.InnerException == null ? string.Empty : e.InnerException.Message;\n</code></pre>\n\n<p>as</p>\n\n<pre><code>var innerExceptionMessage = (e.InnerException ?? e).Message ?? string.Empty;\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-11-01T09:36:54.400", "Id": "8661", "Score": "0", "body": "The original exception message is already captured in: exceptionLog.Add(\"Message\", e.Message). An InnerException can be null and therefore should be inserted as null to avoid misleading troubleshooting." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-11-01T16:00:44.817", "Id": "8674", "Score": "0", "body": "Good point, @Mattias" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-11-05T06:53:45.450", "Id": "8807", "Score": "0", "body": "AFAIK in your code the left operand of ?? will never be null ..." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-11-05T20:51:20.593", "Id": "8814", "Score": "0", "body": "@ashutoshraina, thank you, I couldn't recall." } ], "meta_data": { "CommentCount": "4", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-10-31T20:28:50.920", "Id": "5720", "ParentId": "5682", "Score": "1" } } ]
{ "AcceptedAnswerId": "5683", "CommentCount": "3", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-10-29T09:00:55.440", "Id": "5682", "Score": "5", "Tags": [ "c#", "logging" ], "Title": "How do I improve this logging mechanism?" }
5682
<p>I need some feedback here. Due to a weird issue on my server system, the network card disconnects from the network regularly. I'll fix this at a later date. But I wanted to know if the below script can be improved.</p> <p>It's comprised of two files. A python script (<code>autoConnect.py</code>), and a Bash script (<code>checkOnline.sh</code>).</p> <p><code>autoConnect.py</code>:</p> <pre><code>#!/usr/bin/python from subprocess import call, Popen, PIPE, STDOUT import time cmd = './checkOnline.sh' while True: p = Popen(cmd, shell=True, stdin=PIPE, stdout=PIPE, stderr=STDOUT, close_fds=True) if "0" in p.stdout.read(): print time.ctime() + ": Offline" print "Attempting to reconnect..." print "Determining network profile..." cmdTwo = "wicd-cli -ySl | sed -n '2 p' | grep -i paws -c" pTwo = Popen(cmdTwo, shell=True, stdin=PIPE, stdout=PIPE, stderr=STDOUT, close_fds=True) if "1" in pTwo.stdout.read(): print "Network profile is \"1\"" defNum = 1 else: print "Network profile is \"2\"" defNum = 2 print "Connecting to network..." p = Popen(cmd, shell=True, stdin=PIPE, stdout=PIPE, stderr=STDOUT, close_fds=True) while "0" in p.stdout.read(): call("wicd-cli -yn " + defNum + " -c") p = Popen(cmd, shell=True, stdin=PIPE, stdout=PIPE, stderr=STDOUT, close_fds=True) time.sleep(3) if "0" in p.stdout.read(): print "Failed to connect. Trying again..." print "Success, connected to network!" else: print time.ctime() + ": Online" time.sleep(5) </code></pre> <p><code>checkOnline.sh</code>:</p> <pre><code>#!/bin/bash host=google.com (ping -w5 -c3 $host &gt; /dev/null 2&gt;&amp;1) &amp;&amp; echo "1" || (echo "0" &amp;&amp; exit 1) </code></pre> <p>The former is the main file to be run. <code>checkOnline</code> pings <code>google.com</code> 3 times for 5 seconds, if nothing is returned within 5 seconds, it will return <code>0</code>. If it gets something, it returns <code>1</code> into <code>stdout</code>.</p> <p>I wanted to know if this can be improved for what I want it to do (check if the network is online, search for networks, connect, repeat). As of right now, I'm away from my server's physical location and am unable to test it on the current system I'm using, but the script should be functional.</p>
[ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-10-29T16:33:29.003", "Id": "8601", "Score": "0", "body": "Welcome to Code Review, any code you want reviewed needs to be posted in the question itself." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-10-29T16:59:56.430", "Id": "8602", "Score": "0", "body": "Right. Added that." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-10-29T17:30:14.707", "Id": "8603", "Score": "1", "body": "Good. The only thing for future reference is that the plain english description of your algorithm isn't really necessary. We are all coders here, we read code. The english is only helpful if your algorithm is incomphrensible, which isn't the case here." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-10-29T17:32:53.893", "Id": "8604", "Score": "0", "body": "Right. Okay, I'll remove that." } ]
[ { "body": "<ol>\n<li>I'd move the contents of the script into a main function and then use the <code>if __name__ == '__main__'</code> boilerplate to start it.</li>\n<li>I wouldn't use external tools like bash/sed/grep to do additional logic. I'd implement that logic in python.</li>\n<li>I'd use the communicate method for POpen objects rather then reading the stdout attribute</li>\n<li>Your POpens are all very similiar. I'd write a function that takes a command line executes it and returns the standard output</li>\n<li>You check if you are connected in multiple places, write a am_connected() function which returns True or False and use it multiple times</li>\n<li>I'd probably write a function for each external command you execute even if they are not repeated because it'll make your code cleaner. </li>\n</ol>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-10-29T17:28:38.593", "Id": "5687", "ParentId": "5685", "Score": "7" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "4", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-10-29T16:19:13.127", "Id": "5685", "Score": "6", "Tags": [ "python", "performance", "bash" ], "Title": "How to improve my auto-reconnection Python script" }
5685
<p>I want to make a form which looks like this:</p> <pre><code> Column A Column B 1 Textbox AA Textbox BB 2 Textbox AA Textbox BB </code></pre> <p>I've coded it like this:</p> <pre><code> &lt;form id="deps" name="deps" action="" method="POST"&gt; &lt;ul&gt; &lt;li&gt; &lt;span class="er"&gt;&amp;nbsp;&lt;/span&gt; &lt;/li&gt; &lt;br /&gt; &lt;li&gt; &lt;div class="field"&gt;&amp;nbsp;&lt;/div&gt; &lt;div class="field cv"&gt;&lt;label for="met"&gt;A&lt;/label&gt; &lt;/div&gt; &lt;div class="field cv"&gt;&lt;label for="eng"&gt;B&lt;/label&gt; &lt;/div&gt; &lt;/li&gt; &lt;br /&gt; &lt;li&gt; &lt;div class="field head"&gt; &lt;label for="bd"&gt;1&lt;/label&gt; &lt;/div&gt; &lt;div class="field"&gt;&lt;input type="text" name="bdmm" id="bdmm" /&gt; &lt;label for="bdmm"&gt;M&lt;/label&gt; &lt;/div&gt; &lt;div class="field"&gt;&lt;input type="text" name="bdinch" id="bdinch" /&gt; &lt;label for="bdinch"&gt;I&lt;/label&gt; &lt;/div&gt; &lt;/li&gt; &lt;br /&gt; &lt;li&gt; &lt;div class="field head"&gt; &lt;label for="sd"&gt;2&lt;/label&gt; &lt;/div&gt; &lt;div class="field"&gt;&lt;input type="text" name="sdmm" id="sdmm" /&gt; &lt;label for="sdmm"&gt;M&lt;/label&gt; &lt;/div&gt; &lt;div class="field"&gt;&lt;input type="text" name="sdinch" id="sdinch" /&gt; &lt;label for="sdinch"&gt;I&lt;/label&gt; &lt;/div&gt; &lt;/li&gt; &lt;br /&gt; &lt;li&gt; &lt;div class="field head"&gt;&lt;label for="tw"&gt;TW&lt;/label&gt; &lt;/div&gt; &lt;div class="field"&gt;&lt;input type="text" name="twkg" id="twkg" /&gt; &lt;label for="twkg"&gt;KG&lt;/label&gt; &lt;/div&gt; &lt;div class="field"&gt;&lt;input type="text" name="twlbs" id="twlbs" /&gt; &lt;label for="twlbs"&gt;LBS&lt;/label&gt;&lt;/div&gt; &lt;/li&gt; &lt;br /&gt; &lt;/ul&gt; &lt;input type="submit" value="Calculate" onclick="getText();" /&gt; &lt;/form&gt; </code></pre> <p>CSS:</p> <pre><code>form{ padding:3px 0; font-family: Georgia, arial, serif; } ul { list-style: none; } ul li { clear:both; margin:0px; padding:2px 0px; vertical-align: middle; } input{ font-size: 1em; margin: 5px; padding: 5px 8px; border: solid 1px #E5E5E5; outline: 0; width: 100px; } input:focus { border: solid 1px #8CDED7; } label { margin: 2px; padding: 2px; text-align: right; font-size: 1em; text-shadow: 0px 1px 0px #e5e5ee; display: inline-block; } label, input, h4 { letter-spacing: 1.5px; line-height: 20px; font-family: Georgia, 'Times New Roman'; text-transform: uppercase; } .field { float: left; display:inline-block; width: 200px; vertical-align: middle; } .head { padding-top: 5px; } .er { font-size: 1em; margin-right: 10px; padding: 8px; background: #CC0000; color: #F7F7F7; float:right; } .cv { float: left; } input[type=submit]{ margin-top: 35px; padding: 9px; width: auto; text-align: center; cursor:pointer; font-family: Georgia, arial, serif; font-size: 1em; color: #565463; background: #8CDED7; border: 2px solid #8CDED7; text-shadow: 0px 1px 0px #e5e5ee; } </code></pre> <p>This works fine as I want: <a href="http://jsfiddle.net/4kWdQ/">http://jsfiddle.net/4kWdQ/</a>. But I would like to know, <strong>if putting a div in an unordered list is good practice</strong> or not? And anyway I can improve the CSS code?</p>
[]
[ { "body": "<p>Divs of any kind are a bit of a \"lesser evil\" -- they carry no semantic info, and should be used only when (1) you need an element there and (2) there's no semantic equivalent.</p>\n\n<p>In this case, you do have a semantic equivalent. You have rows, columns, headers...data that must be arranged in those rows/columns and have those headers or it doesn't make sense...what you have here is a bona fide table. And it should be coded as one, rather than as a list of divs. (\"Tables bad, CSS good\" applies to layout tables, not tables in general. If you have tabular data, putting it in a table just makes sense.)</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-10-29T21:14:06.637", "Id": "8606", "Score": "0", "body": "Thanks for the feedback. I thought so, I would use a table, but wasn't sure it would apply here for some odd reason." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-11-02T14:54:40.993", "Id": "8710", "Score": "1", "body": "Like any other tag, `<table>` should only be used where it is semantically appropriate. In this case, the data is tabular, so it's absolutely appropriate!" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-11-04T01:39:36.113", "Id": "8779", "Score": "4", "body": "Sadly, tables have gotten such a bad rap the past few years that so many folks don't immediately think of it when it is actually needed! Good question and good answer! (sadly, a table had not come to mind when I reviewed the code)." } ], "meta_data": { "CommentCount": "3", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-10-29T18:35:17.457", "Id": "5688", "ParentId": "5686", "Score": "13" } }, { "body": "<p>And to add to cHao's comment, also using the table for your purpose will help in providing a construct that will give you some predefined spacing or cells to work with that you can add padding/marging via css classes instead of having to add extraneous tags like <code>&lt;br /&gt;</code></p>\n\n<p>A goal I try to set is to have the least or optimal html markup possible so it's clean and to have the css define the look and feel. Hope this helps.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-10-01T17:42:03.890", "Id": "117819", "Score": "1", "body": "It should also be noted that having `<br />` elements between the `<li>` elements is invalid HTML. The only child element allowed for `<ul>` is `<li>`." } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-10-30T05:04:32.473", "Id": "5695", "ParentId": "5686", "Score": "5" } } ]
{ "AcceptedAnswerId": "5688", "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-10-29T16:26:24.943", "Id": "5686", "Score": "8", "Tags": [ "html", "css" ], "Title": "Div in unordered list - good practice?" }
5686
<p>I'm new to Ruby. I normally sling code in C#. What could I do to make this simple Soundex class more Rubyesque?</p> <pre><code>class Surname attr_accessor :value def initialize(input) @value = input end def soundex result = '' @value.chars.drop(1).each do |s| number = soundex_value(s).to_s result &amp;lt;&amp;lt; number unless result[-1,1] == number end @value.chars.first &amp;lt;&amp;lt; result.ljust(3,'0') end def soundex_value(s) case s when /[bfpv]/ 1 when /[cgjkqsxz]/ 2 when /[dt]/ 3 when /l/ 4 when /[mn]/ 5 when /r/ 6 else '' end end end def print_name(input) surname = Surname.new(input) puts(surname.value + ' =&gt; ' + surname.soundex) end ['Smith', 'Johnson', 'Williams', 'Jones', 'Brown'].each do |s| print_name s end </code></pre> <p>The output is: </p> <pre> Smith => S530 Johnson => J525 Williams => W452 Jones => J520 Brown => B650 </pre>
[]
[ { "body": "<p>First of all: install RSpec and write some tests if you haven't already. That will make sure you don't break anything while refactoring. (And then do all development test-first if you don't already.) Also, there are existing Ruby Soundex implementations. You might want to use one instead of writing your own.</p>\n\n<p>For the rest of it:</p>\n\n<ul>\n<li><p>I think your implementation is incorrect! Try this: does \"Atchison\" yield \"A322\"? It should.</p></li>\n<li><p>Why do you need a separate class for <code>Surname</code>? It may make sense to have a module with the Soundex algorithm that either gets mixed into Strings as necessary or calls the method with function syntax (e.g. <code>Soundex::encode last_name</code>). I'm not sure.</p></li>\n<li><p>If you <em>do</em> need a separate class for <code>Surname</code>, perhaps it should extend <code>String</code>, or delegate to its String member, so that you can easily call String methods on it. But I think a plain old String with a module included would work better.</p></li>\n<li><p><code>@value</code> seems like a nondescriptive name. Perhaps <code>@name</code> or something?</p></li>\n<li><p>You may not need the <code>attr_accessor</code>, since <code>@surname.to_s</code> would be more idiomatic than <code>@surname.value</code>.</p></li>\n<li><p>Instead of that <code>@value.chars.drop(1).each</code> block, you may want to use <code>map</code>.</p></li>\n<li><p>Regular expressions may not be the right thing for the <code>case</code> expression; you may want <code>when 'b', 'p'</code> instead. Or you may want to drop the <code>case</code> entirely and have a hash: <code>{'b' =&gt; 1, 'c' =&gt; 2, 'd' =&gt; 3, 'f' =&gt; 1, ... }</code>. Or I seem to recall that <code>Array#assoc</code> might be useful here...</p></li>\n<li><p>Since you're calling <code>to_s</code> on <code>soundex_value</code> the only time you use it, maybe it should just return a string in the first place.</p></li>\n</ul>\n\n<p>Good luck! I hope these suggestions are helpful.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-11-01T16:08:35.447", "Id": "8675", "Score": "0", "body": "Yes, very helpful. RSpec is an excellent suggestion, as is map. I am blind to those features I don't know exist. :)" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-11-01T16:19:09.677", "Id": "8678", "Score": "0", "body": "You are also correct that there is a bug in my algorithm." } ], "meta_data": { "CommentCount": "2", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-11-01T15:38:53.720", "Id": "5739", "ParentId": "5689", "Score": "1" } }, { "body": "<p>Per your request, your code converted to the Ruby way perhaps would be as follows.</p>\n\n<p>A small point: in our output, in the Ruby world, we would avoid the <strong>=></strong> <a href=\"http://en.wikipedia.org/w/index.php?title=Fat_comma&amp;oldid=546331414\" rel=\"nofollow noreferrer\">fat comma</a> which Rubyists (at least in the English-speaking world) call a 'hash-rocket' because:</p>\n\n<ul>\n<li>It reads like Ruby's (<a href=\"https://stackoverflow.com/questions/10004158/is-hash-rocket-deprecated\">older</a>) hash accessing syntax.</li>\n<li>In Ruby language documentation (e.g., see <a href=\"http://www.ruby-doc.org/core-2.0/Array.html\" rel=\"nofollow noreferrer\">Array</a>), the similar <strong>#=></strong>, comprising a hash to introduce a comment, followed by a hash-rocket (presumably, this gave us the name), shows us the result (or value) of an <em>individual</em> line of code—the two meanings conflict.</li>\n</ul>\n\n<p>BTW, we also would avoid <strong>-></strong>, dash-greater-than, which in Ruby (syntax) generates a lambda.\n</p>\n\n<pre><code>class Soundex &lt; String\n IGNORED_BEGINNING_LENGTH = 1\n MINIMUM_LENGTH = 3\n\n CASES = [ # Keep order.\n /[bfpv]/,\n /[cgjkqsxz]/,\n /[dt]/,\n /l/,\n /[mn]/,\n /r/,\n ]\n CASES_LENGTH = CASES.length\n\n def initialize(surname)\n a = surname.split ''\n kept = a.take(IGNORED_BEGINNING_LENGTH).join ''\n indices = a.drop(IGNORED_BEGINNING_LENGTH).map do |e|\n (0...CASES_LENGTH).detect{|i| e =~ (CASES.at i)}\n end.compact\n# Adjust to one-based notation; collapse repetition; right-pad with zeros.\n digits = indices.map(&amp;:succ).join('').squeeze.ljust MINIMUM_LENGTH, '0'\n super kept + digits\n end\n\n def self.show(s) \"#{s}: #{new s}\" end\nend\n\nnames = %w[Smith Johnson Williams Jones Brown Atchison]\nnames.each{|s| puts Soundex.show s}\n</code></pre>\n\n<p>gives the results</p>\n\n<pre>\nSmith: S530\nJohnson: J525\nWilliams: W452\nJones: J520\nBrown: B650\nAtchison: A325\n</pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-01-24T19:22:14.260", "Id": "12895", "Score": "0", "body": "Thank you! I'll study what you did here and fill in some holes in my Ruby knowledge." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-02-01T06:27:05.453", "Id": "13324", "Score": "0", "body": "Rather than thanking me, would you consider voting up or accepting my answer? :)" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-02-13T15:29:31.613", "Id": "412778", "Score": "0", "body": "I believe that `=>` is known as a “hashrocket” because it’s used in hashes (associative arrays), not because it’s associated with the number sign. And there’s nothing wrong with using it in sample output IMHO." } ], "meta_data": { "CommentCount": "3", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-01-22T01:51:49.807", "Id": "8180", "ParentId": "5689", "Score": "3" } } ]
{ "AcceptedAnswerId": "8180", "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-10-29T20:52:06.693", "Id": "5689", "Score": "5", "Tags": [ "algorithm", "ruby" ], "Title": "Ruby implementation of Soundex algorithm" }
5689
<p>I created a simple function for swiftmailer to send two different messages for support and client. Not sure i did it the rigth way as I am using two different instances for message and one mailer instance. Everything works just fine but am I doing it the right way or I have to create separate mailer instance for each message? Here is my code, if someone could point out if it is ok or could be done better:</p> <pre><code>&lt;?php if ((isset($_POST['email'])) &amp;&amp; (strlen(trim($_POST['email'])) &gt; 0)) { $email = stripslashes(strip_tags($_POST['email'])); } else {$email = 'No data';} require_once '/home/sitename/public_html/inc/swift/lib/swift_required.php'; function send_email($info){ $transport = Swift_MailTransport::newInstance(); $mailer = Swift_Mailer::newInstance($transport); //Create the message for support $message = Swift_Message::newInstance() -&gt;setSubject('Subject 1') -&gt;setFrom(array('info@domain.com' =&gt; 'Info')) -&gt;setTo(array( 'name1@domain.com', 'name2@domain.com', )) -&gt;setBody($info['message_support'],'text/html'); //Create the message for client $message2 = Swift_Message::newInstance() -&gt;setSubject('Subject 2') -&gt;setFrom(array('info@domain.com' =&gt; 'Info')) -&gt;setTo(array( $info['email'] )) -&gt;setBody($info['message_client'],'text/html'); if ($mailer-&gt;send($message) &amp;&amp; $mailer-&gt;send($message2)) return true; else return false; } $info = array( 'email' =&gt; $email, 'message_support' =&gt; '&lt;p&gt;Dear Support&lt;/p&gt;&lt;p&gt;Hello World&lt;/p&gt;', 'message_client' =&gt; '&lt;p&gt;Dear Client&lt;/p&gt;&lt;p&gt;Hello World&lt;/p&gt;' ); if (send_email($info)) { header("Location:/thank-you"); } else { header("Location:/error"); } ?&gt; </code></pre>
[]
[ { "body": "<p><sub>Note: this is intended to be a Community wiki since it was taken from a deleted answer by <a href=\"https://codereview.stackexchange.com/users/4673/yannis\">yannis</a>; The suggestion to do this was <a href=\"https://codereview.meta.stackexchange.com/a/10625/120114\">here</a></sub></p>\n<hr />\n<p>Using two message instances is fine as is most of your code. There is one major issue though, you don't validate the email, you just check if the <code>$_POST</code> variable was set and is not empty but you don't check if the email format is &quot;name@domain.tld&quot;. The simplest thing you could do is:</p>\n<pre><code>$email = \n isset($_POST[&quot;email&quot;]) &amp;&amp; !empty($_POST[&quot;email&quot;]) \n ? filter_var($email, filter_var($_POST[&quot;email&quot;], FILTER_SANITIZE_EMAIL) )\n : &quot;No data&quot;;\n</code></pre>\n<p>The <a href=\"http://www.php.net/manual/en/book.filter.php\" rel=\"nofollow noreferrer\">filter extension</a> greatly helps you sanitize and validate variables. It's on by default since PHP 5.2, if you are working on an earlier version, you can substitute it with an email validation regular expression. By the way, if you are unfamiliar with the conditional format I'm using, it's called <a href=\"http://php.net/manual/en/language.operators.comparison.php\" rel=\"nofollow noreferrer\">ternary operator</a> and it goes something like this:</p>\n<pre><code>$variable = \n ( condition )\n ? ( value if condition is true )\n : ( value if condition is false );\n</code></pre>\n<p>When actually sending the email, you should do:</p>\n<pre><code>if( $email != &quot;No Data&quot; &amp;&amp; send_email($info) ) {\n header(&quot;Location:/thank-you&quot;); \n} else {\n header(&quot;Location:/error&quot;);\n}\n</code></pre>\n<p>That way and since the check <code>$email != &quot;No Data&quot;</code> is first, <code>send_email($info)</code> will never execute for a missing or invalid email. So the 2 instances of a hefty library will never instantiate needlessly.</p>\n<p>Lastly, a very minor change, that might be considered a matter of style. Here:</p>\n<pre><code>if ($mailer-&gt;send($message) &amp;&amp; $mailer-&gt;send($message2)) \n return true;\nelse\n return false; \n</code></pre>\n<p>You are returning a <code>boolean</code> value based on the <code>boolean</code> return of <code>$mailer-&gt;send($message) &amp;&amp; $mailer-&gt;send($message2)</code>. You can simply rewrite as:</p>\n<pre><code>return $mailer-&gt;send($message) &amp;&amp; $mailer-&gt;send($message2);\n</code></pre>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-02-02T17:12:37.920", "Id": "255515", "ParentId": "5690", "Score": "2" } } ]
{ "AcceptedAnswerId": "255515", "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-10-29T23:35:02.140", "Id": "5690", "Score": "5", "Tags": [ "php", "php5" ], "Title": "php swiftmailer two message instances with one mailer instance?" }
5690
<p>I got this code working with the <a href="http://plugins.jquery.com/project/countdown2" rel="nofollow">jQuery Countdown Plugin</a> to take a string input and output a countdown in a div. Is there a better way of implementing this? </p> <p><a href="http://jsfiddle.net/RN2zj/2/" rel="nofollow">JSFiddler</a></p> <p>HTML</p> <pre><code>&lt;div id="defaultCountdown" class="arg"&gt;Here&lt;/div&gt; </code></pre> <p>Script</p> <pre><code>function stringToCountdown(element,str){ /* Parse the String */ var hh = parseInt(str.substr(0,2),10); var mm = parseInt(str.substr(2,2),10); var ss = parseInt(str.substr(4,2),10); var parity = parseInt(str.substr(4,2),10); var austDay = new Date(); austDay = new Date( austDay.getFullYear() , austDay.getMonth(), austDay.getDate(),austDay.getHours()+hh, austDay.getMinutes()+mm, austDay.getSeconds()+ss ); $('#defaultCountdown').countdown({until:austDay , compact: true,format: 'dHMs',expiryText: 'No More Counter for you'}); } $(function () { stringToCountdown('#defaultCountdown6','000005'); }); </code></pre> <p>Should I rewrite this to make it simpler and faster?</p>
[]
[ { "body": "<p>You may combine <code>var</code> statements and put them top of your function. Strip unused variables like <code>parity</code> and use <code>element</code> variable instead of using <code>#defaultCountdown</code> directly. And lastly, a little formatting will make your code much readable. <a href=\"http://jsfiddle.net/karalamalar/RN2zj/8/\" rel=\"nofollow\">Here</a> is the result.</p>\n\n<p>If you're trying to accomplish relative countdown, plugin itself supports it. I also put an example to show how to do it.</p>\n\n<pre><code>function stringToCountdown(selector, str){\n var hh = parseInt(str.substr(0,2), 10),\n mm = parseInt(str.substr(2,2), 10),\n ss = parseInt(str.substr(4,2), 10),\n austDay = new Date();\n\n austDay = new Date(\n austDay.getFullYear(),\n austDay.getMonth(),\n austDay.getDate(),\n austDay.getHours() + hh,\n austDay.getMinutes() + mm,\n austDay.getSeconds() + ss\n );\n\n $(selector).countdown({\n until: austDay,\n compact: true,\n format: 'dHMs',\n expiryText: 'No More Counter for you'\n });\n}\n\n$(function () { \n stringToCountdown('#defaultCountdown','000010');\n});\n</code></pre>\n\n<p>And this is less readable version. There is no extra variable. So it may run a little bit faster.</p>\n\n<pre><code>function stringToCountdown(selector, str){\n var austDay = new Date();\n $(selector).countdown({\n until: new Date(\n austDay.getFullYear(),\n austDay.getMonth(),\n austDay.getDate(),\n austDay.getHours() + parseInt(str.substr(0,2), 10),\n austDay.getMinutes() + parseInt(str.substr(2,2), 10),\n austDay.getSeconds() + parseInt(str.substr(4,2), 10)\n ),\n compact: true,\n format: 'dHMs',\n expiryText: 'No More Counter for you'\n });\n}\n\n$(function () { \n stringToCountdown('#defaultCountdown','000010');\n});\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-05-22T08:28:41.583", "Id": "88728", "Score": "0", "body": "Performance is just not an issue here. The first version is clearly better. I would go one step further and create two `Date` objects for clarity: one called `now` and one called `end`." } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-10-31T09:30:44.593", "Id": "5711", "ParentId": "5691", "Score": "3" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-10-29T23:42:17.840", "Id": "5691", "Score": "4", "Tags": [ "javascript", "jquery", "strings", "datetime", "timer" ], "Title": "Outputting a countdown in a div" }
5691
<p>I have a <a href="http://swolepersonaltraining.com/beta/?page_id=67" rel="noreferrer">dynamic order page</a> which has to update multiple elements when a value is changed. </p> <p>Here is the main function that does that. Note it only updates the values if they are different from what is already there. So for example it doesn't update with a checkmark, if there already is a check mark there.</p> <pre><code> function reput(element, content, animate) { target = $(element); target_check = target.html().indexOf("check_mark"); //checks if target already has a check mark content_check = content.indexOf("check_mark"); //checks if new value has check mark th = target.html(); if(th == content || (target_check == content_check &amp;&amp; target_check != -1)) { return true; //if any of the values match, then don't do anything } else { //values didn't match so update the element if (animate || animate == undefined) target.fadeOut(100).empty().fadeIn(200).append(content); else target.empty().append(content); } } </code></pre> <p>This function is called multiple times in several places like so:</p> <pre><code>reput(("#email"), (cp.email)); reput(("#chat"), (cp.chat)); reput(("#voice"), (cp.voice)); reput(("#member"), (cp.member)); reput(("#price"), ('$' + cp.price), false); </code></pre> <p>What would be the best way to improve the load time of this function? Having it accept an array, iterating through it and appending the values one by one? Would it save resources to just use fadeIn instead of fadeOut/fadeIn? </p> <p>Bonus question: What are some ways to test how much processing power your script/function is using up?</p>
[ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-11-04T16:49:06.617", "Id": "62827", "Score": "0", "body": "jQuery 1.7 better handles animations with increased performance. You could try updating jQuery if it helps. http://blog.jquery.com/2011/11/03/jquery-1-7-released/" } ]
[ { "body": "<p>for optimizing this function - will be better if you'll give an example of working code. Just upload some sample to <a href=\"http://jsfiddle.net/\" rel=\"noreferrer\">http://jsfiddle.net/</a>.</p>\n\n<p>Anyway, to reduce the load on any animations, use default CSS transitions.</p>\n\n<pre><code>-moz-transition: all 0.5s ease-out;\n-o-transition: all 0.5s ease-out;\n-webkit-transition: all 0.5s ease-out;\ntransition: all 0.5s ease-out;\n</code></pre>\n\n<p>And then change the opacity from 1 to 0 or change class. Here is an working example <a href=\"http://jsfiddle.net/x6fxx/\" rel=\"noreferrer\">http://jsfiddle.net/x6fxx/</a> , works much faster then jquery's script, this one is css based solution which is using hardware acceleration ( modern browsers ).</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-10-30T09:52:24.170", "Id": "5698", "ParentId": "5692", "Score": "7" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "1", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-10-30T00:36:06.353", "Id": "5692", "Score": "5", "Tags": [ "javascript", "jquery", "performance" ], "Title": "How to reduce load when fading in multiple elements in jQuery" }
5692
<p>This is the first time I have written Unit Tests. I am testing code that I have already written and would like to move to TDD once I have managed to get units written for everything that is already in my application. </p> <p>Just wanted to be sure that the tests that I have written look good, or if there is a different approach I should be taken. These are for CakePHP 2.0</p> <pre><code>&lt;?php App::uses('Player', 'Model'); class PlayerTestCase extends CakeTestCase { public $fixtures = array('app.player', 'app.club', 'app.position', 'app.stat', 'app.selection', 'app.period', 'app.league', 'app.draft', 'app.team'); public function setup() { parent::setUp(); $this-&gt;Player = ClassRegistry::init('Player'); } /** * testGetPlayers method * * @return void */ function testGetPlayers() { //Specific Player, All Stats, No Position Exclusion $result = $this-&gt;Player-&gt;GetPlayers(11, 'all', null); $expected = array( 'Player' =&gt; array ('id' =&gt; 11, 'name' =&gt; 'Forward 2', 'status' =&gt; 'doubtful', 'note' =&gt; '', 'club_id' =&gt; '2', 'position_id' =&gt; '4'), 'Club' =&gt; array ('id' =&gt; 2, 'name' =&gt; 'Club 2', 'abbreviation' =&gt; 'clb2'), 'Position' =&gt; array ('id' =&gt; 4, 'name' =&gt; 'Forward', 'abbreviation' =&gt; 'fw', 'min' =&gt; 1, 'max' =&gt; 3, 'need' =&gt; 2, 'db_abbr' =&gt; 'fw'), 'Stat' =&gt; array ( array ('id' =&gt; 11, 'rank' =&gt; 11, 'goals' =&gt; 0, 'saves' =&gt; 0, 'penaltysaves' =&gt; 0, 'assists' =&gt; 0, 'cleansheet' =&gt; 0, 'redcard' =&gt; 0, 'yellowcard' =&gt; 0, 'foulsconc' =&gt; 0, 'foulswon' =&gt; 0, 'tackleslost' =&gt; 0, 'tackleswon' =&gt; 0, 'shotontarget' =&gt; 0, 'totalshot' =&gt; 0, 'appearances' =&gt; 0, 'attcreated' =&gt; 0, 'totalpasses' =&gt; 0, 'accpasses' =&gt; 0, 'minutesplayed' =&gt; 0, 'conceded' =&gt; 0, 'player_id' =&gt; '11', 'team_id' =&gt; 0, 'period_id' =&gt; '1'), array ('id' =&gt; 23, 'rank' =&gt; 11, 'goals' =&gt; 0, 'saves' =&gt; 0, 'penaltysaves' =&gt; 0, 'assists' =&gt; 0, 'cleansheet' =&gt; 0, 'redcard' =&gt; 0, 'yellowcard' =&gt; 0, 'foulsconc' =&gt; 0, 'foulswon' =&gt; 0, 'tackleslost' =&gt; 0, 'tackleswon' =&gt; 0, 'shotontarget' =&gt; 0, 'totalshot' =&gt; 0, 'appearances' =&gt; 0, 'attcreated' =&gt; 0, 'totalpasses' =&gt; 0, 'accpasses' =&gt; 0, 'minutesplayed' =&gt; 0, 'conceded' =&gt; 0, 'player_id' =&gt; '11', 'team_id' =&gt; 0, 'period_id' =&gt; '2') ) ); $this-&gt;assertEquals($expected, $result); //Specific Player, No Stats, No Position Exclusion $result = $this-&gt;Player-&gt;GetPlayers(10, false, null); $expected = array( 'Player' =&gt; array ('id' =&gt; 10, 'name' =&gt; 'Forward 1', 'status' =&gt; 'available', 'note' =&gt; '', 'club_id' =&gt; '1', 'position_id' =&gt; '4'), 'Club' =&gt; array ('id' =&gt; 1, 'name' =&gt; 'Club 1', 'abbreviation' =&gt; 'clb1'), 'Position' =&gt; array ('id' =&gt; 4, 'name' =&gt; 'Forward', 'abbreviation' =&gt; 'fw', 'min' =&gt; 1, 'max' =&gt; 3, 'need' =&gt; 2, 'db_abbr' =&gt; 'fw') ); $this-&gt;assertEquals($expected, $result); //No Specific Player, No Stats, Position Exclusion (Array) $result = $this-&gt;Player-&gt;GetPlayers(null, false, array('def', 'mid', 'fw')); $expected = array( array( 'Player' =&gt; array ('id' =&gt; 1, 'name' =&gt; 'Goalkeeper 1', 'status' =&gt; 'available', 'note' =&gt; '', 'club_id' =&gt; '1', 'position_id' =&gt; '1'), 'Club' =&gt; array ('id' =&gt; 1, 'name' =&gt; 'Club 1', 'abbreviation' =&gt; 'clb1'), 'Position' =&gt; array ('id' =&gt; 1, 'name' =&gt; 'Goalkeeper', 'abbreviation' =&gt; 'gk', 'min' =&gt; 1, 'max' =&gt; 1, 'need' =&gt; 1, 'db_abbr' =&gt; 'gk') ), array( 'Player' =&gt; array ('id' =&gt; 2, 'name' =&gt; 'Goalkeeper 2', 'status' =&gt; 'doubtful', 'note' =&gt; '', 'club_id' =&gt; '2', 'position_id' =&gt; '1'), 'Club' =&gt; array ('id' =&gt; 2, 'name' =&gt; 'Club 2', 'abbreviation' =&gt; 'clb2'), 'Position' =&gt; array ('id' =&gt; 1, 'name' =&gt; 'Goalkeeper', 'abbreviation' =&gt; 'gk', 'min' =&gt; 1, 'max' =&gt; 1, 'need' =&gt; 1, 'db_abbr' =&gt; 'gk') ), array( 'Player' =&gt; array ('id' =&gt; 3, 'name' =&gt; 'Goalkeeper 3', 'status' =&gt; 'unavailable', 'note' =&gt; '', 'club_id' =&gt; '3', 'position_id' =&gt; '1'), 'Club' =&gt; array ('id' =&gt; 3, 'name' =&gt; 'Club 3', 'abbreviation' =&gt; 'clb3'), 'Position' =&gt; array ('id' =&gt; 1, 'name' =&gt; 'Goalkeeper', 'abbreviation' =&gt; 'gk', 'min' =&gt; 1, 'max' =&gt; 1, 'need' =&gt; 1, 'db_abbr' =&gt; 'gk') ) ); $this-&gt;assertEquals($expected, $result); //No Specific Player, Default Stats, Position Exclusion (String) $result = $this-&gt;Player-&gt;GetPlayers(null, true, 'gk'); $expected = array( array( 'Player' =&gt; array ('id' =&gt; 4, 'name' =&gt; 'Defender 1', 'status' =&gt; 'available', 'note' =&gt; '', 'club_id' =&gt; '1', 'position_id' =&gt; '2'), 'Club' =&gt; array ('id' =&gt; 1, 'name' =&gt; 'Club 1', 'abbreviation' =&gt; 'clb1'), 'Position' =&gt; array ('id' =&gt; 2, 'name' =&gt; 'Defender', 'abbreviation' =&gt; 'def', 'min' =&gt; 3, 'max' =&gt; 5, 'need' =&gt; 4, 'db_abbr' =&gt; 'def'), 'Stat' =&gt; array ('id' =&gt; 4, 'rank' =&gt; 4, 'goals' =&gt; 0, 'saves' =&gt; 0, 'penaltysaves' =&gt; 0, 'assists' =&gt; 0, 'cleansheet' =&gt; 0, 'redcard' =&gt; 0, 'yellowcard' =&gt; 0, 'foulsconc' =&gt; 0, 'foulswon' =&gt; 0, 'tackleslost' =&gt; 0, 'tackleswon' =&gt; 0, 'shotontarget' =&gt; 0, 'totalshot' =&gt; 0, 'appearances' =&gt; 0, 'attcreated' =&gt; 0, 'totalpasses' =&gt; 0, 'accpasses' =&gt; 0, 'minutesplayed' =&gt; 0, 'conceded' =&gt; 0, 'player_id' =&gt; '4', 'team_id' =&gt; 0, 'period_id' =&gt; '1') ), array( 'Player' =&gt; array ('id' =&gt; 5, 'name' =&gt; 'Defender 2', 'status' =&gt; 'doubtful', 'note' =&gt; '', 'club_id' =&gt; '2', 'position_id' =&gt; '2'), 'Club' =&gt; array ('id' =&gt; 2, 'name' =&gt; 'Club 2', 'abbreviation' =&gt; 'clb2'), 'Position' =&gt; array ('id' =&gt; 2, 'name' =&gt; 'Defender', 'abbreviation' =&gt; 'def', 'min' =&gt; 3, 'max' =&gt; 5, 'need' =&gt; 4, 'db_abbr' =&gt; 'def'), 'Stat' =&gt; array ('id' =&gt; 5, 'rank' =&gt; 5, 'goals' =&gt; 0, 'saves' =&gt; 0, 'penaltysaves' =&gt; 0, 'assists' =&gt; 0, 'cleansheet' =&gt; 0, 'redcard' =&gt; 0, 'yellowcard' =&gt; 0, 'foulsconc' =&gt; 0, 'foulswon' =&gt; 0, 'tackleslost' =&gt; 0, 'tackleswon' =&gt; 0, 'shotontarget' =&gt; 0, 'totalshot' =&gt; 0, 'appearances' =&gt; 0, 'attcreated' =&gt; 0, 'totalpasses' =&gt; 0, 'accpasses' =&gt; 0, 'minutesplayed' =&gt; 0, 'conceded' =&gt; 0, 'player_id' =&gt; '5', 'team_id' =&gt; 0, 'period_id' =&gt; '1') ), array( 'Player' =&gt; array ('id' =&gt; 6, 'name' =&gt; 'Defender 3', 'status' =&gt; 'unavailable', 'note' =&gt; '', 'club_id' =&gt; '3', 'position_id' =&gt; '2'), 'Club' =&gt; array ('id' =&gt; 3, 'name' =&gt; 'Club 3', 'abbreviation' =&gt; 'clb3'), 'Position' =&gt; array ('id' =&gt; 2, 'name' =&gt; 'Defender', 'abbreviation' =&gt; 'def', 'min' =&gt; 3, 'max' =&gt; 5, 'need' =&gt; 4, 'db_abbr' =&gt; 'def'), 'Stat' =&gt; array ('id' =&gt; 6, 'rank' =&gt; 6, 'goals' =&gt; 0, 'saves' =&gt; 0, 'penaltysaves' =&gt; 0, 'assists' =&gt; 0, 'cleansheet' =&gt; 0, 'redcard' =&gt; 0, 'yellowcard' =&gt; 0, 'foulsconc' =&gt; 0, 'foulswon' =&gt; 0, 'tackleslost' =&gt; 0, 'tackleswon' =&gt; 0, 'shotontarget' =&gt; 0, 'totalshot' =&gt; 0, 'appearances' =&gt; 0, 'attcreated' =&gt; 0, 'totalpasses' =&gt; 0, 'accpasses' =&gt; 0, 'minutesplayed' =&gt; 0, 'conceded' =&gt; 0, 'player_id' =&gt; '6', 'team_id' =&gt; 0, 'period_id' =&gt; '1') ), array( 'Player' =&gt; array ('id' =&gt; 7, 'name' =&gt; 'Midfielder 1', 'status' =&gt; 'available', 'note' =&gt; '', 'club_id' =&gt; '1', 'position_id' =&gt; '3'), 'Club' =&gt; array ('id' =&gt; 1, 'name' =&gt; 'Club 1', 'abbreviation' =&gt; 'clb1'), 'Position' =&gt; array ('id' =&gt; 3, 'name' =&gt; 'Midfielder', 'abbreviation' =&gt; 'mid', 'min' =&gt; 2, 'max' =&gt; 5, 'need' =&gt; 4, 'db_abbr' =&gt; 'mid'), 'Stat' =&gt; array ('id' =&gt; 7, 'rank' =&gt; 7, 'goals' =&gt; 0, 'saves' =&gt; 0, 'penaltysaves' =&gt; 0, 'assists' =&gt; 0, 'cleansheet' =&gt; 0, 'redcard' =&gt; 0, 'yellowcard' =&gt; 0, 'foulsconc' =&gt; 0, 'foulswon' =&gt; 0, 'tackleslost' =&gt; 0, 'tackleswon' =&gt; 0, 'shotontarget' =&gt; 0, 'totalshot' =&gt; 0, 'appearances' =&gt; 0, 'attcreated' =&gt; 0, 'totalpasses' =&gt; 0, 'accpasses' =&gt; 0, 'minutesplayed' =&gt; 0, 'conceded' =&gt; 0, 'player_id' =&gt; '7', 'team_id' =&gt; 0, 'period_id' =&gt; '1') ), array( 'Player' =&gt; array ('id' =&gt; 8, 'name' =&gt; 'Midfielder 2', 'status' =&gt; 'doubtful', 'note' =&gt; '', 'club_id' =&gt; '2', 'position_id' =&gt; '3'), 'Club' =&gt; array ('id' =&gt; 2, 'name' =&gt; 'Club 2', 'abbreviation' =&gt; 'clb2'), 'Position' =&gt; array ('id' =&gt; 3, 'name' =&gt; 'Midfielder', 'abbreviation' =&gt; 'mid', 'min' =&gt; 2, 'max' =&gt; 5, 'need' =&gt; 4, 'db_abbr' =&gt; 'mid'), 'Stat' =&gt; array ('id' =&gt; 8, 'rank' =&gt; 8, 'goals' =&gt; 0, 'saves' =&gt; 0, 'penaltysaves' =&gt; 0, 'assists' =&gt; 0, 'cleansheet' =&gt; 0, 'redcard' =&gt; 0, 'yellowcard' =&gt; 0, 'foulsconc' =&gt; 0, 'foulswon' =&gt; 0, 'tackleslost' =&gt; 0, 'tackleswon' =&gt; 0, 'shotontarget' =&gt; 0, 'totalshot' =&gt; 0, 'appearances' =&gt; 0, 'attcreated' =&gt; 0, 'totalpasses' =&gt; 0, 'accpasses' =&gt; 0, 'minutesplayed' =&gt; 0, 'conceded' =&gt; 0, 'player_id' =&gt; '8', 'team_id' =&gt; 0, 'period_id' =&gt; '1') ), array( 'Player' =&gt; array ('id' =&gt; 9, 'name' =&gt; 'Midfielder 3', 'status' =&gt; 'unavailable', 'note' =&gt; '', 'club_id' =&gt; '3', 'position_id' =&gt; '3'), 'Club' =&gt; array ('id' =&gt; 3, 'name' =&gt; 'Club 3', 'abbreviation' =&gt; 'clb3'), 'Position' =&gt; array ('id' =&gt; 3, 'name' =&gt; 'Midfielder', 'abbreviation' =&gt; 'mid', 'min' =&gt; 2, 'max' =&gt; 5, 'need' =&gt; 4, 'db_abbr' =&gt; 'mid'), 'Stat' =&gt; array ('id' =&gt; 9, 'rank' =&gt; 9, 'goals' =&gt; 0, 'saves' =&gt; 0, 'penaltysaves' =&gt; 0, 'assists' =&gt; 0, 'cleansheet' =&gt; 0, 'redcard' =&gt; 0, 'yellowcard' =&gt; 0, 'foulsconc' =&gt; 0, 'foulswon' =&gt; 0, 'tackleslost' =&gt; 0, 'tackleswon' =&gt; 0, 'shotontarget' =&gt; 0, 'totalshot' =&gt; 0, 'appearances' =&gt; 0, 'attcreated' =&gt; 0, 'totalpasses' =&gt; 0, 'accpasses' =&gt; 0, 'minutesplayed' =&gt; 0, 'conceded' =&gt; 0, 'player_id' =&gt; '9', 'team_id' =&gt; 0, 'period_id' =&gt; '1') ), array( 'Player' =&gt; array ('id' =&gt; 10, 'name' =&gt; 'Forward 1', 'status' =&gt; 'available', 'note' =&gt; '', 'club_id' =&gt; '1', 'position_id' =&gt; '4'), 'Club' =&gt; array ('id' =&gt; 1, 'name' =&gt; 'Club 1', 'abbreviation' =&gt; 'clb1'), 'Position' =&gt; array ('id' =&gt; 4, 'name' =&gt; 'Forward', 'abbreviation' =&gt; 'fw', 'min' =&gt; 1, 'max' =&gt; 3, 'need' =&gt; 2, 'db_abbr' =&gt; 'fw'), 'Stat' =&gt; array ('id' =&gt; 10, 'rank' =&gt; 10, 'goals' =&gt; 0, 'saves' =&gt; 0, 'penaltysaves' =&gt; 0, 'assists' =&gt; 0, 'cleansheet' =&gt; 0, 'redcard' =&gt; 0, 'yellowcard' =&gt; 0, 'foulsconc' =&gt; 0, 'foulswon' =&gt; 0, 'tackleslost' =&gt; 0, 'tackleswon' =&gt; 0, 'shotontarget' =&gt; 0, 'totalshot' =&gt; 0, 'appearances' =&gt; 0, 'attcreated' =&gt; 0, 'totalpasses' =&gt; 0, 'accpasses' =&gt; 0, 'minutesplayed' =&gt; 0, 'conceded' =&gt; 0, 'player_id' =&gt; '10', 'team_id' =&gt; 0, 'period_id' =&gt; '1') ), array( 'Player' =&gt; array ('id' =&gt; 11, 'name' =&gt; 'Forward 2', 'status' =&gt; 'doubtful', 'note' =&gt; '', 'club_id' =&gt; '2', 'position_id' =&gt; '4'), 'Club' =&gt; array ('id' =&gt; 2, 'name' =&gt; 'Club 2', 'abbreviation' =&gt; 'clb2'), 'Position' =&gt; array ('id' =&gt; 4, 'name' =&gt; 'Forward', 'abbreviation' =&gt; 'fw', 'min' =&gt; 1, 'max' =&gt; 3, 'need' =&gt; 2, 'db_abbr' =&gt; 'fw'), 'Stat' =&gt; array ('id' =&gt; 11, 'rank' =&gt; 11, 'goals' =&gt; 0, 'saves' =&gt; 0, 'penaltysaves' =&gt; 0, 'assists' =&gt; 0, 'cleansheet' =&gt; 0, 'redcard' =&gt; 0, 'yellowcard' =&gt; 0, 'foulsconc' =&gt; 0, 'foulswon' =&gt; 0, 'tackleslost' =&gt; 0, 'tackleswon' =&gt; 0, 'shotontarget' =&gt; 0, 'totalshot' =&gt; 0, 'appearances' =&gt; 0, 'attcreated' =&gt; 0, 'totalpasses' =&gt; 0, 'accpasses' =&gt; 0, 'minutesplayed' =&gt; 0, 'conceded' =&gt; 0, 'player_id' =&gt; '11', 'team_id' =&gt; 0, 'period_id' =&gt; '1') ), array( 'Player' =&gt; array ('id' =&gt; 12, 'name' =&gt; 'Forward 3', 'status' =&gt; 'unavailable', 'note' =&gt; '', 'club_id' =&gt; '3', 'position_id' =&gt; '4'), 'Club' =&gt; array ('id' =&gt; 3, 'name' =&gt; 'Club 3', 'abbreviation' =&gt; 'clb3'), 'Position' =&gt; array ('id' =&gt; 4, 'name' =&gt; 'Forward', 'abbreviation' =&gt; 'fw', 'min' =&gt; 1, 'max' =&gt; 3, 'need' =&gt; 2, 'db_abbr' =&gt; 'fw'), 'Stat' =&gt; array ('id' =&gt; 12, 'rank' =&gt; 12, 'goals' =&gt; 0, 'saves' =&gt; 0, 'penaltysaves' =&gt; 0, 'assists' =&gt; 0, 'cleansheet' =&gt; 0, 'redcard' =&gt; 0, 'yellowcard' =&gt; 0, 'foulsconc' =&gt; 0, 'foulswon' =&gt; 0, 'tackleslost' =&gt; 0, 'tackleswon' =&gt; 0, 'shotontarget' =&gt; 0, 'totalshot' =&gt; 0, 'appearances' =&gt; 0, 'attcreated' =&gt; 0, 'totalpasses' =&gt; 0, 'accpasses' =&gt; 0, 'minutesplayed' =&gt; 0, 'conceded' =&gt; 0, 'player_id' =&gt; '12', 'team_id' =&gt; 0, 'period_id' =&gt; '1') ) ); $this-&gt;assertEquals($expected, $result); //Specific Player, Default Stats, No Position Exclusion $result = $this-&gt;Player-&gt;GetPlayers(10, true, null); $expected = array( 'Player' =&gt; array ('id' =&gt; 10, 'name' =&gt; 'Forward 1', 'status' =&gt; 'available', 'note' =&gt; '', 'club_id' =&gt; '1', 'position_id' =&gt; '4'), 'Club' =&gt; array ('id' =&gt; 1, 'name' =&gt; 'Club 1', 'abbreviation' =&gt; 'clb1'), 'Position' =&gt; array ('id' =&gt; 4, 'name' =&gt; 'Forward', 'abbreviation' =&gt; 'fw', 'min' =&gt; 1, 'max' =&gt; 3, 'need' =&gt; 2, 'db_abbr' =&gt; 'fw'), 'Stat' =&gt; array ('id' =&gt; 10, 'rank' =&gt; 10, 'goals' =&gt; 0, 'saves' =&gt; 0, 'penaltysaves' =&gt; 0, 'assists' =&gt; 0, 'cleansheet' =&gt; 0, 'redcard' =&gt; 0, 'yellowcard' =&gt; 0, 'foulsconc' =&gt; 0, 'foulswon' =&gt; 0, 'tackleslost' =&gt; 0, 'tackleswon' =&gt; 0, 'shotontarget' =&gt; 0, 'totalshot' =&gt; 0, 'appearances' =&gt; 0, 'attcreated' =&gt; 0, 'totalpasses' =&gt; 0, 'accpasses' =&gt; 0, 'minutesplayed' =&gt; 0, 'conceded' =&gt; 0, 'player_id' =&gt; '10', 'team_id' =&gt; 0, 'period_id' =&gt; '1') ); $this-&gt;assertEquals($expected, $result); //Specific Player, Specific Stats, No Position Exclusion $result = $this-&gt;Player-&gt;GetPlayers(10, 2, null); $expected = array( 'Player' =&gt; array ('id' =&gt; 10, 'name' =&gt; 'Forward 1', 'status' =&gt; 'available', 'note' =&gt; '', 'club_id' =&gt; '1', 'position_id' =&gt; '4'), 'Club' =&gt; array ('id' =&gt; 1, 'name' =&gt; 'Club 1', 'abbreviation' =&gt; 'clb1'), 'Position' =&gt; array ('id' =&gt; 4, 'name' =&gt; 'Forward', 'abbreviation' =&gt; 'fw', 'min' =&gt; 1, 'max' =&gt; 3, 'need' =&gt; 2, 'db_abbr' =&gt; 'fw'), 'Stat' =&gt; array ('id' =&gt; 22, 'rank' =&gt; 10, 'goals' =&gt; 0, 'saves' =&gt; 0, 'penaltysaves' =&gt; 0, 'assists' =&gt; 0, 'cleansheet' =&gt; 0, 'redcard' =&gt; 0, 'yellowcard' =&gt; 0, 'foulsconc' =&gt; 0, 'foulswon' =&gt; 0, 'tackleslost' =&gt; 0, 'tackleswon' =&gt; 0, 'shotontarget' =&gt; 0, 'totalshot' =&gt; 0, 'appearances' =&gt; 0, 'attcreated' =&gt; 0, 'totalpasses' =&gt; 0, 'accpasses' =&gt; 0, 'minutesplayed' =&gt; 0, 'conceded' =&gt; 0, 'player_id' =&gt; '10', 'team_id' =&gt; 0, 'period_id' =&gt; '2') ); $this-&gt;assertEquals($expected, $result); //Player That Doesn't Exist $result = $this-&gt;Player-&gt;GetPlayers(999999, true, null); $this-&gt;assertFalse($result); //Stats That Don't Exist $result = $this-&gt;Player-&gt;GetPlayers(null, 9999999, null); $this-&gt;assertFalse($result); //Filter All Positions $result = $this-&gt;Player-&gt;GetPlayers(null, 9999999, array('gk', 'def', 'mid', 'fw')); $this-&gt;assertFalse($result); } //GetAvailablePlayers($league_id = null, $get_stats = true, $top_ranked_only = false, $exclude_positions = null) { function testGetAvailablePlayers() { //Get The Top Ranked Available Player with Stats $result = $this-&gt;Player-&gt;GetAvailablePlayers(1, null, true, null); $expected = array( 'Player' =&gt; array ('id' =&gt; 2, 'name' =&gt; 'Goalkeeper 2', 'status' =&gt; 'doubtful', 'note' =&gt; '', 'club_id' =&gt; '2', 'position_id' =&gt; '1'), 'Club' =&gt; array ('id' =&gt; 2, 'name' =&gt; 'Club 2', 'abbreviation' =&gt; 'clb2'), 'Position' =&gt; array ('id' =&gt; 1, 'name' =&gt; 'Goalkeeper', 'abbreviation' =&gt; 'gk', 'min' =&gt; 1, 'max' =&gt; 1, 'need' =&gt; 1, 'db_abbr' =&gt; 'gk'), 'Stat' =&gt; array ('id' =&gt; 2, 'rank' =&gt; 2, 'goals' =&gt; 0, 'saves' =&gt; 0, 'penaltysaves' =&gt; 0, 'assists' =&gt; 0, 'cleansheet' =&gt; 0, 'redcard' =&gt; 0, 'yellowcard' =&gt; 0, 'foulsconc' =&gt; 0, 'foulswon' =&gt; 0, 'tackleslost' =&gt; 0, 'tackleswon' =&gt; 0, 'shotontarget' =&gt; 0, 'totalshot' =&gt; 0, 'appearances' =&gt; 0, 'attcreated' =&gt; 0, 'totalpasses' =&gt; 0, 'accpasses' =&gt; 0, 'minutesplayed' =&gt; 0, 'conceded' =&gt; 0, 'player_id' =&gt; '2', 'team_id' =&gt; 0, 'period_id' =&gt; '1'), 'Selection' =&gt; array ('id' =&gt; '', 'drafted' =&gt; '', 'locked' =&gt; '', 'position_id' =&gt; '', 'league_id' =&gt; '', 'team_id' =&gt; '', 'player_id' =&gt; '', 'period_id' =&gt; '') ); $this-&gt;assertEquals($expected, $result); //Get All Available Players with No Stats Filtered by Position $result = $this-&gt;Player-&gt;GetAvailablePlayers(1, false, null, array('def', 'mid', 'fw')); $expected = array( array( 'Player' =&gt; array ('id' =&gt; 2, 'name' =&gt; 'Goalkeeper 2', 'status' =&gt; 'doubtful', 'note' =&gt; '', 'club_id' =&gt; '2', 'position_id' =&gt; '1'), 'Club' =&gt; array ('id' =&gt; 2, 'name' =&gt; 'Club 2', 'abbreviation' =&gt; 'clb2'), 'Position' =&gt; array ('id' =&gt; 1, 'name' =&gt; 'Goalkeeper', 'abbreviation' =&gt; 'gk', 'min' =&gt; 1, 'max' =&gt; 1, 'need' =&gt; 1, 'db_abbr' =&gt; 'gk'), 'Selection' =&gt; array ('id' =&gt; '', 'drafted' =&gt; '', 'locked' =&gt; '', 'position_id' =&gt; '', 'league_id' =&gt; '', 'team_id' =&gt; '', 'player_id' =&gt; '', 'period_id' =&gt; '') ), array( 'Player' =&gt; array ('id' =&gt; 3, 'name' =&gt; 'Goalkeeper 3', 'status' =&gt; 'unavailable', 'note' =&gt; '', 'club_id' =&gt; '3', 'position_id' =&gt; '1'), 'Club' =&gt; array ('id' =&gt; 3, 'name' =&gt; 'Club 3', 'abbreviation' =&gt; 'clb3'), 'Position' =&gt; array ('id' =&gt; 1, 'name' =&gt; 'Goalkeeper', 'abbreviation' =&gt; 'gk', 'min' =&gt; 1, 'max' =&gt; 1, 'need' =&gt; 1, 'db_abbr' =&gt; 'gk'), 'Selection' =&gt; array ('id' =&gt; '', 'drafted' =&gt; '', 'locked' =&gt; '', 'position_id' =&gt; '', 'league_id' =&gt; '', 'team_id' =&gt; '', 'player_id' =&gt; '', 'period_id' =&gt; '') ), ); $this-&gt;assertEquals($expected, $result); //Test With League That Doesn't Exist $result = $this-&gt;Player-&gt;GetAvailablePlayers(5); $this-&gt;assertFalse($result); } function testIsAvailable() { $result = $this-&gt;Player-&gt;IsAvailable(1, 1); $this-&gt;assertFalse($result); $result = $this-&gt;Player-&gt;IsAvailable(2, 1); $this-&gt;assertTrue($result); $result = $this-&gt;Player-&gt;IsAvailable(1, 999999); $this-&gt;assertFalse($result); } } ?&gt; </code></pre>
[ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-10-31T17:35:33.147", "Id": "8636", "Score": "0", "body": "Where does `$this->Player->GetPlayers(11, 'all', null);` get its data from in this test?" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-11-07T23:38:18.960", "Id": "8944", "Score": "0", "body": "It's a method in my Player model." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-11-07T23:40:13.240", "Id": "8945", "Score": "0", "body": "I can see that what I mean is where does that method get it's data?" } ]
[ { "body": "<p>First of all, I'd create a distinct method for every <code>assertEquals()</code> call. It helps <a href=\"http://xunitpatterns.com/Goals%20of%20Test%20Automation.html#Defect%20Localization\" rel=\"nofollow\">defect localization</a>. If the first <code>assert</code> throws an error you'll have no idea that the 2nd, 3rd and the others are OK or not. Having only one <code>assert</code> call per test method is a good practice. The comments should be the name of these methods. (Comment usually is a code smell.)</p>\n\n<p>The <code>$expected</code> arrays are rather complicated. If the <code>Player</code> class get a new field (e.g. nickname) you probably have to modify all of your tests which could be a huge pain. I suggest using <a href=\"http://xunitpatterns.com/Custom%20Assertion.html\" rel=\"nofollow\">custom assert methods</a>. For example, instead of</p>\n\n<pre><code>//Get All Available Players with No Stats Filtered by Position\n$result = $this-&gt;Player-&gt;GetAvailablePlayers(1, false, null, array('def', 'mid', 'fw'));\n$expected = array(...)\n$this-&gt;assertEquals($expected, $result);\n</code></pre>\n\n<p>try</p>\n\n<pre><code>function testGetAllAvailablePlayersWithNoStatsFilteredByPosition() {\n $result = $this-&gt;Player-&gt;GetAvailablePlayers(1, false, null, \n array('def', 'mid', 'fw'));\n $this-&gt;assertPlayerCount(\"playerCount\", 2, $result);\n $this-&gt;assertPlayerIdEquals(\"player id 1\", 2, $result[0]);\n $this-&gt;assertPlayerIdEquals(\"player id 2\", 3, $result[1]);\n}\n</code></pre>\n\n<p>(Of course you have write the <code>assertPlayerCount</code> and <code>assertPlayerIdEquals</code> methods. The first string parameter is an <a href=\"http://xunitpatterns.com/Assertion%20Message.html\" rel=\"nofollow\">assertion message</a>. It's useful if you have more than one <code>assert</code> call in one test method.)</p>\n\n<p>In this test class you use <a href=\"http://xunitpatterns.com/Shared%20Fixture.html\" rel=\"nofollow\">Shared Fixture</a>. If it's possible try using fresh fixture with <a href=\"http://xunitpatterns.com/Inline%20Setup.html\" rel=\"nofollow\">Inline Setup</a>. From \n<a href=\"http://xunitpatterns.com/TestStrategy.html#The%20Three%20Major%20Fixture%20Strategies\" rel=\"nofollow\">Test Automation Strategy, The Three Major Fixture Strategies</a>:</p>\n\n<blockquote>\n <p>This Shared Fixture strategy is often used to improve the execution\n speed of tests that use a Persistent Fresh Fixture but it comes with a\n fair amount of baggage. These test require the use of one of the\n fixture construction and tear down triggering patterns. They also\n involve tests that interact with each other, whether by design or\n consequence, and this often leads to Erratic Tests (page X) and High\n Test Maintenance Costs.</p>\n</blockquote>\n\n<p>(The cited text has links, check them.)</p>\n\n<p>If you have enough time it's worth reading the whole <a href=\"http://xunitpatterns.com/\" rel=\"nofollow\">XUnit Test Patterns</a> book. Reading just the Part I (and Part II.) is also beneficial.</p>\n\n<p>(Please note that I haven't written any PHP code in last few years, so the sample codes probably don't compile etc.)</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-10-30T23:09:46.043", "Id": "8620", "Score": "0", "body": "Thanks, this is really useful. Will have a read through everything and hopefully tidy everything up. One other question - if you don't mind, some of my save functions update various fields in the DB. Should I test them using a custom assert function too - to ensure that the data in the DB is as expected." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-10-30T23:46:00.477", "Id": "8622", "Score": "0", "body": "You are welcome :) Yes, you should. Just keep it DRY (Don't Repeat Yourself). Less redundancy in a the code -> easier to maintain. Custom assert methods helps to avoid redundant test code (and increase test readability etc.)." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-10-30T23:46:37.947", "Id": "8623", "Score": "3", "body": "Anyway, testing with database sounds like an integration test not an unit test. In tests try mocking the database or use in-memory databases to avoid the possibility of [interacting tests](http://xunitpatterns.com/Erratic%20Test.html#Interacting%20Tests). \n\n(If a test hasn't cleaned the database the next test could fail because of the remained records in the database. Life is easier with a fresh fixture.) (Furthermore, it's much faster of course.)" } ], "meta_data": { "CommentCount": "3", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-10-30T18:11:24.507", "Id": "5705", "ParentId": "5701", "Score": "4" } } ]
{ "AcceptedAnswerId": "5705", "CommentCount": "3", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-10-30T14:05:42.567", "Id": "5701", "Score": "4", "Tags": [ "php", "unit-testing" ], "Title": "Are my Unit Tests any good?" }
5701
<p>I have this function that should merge two array of classes when <code>id</code> of array1 is equal to <code>id</code> of array2.</p> <p>For simplicity I converted one array into an ArrayList so I can remove the occurrence merged into the other one..</p> <p>I'm looking a way to improve it, also in cpu-time, because the two arrays can have more then 20000rows. The actual way, should take some time..</p> <pre><code>public Asset[] merge(Asset[] a2, ArrayList&lt;countR&gt; a) { while (a.size()!=0){ int i=0; Boolean b=false; while (i&lt;a2.length &amp;&amp; b==false) { if (a.get(0).id.equals(a2[i].id)){ a2[i].TotaleRegistrazioni = a.get(0).tot; b=true; } i++; } a.remove(0); } return a2; } </code></pre>
[ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-10-30T18:29:24.733", "Id": "8612", "Score": "0", "body": "Have you done any performance test which shows that this is a performance bottleneck? 20k item isn't so much..." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-10-30T19:55:58.200", "Id": "8617", "Score": "0", "body": "without looking at the time to scroll the entire array, I only would like to know if there is a better way to do this :)" } ]
[ { "body": "<p>Staying with your original code you can change <code>b</code> to a simple <code>break</code> and you can change the inner <code>while</code> to a <code>for</code> which is easier to read:</p>\n\n<pre><code>public Asset[] merge2(final Asset[] firstArray, final ArrayList&lt;CountR&gt; secondList) {\n while (secondList.size() != 0) {\n for (int i = 0; i &lt; firstArray.length; i++) {\n final CountR countR = secondList.get(0);\n final Asset asset = firstArray[i];\n if (countR.id.equals(asset.id)) {\n asset.TotaleRegistrazioni = countR.tot;\n break;\n }\n }\n secondList.remove(0);\n }\n return firstArray;\n}\n</code></pre>\n\n<p>Searching in a <code>HashMap</code> should be faster than iterating through the whole array, so I'd do the following:</p>\n\n<pre><code>public Asset[] merge3(final Asset[] firstArray, final CountR[] secondArray) {\n final Map&lt;Id, Asset&gt; assetCache = new HashMap&lt;Id, Asset&gt;();\n for (final Asset asset : firstArray) {\n final Id id = asset.getId();\n assetCache.put(id, asset);\n }\n\n for (final CountR countR : secondArray) {\n final Id countRId = countR.getId();\n final Asset asset = assetCache.get(countRId);\n if (asset != null) {\n // I supposed that it's int\n final int total = countR.getTot();\n asset.setTotaleRegistrazioni(total); \n }\n }\n\n return firstArray;\n}\n</code></pre>\n\n<p>(I supposed that the <code>Asset.id</code> is unique in the array.) In this case you don't have to convert the second parameter to an array (just the first to a map). Maybe it worth playing with the <code>initialCapacity</code> and <code>loadFactor</code> parameters of the <code>HashMap</code> to avoid the <a href=\"http://en.wikipedia.org/wiki/Hash_table#Dynamic_resizing\">resizing</a>. </p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-10-30T21:56:56.397", "Id": "5707", "ParentId": "5703", "Score": "5" } } ]
{ "AcceptedAnswerId": "5707", "CommentCount": "2", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-10-30T17:15:00.477", "Id": "5703", "Score": "6", "Tags": [ "java", "optimization", "performance", "array" ], "Title": "Merging two array of classes" }
5703
<p>well, as said in the title: We need to get a mac-address of a NIC that is providing the connection to a particular host. We use the mac-address during the login process using MSSQL and Entity Framework.</p> <p>technology: C#.NET 4.0, EF 4.1</p> <pre><code>private string _max_address; public string ConnectionString { get; }; public string MacAddress { get { if (this._mac_address == null) { SqlConnectionStringBuilder csb = new SqlConnectionStringBuilder(this.ConnectionString); IPAddress[] addres = Dns.GetHostAddresses(csb.DataSource.Split('\\')[0]); //find nic interface address from routing table Process p = new Process(); // Redirect the output stream of the child process. p.StartInfo.UseShellExecute = false; p.StartInfo.RedirectStandardOutput = true; p.StartInfo.WindowStyle = ProcessWindowStyle.Hidden; p.StartInfo.CreateNoWindow = false; p.StartInfo.FileName = "route"; p.StartInfo.Arguments = "PRINT"; p.Start(); string output = p.StandardOutput.ReadToEnd(); p.WaitForExit(); p.Close(); p.Dispose(); string[] lines = output.Split(new string[]{"\r\n"}, StringSplitOptions.RemoveEmptyEntries); List&lt;Route&gt; routes = new List&lt;Route&gt;(); bool found = false; foreach (string line in lines) { if (line == "Active Routes:") { if (found) //if routes have already been found exit loop, meaning this is IPv6 routes, should never reach this point break; found = true; continue; //next line } if (found) { if (line[0] == 'N') //if the line is headers skip it continue; else if (line[0] == '=') //if the routes have ended exit loop break; routes.Add(new Route(line)); //read route, custom class } } routes.Sort(); //sort routes by Mask, then by Address string nic_addr = ""; foreach (IPAddress addr in addres) { if (addr.AddressFamily == AddressFamily.InterNetwork) { //if IPv4 for (int i = routes.Count - 1; i &gt;= 0; i--) { //start from the largest Mask if(routes[i].IncludesHost(addr)) { //whether the ip fits in the subnet nic_addr = routes[i].ReadableInterface; break; //if so, save interface name, exit loop } } break; } } //Get NIC of found Interface by IP foreach (NetworkInterface nic in NetworkInterface.GetAllNetworkInterfaces()) { if (nic.OperationalStatus == OperationalStatus.Up) { IPInterfaceProperties properties = nic.GetIPProperties(); foreach (UnicastIPAddressInformation addr_info in properties.UnicastAddresses) { if (addr_info.Address.AddressFamily == AddressFamily.InterNetwork &amp;&amp; addr_info.Address.ToString()==nic_addr) { this._mac_address = nic.GetPhysicalAddress().ToString(); break; //if address matches that of the routing table interface address then save MAC and exit loop } } if (this._mac_address != null) break; //if mac address is found exit loop; } } } return this._mac_address; } } public class Route : IComparable { private uint _address; private uint _mask; private uint _interface; private int _metric; public uint Address { get { return this._address; } } public uint Mask { get { return this._mask; } } public uint Interface { get { return this._interface; } } public string ReadableAddress { get { return Route.IPLongToString(this._address); } } public string ReadableMask { get { return Route.IPLongToString(this._mask); } } public string ReadableInterface { get { return Route.IPLongToString(this._interface); } } public Route(string[] route) { this._address=IPStringToLong(route[0]); this._mask=IPStringToLong(route[1]); this._interface=IPStringToLong(route[3]); this._metric=UInt16.Parse(route[4]); } public Route(string line) : this(line.Split(new char[]{' '}, StringSplitOptions.RemoveEmptyEntries)) { } public static uint IPStringToLong(string str) { string[] values = str.Split(new char[]{'.'}); uint multiplier = 1; uint value = 0; for(int i=3;i&gt;=0;i--) { value+=UInt32.Parse(values[i])*multiplier; multiplier*=256; } return value; } public static string IPLongToString(uint addr) { byte[] bytes = BitConverter.GetBytes(addr); string[] bs = new string[]{"","","",""}; for(int i=0;i&lt;4;i++) { bs[i] = bytes[3-i].ToString(); } return String.Join(".",bs); } public bool IncludesHost(IPAddress addr) { if (addr.AddressFamily == AddressFamily.InterNetwork) return this.IncludesHost(Route.IPStringToLong(addr.ToString())); else return false; } public bool IncludesHost(string addr) { return this.IncludesHost(Route.IPStringToLong(addr)); } public bool IncludesHost(long addr) { return (this._mask&amp;this._address) == (this._mask&amp;addr); } public int CompareTo(object _y) { Route y = (Route)_y; if (y == null) return 1; else { int retval = this.Mask.CompareTo(y.Mask); if (retval != 0) return retval; else return this.CompareToByAddress(y); } } } </code></pre> <p>EDIT:</p> <p>so far, it's a mess I don't like the solution i've come up with.</p> <ol> <li>get host name from connectionstring</li> <li>get host ip from hostname</li> <li>execute "route PRINT"</li> <li>put output in string arrray</li> <li>loop through output lines</li> <li>find "Active Routes" line</li> <li>skip header</li> <li>load route into custom Route class</li> <li>exit line loop</li> <li>loop through found routes</li> <li>find matching host ip&amp;mask network&amp;mask</li> <li>save its interface ip</li> <li>loop through NIC</li> <li>check whether ipv4 if so check interface ip</li> <li>get mac of found NIC</li> </ol> <p>isn't here a more elegant way accomplishing steps 1 through 14, it's just so much code just to get a MAC-address of a particular NIC\</p> <p>OR at least a better way to accomlish steps 3 through 10</p> <p>EDIT: I've missed declaration of CompareToByAddress()</p> <pre><code>public int CompareToByAddress( Route y) { if (y == null) { return 1; } else { int retval = this.Address.CompareTo(y.Address); if (retval != 0) { return retval; } else { //should never reach this point meaning there's duplicate entry in the routing table return 0; } } } </code></pre> <p>though, the solutions below do not use the CompareTo methods;</p>
[]
[ { "body": "<p>I don't know about doing it more directly, but the code can definitely be cleaned up using linq as a start.</p>\n\n<pre><code>var addr = addres.First(e =&gt; e.AddressFamily == AddressFamily.InterNetwork);\nvar nic_addr = output.Split(new string[] { \"\\r\\n\" }, StringSplitOptions.RemoveEmptyEntries)\n .SkipWhile(e =&gt; e != \"Active Routes:\")\n .Skip(1)\n .TakeWhile(e =&gt; e != \"Active Routes:\") //if routes have already been found exit loop, meaning this is IPv6 routes, should never hit this case\n .TakeWhile(e =&gt; e != \"=\") //until the routes have ended\n .Where(e =&gt; !e.StartsWith(\"N\")) //skip header lines\n .Select(e =&gt; new Route(e))\n .OrderByDescending(e =&gt; e.Mask)\n .ThenByDescending(e =&gt; e.Address)\n .First(e =&gt; e.IncludesHost(addr))\n .ReadableInterface;\n\n//Choose NIC matching the IP address\nvar result = NetworkInterface.GetAllNetworkInterfaces()\n .Where(e =&gt; e.OperationalStatus == OperationalStatus.Up)\n .SelectMany(e =&gt; e.GetIPProperties().UnicastAddresses)\n .Where(e =&gt; e.Address.AddressFamily == AddressFamily.InterNetwork)\n .Where(e =&gt; e.Address.ToString() == nic_addr)\n .First();\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-11-03T01:07:02.483", "Id": "8736", "Score": "0", "body": "wow this is awesome, how much experience do you guys have to automatically write this stuff?" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-11-03T07:12:41.000", "Id": "8743", "Score": "0", "body": "and yes I was hoping to find an already-made/\"direct\" solution to this problem, I'm sure there are some out there. I mean, anyone might need a mac address of the NIC making a connection to a host. I was surprised to find so little in .NET, or probably I wasn't looking in the right places. Though, I did get a hint that such solution might be found using WMI." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-11-03T17:01:00.253", "Id": "8764", "Score": "0", "body": "Generally the linq version is easier to write than the explicit version. Instead of writing a whole for loop that sets a variable and breaks when a condition becomes true, you use 'First(condition)'. Etc." } ], "meta_data": { "CommentCount": "3", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-11-02T02:43:13.377", "Id": "5747", "ParentId": "5709", "Score": "0" } }, { "body": "<p>To expand on Strilanc's answer, you can clean up a bit further with the following:</p>\n\n<pre><code>var address = addres.First(e =&gt; e.AddressFamily.Equals(AddressFamily.InterNetwork));\n\n// Retrieve routing table\nstring output = string.Empty;\nusing (Process p = new Process()\n {\n StartInfo = new ProcessStartInfo()\n {\n UseShellExecute = false,\n RedirectStandardOutput = true,\n WindowStyle = ProcessWindowStyle.Hidden,\n CreateNoWindow = false,\n FileName = \"route\",\n Arguments = \"PRINT\"\n }\n })\n{\n p.Start();\n output = p.StandardOutput.ReadToEnd();\n p.WaitForExit();\n p.Close();\n}\n\n// Find NIC interface from table\nvar nicAddr = output.Split(new string[] { Environment.NewLine }, StringSplitOptions.RemoveEmptyEntries)\n .SkipWhile(e =&gt; !e.Equals(\"Active Routes:\"))\n .Skip(1)\n .TakeWhile(e =&gt; !e.Equals(\"Active Routes:\"))\n .TakeWhile(e =&gt; !e.StartsWith(\"=\"))\n .Where(e =&gt; !e.StartsWith(\"N\"))\n .Select(e =&gt; new Route(e))\n .OrderByDescending(e =&gt; e.Mask)\n .ThenByDescending(e =&gt; e.Address)\n .First(e =&gt; e.IncludesHost(address))\n .ReadableInterface;\n\n// Get MAC address of associated IP address\nvar macAddress = NetworkInterface.GetAllNetworkInterfaces()\n .Where(e =&gt; e.OperationalStatus.Equals(OperationalStatus.Up))\n .Where(e =&gt; e.GetIPProperties().UnicastAddresses\n .Where(a =&gt; a.Address.AddressFamily.Equals(AddressFamily.InterNetwork) &amp;&amp;\n a.Address.ToString().Equals(nicAddr)).FirstOrDefault() != null)\n .Select(a =&gt; a.GetPhysicalAddress()).FirstOrDefault();\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-11-03T01:07:20.610", "Id": "8737", "Score": "0", "body": "thank you, very much i'll be on this in a couple of minutes" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-11-03T04:14:52.013", "Id": "8740", "Score": "0", "body": "Worked like a charm, though I wonder, how much performance is being sacrificed on the LINQ statements. I did a small bench testing EF:LINQ against string written ADO.SQL statement, turned out about additional 200ms execution time on the EF:LINQ statement, so I just assumed EF+LINQ takes around 200ms to parse the LINQ statement to an SQL statement." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-11-03T12:25:07.383", "Id": "8756", "Score": "0", "body": "I don't see much of a performance hit at all. The greatest burden is the 'route print' process. Aside from that, I'm only seeing a >1ms difference (average from several hundred iterations) between your long form and the LINQ posted above." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-11-03T21:09:06.793", "Id": "8774", "Score": "0", "body": "A tip about LINQ: FirstOrDefault will return what you're looking for in the collection, or the default type if the collection is empty (often null). First will throw a runtime exception if there is nothing that matches the predicate. I tend to prefer using FirstOrDefault unless I'm guaranteed to have an element within the collection." } ], "meta_data": { "CommentCount": "4", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-11-02T19:43:30.303", "Id": "5766", "ParentId": "5709", "Score": "2" } } ]
{ "AcceptedAnswerId": "5766", "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-10-31T01:52:42.627", "Id": "5709", "Score": "4", "Tags": [ "c#" ], "Title": "C# .NET getting mac-address of a local NIC that's making a connection to a particular host" }
5709