body
stringlengths
25
86.7k
comments
list
answers
list
meta_data
dict
question_id
stringlengths
1
6
<p>In my application, I have a small hierarchy of related classes (<em>partner categories - partners - partner points</em>).</p> <p>The application has two representations of its content:</p> <ul> <li>in the form of partners points on the map</li> <li>in the form of a list of partner categories or partners within a category</li> </ul> <p>The application has the filters for searching and sorting. The map used only the search filters, but in the list used both types of filters.</p> <p>Please, criticize my code and help me choose a proper name instead of <code>SearchableSortable</code>.</p> <p>This class was written using TDD.</p> <p><strong>SearchableSortable.java</strong></p> <pre><code>public class SearchableSortable&lt;T&gt; implements Serializable { public static interface OnEachHandler&lt;T&gt; { void onEach(T each, boolean meetsCriteria); } public static interface SearchCriteria&lt;T&gt; { boolean meetCriteria(T obj); } private final List&lt;T&gt; elements; private final List&lt;SearchCriteria&lt;T&gt;&gt; searchCriterias; private final List&lt;Comparator&lt;T&gt;&gt; comparators; public static &lt;T&gt; SearchableSortable&lt;T&gt; newInstance(Collection&lt;T&gt; elements) { return new SearchableSortable&lt;T&gt;(elements); } private SearchableSortable(Collection&lt;T&gt; elements) { this.elements = new ArrayList&lt;T&gt;(elements); this.searchCriterias = new ArrayList&lt;SearchCriteria&lt;T&gt;&gt;(); this.comparators = new ArrayList&lt;Comparator&lt;T&gt;&gt;(); } public void addSearchCriteria(SearchCriteria&lt;T&gt; searchCriteria) { searchCriterias.add(searchCriteria); } public void addComparator(Comparator&lt;T&gt; comparator) { comparators.add(comparator); } public void clear() { searchCriterias.clear(); comparators.clear(); } public void forEach(OnEachHandler&lt;T&gt; onEachHandler) { for (T each : elements) { onEachHandler.onEach(each, meetCriteria(each)); } } private boolean meetCriteria(T element) { for (SearchCriteria&lt;T&gt; searchCriteria : searchCriterias) { if (!searchCriteria.meetCriteria(element)) { return false; } } return true; } public void sort() { sort(elements); } private void sort(List&lt;T&gt; list) { for (Comparator&lt;T&gt; comparator : comparators) { Collections.sort(list, comparator); } } public List&lt;T&gt; toUnsortedList() { List&lt;T&gt; list = new ArrayList&lt;T&gt;(); for (T each : elements) { if (meetCriteria(each)) { list.add(each); } } return list; } public List&lt;T&gt; toSortedList() { List&lt;T&gt; list = toUnsortedList(); sort(list); return list; } } </code></pre> <p><strong>TestSearchableSortable.java</strong></p> <pre><code>public class TestSearchableSortable extends TestCase { private final Integer[] array = { 1, 2, 3, 4, 5, 6, 7, 8, 9 }; private List&lt;Integer&gt; collection; private SearchableSortable&lt;Integer&gt; searchableSortable; private int index; @Override public void setUp() throws Exception { super.setUp(); collection = Arrays.asList(array); searchableSortable = SearchableSortable.newInstance(collection); } public void testClassUsesCopyOfInputCollection() { List&lt;Integer&gt; before = new ArrayList&lt;Integer&gt;(collection); searchableSortable.addComparator(new ReverseOrderComparator()); searchableSortable.addSearchCriteria(new OnlyEvenNumbersSearchFilter()); searchableSortable.sort(); searchableSortable.forEach(new SearchableSortable.OnEachHandler&lt;Integer&gt;() { @Override public void onEach(Integer each, boolean meetsCriteria) { // do nothing } }); assertEquals(before, collection); } public void testForEachWithoutSearchFilterAndComparator() { checkForEach(new SearchableSortable.OnEachHandler&lt;Integer&gt;() { @Override public void onEach(Integer each, boolean meetsCriteria) { assertEquals(array[index], each); assertTrue(meetsCriteria); } }); } public void testForEachWithSearchFilter() { searchableSortable.addSearchCriteria(new OnlyEvenNumbersSearchFilter()); checkForEach(new SearchableSortable.OnEachHandler&lt;Integer&gt;() { @Override public void onEach(Integer each, boolean meetsCriteria) { assertEquals(array[index], each); assertEquals(evenNumber(each), meetsCriteria); } }); } private static class OnlyEvenNumbersSearchFilter implements SearchableSortable.SearchCriteria&lt;Integer&gt; { @Override public boolean meetCriteria(Integer number) { return evenNumber(number); } } private static boolean evenNumber(Integer number) { return number % 2 == 0; } private void checkForEach(final SearchableSortable.OnEachHandler&lt;Integer&gt; onEachHandler) { index = 0; searchableSortable.forEach(new SearchableSortable.OnEachHandler&lt;Integer&gt;() { @Override public void onEach(Integer each, boolean meetsCriteria) { onEachHandler.onEach(each, meetsCriteria); ++index; } }); assertEquals(array.length, index); } public void testForEachWithSeveralSearchFilters() { searchableSortable.addSearchCriteria(new OnlyEvenNumbersSearchFilter()); final Integer[] numbers = { 2, 8, 120, 133, 1 }; searchableSortable.addSearchCriteria(new OnlyTheseNumbersSearchFilter(numbers)); checkForEach(new SearchableSortable.OnEachHandler&lt;Integer&gt;() { @Override public void onEach(Integer each, boolean meetsCriteria) { assertEquals(array[index], each); boolean expectedMeetsCriteria = (evenNumber(each) &amp;&amp; arrayContainsElement(numbers, each)); assertEquals(expectedMeetsCriteria, meetsCriteria); } }); } private static class OnlyTheseNumbersSearchFilter implements SearchableSortable.SearchCriteria&lt;Integer&gt; { private final Integer[] numbers; OnlyTheseNumbersSearchFilter(Integer... numbers) { this.numbers = numbers; } @Override public boolean meetCriteria(Integer element) { return arrayContainsElement(numbers, element); } } private static &lt;T&gt; boolean arrayContainsElement(T[] arr, T element) { for (T each : arr) { if (each.equals(element)) { return true; } } return false; } public void testForEachWithComparator() { searchableSortable.addComparator(new ReverseOrderComparator()); searchableSortable.sort(); checkForEach(new SearchableSortable.OnEachHandler&lt;Integer&gt;() { @Override public void onEach(Integer each, boolean meetsCriteria) { assertEquals(getElementFromReversedArray(index), each); assertTrue(meetsCriteria); } }); } private static class ReverseOrderComparator implements Comparator&lt;Integer&gt; { @Override public int compare(Integer number1, Integer number2) { return -(number1 - number2); } } private Integer getElementFromReversedArray(int index) { int lastIndex = array.length - 1; return array[lastIndex - index]; } private static class PairOfNumbers extends Pair&lt;Integer, Integer&gt; { public PairOfNumbers(Integer first, Integer second) { super(first, second); } } public void testForEachWithSeveralComparators() { final List&lt;PairOfNumbers&gt; pairs = Arrays.asList( new PairOfNumbers(2, 4), new PairOfNumbers(6, 3), new PairOfNumbers(1, 4), new PairOfNumbers(2, 3) ); final List&lt;PairOfNumbers&gt; expectedPairsAfterSorting = Arrays.asList( new PairOfNumbers(1, 4), new PairOfNumbers(2, 3), new PairOfNumbers(2, 4), new PairOfNumbers(6, 3) ); SearchableSortable&lt;PairOfNumbers&gt; searchableSortablePairs = SearchableSortable.newInstance(pairs); searchableSortablePairs.addComparator(createComparatorBySecondComponent()); searchableSortablePairs.addComparator(createComparatorByFirstComponent()); index = 0; searchableSortablePairs.sort(); searchableSortablePairs.forEach(new SearchableSortable.OnEachHandler&lt;PairOfNumbers&gt;() { @Override public void onEach(PairOfNumbers each, boolean meetsCriteria) { assertEquals(expectedPairsAfterSorting.get(index), each); assertTrue(meetsCriteria); ++index; } }); assertEquals(expectedPairsAfterSorting.size(), index); } private Comparator&lt;PairOfNumbers&gt; createComparatorBySecondComponent() { return new Comparator&lt;PairOfNumbers&gt;() { @Override public int compare(PairOfNumbers pair1, PairOfNumbers pair2) { return pair1.second - pair2.second; } }; } private Comparator&lt;PairOfNumbers&gt; createComparatorByFirstComponent() { return new Comparator&lt;PairOfNumbers&gt;() { @Override public int compare(PairOfNumbers pair1, PairOfNumbers pair2) { return pair1.first - pair2.first; } }; } public void testToSortedListWithoutSearchFilterAndComparator() { assertEquals(collection, searchableSortable.toSortedList()); } public void testToSortedListWithSearchFilter() { SearchableSortable.SearchCriteria&lt;Integer&gt; searchCriteria = new OnlyEvenNumbersSearchFilter(); searchableSortable.addSearchCriteria(searchCriteria); Collection&lt;Integer&gt; numbersWhichMeetCriteria = getNumbersWhichMeetCriteria(collection, searchCriteria); assertEquals(numbersWhichMeetCriteria, searchableSortable.toSortedList()); } private Collection&lt;Integer&gt; getNumbersWhichMeetCriteria(Collection&lt;Integer&gt; numbers, SearchableSortable.SearchCriteria&lt;Integer&gt;... searchCriterias) { Collection&lt;Integer&gt; numbersWhichMeetCriteria = new ArrayList&lt;Integer&gt;(); for (Integer each : numbers) { if (meetCriteria(each, searchCriterias)) { numbersWhichMeetCriteria.add(each); } } return numbersWhichMeetCriteria; } private boolean meetCriteria(Integer each, SearchableSortable.SearchCriteria&lt;Integer&gt;... searchCriterias) { for (SearchableSortable.SearchCriteria&lt;Integer&gt; searchCriteria : searchCriterias) { if (!searchCriteria.meetCriteria(each)) { return false; } } return true; } public void testToSortedListWithSeveralSearchFilters() { SearchableSortable.SearchCriteria&lt;Integer&gt; onlyEvenNumbersSearchCriteria = new OnlyEvenNumbersSearchFilter(); SearchableSortable.SearchCriteria&lt;Integer&gt; onlyTheseNumbersSearchCriteria = new OnlyTheseNumbersSearchFilter(2, 4, 6); searchableSortable.addSearchCriteria(onlyEvenNumbersSearchCriteria); searchableSortable.addSearchCriteria(onlyTheseNumbersSearchCriteria); Collection&lt;Integer&gt; numbersWhichMeetCriteria = getNumbersWhichMeetCriteria(collection, onlyEvenNumbersSearchCriteria, onlyTheseNumbersSearchCriteria); assertEquals(numbersWhichMeetCriteria, searchableSortable.toSortedList()); } public void testToListWithComparator() { searchableSortable.addComparator(new ReverseOrderComparator()); assertEquals(reversed(collection), searchableSortable.toSortedList()); } private List&lt;Integer&gt; reversed(List&lt;Integer&gt; list) { List&lt;Integer&gt; reversedList = new ArrayList(list.size()); for (int i = list.size() - 1; i &gt;= 0; --i) { reversedList.add(list.get(i)); } return reversedList; } public void testToSortedListWithSeveralComparators() { final List&lt;PairOfNumbers&gt; pairs = Arrays.asList( new PairOfNumbers(2, 4), new PairOfNumbers(6, 3), new PairOfNumbers(1, 4), new PairOfNumbers(2, 3) ); final List&lt;PairOfNumbers&gt; expectedPairs = Arrays.asList( new PairOfNumbers(1, 4), new PairOfNumbers(2, 3), new PairOfNumbers(2, 4), new PairOfNumbers(6, 3) ); SearchableSortable&lt;PairOfNumbers&gt; searchableSortablePairs = SearchableSortable.newInstance(pairs); searchableSortablePairs.addComparator(createComparatorBySecondComponent()); searchableSortablePairs.addComparator(createComparatorByFirstComponent()); assertEquals(expectedPairs, searchableSortablePairs.toSortedList()); } public void testRemoveAllFilters() { final List&lt;PairOfNumbers&gt; pairs = Arrays.asList( new PairOfNumbers(2, 4), new PairOfNumbers(6, 3), new PairOfNumbers(1, 4), new PairOfNumbers(2, 3), new PairOfNumbers(1, 1), new PairOfNumbers(5, 5), new PairOfNumbers(2, 2) ); SearchableSortable&lt;PairOfNumbers&gt; searchableSortablePairs = SearchableSortable.newInstance(pairs); searchableSortablePairs.addSearchCriteria(new SearchableSortable.SearchCriteria&lt;PairOfNumbers&gt;() { @Override public boolean meetCriteria(PairOfNumbers obj) { return obj.first != obj.second; } }); searchableSortablePairs.addComparator(createComparatorBySecondComponent()); searchableSortablePairs.addComparator(createComparatorByFirstComponent()); searchableSortablePairs.clear(); index = 0; searchableSortablePairs.forEach(new SearchableSortable.OnEachHandler&lt;PairOfNumbers&gt;() { @Override public void onEach(PairOfNumbers each, boolean meetsCriteria) { assertEquals(pairs.get(index), each); assertTrue(meetsCriteria); ++index; } }); assertEquals(pairs.size(), index); assertEquals(pairs, searchableSortablePairs.toSortedList()); } } </code></pre> <p><strong>Filter classes</strong></p> <pre><code>public interface Filter&lt;T&gt; { void includeIn(SearchableSortable&lt;T&gt; searchableSortable); } public abstract class SearchFilter&lt;T&gt; implements Filter&lt;T&gt;, SearchableSortable.SearchCriteria&lt;T&gt; { @Override public void includeIn(SearchableSortable&lt;T&gt; searchableSortable) { searchableSortable.addSearchCriteria(this); } } public abstract class SortingFilter&lt;T&gt; implements Filter&lt;T&gt;, Comparator&lt;T&gt; { @Override public void includeIn(SearchableSortable&lt;T&gt; searchableSortable) { searchableSortable.addComparator(this); } } </code></pre> <p>Or maybe I should divide <code>SearchableSortable</code> class into 2 classes:</p> <p><code>Searchable</code> and <code>SearchableSortable</code> (based on <code>Searchable</code> class) and replace the methods <code>toUnsortedList()</code> and <code>toSortedList()</code> by single method <code>toList()</code> (which returns unsorted list in <code>Searchable</code> class and returns sorted list in <code>SearchableSortable</code> class).</p>
[]
[ { "body": "<p>I am not particularly fussed with the name <code>SearchableSortable</code>. This is a generic class ... if it was directly linked to Partners, then it would be different. You could probably do something to indicate the underlying data infrastructure, like <code>ListView</code> which allows you to understand that the tool manipulates Lists to show different views of the data, and, in this case, two tools are available for modifying the View, sorting, and filtering.</p>\n\n<p>Other things I think you should consider changing though, are:</p>\n\n<ul>\n<li><p>your abstract classes (<code>SearchingFilter&lt;T&gt;</code>, <code>SortingFilter&lt;T&gt;</code>) and their underlying interface <code>Filter&lt;T&gt;</code> have the method <code>includeIn(...)</code>. This type of double-abstraction leads to confusion and gnashing of teeth. The issue is that the way the instances get included in to the <code>ListView</code> is dependant on the instance type. These methods also add no value.... is it really a problem to have:</p>\n\n<pre><code>listview.addSearchCriteria(criteria);\nlistview.addComparator(comparator);\n</code></pre>\n\n<p>Do you really also need</p>\n\n<pre><code>criteria.includeIn(listview);\ncomparator.includeIn(listview);\n</code></pre>\n\n<p>The second (redundant) versions of the operation lead to confusion, you have to <strong>know</strong> what type of instance is being called in order to understand what the operation is doing.</p>\n\n<p>Remove the <code>includeIn(*)</code> redundancies.</p></li>\n<li><p><code>clear()</code> should, in theory, clear the <code>elements</code> data as well.</p></li>\n<li>Adding multiple Comparators is likely going to lead to problems. The implementation you have will result in the last-comparator-added being used to sort the whole dataset. Is that what you want?</li>\n<li><code>Serializable</code> implies you can serialize all the data, but, in fact, you cant be sure that your <code>&lt;T&gt;</code> data type is serializable. You should probably define your class as <code>&lt;T extends Serializable&gt;</code> or remove the Serializable entirely from your class.</li>\n</ul>\n\n<p>All in all, it looks like the code is relatively well structured, and it looks like you have some good ideas in there.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-01-20T15:53:47.857", "Id": "39660", "ParentId": "39641", "Score": "2" } }, { "body": "<p>Your class feels wrongly named. The first sign of a problem is that \"-able\" and \"-ible\" suffixes are generally used for interfaces rather than classes. Let's see what it is really trying to do:</p>\n\n<ul>\n<li>It represents an ordered collection of objects of type <code>T</code> (<code>private final List&lt;T&gt; elements</code>)</li>\n<li><p>It associates several search criteria with the collection (<code>private final List&lt;SearchCriteria&lt;T&gt;&gt; searchCriterias</code>)</p>\n\n<p><em>By the way,</em> <strong>criterion</strong> <em>is singular</em> ; <strong>criteria</strong> <em>is its plural form</em>.</p></li>\n<li>It associates several sorting keys with the collection (<code>private final List&lt;Comparator&lt;T&gt;&gt; comparators</code>)</li>\n</ul>\n\n<p>I would call the class <code>SearchableListing&lt;T&gt;</code>. I chose \"listing\" instead of \"list\" because it merely helps enumerate the items in the list; the class does not actually <code>extend List&lt;T&gt;</code>. I would leave \"sortable\" out of the name, as \"listing\" somewhat implies that the search results can be ordered by relevance.</p>\n\n<p>The search criteria and comparator seem like they should be more intimately related. For example, if you search for partners located within <em>n</em> kilometers of a location, that implies that you also want to rank the search results by distance.</p>\n\n<p>My suggestion for an interface would be:</p>\n\n<pre><code>public class SearchableListing&lt;T&gt; implements Iterable&lt;T&gt; {\n\n public static interface Criterion&lt;T&gt; extends Comparator&lt;T&gt; {\n public boolean filter(T t);\n }\n\n /**\n * Iterator that produces all elements that meet the search criteria,\n * sorted by the natural ordering for those search criteria.\n */\n private class ResultIterator&lt;T&gt; implements Iterator&lt;T&gt; {\n public ResultIterator(List&lt;T&gt; list, List&lt;Criterion&gt; crit) {\n }\n\n @Override\n public void remove() { throw new UnsupportedOperationException(); }\n\n @Override\n public boolean hasNext() { /* TODO */ }\n\n @Override\n public T next() { /* TODO */ }\n }\n\n private Collection&lt;T&gt; elements;\n private List&lt;Criterion&gt; criteria;\n\n public void SearchableListing(Collection&lt;T&gt; elements) { /* TODO */ }\n\n public void addCriterion(Criterion c) { /* TODO */ }\n\n @Override\n public Iterator&lt;T&gt; iterator() {\n return new ResultIterator&lt;T&gt;(this.list, this.criteria);\n }\n}\n</code></pre>\n\n<p>Example usage:</p>\n\n<pre><code>List&lt;Partner&gt; partners = getPartners();\nSearchableListing&lt;Partner&gt; partnerListing = new SearchableListing(partners);\npartnerListing.addCriterion(new DistanceFromPoint(here));\nfor (Partner p : partnerListing) {\n // Do stuff with p\n}\n</code></pre>\n\n<p>One main difference, which may be either an advantage or disadvantage, is that you would avoid having multiple unmanaged <code>List</code>s floating around, as the caller is forced to enumerate the results using your class. </p>\n\n<p>That's just a suggestion; you'll probably have to adapt it for your situation as appropriate.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-01-20T21:59:42.433", "Id": "39691", "ParentId": "39641", "Score": "3" } } ]
{ "AcceptedAnswerId": "39691", "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-01-20T05:58:24.190", "Id": "39641", "Score": "6", "Tags": [ "java" ], "Title": "Class that represents searchable and sortable elements" }
39641
<p><a href="http://projecteuler.net/problem=26" rel="nofollow">Project Euler problem 26</a> asks us to:</p> <blockquote> <p>Find the value of <em>d</em> &lt; 1000 for which 1/<em>d</em> contains the longest recurring cycle in its decimal fraction part.</p> </blockquote> <p>I wrote this function in Python to find the decimal representation of a rational number p/q. How can I improve it? Also suggest good coding styles.</p> <pre><code>#! /usr/bin/env python # -*- coding - utf-8 -*- """This program converts a rational number into its decimal representation. A rational number is a number of the form p/q where p and q are integers and q is not zero. The decimal representation of a rational number is either terminating or non-terminating but repeating. """ def gcd(a, b): """Computes gcd of a, b using Euclid algorithm. """ if not isinstance(a, int) or not isinstance(b, int): return None a = abs(a) b = abs(b) while b != 0: a, b = b, a % b return a def decimal(p, q): """Computes the decimal representation of the rational number p/q. If the representation is non-terminating, then the recurring part is enclosed in parentheses. The result is returned as a string. """ if not isinstance(p, int) or not isinstance(q, int): return '' if q == 0: return '' abs_p = abs(p) abs_q = abs(q) s = (p / abs_p) * (q / abs_q) g = gcd(abs_p, abs_q) p = abs_p / g q = abs_q / g rlist = [] qlist = [] quotient, remainder = divmod(p, q) qlist.append(quotient) rlist.append(remainder) if remainder == 0: return str(quotient) while remainder != 0: remainder *= 10 quotient, remainder = divmod(remainder, q) qlist.append(quotient) if remainder in rlist: break else: rlist.append(remainder) qlist = map(str, qlist) if remainder: recur_index = rlist.index(remainder) + 1 dstring = qlist[0] + '.' + ''.join(qlist[1:recur_index]) + \ '(' + ''.join(qlist[recur_index:]) + ')' if s &lt; 0: dstring = '-' + dstring else: dstring = qlist[0] + '.' + ''.join(qlist[1:]) if s &lt; 0: dstring = '-' + dstring return dstring if __name__ == '__main__': p = raw_input('p: ') q = raw_input('q: ') try: p = int(p) q = int(q) if q == 0: raise ValueError print '%d/%d =' % (p, q), decimal(p, q) except ValueError: print 'invalid input' </code></pre>
[ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-01-20T09:18:51.987", "Id": "66503", "Score": "0", "body": "Probably not worth an actual answer but gcd and decimal should probably raise ValueError if type is wrong or q is 0. Also, you are computing much more than what you realy need for the problem 26. Actual solution should be much simpler." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-01-20T09:31:22.877", "Id": "66504", "Score": "0", "body": "How can I simplify it to just solve the problem 26?" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-01-20T21:33:37.677", "Id": "66565", "Score": "1", "body": "Do you really have to care that `a` and `b` are ints?" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-01-21T06:06:11.733", "Id": "66626", "Score": "0", "body": "gcd is defined for ints only, so yes." } ]
[ { "body": "<p>Trying to generate the actual string representation is interesting to understand the problem but you do not need to keep all that complexity in your code for problem 26. Indeed, you are only interested in the length of the cycle for <code>1/d</code>. Thus, what I did was to :</p>\n\n<ul>\n<li>remove all the logic corresponding to string construction at the end of the function</li>\n<li>simplify argument handling by removing <code>p</code> (always 1) and considering only positive <code>q</code> (renamed <code>d</code>).</li>\n<li>notice that we can actually return the value directly from the <code>while</code> loop and 0 if we get out of the loop.</li>\n<li>notice that we don't actually need the content of <code>qlist</code> but we do need its length.</li>\n<li>notice that the first iteration is somehow just an iteration like the other to remove a bit of code.</li>\n<li>notice that we don't need the quotients anymore</li>\n</ul>\n\n<p>At the end, here's what the code is like :</p>\n\n<pre><code>def cycle_length(d):\n \"\"\"Computes the length of the recurring cycle in the decimal representation\n of the rational number 1/d if any, 0 otherwise\n \"\"\"\n\n if not isinstance(d, int) or d &lt;= 0:\n raise ValueError(\"cycle_length(d): d must be a positive integer\")\n\n rlist = []\n qlist_len = 0\n remainder = 1\n\n while remainder:\n remainder = remainder % d\n if remainder in rlist:\n return qlist_len - rlist.index(remainder)\n rlist.append(remainder)\n remainder *= 10\n qlist_len+=1\n\n return 0\n\n\nif __name__ == '__main__':\n for d in range(1,20): #d = raw_input('d: ')\n try:\n print '1/%s =' % (d), cycle_length(int(d))\n except ValueError:\n print 'invalid input'\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-01-20T19:26:36.460", "Id": "66554", "Score": "0", "body": "Won't your `remainder` overflow if the cycle is long enough?" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-01-21T08:34:28.177", "Id": "66635", "Score": "0", "body": "Integers do not overflow in Python, do they ?" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-01-21T08:45:18.890", "Id": "66637", "Score": "0", "body": "@Josey, Ah true, didn't realize that they are arbitrary precision." } ], "meta_data": { "CommentCount": "3", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-01-20T11:41:04.370", "Id": "39651", "ParentId": "39642", "Score": "4" } }, { "body": "<p>I'm just going to comment on your <code>gcd</code> function.</p>\n\n<ol>\n<li><p>The docstring mixes up the function's <em>interface</em> (\"computes gcd of a, b\") with its <em>implementation</em> (\"using Euclidean algorithm\"). It's best to restrict the docstring to the interface (which is what the user needs to know); if you also need to document the implementation, put it in comments.</p></li>\n<li><p>Your <code>gcd</code> implementation returns <code>None</code> if its arguments are not integers. This behaviour should be mentioned in the docstring.</p></li>\n<li><p><strong>But</strong> returning exceptional values is generally a bad idea: it pushes the complexity of error handling onto the caller, where it would be easy to forget to do the checking. And in fact you <em>have</em> failed to check that the result is not <code>None</code>:</p>\n\n<pre><code>g = gcd(abs_p, abs_q)\np = abs_p / g # What if g is None here?\n</code></pre>\n\n<p>It is better for a function to raise an exception if it is given the wrong arguments: that way the caller doesn't need to take any special precautions, but the error is reliably detected and reported.</p></li>\n<li><p>The test <code>isinstance(a, int)</code> is too restrictive. Euclid's GCD algorithm will work on other kinds of numbers too, and it would be nice to be able to support:</p>\n\n<pre><code>&gt;&gt;&gt; from fractions import Fraction\n&gt;&gt;&gt; gcd(Fraction(1, 3), Fraction(1,4))\nFraction(1, 12)\n</code></pre>\n\n<p>or:</p>\n\n<pre><code>&gt;&gt;&gt; from decimal import Decimal\n&gt;&gt;&gt; gcd(Decimal('11.1'), Decimal('2.1'))\nDecimal('0.3')\n</code></pre>\n\n<p>instead of having to write separate <code>gcd</code> implementations for these other types.</p>\n\n<p>So in fact the best thing to do is not to have any type-checking at all in your <code>gcd</code> function. If someone calls it with the wrong type of object, they will get a <code>TypeError</code>:</p>\n\n<pre><code>&gt;&gt;&gt; gcd('hello', 'world')\nTraceback (most recent call last):\n ...\nTypeError: not all arguments converted during string formatting\n</code></pre></li>\n<li><p>You call <code>abs</code> on the arguments <code>a</code> and <code>b</code>. But in fact you only ever call <code>gcd</code> with arguments that have non-negative values already. So the extra calls to <code>abs</code> are wasted.</p></li>\n<li><p>So in summary, I would write the <code>gcd</code> function like this:</p>\n\n<pre><code>def gcd(a, b):\n \"\"\"Return the greatest common divisor of a and b.\"\"\"\n while b != 0:\n a, b = b, a % b\n return a\n</code></pre></li>\n<li><p><strong>But</strong> in fact Python already has a built-in <a href=\"http://docs.python.org/3/library/fractions.html#fractions.gcd\"><code>gcd</code></a> function (in the <a href=\"http://docs.python.org/3/library/fractions.html\"><code>fractions</code></a> module), so all you actually have to do is write:</p>\n\n<pre><code>from fractions import gcd\n</code></pre></li>\n</ol>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-01-22T15:51:39.193", "Id": "39822", "ParentId": "39642", "Score": "7" } } ]
{ "AcceptedAnswerId": "39651", "CommentCount": "4", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-01-20T06:35:58.550", "Id": "39642", "Score": "7", "Tags": [ "python", "project-euler", "mathematics" ], "Title": "Helper function to solve Project Euler question 26" }
39642
<p>I wrote a simple class in Python, which controls code invocation, in a multi-threaded environment, with the following logic:</p> <p>The class' main method, named <code>try_to_do</code>, takes two function pointers as arguments: <code>yes_we_can_fn</code> and <code>no_we_cannot_fn</code>.</p> <p>In any point in time, only a single thread can invoke code the function passed as <code>yes_we_can_fn</code> argument.</p> <p>If a specific thread tries to invoke its code, but some other thread is already invoking its code, then the <code>no_we_cannot_fn</code> is invoked <strong>instead of</strong> <code>yes_we_can_fn</code>.</p> <p>If there's an exception in the code being executed, it should raise to the calling context.</p> <p>The code:</p> <pre><code>from threading import Lock class MyController(): def __init__(self): self.locker = Lock() self.is_active = False def try_to_do(self, yes_we_can_fn, no_we_cannot_fn): with self.locker: if self.is_active: we_can_do_it = False else: we_can_do_it = True self.is_active = True try: if we_can_do_it: yes_we_can_fn() else: no_we_cannot_fn() finally: if we_can_do_it: with self.locker: self.is_active = False </code></pre> <p>Usage:</p> <pre><code>ctl = MyController() def p1(): from time import sleep print 'before sleep' sleep(2) print 'done' def p2(): print 'too busy, will try some other time' ctl.try_to_do(p1, p2) </code></pre> <p>I'd like to get some reviews: thread safety (maybe I'm missing something?), coding style, etc.</p>
[]
[ { "body": "<p>You could avoid the <code>is_active</code> variable by using the lock in a non-blocking manner:</p>\n\n<pre><code>def try_to_do(self, yes_we_can_fn, no_we_cannot_fn):\n if self.locker.acquire(False):\n try:\n yes_we_can_fn()\n finally:\n self.locker.release()\n else:\n no_we_cannot_fn()\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-01-20T19:04:18.840", "Id": "66551", "Score": "0", "body": "That's a great idea. Note that there should also be a `try/finally` around the `no_we_cannot_fn()`." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-01-20T19:09:24.790", "Id": "66552", "Score": "0", "body": "@RonKlein In your version the `finally` block does nothing in the case where `no_we_cannot_fn()` gets called." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-01-20T21:52:46.760", "Id": "66572", "Score": "0", "body": "After another look in your suggested code, I see that even if there was as exception while invoking `no_we_cannot_fn`, the class' state won't get affected. In my (original) code, it would be. So you're absolutely right, there's no need for a `try` wrapper around `no_we_cannot_fn()` in your suggestion." } ], "meta_data": { "CommentCount": "3", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-01-20T14:40:09.787", "Id": "39655", "ParentId": "39647", "Score": "2" } } ]
{ "AcceptedAnswerId": "39655", "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-01-20T10:17:02.580", "Id": "39647", "Score": "3", "Tags": [ "python", "multithreading", "thread-safety" ], "Title": "Invoke only by a single thread" }
39647
<p>We all know about the <a href="http://loungecpp.wikidot.com/tips-and-tricks%3aindices" rel="noreferrer">indices trick</a>, right? Here's (hopefully) an improved version...</p> <pre><code>template &lt;::std::size_t...&gt; struct indices { }; namespace detail { template&lt;class A, class B&gt; struct catenate_indices; template &lt;::std::size_t ...Is, ::std::size_t ...Js&gt; struct catenate_indices&lt;indices&lt;Is...&gt;, indices&lt;Js...&gt; &gt; { using indices_type = indices&lt;Is..., Js...&gt;; }; template &lt;::std::size_t, ::std::size_t, typename = void&gt; struct expand_indices; template &lt;::std::size_t A, ::std::size_t B&gt; struct expand_indices&lt;A, B, typename ::std::enable_if&lt;A == B&gt;::type&gt; { using indices_type = indices&lt;A&gt;; }; template &lt;::std::size_t A, ::std::size_t B&gt; struct expand_indices&lt;A, B, typename ::std::enable_if&lt;A != B&gt;::type&gt; { static_assert(A &lt; B, "A &gt; B"); using indices_type = typename catenate_indices&lt; typename expand_indices&lt;A, (A + B) / 2&gt;::indices_type, typename expand_indices&lt;(A + B) / 2 + 1, B&gt;::indices_type &gt;::indices_type; }; } template &lt;::std::size_t A&gt; struct make_indices : detail::expand_indices&lt;0, A&gt;::indices_type { }; template &lt;::std::size_t A, ::std::size_t B&gt; struct make_indices_range : detail::expand_indices&lt;A, B&gt;::indices_type { }; </code></pre> <p>Usage:</p> <pre><code>#include &lt;iostream&gt; #include "utility.hpp" template &lt;::std::size_t ...Is&gt; void show_indices(indices&lt;Is...&gt;) { [](...){}((((::std::cout &lt;&lt; Is &lt;&lt; ::std::endl), 0))...); } int main() { show_indices(make_indices_range&lt;3, 9&gt;()); return 0; } </code></pre> <p>Any suggestions?</p>
[]
[ { "body": "<p>You can get rid of the <code>&lt;type_traits&gt;</code> header by replacing your <code>std::enable_if</code> by a <code>bool</code> template specialization:</p>\n\n<pre><code>template &lt;::std::size_t, ::std::size_t, bool&gt;\nstruct expand_indices_impl;\n\ntemplate &lt;::std::size_t A, ::std::size_t B&gt;\nstruct expand_indices:\n expand_indices_impl&lt;A, B, A==B&gt;\n{};\n\ntemplate &lt;::std::size_t A, ::std::size_t B&gt;\nstruct expand_indices_impl&lt;A, B, true&gt;\n{\n using indices_type = indices&lt;A&gt;;\n};\n\ntemplate &lt;::std::size_t A, ::std::size_t B&gt;\nstruct expand_indices_impl&lt;A, B, false&gt;\n{\n static_assert(A &lt; B, \"A &gt; B\");\n using indices_type = typename catenate_indices&lt;\n typename expand_indices&lt;A, (A + B) / 2&gt;::indices_type,\n typename expand_indices&lt;(A + B) / 2 + 1, B&gt;::indices_type\n &gt;::indices_type;\n};\n</code></pre>\n\n<hr>\n\n<p>Moreover, in C++ (and many other programming languages, see Python <code>range</code> for example), ranges tend to have the end-exclusive form <code>[begin, end)</code>; therefore, <code>make_indices_range&lt;3, 9&gt;</code> should contain the indices from 3 to 8, and not from 3 to 9. It is easy to alter the behaviour:</p>\n\n<pre><code>template &lt;::std::size_t A&gt;\nstruct make_indices:\n detail::expand_indices&lt;0, A-1&gt;::indices_type\n{};\n\ntemplate &lt;::std::size_t A, ::std::size_t B&gt;\nstruct make_indices_range:\n detail::expand_indices&lt;A, B-1&gt;::indices_type\n{};\n</code></pre>\n\n<p>As proposed in the comments, <code>make_indices_range</code> also needs to provide an empty range when <code>A == B</code>:</p>\n\n<pre><code>template &lt;::std::size_t A&gt;\nstruct make_indices_range&lt;A, A&gt;:\n indices&lt;&gt;\n{};\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-03-01T14:46:03.873", "Id": "74449", "Score": "1", "body": "You did not provide for the special case of `make_indices_range<A, A>` in which case you need to inherit from `indices<>`." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-03-02T19:51:55.043", "Id": "74611", "Score": "0", "body": "@user1095108 Well, that's actually a good idea :)" } ], "meta_data": { "CommentCount": "2", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-02-28T13:54:20.727", "Id": "43061", "ParentId": "39648", "Score": "11" } } ]
{ "AcceptedAnswerId": "43061", "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-01-20T11:08:07.033", "Id": "39648", "Score": "10", "Tags": [ "c++", "c++11" ], "Title": "Improved indices trick" }
39648
<p>I suspect that this can be done in a much neater way using list comprehension in python:</p> <pre><code>poses = [] for x,y in get_points(spline): pose = Pose2D() pose.theta = 0 pose.x=x pose.y=y poses.append(pose) return poses </code></pre> <p>Is there a way to create a nice one liner for the above? (I do not have a constructor that takes the three arguments for Pose2D)</p>
[]
[ { "body": "<pre><code>def make_pose(pt):\n pose = Pose2D()\n pose.theta = 0\n pose.x, pose.y = pt\n return pose\n\nposes = [make_pose(pt) for pt in get_points(spline)]\n</code></pre>\n\n<p>Alternatively, you could subclass <code>Pose2D</code> to give it an appropriate constructor.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-01-20T20:35:12.773", "Id": "66561", "Score": "0", "body": "I'm wondering why this solution isn't accepted (yet)" } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-01-20T17:08:00.693", "Id": "39666", "ParentId": "39665", "Score": "10" } }, { "body": "<p>In case it's useful you could write a more general object maker function for classes that don't have constructors of the type you want.</p>\n\n<pre><code>def make_object(Class, **kwargs):\n \"\"\" Returns a new object from Class, with the attributes specified as keyword arguments \"\"\"\n object = Class()\n for key, value in kwargs.items():\n setattr(object, key, value)\n return object\n\nposes = [make_object(Pose2D, x=x, y=y, theta=0) for x, y in get_points(spline)]\n</code></pre>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-01-20T22:49:16.863", "Id": "39697", "ParentId": "39665", "Score": "1" } }, { "body": "<p>for completeness sake there's also the <a href=\"http://docs.python.org/2/library/functions.html\" rel=\"nofollow\">map builtin</a> in pythong 2.x. Using @hughbothwell's example:</p>\n\n<pre><code>poses = map (make_pose, points)\n</code></pre>\n\n<p>which is essentially the same as </p>\n\n<pre><code>poses = [makePose(pt) for pt in get_points(spline)]\n</code></pre>\n\n<p>Map is handy for shortening ths common pattern, but I think Guido has officially disowned it for the future</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-01-21T22:02:29.747", "Id": "39766", "ParentId": "39665", "Score": "2" } } ]
{ "AcceptedAnswerId": "39666", "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-01-20T16:50:55.800", "Id": "39665", "Score": "8", "Tags": [ "python" ], "Title": "List iteration, creation, or comprehension" }
39665
<p>I need to write a function that, when given an input (string, float, or int), returns that input as a reduced partial fraction, and it needs to accept a wide array of inputs:</p> <pre><code>1.5 =&gt; "1 1/2" 5/2 =&gt; "2 1/2" "1/3" =&gt; "1/3" 5 =&gt; "5" "6 1/3" =&gt; "6 1/3" 0 =&gt; "0" </code></pre> <p>I've written this function using the Rational class, but was wondering if there were a better, more elegant solution:</p> <pre><code>def format_partial_fraction(fraction) if fraction.include? "/" # to handle "6 1/3" =&gt; "6 1/3" (or maybe I'll just trust user input in this case) fraction = fraction.split(" ").inject{|sum,x| sum.to_r + x.to_r } end rational = fraction.to_r if rational == 0 return "0" elsif rational &lt; 1 # e.g. "1/3" rational.to_s else # e.g. "3 1/2" or just "3" rational.to_i.to_s + ( rational%1 == 0 ? "" : " " + (rational%1).to_s) end end </code></pre> <p>Ruby 2.0.0, Rails 3.2.13</p>
[ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-01-20T22:02:39.923", "Id": "66574", "Score": "1", "body": "I misread the title at first. I was disappointed when I found that no partial _function_ is involved :) Still, good question." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-02-27T20:38:18.203", "Id": "74115", "Score": "0", "body": "f you are satisfied with any of the answers, you should select the one that was most helpful to you." } ]
[ { "body": "<p>Non-string input can lead to surprising results:</p>\n\n<pre><code>p (5/2).to_r #=&gt; (2/1), integer division performed first\np (1.1).to_r #=&gt; (2476979795053773/2251799813685248), float can not be represented in binary\n</code></pre>\n\n<p>The last case is prevented by:</p>\n\n<pre><code>p 1.1.to_s.to_r #=&gt; (11/10)\n</code></pre>\n\n<p>So I'd change <code>rational = fraction.to_r</code> to <code>rational = fraction.to_s.to_r</code>. But the first case is only handled correctly if it is a string to begin with: </p>\n\n<pre><code>p \"5/2\".to_r #=&gt; (5/2)\n</code></pre>\n\n<p>I don't think there is a remedy for that, except accepting string or float input input only.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-01-21T01:19:36.410", "Id": "66596", "Score": "0", "body": "Right. If the method-caller passes in `5/2` as an integer, there's nothing that can be done." } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-01-20T20:12:55.693", "Id": "39677", "ParentId": "39671", "Score": "3" } }, { "body": "<p>this</p>\n\n<pre><code>fraction = fraction.split(\" \").inject{|sum,x| sum.to_r + x.to_r }\n</code></pre>\n\n<p>can also be expressed like this:</p>\n\n<pre><code>fraction = fraction.split(\" \").map(&amp;:to_r).inject(:+)\n</code></pre>\n\n<p>this:</p>\n\n<pre><code>rational.to_i.to_s + ( rational%1 == 0 ? \"\" : \" \" + (rational%1).to_s)\n</code></pre>\n\n<p>is a bit long, and repeats the expression <code>rational%1</code>. I'd use a small private method to clean it up a bit:</p>\n\n<pre><code>rational.to_i.to_s + fractional_part_to_s(rational % 1)\n\n...\n\ndef fraction_part_to_s(f)\n if fractional_part == 0\n \"\"\n else\n fractional_part.to_s\n end\nend\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-01-22T03:30:01.510", "Id": "66736", "Score": "0", "body": "I like your first suggestion but I prefer the compactness of the original over your 2nd suggestion" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-01-22T10:57:55.097", "Id": "66757", "Score": "0", "body": "@Jonah, Although I am not a fan of the trinary operator, it is a reasonable choice, and would serve just as well there." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-01-22T11:10:21.507", "Id": "66759", "Score": "0", "body": "on 2nd thought i do like giving that portion a name. i just really dislike full if else statements. you could do `return f.to_s unless f == 0; \"\"`" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-01-22T11:13:09.163", "Id": "66761", "Score": "0", "body": "@Jonah, There are many ways to skin this cat" } ], "meta_data": { "CommentCount": "4", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-01-20T22:01:27.870", "Id": "39693", "ParentId": "39671", "Score": "1" } } ]
{ "AcceptedAnswerId": "39677", "CommentCount": "2", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-01-20T19:25:20.883", "Id": "39671", "Score": "6", "Tags": [ "ruby", "ruby-on-rails", "mathematics" ], "Title": "Return input as a partial fraction" }
39671
<p>This is a Python program to mint a hashcash token, but my code is a lot slower than using a library. What is slowing my program down? It takes over 10 seconds to mint a 20-bit stamp, but using a library, it takes less than a second.</p> <p>This is my program:</p> <pre><code>from os import urandom from hashlib import sha1 import time def mint(name, bits): t = time.strftime("%y%m%d") out = " " count = 0 while out[:bits] != bits*"0": RandomData = urandom(8).encode("base64").replace("\n", "") data = "1:%d:%s:%s::%s:%s"%(bits, t, name, RandomData, format(count, 'x')) out = (''.join(format(ord(x), '08b') for x in sha1(data).digest())) count += 1 return data print mint("email_address", 20) </code></pre> <p><a href="http://gnosis.cx/download/gnosis/util/hashcash.py">This</a> is the library I am using for comparison.</p>
[ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-01-20T21:25:25.677", "Id": "66564", "Score": "0", "body": "Aside from that you're (1) using strings (and formatters all over the place) rather than numbers, and (2) rebuilding the zeros-string each iteration even though it never changes?" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-01-20T21:34:21.377", "Id": "66566", "Score": "0", "body": "@cHao What do you mean it never changes? I am using `urandom`" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-01-21T00:47:21.610", "Id": "66590", "Score": "0", "body": "When does `bits * \"0\"` ever change?" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-01-21T00:55:36.987", "Id": "66593", "Score": "0", "body": "@cHao it changes when i want to adjust the collision amount" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-01-21T01:01:49.197", "Id": "66594", "Score": "2", "body": "Yeah, but that's once per call. You don't need to re-figure it each time through the loop. And i'm pretty sure `RandomData` doesn't need to be recreated each time through either -- that's the point of `count`, to change the header so you get a different hash. You just keep incrementing `count` (and leave the other fields alone) til you get a hash with enough zeros." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-01-21T02:05:08.847", "Id": "66602", "Score": "0", "body": "What version of Python are you using?" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-01-21T02:43:53.323", "Id": "66610", "Score": "0", "body": "@cHao version 2.7" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-01-24T12:18:31.510", "Id": "67071", "Score": "0", "body": "An optimized c/assembly implementation should be able to run in 0.15 sec or so. A good GPU will take 0.5 *milli*seconds." } ]
[ { "body": "<p>The first thing to do is to profile your code. Hashcash is really designed to make you perform 2^20 hashes: if you do more work than those hashes, something's wrong!</p>\n\n<h2>Profiling</h2>\n\n<p><code>python -m cProfile -s cumtime original.py</code></p>\n\n<p>Let's look at all the places where the algorithms spends more than 0.001 seconds (I've asked for 15 bits since 20 bits is too slow on my computer) :</p>\n\n<pre><code> Ordered by: internal time\n\n ncalls tottime percall cumtime percall filename:lineno(function)\n 1414287 4.087 0.000 7.665 0.000 original.py:12(&lt;genexpr&gt;)\n 1414287 2.433 0.000 2.433 0.000 {format}\n 134695 1.737 0.000 9.402 0.000 {method 'join' of 'str' objects}\n 1346940 1.295 0.000 1.295 0.000 {ord}\n 1 0.886 0.886 12.709 12.709 original.py:5(mint)\n 67347 0.536 0.000 0.969 0.000 base64.py:310(encodestring)\n 67347 0.432 0.000 0.432 0.000 {posix.urandom}\n 67347 0.258 0.000 1.292 0.000 base64_codec.py:13(base64_encode)\n 67347 0.231 0.000 1.525 0.000 {method 'encode' of 'str' objects}\n 67348 0.141 0.000 0.141 0.000 {_hashlib.openssl_sha1}\n 67347 0.131 0.000 0.131 0.000 {method 'digest' of '_hashlib.HASH' objects}\n 134694 0.131 0.000 0.131 0.000 {len}\n 67347 0.126 0.000 0.126 0.000 {binascii.b2a_base64}\n 67348 0.110 0.000 0.110 0.000 {range}\n 67347 0.109 0.000 0.109 0.000 {method 'replace' of 'str' objects}\n 67347 0.066 0.000 0.066 0.000 {method 'append' of 'list' objects}\n 1 0.001 0.001 0.001 0.001 hashlib.py:55(&lt;module&gt;)\n 1 0.001 0.001 0.001 0.001 base64.py:3(&lt;module&gt;)\n</code></pre>\n\n<p>This specific run took 12.7 seconds (original.py:5). It spent 4 seconds in the <code>for x in ...</code> generator, 2.4 seconds in <code>format(ord(x), '08b')</code>, 1.7 seconds in <code>''.join(...)</code>, and 1.3 seconds in <code>ord(x)</code>.</p>\n\n<p>That's a total of... 9.5 seconds out of 12.7 seconds spent in the <code>out = (''.join(format(ord(x), '08b') for x in sha1(data).digest()))</code> line. This would have been impossible to figure out without profiling (as you can see in kyle k's comment). It's the number one rule of optimizations: since you'll spent 80% of your time in 20% of the code, only optimize what you know to be slow!</p>\n\n<h2>Removing the 80%</h2>\n\n<p>So, how can we replace this line? The idea is to use <code>hexdigest</code> instead of <code>digest</code>. The issue with <code>hexdigest</code> is that we only see hexadecimal digits, not bits. Since 20 bits is 5 hexadecimal numbers, that's not an issue here. If you needed 21 bits, then you would ask for 6 hexadecimal numbers, which is more hashes than necessary, but still worth the speed up.</p>\n\n<p>Here's the new code:</p>\n\n<pre><code>from os import urandom\nfrom hashlib import sha1\nimport time\nfrom math import ceil\n\ndef mint(name, bits):\n t = time.strftime(\"%y%m%d\")\n out = \" \"\n count = 0\n digits = int(ceil(bits/4.0))\n\n while out[:digits] != digits*\"0\":\n RandomData = urandom(8).encode(\"base64\").replace(\"\\n\", \"\")\n RandomData = 'AHZlx9LYMyo='\n data = \"1:%d:%s:%s::%s:%s\"%(bits, t, name, RandomData, format(count, 'x'))\n out = sha1(data).hexdigest()\n count += 1\n return data\n\nprint mint(\"email_address\", 15)\n</code></pre>\n\n<p>And the new profiling:</p>\n\n<pre><code> ncalls tottime percall cumtime percall filename:lineno(function)\n 1 0.750 0.750 3.212 3.212 improved.py:6(mint)\n 67347 0.529 0.000 0.959 0.000 base64.py:310(encodestring)\n 67347 0.427 0.000 0.427 0.000 {posix.urandom}\n 67347 0.251 0.000 1.274 0.000 base64_codec.py:13(base64_encode)\n 67347 0.227 0.000 1.503 0.000 {method 'encode' of 'str' objects}\n 67347 0.155 0.000 0.155 0.000 {format}\n 67348 0.138 0.000 0.138 0.000 {_hashlib.openssl_sha1}\n 67347 0.134 0.000 0.134 0.000 {method 'hexdigest' of '_hashlib.HASH' objects}\n 134694 0.131 0.000 0.131 0.000 {len}\n 67347 0.122 0.000 0.122 0.000 {binascii.b2a_base64}\n 67348 0.109 0.000 0.109 0.000 {range}\n 67347 0.105 0.000 0.105 0.000 {method 'replace' of 'str' objects}\n 67348 0.066 0.000 0.066 0.000 {method 'join' of 'str' objects}\n 67347 0.066 0.000 0.066 0.000 {method 'append' of 'list' objects}\n 1 0.001 0.001 0.001 0.001 hashlib.py:55(&lt;module&gt;)\n 1 0.001 0.001 3.213 3.213 improved.py:1(&lt;module&gt;)\n 1 0.001 0.001 0.001 0.001 base64.py:3(&lt;module&gt;)\n</code></pre>\n\n<p>Yay! Only 3.2 seconds in <code>mint()</code>.</p>\n\n<h2>Removing another 80%</h2>\n\n<p>But hashing is still not the most expensive part. It's now the computing of RandomData (0.5 + 0.2 seconds in base64 encoding, 0.4 seconds in urandom, and so on). @cHao is right, you only need to compute that RandomData once and find the count that provides the correct sha1 hash. Let's move it out of the while loop:</p>\n\n<pre><code>from os import urandom\nfrom hashlib import sha1\nimport time\nfrom math import ceil\n\ndef mint(name, bits):\n t = time.strftime(\"%y%m%d\")\n out = \" \"\n count = 0\n digits = int(ceil(bits/4.0))\n RandomData = urandom(8).encode(\"base64\").replace(\"\\n\", \"\") \n RandomData = 'AHZlx9LYMyo='\n\n while out[:digits] != digits*\"0\":\n data = \"1:%d:%s:%s::%s:%s\"%(bits, t, name, RandomData, format(count, 'x'))\n out = sha1(data).hexdigest()\n count += 1\n return data\n\nprint mint(\"email_address\", 15)\n</code></pre>\n\n<p>The new profile is:</p>\n\n<pre><code> ncalls tottime percall cumtime percall filename:lineno(function)\n 1 0.414 0.414 0.795 0.795 improved.py:6(mint)\n 67347 0.134 0.000 0.134 0.000 {format}\n 67348 0.124 0.000 0.124 0.000 {_hashlib.openssl_sha1}\n 67347 0.121 0.000 0.121 0.000 {method 'hexdigest' of '_hashlib.HASH' objects}\n 1 0.001 0.001 0.001 0.001 hashlib.py:55(&lt;module&gt;)\n 1 0.001 0.001 0.796 0.796 improved.py:1(&lt;module&gt;)\n 1 0.001 0.001 0.001 0.001 base64.py:3(&lt;module&gt;)\n</code></pre>\n\n<p>We only took 0.8 seconds (down from 12.7). <code>format</code> still takes time, but only one third of the time. I don't know what to do about it, so I'll leave it as it is, but you got your 10x speedup with two simple changes.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-01-21T14:24:52.523", "Id": "66665", "Score": "0", "body": "Constructing most of `data` before the loop, leaving only `data = prefix + format(count, 'x')` inside, shaves off further 35 % on my PC." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-01-21T14:43:49.663", "Id": "66669", "Score": "0", "body": "Yeah I had tried it but it didn't help here. Glad you got an improvement. :)" } ], "meta_data": { "CommentCount": "2", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-01-21T09:59:37.103", "Id": "39731", "ParentId": "39674", "Score": "7" } } ]
{ "AcceptedAnswerId": "39731", "CommentCount": "8", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-01-20T19:35:19.250", "Id": "39674", "Score": "8", "Tags": [ "python", "performance", "cryptography" ], "Title": "Python mint hashcash token" }
39674
<p>Just a plain button, in different sizes. I wanted to achieve exactly the same styling cross browser for both anchors, inputs and buttons.</p> <p>I'm just wondering if this could be improved.</p> <p><strong>Markup</strong></p> <pre><code>&lt;!DOCTYPE html&gt; &lt;html&gt; &lt;head&gt; &lt;title&gt;CSS button&lt;/title&gt; &lt;link rel="stylesheet" href="css/main.css"&gt; &lt;/head&gt; &lt;body&gt; &lt;a href="#" class="button button-tiny button-primary"&gt;Sign up&lt;/a&gt; &lt;a href="#" class="button button-primary"&gt;Sign up&lt;/a&gt; &lt;a href="#" class="button button-medium button-primary"&gt;Sign up&lt;/a&gt; &lt;a href="#" class="button button-large button-primary"&gt;Sign up&lt;/a&gt; &lt;hr&gt; &lt;input type="submit" class="button button-tiny button-primary" value="Sign up"&gt; &lt;input type="submit" class="button button-primary" value="Sign up"&gt; &lt;input type="submit" class="button button-medium button-primary" value="Sign up"&gt; &lt;input type="submit" class="button button-large button-primary" value="Sign up"&gt; &lt;hr&gt; &lt;button class="button button-tiny button-primary"&gt;Sign up&lt;/button&gt; &lt;button class="button button-primary"&gt;Sign up&lt;/button&gt; &lt;button class="button button-medium button-primary"&gt;Sign up&lt;/button&gt; &lt;button class="button button-large button-primary"&gt;Sign up&lt;/button&gt; &lt;/body&gt; &lt;/html&gt; </code></pre> <p><strong>CSS</strong></p> <pre><code>body, input, button { font: 14px "Trebuchet MS", sans-serif; } input::-moz-focus-inner, button::-moz-focus-inner { border: 0; padding: 0; } .button { padding:8px 16px; display:inline-block; text-decoration:none; border-radius:3px; border:0; margin:0; } input[type="submit"].button, button.button { cursor:pointer; outline:none; } .button-tiny { font-size:12px; padding:6px 14px; } .button-medium { font-size:16px; padding:10px 18px; } .button-large { font-size:18px; padding:12px 20px; } .button-primary { background:slategrey; color:#fff; } .button-primary:hover { background:lightslategrey; }; </code></pre>
[]
[ { "body": "<p>I took the liberty of adding your code to a <a href=\"http://jsfiddle.net/WbsmE/\" rel=\"nofollow noreferrer\">Fiddle Here</a> so that we could see what it being displayed and test it in different browsers.</p>\n\n<hr>\n\n<p>I tried to set my Browser to IE 8 and less and apparently it doesn't play nice with JSFiddle. but in IE 9 mode it showed up very nicely, exactly the same as in Chrome.</p>\n\n<hr>\n\n<p>I like that you created a CSS class <code>button-primary</code> so that you didn't repeat the code you were going to use in all the buttons. and so you didn't have to write so many <code>:hover</code> statements. </p>\n\n<hr>\n\n<p>Overall I would say that this is some pretty clean code.</p>\n\n<p>But, there is one thing that I would suggest that you do.</p>\n\n<p><strong>Terminate every tag</strong></p>\n\n<p>This</p>\n\n<pre><code>&lt;link rel=\"stylesheet\" href=\"css/main.css\"&gt;\n</code></pre>\n\n<p>Becomes </p>\n\n<pre><code>&lt;link rel=\"stylesheet\" href=\"css/main.css\" /&gt;\n</code></pre>\n\n<p>Notice the <code>/&gt;</code> at the end. if there is no closing tag you should still \"<em>close the tag</em>\"</p>\n\n<p>these are called Self closing Tags. </p>\n\n<p>some Tags are self closing tags and some are not. HTML5 is a little blurry on this, or I am a little blurry on HTML5 </p>\n\n<p>either way you should make sure that these tags</p>\n\n<ol>\n<li><code>&lt;img /&gt;</code></li>\n<li><code>&lt;hr /&gt;</code></li>\n<li><code>&lt;br /&gt;</code></li>\n<li><code>&lt;input /&gt;</code></li>\n<li><code>&lt;area /&gt;</code></li>\n<li><code>&lt;link /&gt;</code></li>\n<li><code>&lt;meta /&gt;</code></li>\n</ol>\n\n<p>and some others. <a href=\"https://stackoverflow.com/a/97585/1214743\">This Answers</a> Lists some more</p>\n\n<hr>\n\n<p>XHTML allows you to Self Close any tag, this isn't really good practice, mostly because most tags are meant to be containers and leaving them empty would be really silly.</p>\n\n<hr>\n\n<p>This <a href=\"https://stackoverflow.com/a/13232170/1214743\">more recent answer from BoltClock</a> explains a little bit better about closing tags.</p>\n\n<p>I recommend always closing your tags, even if the Doctype tells you that you don't have to. it is better practice.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-01-22T16:53:17.933", "Id": "66800", "Score": "0", "body": "Thanks for this feedback! Regarding the self closing tags, I prefer to not self close but I keep this consistent. As you mentioned, HTML5 is a little blurry on this. I think it's preference, to be honest." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-01-22T17:30:10.207", "Id": "66803", "Score": "0", "body": "if you ever code for XML or XHTML and you are used to doing this, you will get errors and not know where they came from. it's not a good idea, and shouldn't be your preference, in my opinion" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-01-23T16:26:25.013", "Id": "66928", "Score": "0", "body": "That's true, and a good point." } ], "meta_data": { "CommentCount": "3", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-01-22T14:41:28.523", "Id": "39812", "ParentId": "39676", "Score": "2" } } ]
{ "AcceptedAnswerId": "39812", "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-01-20T20:09:25.650", "Id": "39676", "Score": "6", "Tags": [ "html", "css" ], "Title": "Plain CSS buttons in different sizes" }
39676
<p><a href="http://www.typescriptlang.org/" rel="nofollow">Typescript</a> was developed by Microsoft and is open-source. It is a superset of Javascript and includes optional static typing and class-based object orientation.</p>
[]
[]
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-01-20T20:52:10.967", "Id": "39678", "Score": "0", "Tags": null, "Title": null }
39678
Typescript is a language which is a super set of JavaScript
[]
[]
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-01-20T20:52:10.967", "Id": "39679", "Score": "0", "Tags": null, "Title": null }
39679
<p>An <a href="http://en.wikipedia.org/wiki/Interpreter_%28computing%29" rel="nofollow">interpreter</a> directly executes programming language instructions without a previously compiling them into a machine language. </p>
[]
[]
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-01-20T20:55:00.883", "Id": "39680", "Score": "0", "Tags": null, "Title": null }
39680
An interpreter is a computer program which directly executes instructions written in a programming language.
[]
[]
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-01-20T20:55:00.883", "Id": "39681", "Score": "0", "Tags": null, "Title": null }
39681
<p><a href="http://en.wikipedia.org/wiki/Cyclomatic_complexity" rel="nofollow">Cyclomatic Complexity (Wikipedia)</a> was developed in 1976 by Thomas J. McCabe Sr. as a measure of the complexity of program methods, programs, or blocks. It works by tracking and counting all the linearly independent paths through a program. The more ways there are to move through the program, the greater the cyclomatic complexity.</p>
[]
[]
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-01-20T20:57:22.783", "Id": "39682", "Score": "0", "Tags": null, "Title": null }
39682
Cyclomatic Complexity is a metric of the complexity of a program or a section of a program.
[]
[]
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-01-20T20:57:22.783", "Id": "39683", "Score": "0", "Tags": null, "Title": null }
39683
<p>I've created this abstract base class for testing the <code>Equals</code> method.</p> <p>The basic idea is that derived class implements methods to get:</p> <ul> <li>the primary test instance, and </li> <li>a list of unequal instances (it's up to the derived class to ensure that this list is sufficient instances for testing all possible inequalities)</li> </ul> <p>The base class then is responsible for using those instances to test.</p> <p>Am I missing any unit tests that would be useful for ensuring that the class is correctly using <code>Equals</code> and <code>GetHashCode</code>?</p> <pre><code>using System.Collections.Generic; using System.Linq; using Microsoft.VisualStudio.TestTools.UnitTesting; /// &lt;summary&gt; /// A base class for testing the Equals method of an object. /// &lt;/summary&gt; [TestClass] public abstract class EqualityTestBase { [TestMethod] public void Equals_PassNull_ReturnFalse() { // -------- Assemble -------- object target = GetPrimary(); bool expected = false; // -------- Act -------- bool actual = target.Equals(null); // -------- Assert -------- Assert.AreEqual(expected, actual); } [TestMethod] public void Equals_PassGenericObject_ReturnFalse() { // -------- Assemble -------- object target = GetPrimary(); object genericObject = new object(); bool expected = false; // -------- Act -------- bool actual = target.Equals(genericObject); // -------- Assert -------- Assert.AreEqual(expected, actual); } [TestMethod] public void Equals_EquivalentObject_ReturnTrue() { // -------- Assemble -------- object target = GetPrimary(); object equivalent = GetPrimary(); bool expected = true; // -------- Act -------- bool actual = target.Equals(equivalent); // -------- Assert -------- Assert.AreEqual(expected, actual); } [TestMethod] public void Equals_SameObject_ReturnTrue() { // -------- Assemble -------- object target = GetPrimary(); bool expected = true; // -------- Act -------- bool actual = target.Equals(target); // -------- Assert -------- Assert.AreEqual(expected, actual); } [TestMethod] public void Equals_DifferentObjects_NoneMatch() { // -------- Assemble -------- object target = GetPrimary(); IEnumerable&lt;object&gt; nonEquivalents = GetNonEquivalentObjects(); bool expected = false; // -------- Act -------- bool anyEqual = nonEquivalents.Any(nonEquivalent =&gt; target.Equals(nonEquivalent)); // -------- Assert -------- Assert.AreEqual(expected, anyEqual); } [TestMethod] public void HashCode_EquivalentObject_BothSame() { // -------- Assemble -------- object target = GetPrimary(); object equivalent = GetPrimary(); bool expected = true; // -------- Act -------- bool actual = target.GetHashCode() == equivalent.GetHashCode(); // -------- Assert -------- Assert.AreEqual(expected, actual); } [TestMethod] public void HashCode_SameObject_BothSame() { // -------- Assemble -------- object target = GetPrimary(); bool expected = true; // -------- Act -------- bool actual = target.GetHashCode() == target.GetHashCode(); // -------- Assert -------- Assert.AreEqual(expected, actual); } [TestMethod] public void HashCode_DifferentObjects_NoneMatch() { // -------- Assemble -------- object target = GetPrimary(); IEnumerable&lt;object&gt; nonEquivalents = GetNonEquivalentObjects(); bool expected = false; // -------- Act -------- bool anyEqual = nonEquivalents.Any(nonEquivalent =&gt; target.GetHashCode() == nonEquivalent.GetHashCode()); // -------- Assert -------- Assert.AreEqual(expected, anyEqual); } /// &lt;summary&gt; /// Get the primary object for testing equality. /// &lt;/summary&gt; /// &lt;returns&gt;The primary object&lt;/returns&gt; protected abstract object GetPrimary(); /// &lt;summary&gt; /// Get the list of objects which should not equal the primary object. /// &lt;/summary&gt; /// &lt;returns&gt;List of non equivalent objects&lt;/returns&gt; protected abstract IEnumerable&lt;object&gt; GetNonEquivalentObjects(); } </code></pre>
[ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-01-21T09:42:13.710", "Id": "66642", "Score": "0", "body": "`HashCode_DifferentObjects_NoneMatch` is wrong. From [`GetHashCode` documentation](http://msdn.microsoft.com/en-us/library/system.object.gethashcode%28v=vs.110%29.aspx) \"Do not test for equality of hash codes to determine whether two objects are equal. (*Unequal objects can have identical hash codes.*)...\" [emphasis added]" } ]
[ { "body": "<p>It seems to be complete but keep in mind that equality is reflexive, symmetric, and transitive so, as a formality, I would add tests:</p>\n\n<ul>\n<li><code>a.Equals(b)</code> has the same value as <code>b.Equals(a)</code></li>\n<li>if <code>a.Equals(b)</code> and <code>b.Equals(c)</code> are both true, then <code>a.Equals(c)</code> is also true</li>\n</ul>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-01-20T21:53:48.260", "Id": "39688", "ParentId": "39684", "Score": "5" } }, { "body": "<p>In addition to Konrad's suggestions a few remarks to some of the test themselves:</p>\n\n<ol>\n<li><p>If you make the base class generic then you can actually have a type for your primary instead of passing it through a plain <code>object</code>.</p></li>\n<li><p>I'm not that fond of the naming of the test cases, they don't rally read that fluently. Some suggestions:</p>\n\n<ul>\n<li><code>PrimaryIsNotEqualToNull</code></li>\n<li><code>PrimaryIsNotEqualToGenericObject</code></li>\n<li><code>PrimaryIsEqualToEquivalentPrimary</code></li>\n<li><code>PrimaryIsEqualToItself</code></li>\n<li>...</li>\n</ul></li>\n<li><p>I would change the abstract interface to two methods:</p>\n\n<ul>\n<li><code>GetSimilarPrimary</code> - should return primary objects which are all similar to each other and should compare equal (but they are different objects)</li>\n<li><code>GetDifferentPrimary</code> - should return primaries which are all different from each other and never compare equal to each other.</li>\n</ul>\n\n<p>This make their usage clearer and you can implement the <code>IEnumerable</code> of different objects in the base class yourself and the derived class doesn't need to care about it.</p></li>\n<li><p>If you do the above then I'd add two test cases to make sure the implementation conforms to the requirement and make sure that objects returned from <code>GetSimilarPrimary</code> always compare equal and objects from <code>GetDifferentPrimary</code> always compare false. This catches programming errors in the unit test implementation for the derived classes.</p></li>\n<li><p>In this test:</p>\n\n<pre><code>[TestMethod]\npublic void HashCode_EquivalentObject_BothSame()\n{\n // -------- Assemble --------\n object target = GetPrimary();\n object equivalent = GetPrimary();\n bool expected = true;\n\n // -------- Act --------\n bool actual = target.GetHashCode() == equivalent.GetHashCode();\n\n // -------- Assert -------- \n Assert.AreEqual(expected, actual);\n}\n</code></pre>\n\n<p>You compare the hashcodes and then compare the result of the comparison which is a bit roundabout and will make the test result a little bit harder to read in case of failure (two bools are different rather than two ints). I'd change that to:</p>\n\n<pre><code>[TestMethod]\npublic void HashCode_EquivalentObject_BothSame()\n{\n // -------- Assemble --------\n object target = GetPrimary();\n object equivalent = GetPrimary();\n\n // -------- Act --------\n int targetHash = target.GetHashCode();\n int equivalentHash = equivalent.GetHashCode();\n\n // -------- Assert -------- \n Assert.AreEqual(targetHash , equivalentHash);\n}\n</code></pre>\n\n<p>If you want keep something for the <code>Act</code> part then introduce two local variables to store the hash codes.</p></li>\n<li><p>There is also the general requirement that if two objects compare as equal then their hash codes should be equal. While this is implicitly caught by the tests I'd actually consider adding another test which checks that explicitly.</p></li>\n</ol>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-01-22T20:10:24.770", "Id": "66831", "Score": "0", "body": "Thanks. WRT #1, this would be ideal, but VS2010 won't pick up the unit tests if I make it generic. It's a known issue. WRT #2 & 5, that's policy where I work. WRT #3 & 4, good call. WRT #6, I didn't know that. Thanks, I'll update my tests." } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-01-21T01:36:44.983", "Id": "39705", "ParentId": "39684", "Score": "3" } } ]
{ "AcceptedAnswerId": "39688", "CommentCount": "1", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-01-20T21:23:30.867", "Id": "39684", "Score": "8", "Tags": [ "c#", "unit-testing" ], "Title": "Am I missing any unit tests in this base class for testing equality?" }
39684
<p>I have implemented a calculation of Pi in Python, just for the lulz. But now I wonder if I could improve this more. Could you help me out? I do not program a lot in Python.</p> <pre><code>from time import time from decimal import * def faculty(m): k=m n=1 while(n&lt;m): k=k*n n+=1 if(k&gt;0): return k else: return 1 def ramanujan(b, n): return b+Decimal(faculty(4*n)*(1103+26390*n))/Decimal((faculty(n)**4)*396**(4*n)) def chudnovsky(b, n): return b+(((-1)**n)*(faculty(6*n))*(13591409+(545140134*n)))/(faculty(Decimal(3)*n)*(faculty(n)**3)*640320**(3*n+(Decimal(3)/Decimal(2)))) def calc(x, a, func): b=Decimal(0) n=Decimal(0) while(n&lt;x): b = func(b, n) n=n+1 return ((a*b)**(-1)) def calcrama(): return calc(20, Decimal((2*Decimal(2).sqrt())/9801), ramanujan) def calcchud(): return calc(20, 12, chudnovsky) def save(name, func): fobj = open(name, "w") t = time() pi = func() t = time() - t fobj.write("Time: "+str(t)+"\nPi: "+str(pi)) fobj.close() getcontext().prec = 1000 save("rama.txt", calcrama) save("chud.txt", calcchud) </code></pre>
[]
[ { "body": "<p>I find that your program is obfuscated and therefore incomprehensible to anyone except for perhaps an expert in those calculations methods. You should pick more informative variable names than <code>a</code>, <code>b</code>, <code>k</code>, <code>m</code>, <code>n</code>, and <code>x</code>.</p>\n\n<p><code>faculty(m)</code> should be renamed <code>factorial(m)</code>. Ideally, you wouldn't need it — see below.</p>\n\n<p>If you could verify that the denominator is always a divisor of the numerator, you should use <code>//</code> integer division.</p>\n\n<p>Use more whitespace for readability. Here, I would break with Python guidelines and be more generous with whitespace than usual.</p>\n\n<p>Verbose comments, especially docstrings, would also be appreciated for complicated mathematics:</p>\n\n<pre><code>def chudnovsky(b, n):\n \"\"\"\n Based on the identity\n\n n\n 1 inf (-1) (6n)! (13591409 + 545140134n)\n ----- = SUM -----------------------------------\n 12 PI n=0 3 3n + 1.5\n (3n)! (n!) 640320\n\n Returns the nth term of the sum.\n \"\"\"\n return b + (\n ((-1)**n) * (factorial(6 * n)) * \n (13591409 + (545140134 * n))\n ) // (\n factorial(Decimal(3) * n) *\n (factorial(n)**3) *\n 640320**(3 * n + (Decimal(3) / Decimal(2)))\n )\n</code></pre>\n\n<p>Many parts of that expression would be more efficiently computed based on their counterparts in the previous term, instead of starting from scratch. You might want to build an <a href=\"http://docs.python.org/2/tutorial/classes.html#generators\" rel=\"nofollow\">generator</a> that caches those intermediate results.</p>\n\n<p>Furthermore, you have very large numbers in both your numerators and denominators, especially factorials. You can help keep those small by cancelling out the factorials in the numerator and denominator as soon as possible.</p>\n\n<pre><code>def ChudnovskyTerms():\n \"\"\"\n Based on the identity\n\n n\n 1 inf 12 (-1) (6n)! (13591409 + 545140134n)\n ---- = SUM --------------------------------------\n PI n=0 3 3n + 1.5\n (3n)! (n!) 640320\n\n yields successive terms of the sum.\n \"\"\"\n term = 0\n sign = 1\n factorial_6_3 = 1 # = factorial(6 * n) / factorial(3 * n)\n numerator_sum = 13591409\n n_factorial_cubed = 1\n denominator = 640320**1.5\n\n while True:\n yield 12 * sign * factorial_6_3 * …\n\n term += 1\n sign *= -1\n for i in range(6):\n factorial_6_3 *= (6 * term - i)\n for i in range(3):\n factorial_6_3 //= (3 * term - i)\n numerator_sum += 545140134\n # etc.\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-01-20T23:37:04.150", "Id": "66581", "Score": "0", "body": "So wrapping it in a class increases the speed significantly?" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-01-20T23:45:06.053", "Id": "66582", "Score": "2", "body": "Keeping intermediate results rather than discarding them increases the speed. Packaging the code in a generator gives it a reasonable interface, and the overhead wouldn't be worse than what you had before." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-01-22T16:02:21.483", "Id": "66794", "Score": "0", "body": "`self.term` looks wrong to me: what's `self`?" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-01-22T16:09:35.733", "Id": "66795", "Score": "0", "body": "@GarethRees Thanks for spotting that. It was left over from an old version before I rewrote it as a generator." } ], "meta_data": { "CommentCount": "4", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-01-20T22:36:05.127", "Id": "39695", "ParentId": "39689", "Score": "7" } } ]
{ "AcceptedAnswerId": "39695", "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-01-20T21:56:54.530", "Id": "39689", "Score": "5", "Tags": [ "python", "mathematics" ], "Title": "Calculating Pi in Python" }
39689
<p>I need to split one <code>NSArray</code> into <code>NSDictionary</code>. Every key in <code>NSDictionary</code> will contain an <code>NSArray</code> with the object with the same value.</p> <p>i.e. I have an array with 1000 customers and I want create an <code>NSDictionary</code> based on their zip code.</p> <p>I wrote this code into an <code>NSArray</code> category and it works, but I'm looking for a better name and a way (if it exists) to do the same job with the KVC.</p> <pre><code>-(NSDictionary *)groupArrayWithBlock:(id&lt;NSCopying&gt; (^)(id obj))block { NSMutableDictionary *dictionary = [NSMutableDictionary dictionary]; for (id obj in self) { id&lt;NSCopying&gt; key = block(obj); if (! dictionary[key]) { NSMutableArray *arr = [NSMutableArray array]; dictionary[key] = arr; } [dictionary[key] addObject:obj]; } return [dictionary copy]; } </code></pre>
[]
[ { "body": "<p>As far as name of the method is concerned I have two points:</p>\n\n<ul>\n<li>There is no need of the work <code>Array</code> here, as it is NSArray instance method.</li>\n<li>The work <code>With</code> gives wrong impression here. (the phrase \"group a with b\" will generally mean to group them together). </li>\n</ul>\n\n<p>So in my opinion <code>groupUsingBlock</code> or <code>dictionaryGroupedUsingBlock</code>, might be better.</p>\n\n<p>Regarding KVC, if grouping is required to be done on a single property and that property is in complaint with <a href=\"https://developer.apple.com/library/ios/documentation/Cocoa/Conceptual/KeyValueCoding/Articles/Compliant.html\" rel=\"nofollow\">the standard</a>, you can have the function as following:</p>\n\n<pre><code> -(NSDictionary *)groupByKey:(NSString *) key {\n NSMutableDictionary *dictionary = [NSMutableDictionary dictionary];\n\n for (id obj in self) {\n id keyValue = [obj valueForKey:key];\n NSMutableArray *arr = dictionary[keyValue];\n if (! arr) {\n arr = [NSMutableArray array];\n dictionary[keyValue] = arr;\n }\n [arr addObject:obj];\n }\n return [dictionary copy];\n}\n</code></pre>\n\n<p>This will make the method slightly easy to use, but will also seriously limit the flexibility. So I would suggest that you keep the method which uses Block and implement the KVC version of the method by using it, like following:</p>\n\n<pre><code> -(NSDictionary *)groupByKey:(NSString *) key {\n return [self groupUsingBlock:^(id obj) {\n return [obj valueForKey:key];\n }];\n}\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-01-21T20:14:11.157", "Id": "66706", "Score": "0", "body": "Thank you and thanks to Jamal for fixing my poor english :). The code is available here: https://github.com/ignazioc/GroupNSarray and i think it's really usefull for create indexed tableview or somethinkg like this." } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-01-21T08:15:17.883", "Id": "39727", "ParentId": "39690", "Score": "2" } }, { "body": "<p>Why not form a method based around <code>enumerateOptionsUsingBlock</code>? More specifically, if you use <code>enumerateObjectsWithOptions:usingBlock</code>, you can specify <code>NSEnumerationConcurrent</code> which will make the processing much faster (which given you have an array with 1000 entries, it sounds like you may need).</p>\n\n<p>Just an idea for an improvement, as the answer here seems to work fine :)</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-02-05T18:50:43.027", "Id": "70245", "Score": "0", "body": "i'm afraid that the speedup isn't very appreciable.\nI tried with one million of item and execution time was `0.516586` and with the concurrent option the time was `0.464959`...by the way...i have even a bizarre error on creaing the array. (see my original post)" } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-02-04T09:27:42.360", "Id": "40833", "ParentId": "39690", "Score": "0" } } ]
{ "AcceptedAnswerId": "39727", "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-01-20T21:59:38.593", "Id": "39690", "Score": "6", "Tags": [ "array", "objective-c", "hash-map" ], "Title": "Splitting an NSArray into an NSDictionary of array more elegantly" }
39690
<p>I used the following code:</p> <pre><code>#include&lt;vector&gt; class UltrasonicRecorder { public: UltrasonicRecorder(int referenceValue, Input referenceInput) : _referenceValue(referenceValue), _referenceInput(referenceInput) {} std::vector&lt;int&gt; GetData(); void RecordData(Input); int CompensateTemperatur(int); private: double _compensation; int _referenceValue; Input _referenceInput; std::vector&lt;int&gt; _data; }; std::vector&lt;int&gt; UltrasonicRecorder::GetData() { std::vector&lt;int&gt; ret; std::swap(ret, _data); return ret; } void UltrasonicRecorder::RecordData(Input input) { int value = (ANALOG_VALUE_RANGE - 1) - GetAnalogValue(input); value = CompensateTemperature(value); _data.push_back(value); } int UltrasonicRecorder::CompensateTemperature(int value) { int measuredValue = GetAnalogValue(_referenceInput); if(measuredValue &gt; 0) { static const double delta = 1.0e-6; _compensation = (1.0 - delta) * _compensation + delta * _referenceValue / (double)measuredValue; } return static_cast&lt;int&gt;(value * _compensation); } </code></pre> <p><code>int GetAnalogValue(Input)</code> returns a 12 bit value from a ultrasonic sensor measuring distance (0-4095, <code>ANALOG_VALUE_RANGE = 4096</code>). <code>double _compensation;</code> is a member of the encapsulating class. <code>_referenceValue</code> is the initial reference value from <code>_referenceInput</code> (normally it has a low fluctuation, with a value somewhere in the middle of the 12 bit range, but it changes with temperature). </p> <p><code>RecordData()</code> is called every 2 milliseconds (more or less, running on Windows). So a high update rate for the reference value, but I wanted a gradual compensation over time. Therefore I used an exponential moving average, the <code>delta</code> is empirically determined and may need to be changed later. </p> <p><code>GetData()</code> is called approximately every second to flush <code>_data</code> and use the record for further evaluation.</p> <p>We started testing this code on customer facilities, but got the feedback that values are drifting away after a few days. I think it's a numerical unstable algorithm that accumulates rounding errors. Can someone with more experience with the subtleties of floating-point arithmetic answer me:</p> <p>Can this exponential moving average algorithm be improved to achieve better stability?</p> <p>Notes for additional improvements of the code are welcomed as well.</p>
[ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-02-19T01:49:47.763", "Id": "72426", "Score": "0", "body": "This does not look like a moving average. Could you separate the compensation part from the averaging part?" } ]
[ { "body": "<p>How about initializing the compensation factor so that it doesn't have to do the convergence from an undefined state?</p>\n\n<pre><code>UltrasonicRecorder(int referenceValue, Input referenceInput) :\n _referenceValue(referenceValue),\n _referenceInput(referenceInput)\n{\n _compensation = 1.0; // This!\n}\n</code></pre>\n\n<p>Edit: Your EWMA is correct. Your woes of compounding errors are unfounded. As you always \"move towards\" the measurement value, any compounding errors will be limited. In fact the compound error will at any point in time be less than:</p>\n\n<pre><code>(sum{i=0,infty} (1-delta)^i)*ULP(ANALOG_VALUE_RANGE) ~ 2^-(52-12) / delta ~ 10^-6\n</code></pre>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-03-11T17:36:57.387", "Id": "44086", "ParentId": "39694", "Score": "3" } } ]
{ "AcceptedAnswerId": "44086", "CommentCount": "1", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-01-20T22:34:07.683", "Id": "39694", "Score": "7", "Tags": [ "c++", "algorithm", "floating-point" ], "Title": "stability of an exponential moving average" }
39694
<p>I would like to replace the string "The quick brown fox jumps over the lazy dog" with the string "The1 quick2 brown3 fox4 jumps5 over6 the7 lazy8 dog9".</p> <p>Is there an cleaner, more elegant, sexier way?</p> <pre><code>String.prototype.concatWordNumber = function() { var myArray = this.split(' '); var myString = ""; for (var i=0, len = myArray.length; i&lt;len; i++) { myString += myArray[i]+[i+1]+ " " ; } return myString; } var text = "The quick brown fox jumps over the lazy dog"; console.log(text.concatWordNumber()); </code></pre>
[]
[ { "body": "<blockquote>\n <p>Is there an cleaner, more elegant, sexier way?</p>\n</blockquote>\n\n<p>I guess regex makes it more elegant and sexier, but your implementation is fine:</p>\n\n<pre><code>String.prototype.concatWordNumber = function() {\n var i = 1;\n return this.replace(/\\b\\w+\\b/g, function(word) {\n return word + i++;\n });\n};\n</code></pre>\n\n<p>Or you could use <code>map</code>:</p>\n\n<pre><code>String.prototype.concatWordNumber = function() {\n var plusIdx = function(x,i) {\n return x + ++i;\n };\n return this.split(' ').map(plusIdx).join(' ');\n};\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-01-21T00:10:28.187", "Id": "66587", "Score": "0", "body": "`\"the quick brown fox \"` returns `\"the1 quick2 brown3 fox4 5 6\"`. Maybe `return x.trim() ? x + ++i : x;` would fix it? But maybe its not worth it." } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-01-20T23:26:35.837", "Id": "39700", "ParentId": "39699", "Score": "3" } } ]
{ "AcceptedAnswerId": "39700", "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-01-20T23:20:47.017", "Id": "39699", "Score": "5", "Tags": [ "javascript", "strings" ], "Title": "Edit string to concatenate word numbers in javascript" }
39699
<p>I am starting with a starting colour, a target colour and a starting position in an image. I want to change every contiguous pixel if it is close to the starting colour.</p> <p>Imagine a stop sign. It has white letters on a red background. But the red is faded to a bunch of different reds. It should work that all of the red around the letters is one shape to be filled any colour, each letter is another shape to be coloured, and the holes of the O and P should also be shapes to be coloured. If I picked a midrange red from the stop sign and my starting point is on the outside of the letters, I would want all the outside red to be changed to the target colour. </p> <p>So I used colormath to do a delta_e on each pixel to see if it is less than the max acceptable delta, and it works. However, it is painfully slow. I was thinking instead of doing a delta_e on each pixel I could do a histogram of all the colours and then have some sort of look up table. However, I am brand spankin new to Python and I was hoping to get some help with how I would do that.</p> <p>Please help optimize it for speed.</p> <pre><code>from colormath.color_objects import RGBColor import Image def floodFill(x,y, d,e,f, g,h,i, image): toFill = set() alreadyfilled = set() toFill.add((x,y)) image = Image.open(image) xsize, ysize = image.size print(xsize,ysize) print(image.getpixel((x,y))) while (toFill): (x,y) = toFill.pop() alreadyfilled.add((x,y)) #print (x,y) (a,b,c) = image.getpixel((x,y)) if not (FindDeltaColor(a,b,c,d,e,f) &lt; 50): continue image.putpixel((x,y), (g,h,i)) if x != 0: if (x-1,y) not in alreadyfilled: toFill.add((x-1,y)) if y != 0: if (x,y-1) not in alreadyfilled: toFill.add((x,y-1)) if x != (xsize-1): if (x+1,y) not in alreadyfilled: toFill.add((x+1,y)) if y != (ysize-1): if (x,y+1) not in alreadyfilled: toFill.add((x,y+1)) return image def FindDeltaColor(r1,g1,b1,r2,g2,b2): rgb1 = RGBColor(r1,g1,b1, rgb_type='sRGB') rgb2 = RGBColor(r2,g2,b2, rgb_type='sRGB') lab1 = rgb1.convert_to('lab', target_illuminant='D50') lab2 = rgb2.convert_to('lab', target_illuminant='D50') return lab1.delta_e(lab2, mode='cie1994') newimg = floodFill(1,1,255,255,255,245,224,60,original.jpg' ) newimg.save(r'midway.jpg') img = floodFill(205,350,0,0,0,45,178,191,r'midway.jpg') img.save(r'floodfill.jpg') </code></pre>
[]
[ { "body": "<p>An optimization in here would be for you to cache the results of your <code>FindDeltaColor</code> lookup in a dictionary.</p>\n\n<pre><code>deltacache = dict()\n.....\nwhile ...\n (a,b,c) = image.getpixel((x,y))\n delta = deltacache.get((a,b,c));\n if delta is None:\n delta = FindDeltaColor(a,b,c,d,e,f)\n deltacache[(a,b,c)] = delta\n if delta &lt; 50:\n continue\n</code></pre>\n\n<p>This optimization optimistically expects there to be a relatively small set of unique colours... but, even with worst case large colour bit-depths, and ranges, the dict will be not much larger than the values that are similar to the margin test anyway. </p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-01-21T03:14:28.800", "Id": "66613", "Score": "1", "body": "Well that worked quite well. I reduced running time from 1 minute 39 seconds to ... 9 seconds. Would I save even more time to read the image in as a numpy array instead of poking each pixel to see it's color?" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-01-21T03:18:15.543", "Id": "66614", "Score": "0", "body": "@sleepingbeauty frankly I don't know python very well at all (in fact, I actively avoid it).... but I know an algorithmic enhancement when I see one. So, as for numpy, that is more detail than I am familiar with... but I know some people... who know some people." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-01-21T22:59:31.940", "Id": "66720", "Score": "0", "body": "you can get more coherency in the cache by quantizing A,B and C too, if the difference between (.81,.81,.79) and (.8, .8, .8) is not significant. Another possible option is to use lower resolution copies of the image as a quadtree to tell you where to look: if a pixel in a half-res image is more than (delta * 4) from your target color, none of the 4 pixels in the original image which made it up is likely to be one you want...." } ], "meta_data": { "CommentCount": "3", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-01-21T01:11:30.120", "Id": "39704", "ParentId": "39701", "Score": "3" } }, { "body": "<p>numpy and <a href=\"http://scikit-image.org/\" rel=\"nofollow noreferrer\">skimage</a> can do this quite fast. Without plotting the intermediate results in there, this runs in about 120ms.<br>\nUsing some random stopsign image found from google: <a href=\"http://www.ecovelo.info/images/stop-sign.jpg\" rel=\"nofollow noreferrer\">http://www.ecovelo.info/images/stop-sign.jpg</a><br>\nUsing a formula from wikipedia to calculate color difference: <a href=\"http://en.wikipedia.org/wiki/Color_difference\" rel=\"nofollow noreferrer\">http://en.wikipedia.org/wiki/Color_difference</a></p>\n\n<pre><code>from skimage.data import imread\nfrom skimage.color import rgb2lab\nfrom skimage.morphology import label\nimport numpy as np\nimport matplotlib.pyplot as plt\n\nimg = imread('stop-sign.jpg')\nimgLab = rgb2lab(img)\n\nfig = plt.figure()\nfig.add_subplot(231)\nplt.imshow(img)\nplt.title(\"original image\")\n\npos = (200, 270)\ncolor = img[pos]\ncolorLab = rgb2lab(color[None, None, :])\n\n#calculate deltaE for the whole image.\ndeltaE = np.sqrt(((imgLab - colorLab)**2).sum(axis=2))\nfig.add_subplot(232)\nplt.imshow(deltaE)\nplt.title(\"Delta E of image\")\n\n#create a boolean mask of where deltaE is less than a given threshold\nmask = np.where(deltaE &lt; 50, True, False)\nfig.add_subplot(233)\nplt.imshow(mask.copy())\nplt.title(\"mask of Delta E\")\n\n#connected labeling calculation, used to find all the pixels in the boolean mask connected to our starting position\nlabel, nlabels = label(mask, 4, False, return_num=True)\nfig.add_subplot(234)\nplt.imshow(label)\nplt.title(\"labeling\")\n#If the algorithm finds more than 1 label, we need to modify our mask.\nif nlabels &gt; 1:\n label_at_pos = label[pos]\n mask[label != label_at_pos] = False\n fig.add_subplot(235)\n plt.imshow(mask.copy())\n plt.title(\"mask connected with start position\")\n\nimg[mask] = color\n#Too see exactly what got filled, uncomment the next line\n#img[~mask] = [0,0,0]\n\nfig.add_subplot(236)\nplt.imshow(img)\nplt.title(\"Result\")\nplt.show()\n</code></pre>\n\n<p>output:<br>\n<img src=\"https://i.stack.imgur.com/bcy1Z.png\" alt=\"enter image description here\"></p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-01-22T14:38:19.673", "Id": "39810", "ParentId": "39701", "Score": "5" } } ]
{ "AcceptedAnswerId": "39810", "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-01-21T00:21:32.853", "Id": "39701", "Score": "10", "Tags": [ "python", "performance", "beginner", "image" ], "Title": "Recolour a shape" }
39701
<p>I made a simple program to catalog some old records I have. It seems a tad redundant in the searching function. Does anyone know what I can do about that?</p> <pre><code>import easygui as eg import sys namedoc = open(r"C:\Users\User\Desktop\RcrdCat\names.txt", 'a') nd2 = open(r"C:\Users\User\Desktop\RcrdCat\names(2).txt", 'a') authdoc = open(r"C:\Users\User\Desktop\RcrdCat\authors.txt", 'a') yeardoc = open(r"C:\Users\User\Desktop\RcrdCat\dates.txt", 'a') pubdoc = open(r"C:\Users\User\Desktop\RcrdCat\pubs.txt", 'a') rpmdoc = open(r"C:\Users\User\Desktop\RcrdCat\rpms.txt", 'a') conddoc = open(r"C:\Users\User\Desktop\RcrdCat\conditions.txt", 'a') sleevedoc = open(r"C:\Users\User\Desktop\RcrdCat\sleeves.txt", 'a') doclist = [namedoc, yeardoc, pubdoc, rpmdoc, conddoc, sleevedoc] def getlen(doc): templist = doc.readlines() listlen = len(templist) templist = [] return listlen def mainmenus(): mm = eg.buttonbox("What would you like to do?", "Categorizer", ["Add Records", "Search Records", "Exit"]) if mm == "Exit": exitprgm() elif mm == "Add Records": addrecs() elif mm == "Search Records": searchrecs(getsearchterms()) def addrecs(): info = eg.multenterbox("Please enter all record info", "Add Records", ["Name", "Year", "Publisher", "RPM", "Condition", "Sleeve", "Name (2)", "Artist"]) if info == None: mainmenus() else: namedoc.write(info[0] + " \r\n") yeardoc.write(info[1] + " \r\n") pubdoc.write(info[2] + " \r\n") rpmdoc.write(info[3] + " \r\n") conddoc.write(info[4] + " \r\n") nd2.write(info[6] + " \r\n") authdoc.write(info[7] + " \r\n") if info[5] == "Yes" or info[5] == "No": sleevedoc.write(info[5] + " \r\n") else: eg.msgbox("Please enter \"Yes\" or \"No\"") addrecs() addrecs() def getsearchterms(): term = eg.enterbox("Please enter your term in the following way: the word \"name\", \"year\", \"pub\", \"rpm\", \"cond\", or \"sleeve\", then a space, then the corresponding value") try: term = term.split() return term except AttributeError: mainmenus() def searchrecs(term): hits = [] if term[0] == "name": myrange = getlen(namedoc) for number in range(getlen(namedoc)): locstring = namedoc.readlines(number) if term[1] in locstring == True: hits.append(number) else: pass elif term[0] == "year": for number in range(getlen(yeardoc)): locstring = yeardoc.readlines(number) if term[1] in locstring == True: hits.append(number) else: pass elif term[0] == "pub": for number in range(getlen(pubdoc)): locstring = pubdoc.readlines(number) if term[1] in locstring == True: hits.append(number) else: pass elif term[0] == "rpm": for number in range(getlen(rpmdoc)): locstring = rpmdoc.readlines(number) if term[1] in locstring == True: hits.append(number) else: pass elif term[0] == "cond": for number in range(getlen(conddoc)): locstring = conddoc.readlines(number) if term[1] in locstring == True: hits.append(number) else: pass elif term[0] == "sleeve": for number in range(getlen(sleevedoc)): locstring = sleevedoc.readlines(number) if term[1] in locstring == True: hits.append(number) else: pass else: eg.msgbox("Please enter valid search criteria") hitnums = len(hits) allinfo = [] eg.msgbox("Found " + str(hitnums) + " hits. Click OK to view.") for number in hits: for doc in doclist: allinfo.append(doc.readlines(number)) mation = ["Name: " + allinfo[0], "Year: " + allinfo[1], "Publisher: " + allinfo[2], "RPM: " + allinfo[3],"Condition: " + allinfo[4],"Sleeve: " + allinfo[5]] ftext = str() for num in range(len(mation)): ftext = ftext + num + " " eg.textbox("", "Results", ftext) def exitprgm(): for file in doclist: file.write("\r\n") file.close() sys.exit() mainmenus() </code></pre>
[ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-01-21T00:52:23.233", "Id": "66592", "Score": "1", "body": "I think you may be confused about how `readlines` works http://stackoverflow.com/questions/14541010/pythons-function-readlinesn-behavior" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-01-21T01:06:17.633", "Id": "66595", "Score": "0", "body": "@stuart lol, you are totally right. Still, it doesn't seem that this would affect the redundancy of the list. I just have to run `readlines()` first to get a table and iterate over that :)." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-01-21T07:55:25.683", "Id": "66634", "Score": "0", "body": "Don't you get an error trying to read from files opened in `'a'` mode?" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-01-21T19:10:03.353", "Id": "66690", "Score": "0", "body": "@JanneKarila Guilty... Originally wrote this so they opened in 'r+'. However, I wanted to append to files instead of overwriting them so I just don't use search... If I wanted to I would probably use with/as and the 'a' mode for writing and make them open as 'r' for reading, but I never use the search function anyway" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-01-22T16:51:48.843", "Id": "66799", "Score": "0", "body": "Have you considered using SQLite?" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-01-22T21:45:31.587", "Id": "66834", "Score": "0", "body": "@JoelCornett I'm not huge on it in general but I realize I probably should look past that... Thanks." } ]
[ { "body": "<p>So I've got a little disclaimer. I'm not at a pc with python on it.</p>\n\n<p>A quick look would sugggest an approach like:</p>\n\n<pre><code>def searchrecs(term):\n hits = []\n\n searchterms = {\n \"name\": namedoc,\n \"year\": yeardoc,\n \"pub\": pubdoc,\n }\n\n if(term[0] in searchterms.keys()):\n for searchterm, searchdoc in searchterms:\n if term[0] == searchterm:\n myrange = getlen(searchdoc)\n for number in range(getlen(searchdoc)):\n locstring = searchdoc.readlines(number)\n if term[1] in locstring == True:\n hits.append(number)\n else:\n pass\n else:\n eg.msgbox(\"Please enter valid search criteria\")\n</code></pre>\n\n<p><em>Forgive any c# syntax in this. I will fix any errors as I found them.</em></p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-01-21T01:35:02.373", "Id": "66600", "Score": "0", "body": "Very interesting. I like the if/in usage. Much more efficient than my original code, thanks very much!" } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-01-21T00:44:47.553", "Id": "39703", "ParentId": "39702", "Score": "3" } }, { "body": "<p>This can be simplified a bit further and made more efficient. You only need to open one of the text files (the one corresponding to the search term) to count the number of hits, and can then search through the others one at a time to get the full search results. Iterating through a file (e.g. <code>for line_number, line in enumerate(file)</code>) is probably better than using <code>readlines</code> here.</p>\n\n<pre><code>path = 'r\"C:\\Users\\User\\Desktop\\RcrdCat\\{}.txt'.format\n\n# fields consist of an abbreviation, file name, and label\nfields = (('name', 'names', 'Names'),\n ('authors', 'authors', 'Authors'),\n ('year', 'dates', 'Year'),\n ('pub', 'pubs', 'Publisher'),\n ('rpm', 'rpms', 'RPM'),\n ('cond', 'conditions', 'Condition'),\n ('sleeve', 'sleeves', 'Sleeve'))\nfield_dict = {field[0]: field[1] for field in fields}\n\ndef searchrecs(term):\n search_field, search_term = term\n try:\n file_name = field_dict[search_field]\n except KeyError:\n eg.msgbox(\"Please enter valid search criteria\")\n return\n with open(path(file_name), 'r') as file:\n results = [{'line number': i, search_field: line} \n for i, line in enumerate(file) if search in line]\n eg.msgbox(\"Found {} hits. Click OK to view.\".format(len(results)))\n for field, file_name, _ in fields:\n if field == search_field: # we've already searched this one\n continue\n with open(path(file_name), 'r') as file:\n numbered_file = enumerate(file)\n for result in results:\n for i, line in numbered_file:\n if i == result['line number']:\n result[field] = line\n break\n text = ''\n for result in results:\n text += ' '.join('{}: {}'.format(label, result[field])\n for field, _, label in fields) + '\\n'\n eg.textbox('', 'Results', text)\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-01-21T03:29:04.373", "Id": "66616", "Score": "0", "body": "This is an interesting approach which I like except that it opens and closes files each time it is run. Is it not possible that each file is only opened once?" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-01-21T10:16:39.627", "Id": "66644", "Score": "0", "body": "yes it is possible as in your original code. You can append the opened file objects to the tuples in `fields` and just refer to the file in subsequent code rather than using `with open...`" } ], "meta_data": { "CommentCount": "2", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-01-21T02:31:06.867", "Id": "39709", "ParentId": "39702", "Score": "3" } }, { "body": "<p>Another piece of python wisdom to consider is 'if you can do it with the standard library, do!' </p>\n\n<p>Field and record based storage is really easy to do with the <a href=\"http://docs.python.org/2/library/csv.html\" rel=\"nofollow\">csv</a> module, which reads and writes comma-separated spreadsheet style files. A file formatted like this:</p>\n\n<pre><code>name,artist,publisher,date,rpm, condition, sleeve\nWee small hours,Frank Sinatra,Columbia,1953,33,good,original\n</code></pre>\n\n<p>is easy to read like so:</p>\n\n<pre><code>import csv \nrecords = []\nwith open ('/path/to/file.csv', 'rb') as filehandle:\n reader = csv.DictReader(filehandle)\n for r in reader: \n # make sure the dates are numeric so you can compare them\n try:\n r['date'] = int(r['date'])\n except:\n r['date'] = 1900 # you might prefer some other default for bad data\n records.append(r)\n</code></pre>\n\n<p>DictReader is especially nice since it automatically parses the first line as the headers and returns a dictionary so you don't need to create a custom class to organize your data (as an aside: you could also do this using the <a href=\"http://docs.python.org/2/library/sqlite3.html\" rel=\"nofollow\">sqllite</a> module, which would let you read and write the entire database directly and query it with SQL. I'm not going to go into that since SQL is it's own thing - but for bigger applications it would be the right thing to research). Writing out the data is the inverse of the above:</p>\n\n<pre><code> # assume our records are dictionaries in the records variable...\n with open ('/path/to/file.csv', 'wb') as filehandle:\n writer = csv.DictWriter(filehandle, fieldnames = ('name','artist','publisher','date','rpm','condition','sleeve'))\n writer.writerows(records)\n</code></pre>\n\n<p>So, using CSV files and DictReader/DictWriter to handle the reading/writing, our 'database' is a list of dictionaries':</p>\n\n<pre><code>[\n{'publisher': 'Columbia', 'name': 'Wee small hours', 'artist': 'Frank Sinatra', ' sleeve': 'original', 'date': '1953', 'rpm': '33', ' condition': 'good'}\n{'publisher': ' Electra', 'name': 'Jump', 'artist': ' Van Halen', ' sleeve': ' repaired', 'date': ' 1983', 'rpm': ' 33', ' condition': ' poor'}\n # etc\n]\n</code></pre>\n\n<p>Searching this can be done very efficiently using the built in <a href=\"http://docs.python.org/2/library/functions.html\" rel=\"nofollow\">filter</a> function. Filter takes a list and a function as arguments; it returns a list of all the items where the function returns true. For example:</p>\n\n<pre><code> sinatra = lambda p: 'sinatra' in p['artist'].lower()\n sinatra_albums = filter(records, sinatra)\n\n before_1970 = lambda p: p['date'] &lt; 1970\n old_stuff = filter(records, before_1970)\n</code></pre>\n\n<p>and so on.</p>\n\n<p>The 'ui' for the program then really amounts to creating custom filter functions and returning them. You can manufacture them easily:</p>\n\n<pre><code> def make_artist_filter(artist):\n return lambda x: artist.lower() in x['artist']\n\n def make_year_filter(year):\n return lambda x: x['date'] == year\n</code></pre>\n\n<p>and so on. You can even combine them:</p>\n\n<pre><code> def and_filter (filter1, filter22):\n return lambda x: filter1(x) and filter2(x)\n\n def or_filter (filter1, filter2):\n return lambda x: filter1(x) or filter2(x)\n</code></pre>\n\n<p>All of these filters automatically return lists, so you don't have to loop or create temporary variables to collect matches. </p>\n\n<p>I think it's easy to extrapolate from this how to write the program very compactly; using standard library functions means you can concentrate on logic and user-facting stuff (do you want to include partial name matches, or regular expressions, for example? Do you silently ignore bad input or scold the user? etc).</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-01-21T20:45:48.387", "Id": "66707", "Score": "0", "body": "This is incredible. I generally don't use csv's but you have convinced me" } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-01-21T20:07:07.770", "Id": "39759", "ParentId": "39702", "Score": "4" } }, { "body": "<p>Here's an example of how to implement with <code>sqlite3</code>.</p>\n\n<p>You'll need to import the following:</p>\n\n<pre><code>import sqlite3\nfrom contextlib import contextmanager\n</code></pre>\n\n<p>And define the following constants:</p>\n\n<pre><code>DATABASE_PATH = '/tmp/my_database.db'\nSCHEMA = '''\\\nDROP TABLE IF EXISTS records;\nCREATE TABLE records (\n id INTEGER PRIMARY KEY AUTOINCREMENT,\n name TEXT,\n year INTEGER,\n name2 TEXT,\n publisher TEXT,\n rpm INTEGER,\n condition TEXT,\n sleeve INTEGER,\n artist TEXT\n);''' # The schema script ONLY needs to be executed once, when first creating the database\n</code></pre>\n\n<p>Then add the following database utility functions to your script.</p>\n\n<pre><code># Provides a database access context that ensures the database object is\n# closed at the end of the transaction, no matter what.\n@contextmanager\ndef get_db():\n try:\n db = sqlite3.connect(DATABASE_PATH)\n db.row_factory = sqlite3.Row\n yield db\n finally:\n db.close()\n\n# Executed ONCE, to create the database.\n# Do the following at the command line:\n# $ python -c \"from import &lt;my_record_program_name&gt; import init_db; print(init_db())\"\ndef init_db():\n try:\n with get_db() as db:\n db.executescript(SCHEMA);\n\n return \"passed\"\n\n except Exception as e:\n return \"failed\", e\n</code></pre>\n\n<p>Now modify <code>add_recs()</code>:</p>\n\n<pre><code>def add_recs():\n\n # Your GUI logic here\n\n with get_db() as db:\n db.execute('''\n INSERT INTO \n records (name, year, publisher, rpm, condition, name2, artist) \n VALUES (?, ?, ?, ?, ?, ?, ?, ?)''', \n info)\n\n db.commit()\n</code></pre>\n\n<p>Finally, rewrite <code>search_recs()</code>:</p>\n\n<pre><code>def search_recs(term):\n with get_db() as db:\n cur = db.execute(\n 'SELECT * FROM records WHERE `%s`=?' % term[0], [term[1]])\n\n results = cur.fetchall()\n\n # Do GUI stuff with \"results\" here.\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-01-23T14:57:18.510", "Id": "66920", "Score": "0", "body": "why `sleeve INTEGER`? Are you suggesting 1 for \"yes\" and 0 for \"no\"? And in case that was an exceptionally stupid question, I really don't use this module often..." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-01-23T16:03:39.553", "Id": "66926", "Score": "0", "body": "`SQLite`, as the name implies, is an extremely light version of SQL, and as such there are only four different data types. Booleans are represented as integers. In any case, if you choose not to use a rdbms, I would recommend a) storing your records in one file, and b) loading them all into memory on program startup. Unless you have millions of records, your computer should have the memory to cope." } ], "meta_data": { "CommentCount": "2", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-01-23T07:45:06.977", "Id": "39862", "ParentId": "39702", "Score": "2" } } ]
{ "AcceptedAnswerId": "39703", "CommentCount": "6", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-01-21T00:35:54.010", "Id": "39702", "Score": "7", "Tags": [ "python", "python-3.x" ], "Title": "Record Cataloging Program" }
39702
<p>This is one of the longest programs I have made with methods and I think I must be doing this rather inefficiently. Any comments to improve would be appreciated.</p> <pre><code>package numberwords2; import java.awt.Component; import javax.swing.JOptionPane; public class NumberWords2 { static String rawInput; static String output = ""; static int hold; private static Component frame; public static void main(String[] args) { rawInput = JOptionPane.showInputDialog("Enter a number between 0 and 9999."); int input = Integer.parseInt(rawInput); if(input == 0) { output += "Zero"; } else if(input &lt; 10) { output += ones(0); } else if(input &lt; 20) { output += teens(0); } else if(input &lt; 100) { output += tens(0); output += ones(1); } else if(input &lt; 1000) { output += hundreds(0); int temp = Integer.parseInt(rawInput.substring(1,3)); if(temp &gt; 10 &amp;&amp; temp &lt; 20) { output += teens(2); } else { output += tens(1); output += ones(2); } } else if(input &lt; 10000) { output += thousands(0); output += hundreds(1); int temp = Integer.parseInt(rawInput.substring(2,4)); if(temp &gt; 10 &amp;&amp; temp &lt; 20) { output += teens(3); } else { output += tens(2); output += ones(3); } } JOptionPane.showMessageDialog(frame, rawInput + " is" + output + "."); output = ""; main(args); } public static String teens(int hold) { String[] teens = {"Ten", "Eleven", "Twelve", "Thirteen", "Fourteen", "Fifteen", "Sixteen", "Seventeen", "Eighteen", "Nighteen"}; int x = Character.getNumericValue(rawInput.charAt(hold)); int y = 0; for(int i = 0; i &lt; 10; i++) { if(i == x) { y = i; break; } } return " " + teens[y]; } private static String tens(int hold) { String[] tens = {"", "Ten", "Twenty", "Thirty", "Fourty", "Fifty", "Sixty", "Seventy", "Eighty", "Ninety"}; int x = Character.getNumericValue(rawInput.charAt(hold)); int y = 0; for(int i = 0; i &lt; 10; i++) { if(i == x) { y = i; } } return " " + tens[y]; } private static String ones(int hold) { String[] ones = {"", "One", "Two", "Three", "Four", "Five", "Six", "Seven", "Eight", "Nine"}; int x = Character.getNumericValue(rawInput.charAt(hold)); int y = 0; for(int i = 1; i &lt; 10; i++) { if(i == x) { y = i; break; } } return " " + ones[y]; } private static String hundreds(int hold) { return ones(hold) + " Hundred"; } private static String thousands(int hold) { return ones(hold) + " Thousand"; } } </code></pre>
[ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-01-21T14:35:50.813", "Id": "66668", "Score": "2", "body": "Minor spelling: 19 = Nineteen 40 = Forty" } ]
[ { "body": "<pre><code>int input = Integer.parseInt(rawInput);\n</code></pre>\n\n<p>This can throw an exception if rawInput isn't a number.</p>\n\n<hr>\n\n<pre><code> else if(input &lt; 10)\n {\n output += ones(0);\n }\n else if(input &lt; 20)\n {\n output += teens(0);\n }\n else if(input &lt; 100)\n {\n output += tens(0);\n output += ones(1);\n }\n else if(input &lt; 1000)\n {\n output += hundreds(0);\n int temp = Integer.parseInt(rawInput.substring(1,3));\n if(temp &gt; 10 &amp;&amp; temp &lt; 20)\n {\n output += teens(2);\n }\n else\n {\n output += tens(1);\n output += ones(2);\n }\n\n }\n</code></pre>\n\n<p>Code (subroutine calls) are duplicated in the above:</p>\n\n<ul>\n<li>If the number is less than 1000 then you call tens, teens, and ones</li>\n<li>If the number is greater than 1000 then you call tens, teens, and ones</li>\n</ul>\n\n<p>There would be less code if you processed it from left to right, like you do when you read and say a number:</p>\n\n<pre><code>if (input &gt; 1000)\n{\n output += thousands;\n subtract thousands from input;\n}\nif (input &gt; 100)\n{\n output += hundreds;\n subtract hundreds from input;\n}\nif (10 &lt; input &lt; 20)\n{\n output += teens;\n}\nelse\n{\n if (input &gt;= 20)\n {\n output += tens;\n subtract tens from input;\n }\n output += ones;\n}\nif (output is empty)\n output = \"Zero\";\n</code></pre>\n\n<hr>\n\n<pre><code>int temp = Integer.parseInt(rawInput.substring(1,3));\n</code></pre>\n\n<p>This is a complicated way to remove the thousands from the input.</p>\n\n<p>A simpler way to subtract thousands from the input is:</p>\n\n<p>input = input - ((input / 1000) * 1000);</p>\n\n<hr>\n\n<pre><code>main(args);\n</code></pre>\n\n<p>This is a strange way to loop forever.</p>\n\n<p>Better would be:</p>\n\n<pre><code>public static void main(String[] args)\n{\n while (true)\n run();\n}\n\nstatic void run()\n{\n rawInput = JOptionPane.showInputDialog(\"Enter a number between 0 and 9999.\");\n ... etc ...\n}\n</code></pre>\n\n<hr>\n\n<p>Perhaps only the first letter should be capitalized; perhaps with hyphens; and the word \"and\"; for example \"Four hundred and forty-three\" not \"Four Hundred Forty Three\".</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-01-21T03:05:40.323", "Id": "66612", "Score": "0", "body": "That's a much way of doing this! Thanks for the help! As for the \"and\" thing, it's technically mathematically incorrect to say \"and\" like that. I won't get into the actual rules for it, if your curious Google should do. Anyways thanks for the help! This is a much better way of doing things than what I had!" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-01-21T13:52:55.300", "Id": "66656", "Score": "0", "body": "Googling suggests that American English often drops the \"and\" (see the Chicago Manual of Style). Keeping the \"and\" is normal in spoken British (and, imo, Canadian) English." } ], "meta_data": { "CommentCount": "2", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-01-21T02:55:54.707", "Id": "39711", "ParentId": "39707", "Score": "7" } }, { "body": "<p>There is no way to stop this program. It will continue to recall <code>main()</code> if no exceptions are thrown. The problem isn't so much that it will run forever, but how you are achieving the <em>looping</em>. If this program is run for a long enough time, it will eventually throw a <code>StackOverflowException</code> because <code>main()</code> has recursed so many times. It would be better to use a real loop instead of using this recursion trick.</p>\n\n<pre><code>String getInput() {\n return JOptionPane.showInputDialog(\"Enter a number between 0 and 9999. q to Quit\");\n}\n\n//...\n\nString rawInput = getInput();\nwhile (!rawInput.equal(\"q\") {\n //...\n rawInput = getInput();\n}\n</code></pre>\n\n<hr>\n\n<p><strong>Variable</strong>:</p>\n\n<p><code>output</code> are only used in <code>main()</code>. It should be scoped accordingly. Having them as static variables means any of your methods can change them at any time. This would a bug that is hard to track down. You might also want to think about passing <code>rawInput</code> as an argument to functions instead of using a static variable.</p>\n\n<p>The static <code>hold</code> variable is never used. Even worse, it is shadowed by a number of method parameters. This is another bug that is hard to track down when it happens. You could set a value to <code>hold</code> in <code>main()</code>, expecting it to be present in a method that uses a variable named <code>hold</code>. But it the method defines a parameter named <code>hold</code>, the value in that scope will be the value the method was called with.</p>\n\n<p>The name <code>hold</code>, what does it mean? It is being used as an index into the input, but without diving into the code, I'm not sure what it is. The name should help people reading your code know what the variable is.</p>\n\n<p><code>frame</code> is defined, but never assigned a value. This means when you call <code>JOptionPane.showMessageDialog()</code>, you are actually passing <code>null</code> as the first argument. This happens to be a valid value, but passing <code>null</code> explicitly is better. Seeing the variable used as an argument may make someone assume that it has a value and attempt to call a method on it.</p>\n\n<hr>\n\n<p><strong>Code repetition</strong>:</p>\n\n<p>There is a lot of it. From little things like <code>hundreds()</code> and <code>thousands()</code> to big structural things like most of the code in <code>main()</code>.</p>\n\n<p><code>hundreds()</code> and <code>thousands()</code> is simple. The only difference is the string appended to the result of <code>ones()</code>. You can make s single function that tasks a value and suffix, which <code>hundreds()</code> and <code>thousands()</code> call. Then when you need to add <code>millions()</code>, it more code reuse instead of code copying. This may seem extreme in this instance, but starting to look for these types of things will make your code much cleaner.</p>\n\n<p><code>ones()</code>, <code>tens()</code>, <code>teens()</code> also look very structurally similar.</p>\n\n<pre><code>private static String suffix(String input, int index, String[] suffixes)\n{\n int x = Character.getNumericValue(input.charAt(index));\n for(int i = 0; i &lt; suffixes.length; i++)\n {\n if(i == x)\n {\n return \" \" + suffixes[i];\n }\n }\n}\n</code></pre>\n\n<p>This function can now be used by each of the three you wrote, simplifying you code. This is a better example of what I was talking about with \n<code>hundreds()</code> and <code>thousands()</code>.</p>\n\n<p>I made a few other changes I wanted to point out:</p>\n\n<ul>\n<li>The for loop is up to the array length. <code>10</code> was a magic number that could mean anything. If later you change the array to have more values, you would never try those. If there were less, you would get an exception.</li>\n<li>I moved the return into the if statement. You aren't doing anything interesting after the loop and it eliminates the need for <code>y</code>. It also removes the need for the <code>break</code>.</li>\n</ul>\n\n<p>The best part about having one function execute the body of these three functions is that you only have one place to have a functional bug. If you look closely at <code>tens()</code>, you forgot the <code>break</code> statement. The code is still correct, but it does more work than it needs to. It's easy to assume that 3 functions that are doing the same thing are implemented the same way, but a subtle bug like this is hard to find.</p>\n\n<hr>\n\n<p><strong><code>main()</code></strong>:</p>\n\n<p>This is a bugger structural change and involves some work to build it up. But if you think about it, the code is going through a list values and checking if the input is less than the specific value. Once it finds the specific value that the input is less than, some work is done to create the output.</p>\n\n<pre><code>interface Converter {\n String convert(int value);\n}\n</code></pre>\n\n<p>Using this concept, you can create a number of classes that implement <code>Converter</code>. Then you can think of the specific values we were testing against as keys that point to the specific <code>Converter</code> that knows how to convert the input. This is done by using a <code>Map</code>.</p>\n\n<p>A <a href=\"http://docs.oracle.com/javase/7/docs/api/java/util/LinkedHashMap.html\"><code>LinkedHashMap</code></a> will allow you to create this mapping and also control how you iterate over the keys in the map.</p>\n\n<pre><code>Map&lt;Integer, Converter&gt; converters = new LinkedHashMap&lt;&gt;();\nconverters.put(1, new ZeroConverter());\nconverters.put(10, new OnesConverter());\n//...\n\nfor (Entry&lt;Integer, Converter&gt; e : converters.entrySet()) {\n if (input &lt; e.getKey()) {\n output = e.getValue().convert(input);\n break;\n }\n}\n</code></pre>\n\n<p>With this structure, your <code>main()</code> method becomes the simple processing constructing the <code>Map</code> at the start, and putting this <code>for</code> loop in the <code>while</code> loop I mentioned earlier.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-01-21T03:21:03.123", "Id": "39713", "ParentId": "39707", "Score": "7" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "1", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-01-21T01:51:29.610", "Id": "39707", "Score": "8", "Tags": [ "java", "parsing", "converting", "extension-methods", "numbers-to-words" ], "Title": "Digit to words converter" }
39707
<p>Below is a Singleton that I designed as a piece of sample code for a website I'm working on for fun. The goal is to use the Singleton to hold an <code>Earth</code> object since Earth is unique and there is only 1 of them. Please let me know your thoughts on the implementation. </p> <p><strong>Singleton.java</strong></p> <pre><code>package design.patterns; /** * This class is a Singleton, we can only have 1 instance of it no matter what! * * We mark the class final so that no other classes try to extend it. Some * designs would want the Singleton to be extendable but we do not! */ public final class Earth { // A static instance of an Earth object private static Earth earth; // Some earthly variables private long ageInYears = 4500000000L; private float daysForFullOrbit = 365.26f; private float degreesOfAxisTilt = 23.4f; private long population = 7046000000L; // Prevent client from instantiating new Earth objects private Earth() { } /** * Global access point (no pun intended :) * * Synchronized so its thread safe. */ public static synchronized Earth getInstance() { // "Lazy load" an Earth Object if (earth == null) { earth = new Earth(); } return earth; } // Basic getters and setters public double getAgeInYears() { return ageInYears; } public void setAgeInYears(long ageInYears) { this.ageInYears = ageInYears; } public float getdaysForFullOrbit() { return daysForFullOrbit; } public void setdaysForFullOrbit(float daysForFullRotation) { this.daysForFullOrbit = daysForFullRotation; } public float getDegreesOfAxisTilt() { return degreesOfAxisTilt; } public void setDegreesOfAxisTilt(float degreesOfAxisTilt) { this.degreesOfAxisTilt = degreesOfAxisTilt; } public double getPopulation() { return population; } public void setPopulation(int population) { this.population = population; } public static void setEarth(Earth earth) { Earth.earth = earth; } } </code></pre> <p><strong>Client.java</strong></p> <pre><code>package design.patterns; public class Client { public static void main(String args[]){ Earth earth = Earth.getInstance(); //Invoke Earth's methods from the instance created on line 7 System.out.printf("Earth is over %1$,.0f Days old. \n", earth.getAgeInYears()); //Invoke Earth's methods from the Singleton directly System.out.println("Earth's orbit takes " + Earth.getInstance().getdaysForFullOrbit() + " days to complete."); //Invoke Earth's methods both ways System.out.println("Earth sits on a " + earth.getDegreesOfAxisTilt() + " degree tilt."); System.out.printf("As of 1/20/2014, there are %1$,.0f people on Earth!", + Earth.getInstance().getPopulation()); } } </code></pre>
[]
[ { "body": "<p>The code you have is nicely formatted, and well documented, etc. ... but, as a singleton, it has a number of problems....</p>\n\n<p>The two most glaring are:</p>\n\n<ol>\n<li><p>It is not a singleton</p>\n\n<pre><code>Earth real = Earth.getInstance();\nEarth.setEarth(null);\nEarth alternate = Earth.getInstance();\nif (real != alternate) {\n System.out.println(\"Oops...\");\n}\n</code></pre></li>\n<li><p>The synchronization.</p>\n\n<p>You suggest in your comments that the <code>getInstance()</code> needs to be synchronized to avoid thread problems... but your other setter/getter methods are not synchronized.... as a result, threads all over the place can be getting stale, wrong, and otherwise incomplete populations, ages, etc.</p></li>\n</ol>\n\n<p>As an example of a singleton 'best use case', this one has some problems... ;-)</p>\n\n<p>But, that's sort of OK, since Earth has problems anyway!</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-01-21T03:42:39.807", "Id": "66618", "Score": "0", "body": "Wow, epic fail demonstrated by use of Eclipse's \"Generate Getters and Setters\" I didn't catch that it made that setEarth method! As far as the Synchronization, I was thinking that since the getInstance method is synchronized, that no 2 threads could access the object, but they clearly can since an object refrence could simply be passed to some concurrent operations. I guess there is no other way than synchronizing all of the getter and setters. Will update code sample in a sec. thanks or your review!" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-01-21T09:07:11.340", "Id": "66641", "Score": "0", "body": "@Shijima: A better way would be to avoid having all those setters in the first place. The getters aren't too terrible, i guess...aside from demoting objects to \"value holders\"....but seriously, should people be able to arbitrarily change the properties of Earth? :P Once you lose the setters, the need for synchronization of anything other than `getInstance` pretty much goes away." } ], "meta_data": { "CommentCount": "2", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-01-21T03:08:23.930", "Id": "39712", "ParentId": "39710", "Score": "5" } }, { "body": "<p>According to the book Effective Java \"a single-element enum type is the best way to implement a singleton\". Example:</p>\n\n<pre><code>package example;\n\npublic enum Earth {\n INSTANCE;\n\n public double getAgeInYears() {\n return 4500000000L;\n }\n\n public float getdaysForFullOrbit() {\n return 365.26f;\n }\n\n public float getDegreesOfAxisTilt() {\n return 23.4f;\n }\n\n public double getPopulation() {\n return 7046000000L;\n }\n}\n</code></pre>\n\n<p>Makes Client look like this:</p>\n\n<pre><code>package example;\n\npublic class Client {\n\n public static void main(String args[]){\n\n Earth earth = Earth.INSTANCE;\n\n //Invoke Earth's methods from the instance created on line 7\n System.out.printf(\"Earth is over %1$,.0f Days old. \\n\", earth.getAgeInYears());\n\n //Invoke Earth's methods from the Singleton directly\n System.out.println(\"Earth's orbit takes \" + Earth.INSTANCE.getdaysForFullOrbit() + \" days to complete.\");\n\n //Invoke Earth's methods both ways\n System.out.println(\"Earth sits on a \" + earth.getDegreesOfAxisTilt() + \" degree tilt.\");\n System.out.printf(\"As of 1/20/2014, there are %1$,.0f people on Earth!\", + Earth.INSTANCE.getPopulation());\n }\n}\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-01-22T22:04:18.523", "Id": "66836", "Score": "0", "body": "While singleton enums are really easy to create and solve the readResolve issue when serializing the singleton for free, it is not always ideal to use enum - especially when dealing with application container where this class might get loaded by custom classloaders. As enums are singletons per se they are hardly collectable by the garbage collector and therefore may produce memory leaks as the whole classloader (and the classes it loaded get uncollectable -> OOM: PermGen)." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-01-22T22:08:53.680", "Id": "66837", "Score": "0", "body": "I therefore try to use WeakSingletons instead, which get eligible for GC when no strong reference is pointing at them (not possible with enums sadly) which further has the limit of losing state (like f.e. a counter) if no class is referencing it and the GC collects \"trash\". This however can be bypassed by letting an object, which got loaded by the same classloader which further acts as manager and therefore exists as long as those classes are needed, hold a strong reference to this singleton(s). A bit more of work, but better memory management." } ], "meta_data": { "CommentCount": "2", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-01-21T17:29:41.780", "Id": "39751", "ParentId": "39710", "Score": "3" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-01-21T02:53:06.397", "Id": "39710", "Score": "6", "Tags": [ "java", "singleton" ], "Title": "Simple Java Singleton" }
39710
<p>This is a parsing function that will at tildes (~) to end of search terms in certain circumstances.</p> <p>Example an inputs and outputs:</p> <pre> Input: Output: name:(john doe) name:(john~ doe~) name:[andy TO charlie] name:[andy TO charlie] john doe john~ doe~ james NOT jane james~ NOT jane james NOT (james smith) james~ NOT (james smith) james NOT jane smith james~ NOT jane smith~ name:"john doe" australia name:"john doe" australia~ </pre> <pre><code>function addTilde(string) { if (!/[\[\[\]~"(NOT)\-\!\d\(\)(OR)(AND)\&amp;\|\: ]/.test(string)) { string = string.concat("~"); } return string; }; function fuzzQuery(rawQuery) { /*split the string into spaces, brackets, double quotes and words*/ re = /(?=[()\[\] "])|(?=[^\W])\b/; strSplit = rawQuery.split(re); newQuery = ""; for (var i = 0; i &lt; strSplit.length; i++) { var s = strSplit[i]; var newElement = ""; /*if it contains a [ or "*/ if (s.indexOf("\x22") != -1 || s.indexOf("[") != -1) { /*determine closing symbol*/ var closingSymbol; if (s == "\x22") { closingSymbol = "\x22"; newElement = newElement.concat(strSplit[i++]); /*need to skip opening one for double quotes*/ } else closingSymbol = "]"; /*concat elements together until closing element found)*/ do { newElement = newElement.concat(strSplit[i]); } while (strSplit[i++] != closingSymbol) } /*if it contains a NOT*/ else if (s.indexOf("NOT") != -1) { newElement = strSplit[i++]; /*concat the NOT*/ /*concat any spaces*/ while (strSplit[i] == " ") { newElement = newElement.concat(strSplit[i++]); } if (strSplit[i] == "(") { do { newElement = newElement.concat(strSplit[i]); } while (strSplit[i++] != ")") } else newElement = newElement.concat(strSplit[i++]); } else(newElement = strSplit[i]); newElement = addTilde(newElement); newQuery = newQuery.concat(newElement); } return newQuery; }; </code></pre> <p>Now <code>fuzzQuery</code> is quite a long method. It essentially has five parts. </p> <ol> <li>Split the initial query out into elements.</li> <li><p>Loop through each element. </p> <p>a) Concat square brackets and double quotes. </p> <p>else b) concat NOTs. </p> <p>now add tilde to element if appropriate</p></li> <li><p>Return the join the elements back together and return the new query. </p></li> </ol> <p>What I was thinking is that you could pass off steps two and three to their own methods, so that the whole query looks something like (but not exactly like!):</p> <pre><code>function fuzzQuery(rawQuery) { strSplit = splitQuery(rawQuery); concatSqrAndDblQuotes(strSplit); concatNots(strSplit); return putBackTogether(strSplit); } </code></pre> <p>ie. </p> <pre><code>function doSquareAndDblQuotes(strSplit, i) { if (s.indexOf("\x22") != -1 || s.indexOf("[") != -1) { /*determine closing symbol*/ var closingSymbol; if (s == "\x22") { closingSymbol = "\x22"; newElement = newElement.concat(strSplit[i++]); /*need to skip opening one for double quotes*/ } else closingSymbol = "]"; /*concat elements together until closing element found)*/ do { newElement = newElement.concat(strSplit[i]); } while (strSplit[i++] != closingSymbol) } return newElement; } </code></pre> <p>But the problem is here that we'd need to be keeping track of a few variables being changed in this function. ie. the i counter, and whether or not that if statement was executed. So you could start using globals (is that even a thing in javascript?)... and it gets messy. </p> <p>So possibly another way, would be to create an object that you pass in, and return, which keeps track of these variables. </p> <p>What do you think?</p>
[ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-01-21T04:04:42.917", "Id": "66622", "Score": "0", "body": "What would be an example of `rawQuery`? Can you provide input and output? I don't fully understand what you're doing here..." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-01-21T04:08:05.073", "Id": "66623", "Score": "0", "body": "Whats `newString` and you should probably deal with the following global variables: `re`, `strSplit`, `newQuery`. Also using `str.prototype.concat` is a poor convention (use `str1 += str2;`" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-01-21T04:25:20.020", "Id": "66624", "Score": "0", "body": "@elclanrs Have updated that now." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-01-21T05:22:12.533", "Id": "66625", "Score": "0", "body": "@dwjohnston what is `newString`?" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-01-21T07:09:36.247", "Id": "66633", "Score": "0", "body": "@megawac Sorry - that's `newQuery` I refactored it when I pasted it in and missed that one... :S" } ]
[ { "body": "<p>You aren't using regular expressions to your advantage. Capture, don't split. Capturing helps you analyze the tokens you are interested in. Splitting just gets you the location of the delimiters.</p>\n\n<pre><code>function fuzzQuery(rawQuery) {\n \"use strict\";\n // ( 1 ) ( 2 ) ( 3 ) ( 4 ) ( 5 ) ( 6 )\n var re = /\\s*(?:(NOT)\\s+)?([a-z]+:)?(?:(\"[^\"]*\")|(\\([^)]*\\))|(\\[[^\\]]*\\])|([a-z]+))\\s*/g;\n var matches;\n var lastIndex = -1;\n while (matches = re.exec(rawQuery)) {\n var relOp = matches[1],\n qualifier = matches[2],\n quotedStr = matches[3],\n parensStr = matches[4],\n bracketStr = matches[5],\n bareWord = matches[6];\n lastIndex = re.lastIndex;\n\n console.log(\"relOp=\" + relOp +\n \", qualifier=\" + qualifier +\n \", quotedStr=\" + quotedStr +\n \", parensStr=\" + parensStr +\n \", bracketStr=\" + bracketStr +\n \", bareWord=\" + bareWord);\n }\n if (lastIndex != rawQuery.length) {\n console.log(\"Junk=\" + rawQuery.substring(lastIndex));\n }\n}\n</code></pre>\n\n<p>Examples:</p>\n\n<ul>\n<li><p><code>name:(john doe)</code></p>\n\n<pre><code>relOp=undefined, qualifier=name:, quotedStr=undefined, parensStr=(john doe), bracketStr=undefined, bareWord=undefined\n</code></pre></li>\n<li><p><code>name:[andy TO charlie]</code></p>\n\n<pre><code>relOp=undefined, qualifier=name:, quotedStr=undefined, parensStr=undefined, bracketStr=[andy TO charlie], bareWord=undefined\n</code></pre></li>\n<li><p><code>john doe</code></p>\n\n<pre><code>relOp=undefined, qualifier=undefined, quotedStr=undefined, parensStr=undefined, bracketStr=undefined, bareWord=john\nrelOp=undefined, qualifier=undefined, quotedStr=undefined, parensStr=undefined, bracketStr=undefined, bareWord=doe\n</code></pre></li>\n<li><p><code>james NOT jane</code></p>\n\n<pre><code>relOp=undefined, qualifier=undefined, quotedStr=undefined, parensStr=undefined, bracketStr=undefined, bareWord=james\nrelOp=NOT, qualifier=undefined, quotedStr=undefined, parensStr=undefined, bracketStr=undefined, bareWord=jane\n</code></pre></li>\n<li><p><code>james NOT (james smith)</code></p>\n\n<pre><code>relOp=undefined, qualifier=undefined, quotedStr=undefined, parensStr=undefined, bracketStr=undefined, bareWord=james\nrelOp=NOT, qualifier=undefined, quotedStr=undefined, parensStr=(james smith), bracketStr=undefined, bareWord=undefined\n</code></pre></li>\n<li><p><code>james NOT jane smith</code></p>\n\n<pre><code>relOp=undefined, qualifier=undefined, quotedStr=undefined, parensStr=undefined, bracketStr=undefined, bareWord=james\nrelOp=NOT, qualifier=undefined, quotedStr=undefined, parensStr=undefined, bracketStr=undefined, bareWord=jane\nrelOp=undefined, qualifier=undefined, quotedStr=undefined, parensStr=undefined, bracketStr=undefined, bareWord=smith\n</code></pre></li>\n<li><p><code>name:\"john doe\" australia</code></p>\n\n<pre><code>relOp=undefined, qualifier=undefined, quotedStr=\"john doe\", parensStr=undefined, bracketStr=undefined, bareWord=undefined\nrelOp=undefined, qualifier=undefined, quotedStr=undefined, parensStr=undefined, bracketStr=undefined, bareWord=australia\n</code></pre></li>\n</ul>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-01-21T19:43:11.297", "Id": "39756", "ParentId": "39715", "Score": "3" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "5", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-01-21T03:55:51.653", "Id": "39715", "Score": "6", "Tags": [ "javascript", "parsing" ], "Title": "Parsing function is 50 lines long" }
39715
<p>I would prefer if more experienced users could give pointers on how I can optimize and think better when writing code.</p> <p>If you are unfamiliar with unity3d, ignore the use of UnityEngine, the heritage from <code>MonoBehaviour</code> as well as the <code>Debug.Log();</code>, <code>Debug.LogWarning();</code>, and <code>Debug.LogError();</code></p> <p><code>Awake</code> is called directly after the constructor.</p> <p>I use <code>int length</code> instead of a function to return the size of <code>List&lt;Gender&gt;</code> genders. Not sure what is preferred (or best).</p> <p>An XML Example can be seen further down.</p> <pre class="lang-cs prettyprint-override"><code>/// &lt;summary&gt; /// Gender manager. /// Access length by GenderManager.Length /// Access gender by index GenderManager.gender[int] /// /// Left to do: Singleton /// /// Author: Emz /// Date: 2014-01-21 /// &lt;/summary&gt; using UnityEngine; using System.Collections; using System.Collections.Generic; using System.Xml; using System; public class GenderManager : MonoBehaviour { private static List&lt;Gender&gt; genders; private static int length; // Use this for initialization public GenderManager () { genders = new List&lt;Gender&gt; (); length = 0; } void Awake () { DontDestroyOnLoad (this); XmlDocument doc = new XmlDocument (); doc.Load (@"genders.xml"); XmlNodeList gs = doc.SelectNodes ("genders/gender"); foreach (XmlNode g in gs) { Gender tg = new Gender (); tg.Name = g.SelectSingleNode("name").InnerText; tg.Desc = g.SelectSingleNode("desc").InnerText; XmlNodeList ams = g.SelectNodes("attributemodifiers/attributemodifier"); foreach (XmlNode am in ams) { // check if attribute does exist in public enum AttributeName under Skill.cs if (Enum.IsDefined(typeof(AttributeName), am.SelectSingleNode ("attribute").InnerText)) { int ta = (int)Enum.Parse(typeof(AttributeName), am.SelectSingleNode ("attribute").InnerText); // returns 0 if conversion failed int tv = Convert.ToInt32(am.SelectSingleNode ("value").InnerText); tg.AddAttributeModifier (ta, tv); // if attribute does not exist in SkillName under Skill.cs } else { Debug.LogError ("Invalid Attribute Name: " + am.SelectSingleNode ("attribute").InnerText); } } XmlNodeList sms = g.SelectNodes("skillmodifiers/skillmodifier"); foreach (XmlNode sm in sms) { // check if skill does exist in public enum SkillName under Skill.cs if (Enum.IsDefined(typeof(SkillName), sm.SelectSingleNode ("skill").InnerText)) { int ts = (int)Enum.Parse(typeof(SkillName), sm.SelectSingleNode ("skill").InnerText); // returns 0 if conversion failed int tv = Convert.ToInt32(sm.SelectSingleNode ("value").InnerText); tg.AddSkillModifier (ts, tv); // if skill does not exist in SkillName under Skill.cs } else { Debug.LogError ("Invalid Skill Name: " + sm.SelectSingleNode ("skill").InnerText); } } // off we go, increment length genders.Add (tg); ++length; } } public static int Length { get {return length;} } public static Gender Gender (int index) { return genders [index]; } } </code></pre> <p><strong>XML</strong></p> <pre class="lang-xml prettyprint-override"><code>&lt;?xml version="1.0" encoding="UTF-8"?&gt; &lt;genders&gt; &lt;gender&gt; &lt;name&gt;Female&lt;/name&gt; &lt;desc&gt;FemDesc&lt;/desc&gt; &lt;attributemodifiers&gt; &lt;attributemodifier&gt; &lt;attribute&gt;Agility&lt;/attribute&gt; &lt;value&gt;1&lt;/value&gt; &lt;/attributemodifier&gt; &lt;/attributemodifiers&gt; &lt;skillmodifiers&gt; &lt;skillmodifier&gt; &lt;skill&gt;Charm&lt;/skill&gt; &lt;value&gt;1&lt;/value&gt; &lt;/skillmodifier&gt; &lt;/skillmodifiers&gt; &lt;/gender&gt; &lt;gender&gt; &lt;name&gt;Male&lt;/name&gt; &lt;desc&gt;MalDesc&lt;/desc&gt; &lt;attributemodifiers&gt; &lt;attributemodifier&gt; &lt;attribute&gt;Strength&lt;/attribute&gt; &lt;value&gt;1&lt;/value&gt; &lt;/attributemodifier&gt; &lt;/attributemodifiers&gt; &lt;skillmodifiers&gt; &lt;skillmodifier&gt; &lt;skill&gt;Intimidation&lt;/skill&gt; &lt;value&gt;1&lt;/value&gt; &lt;/skillmodifier&gt; &lt;/skillmodifiers&gt; &lt;/gender&gt; &lt;gender&gt; &lt;name&gt;Neuter&lt;/name&gt; &lt;desc&gt;NeuDesc&lt;/desc&gt; &lt;attributemodifiers&gt; &lt;attributemodifier&gt; &lt;attribute&gt;Attunement&lt;/attribute&gt; &lt;value&gt;1&lt;/value&gt; &lt;/attributemodifier&gt; &lt;/attributemodifiers&gt; &lt;skillmodifiers&gt; &lt;skillmodifier&gt; &lt;skill&gt;Coercion&lt;/skill&gt; &lt;value&gt;1&lt;/value&gt; &lt;/skillmodifier&gt; &lt;/skillmodifiers&gt; &lt;/gender&gt; &lt;/genders&gt; </code></pre> <p><strong>Enums for AttributeName and SkillName</strong></p> <pre class="lang-xml prettyprint-override"><code>public enum AttributeName { Strength, Agility, Quickness, Endurance, Attunement, Focus }; public enum SkillName { Weight_Capacity, Attack_Power, Intimidation, Coercion, Charm }; </code></pre> <p><strong>And lastly, the Gender class</strong></p> <pre class="lang-cs prettyprint-override"><code>using System.Collections.Generic; public class Gender { private string _name; private string _desc; private List&lt;GenderBonusAttribute&gt; _attributeMods; private List&lt;GenderBonusSkill&gt; _skillMods; public Gender () { _name = string.Empty; _attributeMods = new List&lt;GenderBonusAttribute&gt; (); _skillMods = new List&lt;GenderBonusSkill&gt; (); } public string Name { get {return _name;} set {_name = value;} } public string Desc { get {return _desc;} set {_desc = value;} } public void AddAttributeModifier (int a, int v) { _attributeMods.Add (new GenderBonusAttribute (a, v)); } public void AddSkillModifier (int s, int v) { _skillMods.Add (new GenderBonusSkill (s, v)); } public List&lt;GenderBonusAttribute&gt; AttributeMods { get {return _attributeMods;} } public List&lt;GenderBonusSkill&gt; SkillMods { get {return _skillMods;} } } public class GenderBonusAttribute { public int attribute; public int value; public GenderBonusAttribute (int a, int v) { attribute = a; value = v; } } public class GenderBonusSkill { public int skill; public int value; public GenderBonusSkill (int s, int v) { skill = s; value = v; } } </code></pre> <p>I don't want to hardcode the genders for various reasons.</p> <p>Does this code look good enough? If not, what changes should be made and where can I read more about them?</p>
[]
[ { "body": "<ol>\n<li>Your code style is really inconsistent. As if you were copypasting code blocks from various places and didn't bother to refactor it. Part of the reason your code is hard to read. A somewhat accepted code style is: a) prefix field names with underscores, b) if possible use auto-properties for public members instead of fields and properties with backing fields</li>\n<li><code>public GenderBonusAttribute (int a, int v)</code> what is <code>a</code>? what is <code>v</code>? no way to tell without digging into your code. You should use descriptive names.</li>\n<li>Using static fields in <code>GenderManager</code> and setting them via non-static constructor is a mess. </li>\n<li><code>Length</code> is not descriptive. What is length? If it is the length of <code>genders</code>, then why dont you expose <code>genders.Count</code> instead?</li>\n<li>In my opinion <code>XmlDocument</code> is somewhat depricated. I would use <code>XDocument</code> and Linq-to-Xml instead. It would simplify your code. Though in a sense its probably a matter of taste. </li>\n<li>I think some light weight data base will do a better job in storing game mechanics then xml files.</li>\n</ol>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-01-21T06:41:50.053", "Id": "66628", "Score": "0", "body": "1. I try to use underscore as prefix when there are setters and getters for a variable. 2. a is attribute, v is value. 3. I will get to once I understand more about singletons. 4. Was part of my question, if that was better to do or not, I take it is better. 5. I was told so fairly recently, I used MSDN with a touch of stackoverflow to solve the XML part. 6. Yes, I will change that in the future. Right now, I want to make it as easy as possible for designers without having to craft tools for them." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-01-21T06:44:35.733", "Id": "66629", "Score": "0", "body": "#3 I take it I should start look into singletons to clear that mess? #4 I should also return Genders.Length instead of having a length counter? In C++ it was faster to store the length and return it than use the innate of a vector if I can recall correctly." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-01-21T07:01:19.047", "Id": "66630", "Score": "0", "body": "If you use a property instead of a method it's usually faster. In c++ the vector's size is a method, if I'm not mistaken." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-01-21T09:05:46.147", "Id": "66639", "Score": "0", "body": "@Emz, 1) variable has no setters or getters, only propeties do, and property name should start with a capital letter. 2) you do not need to explain it to me. You should not need to, thats the point. You should use `attribute` instead of `a` in the first place. 3) Singleton is a static instance of non-static class with private constructor. So you will have to tweak your class quite a bit. Also note, that singletons considered an anti-pattern by a lot of developers. In my opinion singletons are rarely needed and are often an excuse for laziness." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-01-21T09:06:56.620", "Id": "66640", "Score": "0", "body": "@Emz, 4) yes, you should return `Count`. Even if there is a performance difference in C# (which i doubt), it is negligible." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-01-21T11:58:31.330", "Id": "66647", "Score": "0", "body": "1. I mean for variables accessible by setters and getters. List<Gender> genders is not, you can only get one index. While private string _name is. 2. Roger, not used to coding with others, sadly! Some things are very clear to me. You make a good point. 3. With singleton I meant http://wiki.unity3d.com/index.php/Toolbox which is supposed to be a better version of Singleton, however, I haven't gotten much into that yet." } ], "meta_data": { "CommentCount": "6", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-01-21T06:19:10.860", "Id": "39719", "ParentId": "39718", "Score": "4" } }, { "body": "<p>In addition to Nik's comments:</p>\n\n<p>If you are not married to the structure of your XML document and are happy to change it then a simpler method would be to use the <a href=\"http://msdn.microsoft.com/en-us/library/system.xml.serialization.xmlserializer%28v=vs.110%29.aspx\" rel=\"nofollow\"><code>XmlSerializer</code></a></p>\n\n<p>Using it your <code>GenderManager</code> can be de/serialized easily by a few lines of code:</p>\n\n<pre><code>public class GenderManager {\n\n public List&lt;Gender&gt; Genders { get; private set; }\n\n // Use this for initialization\n public GenderManager () {\n Genders = new List&lt;Gender&gt;();\n }\n\n public static GenderManager Deserialize()\n {\n using (var reader = new StreamReader(\"genders.xml\"))\n {\n return (GenderManager)new XmlSerializer(typeof(GenderManager)).Deserialize(reader);\n }\n }\n\n public void Serialize()\n {\n using (var writer = new StreamWriter(\"genders.xml\"))\n {\n new XmlSerializer(typeof(GenderManager)).Serialize(writer, this);\n }\n }\n\n\n public int Length {\n get {return Genders.Count;}\n }\n\n public Gender Gender (int index) {\n return Genders [index];\n }\n}\n</code></pre>\n\n<p>Slight catch: </p>\n\n<ol>\n<li>All serialized types need to have a parameterless constructor although it is enough for it to be <code>protected</code>.</li>\n<li>All properties and fields you wish to be serialized need to be public. The serializer will ignore private properties and fields.</li>\n</ol>\n\n<p>Note: I have taken the liberty to remove the static from all fields and just return the <code>Count</code> of the list rather than keeping track of the length separately.</p>\n\n<p>When serialization requirements get more complex it can get problematic but for simple stuff it's hard to beat.</p>\n\n<p>Sample XML file:</p>\n\n<pre><code>&lt;?xml version=\"1.0\" encoding=\"utf-8\"?&gt;\n&lt;GenderManager xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\" xmlns:xsd=\"http://www.w3.org/2001/XMLSchema\"&gt;\n &lt;Genders&gt;\n &lt;Gender&gt;\n &lt;Name /&gt;\n &lt;AttributeMods&gt;\n &lt;GenderBonusAttribute&gt;\n &lt;attribute&gt;0&lt;/attribute&gt;\n &lt;value&gt;10&lt;/value&gt;\n &lt;/GenderBonusAttribute&gt;\n &lt;/AttributeMods&gt;\n &lt;SkillMods /&gt;\n &lt;/Gender&gt;\n &lt;Gender&gt;\n &lt;Name /&gt;\n &lt;AttributeMods /&gt;\n &lt;SkillMods&gt;\n &lt;GenderBonusSkill&gt;\n &lt;skill&gt;4&lt;/skill&gt;\n &lt;value&gt;5&lt;/value&gt;\n &lt;/GenderBonusSkill&gt;\n &lt;/SkillMods&gt;\n &lt;/Gender&gt;\n &lt;/Genders&gt;\n&lt;/GenderManager&gt;\n</code></pre>\n\n<p>Some other remarks:</p>\n\n<ol>\n<li><p>You should use descriptive names for variables and parameters. Descriptive names go a long way of describing the purpose of a variable or parameter which can greatly improve readability and maintainability. See them as built-in documentation.</p></li>\n<li><p>You have defined enums for attribute and skill names so why do you use an <code>int</code> to add them to your object. They should be using the enum types, e.g.:</p>\n\n<pre><code>public class GenderBonusAttribute {\n public AttributeName attribute;\n public int value;\n\n public GenderBonusAttribute (AttributeName attributeName, int val) {\n attribute = attributeName;\n value = val;\n }\n}\n</code></pre></li>\n</ol>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-01-21T12:01:51.150", "Id": "66648", "Score": "0", "body": "It is for the designers sake, so they don't have to remember 0 = Attack_Power (etc). It gets more complex when playing with Items." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-01-26T08:48:59.963", "Id": "67333", "Score": "0", "body": "Reading my comment again, it doesn't much sense at all. Will add that change as well. It is good going over your code again now and then!" } ], "meta_data": { "CommentCount": "2", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-01-21T07:28:21.497", "Id": "39725", "ParentId": "39718", "Score": "4" } } ]
{ "AcceptedAnswerId": "39719", "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-01-21T05:13:09.957", "Id": "39718", "Score": "4", "Tags": [ "c#", "xml", "unity3d" ], "Title": "Dynamic Storing Objects from XML in RPG" }
39718
<p>I have started to learn C and I have tried my hand at temperature conversion. The idea is to convert a temperature from Fahrenheit to Celsius and vice/versa. Can somebody review my code and let me know how I might be able to improve it? My program is as follows:</p> <pre><code>#include &lt;stdio.h&gt; void fahconv() { double fah; puts("Enter value to convert from Fahrenheit to Celsius"); scanf("%lf",&amp;fah); printf("Converted temperature from F to C: %lf",((fah - 32.0)*5.0)/9.0); } void celsconv() { double cels; puts("Enter value to convert from Celsius to Fahrenheit"); scanf("%lf",&amp;cels); printf("Converted temperature from C to F: %lf",(cels*9/5)+32); } void invalidchoice() { printf("Invalid choice..exiting"); } int main() { char choice; puts("Enter (F or f) to convert from Fahrenheit to Celsius"); puts("Enter (C or c) to convert from Celsius to Fahrenheit \n"); scanf("%c",&amp;choice); switch(choice) { case 'c': case 'C': celsconv(); break; case 'f': case 'F': fahconv(); break; default: invalidchoice(); } return 0; } </code></pre>
[ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-01-21T15:46:44.490", "Id": "66671", "Score": "1", "body": "Considering your preference for wide open space for curly-brace-delimited things, your math (and comma) operators feel a bit snug. Regarding the actual math, your use of floats in `fahconv` vs ints in `celsconv` is distracting and worries that reader that it might be significant." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-01-22T15:30:41.957", "Id": "66815", "Score": "0", "body": "Along with what everyone else said, I also notice you have added .0 to the numbers in one function but not in the other. Should probably add it to both." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-01-22T19:09:57.863", "Id": "66819", "Score": "0", "body": "can you perform mathematical operations between integers and doubles in C? the variable `cels` is declared a double." } ]
[ { "body": "<ul>\n<li><p>You don't need <code>invalidchoice()</code> as it just prints a statement and nothing else. Just put the <code>printf()</code> under <code>default</code>.</p></li>\n<li><p>Consider receiving all user input in <code>main()</code> and having the functions only do the calculations. It's best to have a function do one (useful) thing.</p>\n\n<p>In this form, the functions could also <em>return</em> the values to <code>main()</code> and displayed. With the user input eliminated, they should now take the original temperature as an argument.</p></li>\n<li><p>Optionally, you can return <a href=\"http://en.cppreference.com/w/cpp/utility/program/EXIT_status\" rel=\"noreferrer\"><code>EXIT_SUCCESS</code> or <code>EXIT_FAILURE</code></a> instead of <code>0</code> or <code>1</code>, respectively. It's <em>especially</em> important to return a failure value if the conversion was not successful.</p></li>\n</ul>\n\n<p>You could then have something like this:</p>\n\n<pre><code>#include &lt;stdio.h&gt;\n#include &lt;stdlib.h&gt;\n\ndouble fahconv(double fah)\n{\n return (fah - 32) * 5 / 9;\n}\n\ndouble celsconv(double cels)\n{\n return (cels * 9 / 5) + 32;\n}\n\nint main()\n{\n double originalTemp;\n double convertedTemp;\n char choice;\n\n scanf(\"%lf\", originalTemp);\n\n puts(\"Enter (F or f) to convert from Fahrenheit to Celsius\\n\");\n puts(\"Enter (C or c) to convert from Celsius to Fahrenheit\\n\");\n scanf(\"%c\", &amp;choice);\n\n switch (choice)\n {\n case 'c':\n case 'C':\n convertedTemp = celsconv(originalTemp);\n printf(\"Converted temperature from F to C: %lf\", convertedTemp);\n break;\n case 'f': \n case 'F':\n convertedTemp = fahconv(originalTemp);\n printf(\"Converted temperature from F to C: %lf\", convertedTemp);\n break;\n default:\n printf(\"Invalid choice..exiting\");\n return EXIT_FAILURE;\n }\n\n return EXIT_SUCCESS;\n}\n</code></pre>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-01-21T06:54:35.500", "Id": "39722", "ParentId": "39720", "Score": "18" } }, { "body": "<p>Jamal had a lot of good points, so just a few short things to add:</p>\n\n<hr>\n\n<p><code>wordstogether</code> is a confusing naming scheme. You should do one of the more standard naming schemes. In particular, either <code>underscore_separator</code>, or <code>camelCase</code>. It's also fairly common to use <code>PascalCase</code> for structs in C.</p>\n\n<hr>\n\n<p>Rather than celsconv, I would state what the conversion is from and to. For example, <code>fahrenheit_to_celsius</code> and <code>celsius_to_fahrenheit</code>. Those make it immediately clear what the input is and what the output is. From the declaration, it's easy to see what they take, but their usage is more ambiguous (<code>fahconv(deg)</code> -- is <code>deg</code> Celsius? Kelvin?).</p>\n\n<hr>\n\n<p>Since the performance of the switch is not a concern (it's not in a tight loop for example), I would be tempted to use <code>tolower</code> (from <code>ctype.h</code>) to simplify the switch to only have 1 case per character:</p>\n\n<pre><code>switch (tolower(choice)) {\n case 'c':\n /* celsius stuff */\n break;\n case 'f':\n /* ... */\n break;\n default:\n /* ... */\n}\n</code></pre>\n\n<hr>\n\n<p>You should verify that all of the readings are successful. Otherwise, your later use of those variables are pretty dangerous/pointless. <code>scanf</code> returns the number of tokens successfully extracted, so the simplest way to verify it's success is to check <code>number read == number expected</code>.</p>\n\n<p>Example:</p>\n\n<pre><code>double example;\nif (scanf(\"%lf\", &amp;example) == 1) {\n /* success */\n} else {\n /* failed :( */\n}\n</code></pre>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-01-21T06:59:55.713", "Id": "39723", "ParentId": "39720", "Score": "17" } }, { "body": "<p>My C is a bit rusty, but here's what I can do about it:</p>\n\n<p><code>celsconv</code> and <code>fahconv</code> seem redundant. You can simply ask the user the input value and in what way to convert it. Then in your switch, do the conversion. Afterwards output the result. The following is the shortest I could get it, minus some cosmetics.</p>\n\n<pre><code>double input;\nchar convertTo;\n\nscanf(\"%f\",&amp;input);\nscanf(\"%c\",&amp;convertTo);\n\nswitch(convertTo){\n case 'c':\n case 'C':\n printf(\"F to C: %f\",(input - 32) * 5 / 9); \n break;\n case 'f':\n case 'F': \n printf(\"C to F: %f\",(input * 9 / 5) + 32); \n break;\n default: \n printf(\"Invalid choice..exiting\");\n} \n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-01-21T07:03:06.400", "Id": "66631", "Score": "8", "body": "Perhaps in this simple case. However, getting into the habit of breaking things up into functions early is a good habit - personally I'd rather recommend leaving them as functions." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-01-21T07:04:44.760", "Id": "66632", "Score": "0", "body": "@Yuushi I forgot OP did say he was learning, so yeah, point taken. :D" } ], "meta_data": { "CommentCount": "2", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-01-21T07:01:32.490", "Id": "39724", "ParentId": "39720", "Score": "8" } }, { "body": "<p>Another hint: Never use <code>scanf</code> to read numbers from a terminal. If the user types in a letter, the input gets \"stuck\" - this and anything later in the same <code>scanf</code> will not parse any input. (Read the spec for <code>scanf</code> to see what I mean.)</p>\n\n<p>Best way to do this sort of thing: </p>\n\n<ol>\n<li>Declare a buffer of size <code>MAX_INPUT_LENGTH</code> (of your choosing) </li>\n<li>Use <code>fgets</code> to read a buffer of that size </li>\n<li>Use <code>sscanf</code> to parse the number out.</li>\n</ol>\n\n<p>The C library functions dealing with strings are a real disaster (as they can easily cause buffer overflow, among other problems). It's annoying that the safest way to do something as simple as what you're doing is as complex as this.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-01-21T19:21:11.670", "Id": "39754", "ParentId": "39720", "Score": "3" } }, { "body": "<p>Another choice is not to write an interactive program but to put the arguments on the command line. Many UNIX utilities take this simpler approach. Here is your program written that way:</p>\n\n<pre><code>#include &lt;stdio.h&gt;\n#include &lt;stdlib.h&gt;\n\nstatic double f_to_c(double fah)\n{\n return (fah - 32) * 5 / 9;\n}\n\nstatic double c_to_f(double cels)\n{\n return (cels * 9 / 5) + 32;\n}\n\nint main(int argc, char **argv)\n{\n if (argc &gt; 1) {\n double t = strtod(argv[1], 0);\n printf(\"%.2lfC = %.2lfF\\n\", t, c_to_f(t));\n printf(\"%.2lfF = %.2lfC\\n\", t, f_to_c(t));\n } else {\n printf(\"Usage: %s value\\n\", argv[0]);\n }\n return 0;\n}\n</code></pre>\n\n<p>Notice that I have renamed your functions to short name equivalents of <code>fahrenheit_to_celsius</code> and <code>celsius_to_fahrenheit</code> suggested by @Corbin. </p>\n\n<p>You may not have learned about command-line arguments yet. <code>argc</code> is the number of arguments on the command line including the command name itself. <code>argv</code> is an array of the nul-terminated strings, one for the command (<code>argv[0]</code>) and one for each argument you typed (<code>argv[1]</code> etc). </p>\n\n<p>If you name the compiled program <code>convert</code> and run it, it will print the two possible conversions:</p>\n\n<pre><code>$ ./convert 32\n32.00C = 89.60F\n32.00F = 0.00C\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-01-22T14:35:57.123", "Id": "66777", "Score": "0", "body": "For a commandline usage, I would recommend putting a loop on argc, and converting all the values presented." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-01-23T04:14:00.480", "Id": "66876", "Score": "0", "body": "@William Morris - Thanks for this elegant snippet. I was wondering what is the purpose of having static before the functions?" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-01-23T19:28:12.097", "Id": "66956", "Score": "1", "body": "Making functions `static` keeps their name local which avoids polluting the global namespace and makes some compiler optimizations possible. For a single file program that has no significance, but it is good practice when writing larger programs." } ], "meta_data": { "CommentCount": "3", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-01-22T14:24:53.657", "Id": "39809", "ParentId": "39720", "Score": "6" } } ]
{ "AcceptedAnswerId": "39722", "CommentCount": "3", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-01-21T06:19:24.403", "Id": "39720", "Score": "14", "Tags": [ "c", "beginner", "converting" ], "Title": "Temperature conversion in C" }
39720
<p>How could I simplify the <code>onCreate()</code> method? Maybe via compact and properly-named methods?</p> <pre><code>public class FilterActivity extends FragmentActivity { private Bundle args; private FilterFragment filterFragment; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_3_filter); if (savedInstanceState == null) { args = getIntent().getExtras(); } else { args = savedInstanceState.getBundle(Keys.args); } FragmentManager fragmentManager = getSupportFragmentManager(); FragmentTransaction fragmentTransaction = fragmentManager.beginTransaction(); filterFragment = new FilterFragment(); filterFragment.setArguments(args); if (savedInstanceState == null) { fragmentTransaction.add(R.id.containerOfFilterFragment, filterFragment); } else { fragmentTransaction.replace(R.id.containerOfFilterFragment, filterFragment); } fragmentTransaction.commit(); filterFragment = (FilterFragment) getSupportFragmentManager().findFragmentById(R.id.containerOfFilterFragment); } @Override protected void onSaveInstanceState(Bundle outState) { super.onSaveInstanceState(outState); outState.putBundle(Keys.args, args); } } </code></pre>
[]
[ { "body": "<p>Is this method really a problem? Why are you worried about it? There are some small changes you can make, but they do not have much of an impact on the performance of the routine (if it is slow...).</p>\n\n<p>About the only things I can think of improving are:</p>\n\n<ol>\n<li>you check whether the <code>savedInstanceState</code> is null twice, and those two checks can be merged in to one...</li>\n<li>you create a new FilterFragment instance, and you either add it to (if it is not there), or replace it (if there already was one). Thus, you <em>have</em> the filterFragement, and you do not need to <code>findFragmentById(...)</code> since you should be finding the fragment you just put in there....</li>\n</ol>\n\n<p>Here's your method with the lines commented out that I don't think you need, and also two new lines marked with <code>//**ADDED**</code></p>\n\n<pre><code>@Override\nprotected void onCreate(Bundle savedInstanceState) {\n super.onCreate(savedInstanceState);\n setContentView(R.layout.activity_3_filter);\n\n //if (savedInstanceState == null) {\n // args = getIntent().getExtras();\n //} else {\n // args = savedInstanceState.getBundle(Keys.args);\n //}\n\n FragmentManager fragmentManager = getSupportFragmentManager();\n FragmentTransaction fragmentTransaction = fragmentManager.beginTransaction();\n filterFragment = new FilterFragment();\n //filterFragment.setArguments(args);\n if (savedInstanceState == null) {\n filterFragment.setArguments(getIntent().getExtras()); //**ADDED**\n fragmentTransaction.add(R.id.containerOfFilterFragment, filterFragment);\n } else {\n filterFragment.setArguments(savedInstanceState.getBundle(Keys.args)); //**ADDED**\n fragmentTransaction.replace(R.id.containerOfFilterFragment, filterFragment);\n }\n fragmentTransaction.commit();\n\n //filterFragment = (FilterFragment)\n // getSupportFragmentManager().findFragmentById(R.id.containerOfFilterFragment);\n}\n</code></pre>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-01-21T13:45:13.840", "Id": "39742", "ParentId": "39732", "Score": "3" } } ]
{ "AcceptedAnswerId": "39742", "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-01-21T11:33:00.520", "Id": "39732", "Score": "2", "Tags": [ "java", "android" ], "Title": "Filter fragments manager" }
39732
<p>I have finished a program, and it does what I want it to do, but I feel I am "doing it wrong", even though it's seemingly efficient enough. I have prepared a small example of what I feel I am handling wrong with the <code>backgroundworker</code> class and would like to see if I could have handled this any more cleanly.</p> <p>First, I have a form with 1 button, 1 <code>statusstrip</code>, 1 <code>toolstripprogressbar</code>, and 1 <code>toolstriplabel</code>. I update the <code>statusstrio</code> items while the <code>backgroundworker</code> is running, as well as show <code>messageboxes</code> across classes. See below.</p> <h2>Form1.cs</h2> <pre><code>namespace StatusStripTest { public partial class Form1 : Form { public Form1() { InitializeComponent(); } private void prepareToRun() { if (!backgroundWorker1.IsBusy) { backgroundWorker1 = new BackgroundWorker(); backgroundWorker1.DoWork += delegate { Looping.loop(statusStrip1); }; backgroundWorker1.RunWorkerAsync(); } } private void button1_Click(object sender, EventArgs e) { prepareToRun(); } } } </code></pre> <h2>Looping.cs</h2> <pre><code>namespace StatusStripTest { public class Looping { public static void loop(StatusStrip strip) { Form1 Form1 = new Form1(); string alphabet = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz"; while (true) { MessageBox.Show("Time to loop"); foreach (char c in alphabet) { StripHandler.UpdateProgress(strip, alphabet.IndexOf(c), alphabet.Length); StripHandler.UpdateStatus(strip, c.ToString()); } } } } } </code></pre> <h2>StripHandler.cs</h2> <pre><code>namespace StatusStripTest { public class StripHandler { public static void UpdateStatus(StatusStrip ss, String Status) { ss.Invoke((MethodInvoker)delegate { if ((ss.Items[1] as ToolStripStatusLabel) != null) { ss.Items[1].Text = Status; } }); } public static void UpdateProgress(StatusStrip ss, long position, long len) { ss.Invoke((MethodInvoker)delegate { if ((ss.Items[0] as ToolStripProgressBar) != null) { ToolStripProgressBar tspb = (ToolStripProgressBar)ss.Items[0]; tspb.Minimum = 0; tspb.Maximum = (int)len; tspb.Value = (int)position; } }); } } } </code></pre> <p>Am I passing the <code>statusstrip</code> incorrectly?</p>
[ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-01-21T12:10:04.223", "Id": "66649", "Score": "0", "body": "Your thing with the alphabet, what is it supposed to model? Progression of a single process?" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-01-22T18:38:12.870", "Id": "66812", "Score": "0", "body": "Yes, it was a model. The 'Looping.Loop' was supposed to represent one of many different classes that needed calling depending on which button is pressed in my main program. I didn't make that clear at all, however." } ]
[ { "body": "<p>In general, passing controls to the <code>BackgroundWorker</code> should not be necessary at all. Think about it as it simply has some <em>job</em> to do and that's all. However, it can of course <em>report</em> about progress of its job. Those two ideas were taken into account when designing <code>BackgroundWorker</code> class and are reflected by <code>DoWork</code> and <code>ProgressChanged</code> events respectively. There is also a dedicated <a href=\"http://msdn.microsoft.com/en-us/library/a3zbdb1t%28v=VS.90%29.aspx\"><code>BackgroundWorker.ReportProgress</code></a> method which raises <code>ProgressChanged</code> event. </p>\n\n<p>This event should be handled on GUI level so it has access to the controls without passing them down to worker. Draft of solution:</p>\n\n<pre><code>private void prepareToRun()\n{\n if (!backgroundWorker1.IsBusy)\n {\n backgroundWorker1 = new BackgroundWorker();\n backgroundWorker1.DoWork += backgroundWorker_DoWork;\n backgroundWorker1.ProgressChanged += backgroundWorker_ProgressChanged;\n backgroundWorker1.RunWorkerAsync();\n }\n}\n\npublic static void backgroundWorker_DoWork(object sender, DoWorkEventArgs e)\n{\n BackgroundWorker worker = sender as BackgroundWorker;\n\n // use worker.ReportProgress(percent, someData) somewhere here\n\n}\n\nprivate void backgroundWorker_ProgressChanged(object sender, ProgressChangedEventArgs e)\n{\n // Update your statusStrip1 here according to data passed in e.ObjectState\n}\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-01-21T19:15:10.020", "Id": "66692", "Score": "0", "body": "This could be streamlined a little more by setting up your `backgroundWorker1` control at Form1 Load, then just tell it `RunWorkerAsync()` if not `IsBusy`." } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-01-21T12:26:36.520", "Id": "39738", "ParentId": "39733", "Score": "8" } }, { "body": "<p>Here is a technique to do everything your three classes do under one file and one class name. Konrad's code makes good points, but the code below shows how to accomplish your tasks.</p>\n\n<p>Since you have no need to change your <strong>BackgroundWorker</strong>'s event handlers, code them up in the Form's constructor:</p>\n\n<pre><code>private const string alphabet = \"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz\";\n\npublic Form1() {\n InitializeComponent();\n backgroundWorker1 = new BackgroundWorker();\n backgroundWorker1.WorkerReportsProgress = true;\n backgroundWorker1.WorkerSupportsCancellation = true;\n backgroundWorker1.DoWork += new DoWorkEventHandler(backgroundWorker_DoWork);\n backgroundWorker1.ProgressChanged += new ProgressChangedEventHandler(backgroundWorker_ProgressChanged);\n}\n</code></pre>\n\n<p>I also defined <code>alphabet</code> as a constant, since it will never change.</p>\n\n<p>Now, you need to know what <code>backgroundWorker_DoWork</code> and <code>backgroundWorker_ProgressChanged</code> are.</p>\n\n<p>This version is closest to the code you posted, using a <code>foreach</code> loop on the <strong>alphabet</strong> string. Every time you access the next character, that character's index has to be extracted and the length of the fixed array has to be determined again:</p>\n\n<pre><code>private void backgroundWorker_DoWork_obsolete(object sender, DoWorkEventArgs e) {\n var obj = (BackgroundWorker)sender;\n while (!obj.CancellationPending) {\n foreach (char c in alphabet) {\n float calc = ((float)alphabet.IndexOf(c) / alphabet.Length) * 100;\n obj.ReportProgress(Convert.ToInt32(calc));\n }\n }\n}\n</code></pre>\n\n<p>The modified version below is going to create the string using a value that is supplied as the argument (so, now this code can be used for other string values). Since your code basically just walks down the length of the string of characters, I modified this version to use a more efficient <code>for(;;)</code> loop (more efficient because it does not have to extract the index or calculate the string length every time):</p>\n\n<pre><code>private void backgroundWorker_DoWork(object sender, DoWorkEventArgs e) {\n var obj = (BackgroundWorker)sender;\n string alphas = e.Argument.ToString();\n int len = alphas.Length;\n while (!obj.CancellationPending) {\n for (int i = 0; i &lt; len; i++) {\n float calc = ((float)i / len) * 100;\n obj.ReportProgress(Convert.ToInt32(calc));\n }\n }\n}\n</code></pre>\n\n<p>Notice in both examples that I use <code>while (!obj.CancellationPending)</code> instead of <code>while(true)</code>. Now, if you wanted to include a Cancel button on your form, you could simply wire it up like this:</p>\n\n<pre><code>private void cancel_Click(object sender, EventArgs e) {\n backgroundWorker1.CancelAsync();\n}\n</code></pre>\n\n<p>This would halt your BackgroundWorker loop.</p>\n\n<p>Now, the <code>backgroundWorker_ProgressChanged</code> routine is simple:</p>\n\n<pre><code>private void backgroundWorker_ProgressChanged(object sender, ProgressChangedEventArgs e) {\n toolstripprogressbar.Value = e.ProgressPercentage;\n}\n</code></pre>\n\n<p>To execute this code, just be sure to initialize your <code>toolstripprogressbar</code> before calling <code>RunWorkerAsync</code>.</p>\n\n<pre><code>private void prepareToRun() {\n if (!backgroundWorker1.IsBusy) {\n toolstripprogressbar.Minimum = 0;\n toolstripprogressbar.Value = 0;\n toolstripprogressbar.Maximum = alphabet.Length;\n backgroundWorker1.RunWorkerAsync(alphabet);\n }\n}\n\nprivate void button1_Click(object sender, EventArgs e) {\n prepareToRun();\n}\n</code></pre>\n\n<p>A few extra notes:</p>\n\n<p>The <strong>BackgroundWorker.ReportProgress</strong> is overloaded to accept an <code>object userState</code> and the <strong>BackgroundWorker.ProgressChangedEventArgs</strong> contains this <code>UserState</code> object. So, if you wanted to pass the actual item to some <strong>Label</strong> control called <code>lblProgress</code>, that is possible:</p>\n\n<pre><code>private void backgroundWorker_DoWork2(object sender, DoWorkEventArgs e) {\n var obj = (BackgroundWorker)sender;\n string alphas = e.Argument.ToString();\n int len = alphas.Length;\n while (!obj.CancellationPending) {\n foreach (char c in alphas ) {\n float calc = ((float)alphas .IndexOf(c) / len ) * 100;\n obj.ReportProgress(Convert.ToInt32(calc), c);\n }\n }\n}\n\nprivate void backgroundWorker_ProgressChanged2(object sender, ProgressChangedEventArgs e) {\n toolstripprogressbar.Value = e.ProgressPercentage;\n lblProgress.Text = e.UserState.ToString();\n}\n</code></pre>\n\n<p>If you wanted to get fancy, wire up the <strong>BackgroundWorker.RunWorkerCompletedEventHandler</strong>:</p>\n\n<pre><code> backgroundWorker1.RunWorkerCompleted += new RunWorkerCompletedEventHandler(backgroundWorker_RunWorkerCompleted);\n</code></pre>\n\n<p>...add this little piece of code to hide your Progress Bar and enable your Cancel Button:</p>\n\n<pre><code>private void backgroundWorker_RunWorkerCompleted(object sender, RunWorkerCompletedEventArgs e) {\n toolstripprogressbar.Visible = false;\n btnCancel.Enabled = true;\n}\n</code></pre>\n\n<p>...and modify your <code>prepareToRun()</code> statement:</p>\n\n<pre><code>private void prepareToRun() {\n if (!backgroundWorker1.IsBusy) {\n toolstripprogressbar.Minimum = 0;\n toolstripprogressbar.Value = 0;\n toolstripprogressbar.Maximum = alphabet.Length;\n backgroundWorker1.RunWorkerAsync(alphabet);\n if (backgroundWorker1.IsBusy) {\n toolstripprogressbar.Visible = true;\n btnCancel.Enabled = false;\n }\n }\n}\n</code></pre>\n\n<p>Can you tell I have used a lot of BackgroundWorkers?</p>\n\n<p><strong>UPDATE:</strong></p>\n\n<p>Another note, based on the comment you provided. The <strong>DoWorkEventArgs</strong> variable <code>e</code> has an object variable called <strong>Argument</strong> that corresponds to whatever input you supply in <code>backgroundWorker1.RunWorkerAsync(any_object)</code>.</p>\n\n<p>That means <code>any_object</code> can be a class like this:</p>\n\n<pre><code>class MyParameters {\n public int Minimum { get; set; }\n public int Index { get; set; }\n public int Maximum { get; set; }\n public string TextIn { get; set; }\n public string TextOut { get; set; }\n}\n</code></pre>\n\n<p>To use it, simply cast it back to what you passed in:</p>\n\n<pre><code>private const int BG_MSG_1 = 1;\n\nprivate void backgroundWorker_DoWork3(object sender, DoWorkEventArgs e) {\n var obj = (BackgroundWorker)sender;\n var params = (MyParameters)e.Argument;\n params.Minimum = 0;\n params.Index = 0;\n params.Maximum = params.TextIn.Length;\n while (!obj.CancellationPending) {\n foreach (char c in params.TextIn ) {\n params.Index++;\n params.TextOut = string.Format(\"Processed {0}\", c);\n obj.ReportProgress(BG_MSG_1, params);\n }\n }\n}\n</code></pre>\n\n<p>Notice I have re-used the <strong>ReportProgress</strong>'s int variable of <strong>ProgressPercentage</strong> as a way to provide further/deeper options within the ProgressChanged Event Handler.</p>\n\n<p>Now, you can do any calculations you need back in your main thread by extracting your <code>MyParameters</code> out of the <strong>UserState</strong>:</p>\n\n<pre><code>private void backgroundWorker_ProgressChanged3(object sender, ProgressChangedEventArgs e) {\n if (e.ProgressPercentage == BG_MSG_1) {\n var params = (MyParameters)e.UserState;\n float calc = ((float)params.Index / params.Maximum ) * 100;\n toolstripprogressbar.Value = Convert.ToInt32(calc)\n lblProgress.Text = params.TextOut;\n }\n}\n</code></pre>\n\n<p>Now, you are only limited by how complex you want to make whatever class you want to pass back and forth ...or you could create a class for passing data in and another class for passing data out. Really, it's all up to you.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-01-22T12:46:11.083", "Id": "66767", "Score": "0", "body": "Wow! I am stunned at the absolutely phenomenal explanation you have provided! It's much clearer and concise than any other documentation I have read regarding the handling of the statusBar and backgroundworkers. However, it looks as though the code limits my status updating to just the progress done within the backgroundworker's dowork event. In the code of my main program, my \"Looping.loop\" is actually a fairly decent chunk of code which also references other classes where progress I wish to report also happens. It also looks here that I must update the label and bar simultaneously?" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-01-22T13:17:48.453", "Id": "66771", "Score": "0", "body": "Not really. Instead of passing back that single `char` in the `obj.ReportProgress(Convert.ToInt32(calc), c)` line, you can pass **ANY** object you choose (like a class or structure of all your data), then cast it back in the `ProgressChanged` event. I'm late for work, though. Gotta go!" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-01-22T16:32:08.570", "Id": "66797", "Score": "0", "body": "OK, I added an **Update** section towards the bottom without altering what I already stated up top." } ], "meta_data": { "CommentCount": "3", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-01-21T20:04:27.320", "Id": "39758", "ParentId": "39733", "Score": "6" } } ]
{ "AcceptedAnswerId": "39758", "CommentCount": "2", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-01-21T11:38:44.120", "Id": "39733", "Score": "10", "Tags": [ "c#", "thread-safety" ], "Title": "Abuse/Misuse of C# BackgroundWorker?" }
39733
<p>As I understand creating lots of resource managers in C# may be a bad idea so I thought that the best thing to do would be to create a singleton for this.</p> <p>However, I'm not 100% if this is a good idea, or if this is a good way to implement it. </p> <p>The main thing about the implementation I am unsure about is making the "Instance" private and creating number of static functions to expose the functionality. This means I can call Local.GetString instead of Local.Instance.GetString which is less clunky. I have not seen any singleton implementation which does this so I wonder if there is some problem with it.</p> <p>I am also using locking but I don't see how to get around that so that is probably fine. </p> <pre><code>public class Locale { // using System.Lazy&lt;T&gt; -- see http://msdn.microsoft.com/en-us/library/dd642331.aspx static readonly Lazy&lt;Locale&gt; lazy = new Lazy&lt;Locale&gt;(() =&gt; new Locale(), true); static readonly object _locker = new object(); Dictionary&lt;Type, ResourceManager&gt; _managers; public Locale() { _managers = new Dictionary&lt;Type, ResourceManager&gt;(); } static Locale Instance { get { return lazy.Value; } } public static ResourceManager GetManager(Type resourceType) { return Instance.GetResourceManager(resourceType); } public static string GetString(Type resourceType, string name) { var manager = Instance.GetResourceManager(resourceType); return manager.GetString(name); } public static string GetString(Type resourceType, string name, CultureInfo culture) { var manager = Instance.GetResourceManager(resourceType); return manager.GetString(name, culture); } public static object GetObject(Type resourceType, string name) { var manager = Instance.GetResourceManager(resourceType); return manager.GetObject(name); } public static object GetObject(Type resourceType, string name, CultureInfo culture) { var manager = Instance.GetResourceManager(resourceType); return manager.GetObject(name, culture); } ResourceManager GetResourceManager(Type resourceType) { lock (_locker) { ResourceManager manager; if (!_managers.TryGetValue(resourceType, out manager)) { manager = new ResourceManager(resourceType); _managers.Add(resourceType, manager); } return manager; } } } </code></pre> <p>I am using it like so</p> <pre><code>public class LocalizedDescriptionAttribute : DescriptionAttribute { readonly Type _resourceType; readonly string _resourceName; readonly CultureInfo _culture; public LocalizedDescriptionAttribute(Type resourceType, string resourceName) : this(resourceType, resourceName, null) { } public LocalizedDescriptionAttribute(Type resourceType, string resourceName, CultureInfo cultureInfo) : base() { _resourceType = resourceType; _resourceName = resourceName; _culture = cultureInfo; } public override string Description { get { if (_culture == null) return Locale.GetString(_resourceType, _resourceName); return Locale.GetString(_resourceType, _resourceName, _culture); } } } </code></pre> <p>I have of course read Jon Skeet's article on singletons. </p>
[ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-01-23T23:23:24.217", "Id": "67013", "Score": "0", "body": "I think this may be an extension of the same mistake that results in the use of ServiceLocators, in a slightly less dangerous manner. Both are a mess to try to test." } ]
[ { "body": "<blockquote>\n <p>The main thing about the implementation I am unsure about is making the \"Instance\" private and creating number of static functions to expose the functionality. This means I can call Local.GetString instead of Local.Instance.GetString which is less clunky. I have not seen any singleton implementation which does this so I wonder if there is some problem with it.</p>\n</blockquote>\n\n<p>I don't think there's a problem with that. Your static methods are only doing things which otherwise the calling code would do.</p>\n\n<blockquote>\n <p>I am also using locking but I don't see how to get around that so that is probably fine.</p>\n</blockquote>\n\n<p>If your code is single-threaded then you don't need locking at all.</p>\n\n<p>If your code is multi-threaded, perhaps you can construct the singleton before the multi-threading starts: for example by calling a static Locale.CreateInstance method in your program's Main (or from Application_Start if your code is ASP.NET).</p>\n\n<p>If your code is multi-threaded then the non-static Locale methods must also be thread-safe: including your Locale._managers dictionary accessors, <strong>and</strong> your ResourceManager methods. <a href=\"http://msdn.microsoft.com/en-us/library/system.resources.resourcemanager%28v=vs.110%29.aspx\" rel=\"nofollow\">ResourceManager</a> is already documented as a thread-safe class.</p>\n\n<p>An alternative to the explicit <code>lock</code> you implemented is to use the ConcurrentDictionary class instead of Dictionary, specifically its <a href=\"http://msdn.microsoft.com/en-us/library/ee378677%28v=vs.110%29.aspx\" rel=\"nofollow\">GetOrAdd method</a>, something like:</p>\n\n<pre><code>ResourceManager GetResourceManager(Type resourceType)\n{\n Func&lt;Type, ResourceManager&gt; valueFactory =\n resourceType =&gt; new ResourceManager(resourceType);\n return managers.GetOrAdd(resourceType, valueFactory);\n}\n</code></pre>\n\n<p>Stylistically, some people recommend auto-declaring variables types as <code>var</code> for example ...</p>\n\n<pre><code> var valueFactory = resourceType =&gt; new ResourceManager(resourceType);\n</code></pre>\n\n<p>... or simply ...</p>\n\n<pre><code>ResourceManager GetResourceManager(Type resourceType)\n{\n return managers.GetOrAdd(resourceType, resourceType =&gt; new ResourceManager(resourceType));\n}\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-01-21T14:15:22.623", "Id": "66660", "Score": "0", "body": "Oh, I didn't know about the ConcurrentDictionary class. I'll change my code to use that.\n\nI don't really understand your other comments about locking. Are you saying there is something else I am missing, that it isn't thread safe? \n\nThe locking is to avoid creating multiple resource managers with the same \"type\". The only point I am currently accessing the _managers field is under that lock. And the Lazy<> code (thread-safe flag is set to true) should take care of making the singleton thread-safe. I don't see what having a Locale.CreateInstance would do or solve." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-01-21T14:21:13.903", "Id": "66662", "Score": "0", "body": "Locale.CreateInstance at program startup would guarantee it's created before it's used, and mean that you don't need to use Lazy. Perhaps you're trying to avoid locks altogether, and Lazy presumably includes a lock in its implementation." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-01-21T14:23:50.197", "Id": "66664", "Score": "0", "body": "It looks thread-safe as-is. I'm just trying to reduce the number of explicit locks and lines of code (use ConcurrentDictionary instead of Dictionary), and the number of implicit locks (perhaps create on startup instead of using Lazy)." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-01-21T14:31:46.433", "Id": "66666", "Score": "0", "body": "You said, \"I am also using locking but I don't see how to get around that\", so I was showing ways to get around that. I was also trying to warn that if ResourceManager weren't already thread-safe, then the code wouldn't be thread-safe." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-01-21T14:33:07.200", "Id": "66667", "Score": "0", "body": "Oh I see. Well think I'm willing to accept the cost of a Lazy thread-safety. I think it's far more convenient then having to remember to call Locale.CreateInstance (this is for a rather complex system)" } ], "meta_data": { "CommentCount": "5", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-01-21T13:14:04.137", "Id": "39740", "ParentId": "39735", "Score": "3" } } ]
{ "AcceptedAnswerId": "39740", "CommentCount": "1", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-01-21T12:02:56.697", "Id": "39735", "Score": "4", "Tags": [ "c#", "singleton" ], "Title": "ResourceManager Singleton" }
39735
<p>I have made some jQuery Fallback Support for the CSS Property "background-attachment: local" and I am mainly a CSS developer. I do some jQuery, but I thought I would check to see if I am doing this in the more efficient way, as I may have multiple versions of this on one page.</p> <p><a href="http://codepen.io/2ne/pen/gtdsw" rel="nofollow">CODEPEN DEMO</a></p> <p><strong>HTML</strong></p> <pre><code>&lt;div class="container"&gt; &lt;div class="data-holder"&gt; &lt;div id="shadowtop"&gt;&lt;/div&gt; &lt;div id="shadowbottom"&gt;&lt;/div&gt; &lt;div class="block"&gt;hello&lt;/div&gt; &lt;div class="block"&gt;hello&lt;/div&gt; &lt;div class="block"&gt;hello&lt;/div&gt; &lt;div class="block"&gt;hello&lt;/div&gt; &lt;div class="block"&gt;hello&lt;/div&gt; &lt;div class="block"&gt;hello&lt;/div&gt; &lt;div class="block"&gt;hello&lt;/div&gt; &lt;div class="block"&gt;hello&lt;/div&gt; &lt;div class="block"&gt;hello&lt;/div&gt; &lt;div class="block"&gt;hello&lt;/div&gt; &lt;div class="block"&gt;hello&lt;/div&gt; &lt;div class="block"&gt;hello&lt;/div&gt; &lt;div class="block"&gt;hello&lt;/div&gt; &lt;div class="block"&gt;hello&lt;/div&gt; &lt;div class="block"&gt;hello&lt;/div&gt; &lt;div class="block"&gt;hello&lt;/div&gt; &lt;div class="block"&gt;hello&lt;/div&gt; &lt;div class="block"&gt;hello&lt;/div&gt; &lt;div class="block"&gt;hello&lt;/div&gt; &lt;div class="block"&gt;hello&lt;/div&gt; &lt;div class="block"&gt;hello&lt;/div&gt; &lt;div class="block"&gt;hello&lt;/div&gt; &lt;div class="block"&gt;hello&lt;/div&gt; &lt;div class="block"&gt;hello&lt;/div&gt; &lt;div class="block"&gt;hello&lt;/div&gt; &lt;div class="block"&gt;hello&lt;/div&gt; &lt;div class="block"&gt;hello&lt;/div&gt; &lt;div class="block"&gt;hello&lt;/div&gt; &lt;div class="block"&gt;hello&lt;/div&gt; &lt;div class="block"&gt;hello&lt;/div&gt; &lt;/div&gt; &lt;/div&gt; </code></pre> <p><strong>CSS</strong></p> <pre><code>@import "http://fonts.googleapis.com/css?family=Open+Sans:400,600,700"; * { -moz-box-sizing: border-box; -webkit-box-sizing: border-box; box-sizing: border-box; } body { background: none repeat scroll 0 0 #fff; font-family: "Open Sans"; line-height: 26px; margin: 20px; } .container { position: relative; margin-top: 30px; } .data-holder { border-top: 1px solid #eee; border-bottom: 1px solid #eee; width: 200px; height: 300px; overflow: auto; } #shadowtop, #shadowbottom { position: absolute; left: 0; height: 12px; width: 180px; z-index: 9999; display: none; background-size: 100% 12px; } #shadowtop { top: 0; background: radial-gradient(farthest-side at 50% 0, rgba(0,0,0,.15), rgba(0,0,0,0)) 0 100%; } #shadowbottom { bottom: 0; background: radial-gradient(farthest-side at 50% 100%, rgba(0,0,0,.15), rgba(0,0,0,0)) 0 100%; } .block { background: #fff; border-bottom: 1px solid #f4f4f4; padding: 10px; } .block:last-child { border-bottom: 0 none; } </code></pre> <p><strong>jQuery</strong></p> <pre><code>$(document).ready(function(){ $('.data-holder').scroll(function(){ var scrollValue = $(this).scrollTop(); var elementHeight = $(this).height(); if(scrollValue == 0){ $("#shadowtop").fadeOut(200); console.log("at top"); //should remove } else if (scrollValue == ($(this).get(0).scrollHeight - $(this).height())){ $("#shadowbottom").fadeOut(200); console.log("at bottom"); //should remove } else { console.log("in middle"); //should remove $("#shadowtop").fadeIn(200); $("#shadowbottom").fadeIn(200); } }); var scrollValue = $('.data-holder').scrollTop(); if(scrollValue &lt; ($('.data-holder').get(0).scrollHeight - $('.data-holder').height())){ $("#shadowbottom").show(); } }); </code></pre>
[]
[ { "body": "<p>This code annoyed me for a while, the part outside of the initialization does not belong and it seemed silly to add it to the listener. Plus, the code outside of the listener will mess up when you have multiple <code>data-holder</code> elements.</p>\n\n<p>Then I realized that I could take a different approach, do this in 2 steps:</p>\n\n<ol>\n<li>Determine whether I should hide or show the top</li>\n<li>Determine whether I should hide or show the bottom</li>\n</ol>\n\n<p>Then, I do not need the piece of code outside of the listener, and it becomes cleaner.\nAlso, the <code>200</code> has to be a constant, also I would take only the <code>#shadowbottom</code> and <code>#shadowtop</code> belonging to the <code>.data-holder</code>.</p>\n\n<p>So, in all, I would counter propose:</p>\n\n<pre><code>$(document).ready(function(){\n var fadeSpeed = 200;\n $('.data-holder').scroll(function(){\n var scrollValue = $(this).scrollTop(),\n elementHeight = $(this).height(),\n $top = $(this).children('#shadowtop'),\n $bottom = $(this).children('#shadowbottom'),\n atTop = (scrollValue == 0),\n atBottom = (scrollValue == ( this.scrollHeight - elementHeight));\n (atTop) ? $top.fadeOut( fadeSpeed ) : $top.fadeIn( fadeSpeed );\n (atBottom)? $bottom.fadeOut( fadeSpeed ) : $bottom.fadeIn( fadeSpeed );\n }).scroll();\n});\n</code></pre>\n\n<p>I was mildly worried that with each scroll event the top / bottom might flicker because of the repeated <code>fadeIn()</code> calls, but I can tell from your CodePen that does not happen, so there is nothing to worry about there.</p>\n\n<p>Finally, I did not look at your CSS as you actually are a CSS developer and also I did not test my code, but I am confident you get where I am going with this.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-01-24T20:34:15.323", "Id": "67162", "Score": "0", "body": "Very nice answer. Thank you. http://codepen.io/2ne/pen/gELai works here with 2 elements and it is a lot easier to see how your code is done. More universal" } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-01-24T03:58:31.500", "Id": "39931", "ParentId": "39745", "Score": "2" } } ]
{ "AcceptedAnswerId": "39931", "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-01-21T14:51:43.343", "Id": "39745", "Score": "5", "Tags": [ "javascript", "optimization", "jquery", "css" ], "Title": "jQuery Fallback Support for the CSS Property \"background-attachment: local\"" }
39745
<p>I am <a href="http://code.google.com/p/jmapper-framework/" rel="nofollow">using <code>JMapper</code> to map</a> from multiple sources to a destination class. Could you review it and let me know if the code looks OK to you? Please suggest any changes that I can make to improve it.</p> <p>Interface to <code>Map</code> sources to destination object:</p> <pre><code>public interface ObjectMapper&lt;D&gt; { public D getDestination(Object... sources); } </code></pre> <p>Class that implements this interface to perform the desired mapping using <code>JMapper</code>:</p> <pre><code>import org.apache.commons.lang.WordUtils; import com.googlecode.jmapper.JMapper; public class JMapperImpl&lt;S1, S2&gt; implements ObjectMapper&lt;DestinationClazz&gt; { private static ObjectMapper&lt;DestinationClazz&gt; INSTANCE; private static final String CONVERSION_END = "Conversion.xml"; private Class&lt;S1&gt; source1; private Class&lt;S2&gt; source2; private final JMapper&lt;DestinationClazz, S1&gt; mapper1; private final JMapper&lt;DestinationClazz, S2&gt; mapper2; private JMapperImpl(Class&lt;DestinationClazz&gt; destination, Class&lt;S1&gt; source1, Class&lt;S2&gt; source2) { final String mappingFile = getMappingFile(destination); mapper1 = new JMapper&lt;DestinationClazz, S1&gt;(destination, source1, mappingFile); mapper2 = new JMapper&lt;DestinationClazz, S2&gt;(destination, source2, mappingFile); this.source1 = source1; this.source2 = source2; } /** * @param destination * @return uncapitalizes the first letter of destination class name. */ private String getMappingFile(Class&lt;DestinationClazz&gt; destination) { return WordUtils.uncapitalize(destination.getSimpleName())+CONVERSION_END; } public static &lt;S1, S2&gt; ObjectMapper&lt;DestinationClazz&gt; getJMapperInstance(Class&lt;DestinationClazz&gt; destination, Class&lt;S1&gt; source1, Class&lt;S2&gt; source2) { if(INSTANCE == null) { INSTANCE = new JMapperImpl&lt;S1, S2&gt;(destination, source1, source2); } return INSTANCE; } /** * Returns new instance of destination object with its properties mapped from source objects */ @Override public DestinationClazz getDestination(Object... sources) { DestinationClazz destination; try { destination = DestinationClazz.class.newInstance(); for(Object source : sources) { Class&lt;? extends Object&gt; sourceClass = source.getClass(); if(sourceClass == source1) { destination = mapper1.getDestination(destination, (S1)source); } else if(sourceClass == source2) { destination = mapper2.getDestination(destination, (S2)source); } } } catch (InstantiationException e) { throw new CustomException("Couldn't instantiate DestinationClazz class:"+e.getMessage()); } catch (IllegalAccessException e) { throw new CustomException("Couldn't access DestinationClazz class:"+e.getMessage()); } catch (Exception e) { throw new CustomException("Exception while mapping source objects to DestinationClazz object:"+e.getMessage()); } return destination; } } </code></pre>
[ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-07-18T11:08:09.973", "Id": "102547", "Score": "1", "body": "what you need is already implemented: https://code.google.com/p/jmapper-framework/wiki/ExplicitRelations There are many examples that will be useful: https://code.google.com/p/jmapper-framework/wiki/AdvancedExamples" } ]
[ { "body": "<p>I can understand the usefulness of a class/tool like this. The basic thinking is:</p>\n\n<ol>\n<li>need to transform class A to class B.</li>\n<li>also need to transform class C to class B.</li>\n<li>JMapper can help.</li>\n<li>there are other classes that need transformations as well</li>\n<li>we should make a generic factory for it.</li>\n<li>we can also make the concept referencable as an interface, so things other than JMapper can do the mapping if necessary.</li>\n</ol>\n\n<p>This is what I assume your thought process was, so I will review based on that assumption...</p>\n\n<h2>Interface</h2>\n\n<p>First up, the interface idea is a good one.... but the varargs <code>Object</code> parameter is a problem. You should only have a single argument. Also, since you want to keep the input argument anonymous (<code>Object</code> instead of <code>&lt;T&gt;</code>), you should have some exception handling for those times when invalid data is supplied....</p>\n\n<p>The reason for suggesting you have only a single input parameter is because the logic for choosing which instance is used for the transform is not easy to specify when there's multiple candidate input values. You should let the calling code make the decision as to which instance to convert from (note, this is related to a second problem I will address again in a moment)</p>\n\n<p>I would also recommend renaming the interface method to something more verb-like, such as <code>mapToDestination(...)</code> instead of <code>getDestination(...)</code></p>\n\n<p>Bottom line, I would recommend an interface like:</p>\n\n<pre><code>public interface ObjectMapper&lt;D&gt; {\n\n public D mapToDestination(Object source) throws IllegalArgumentException;\n\n}\n</code></pre>\n\n<p>Right, now for the actual implementation.... using JMapper. Unfortunately there are some real concerns I have in here.</p>\n\n<h2>DestinationClazz</h2>\n\n<p>Do you have an actual class called DestinationClazz? I imagine not. I think this is supposed to be a generic type, but then you are not treating it like a normal type. For example, your class definition is:</p>\n\n<pre><code>public class JMapperImpl&lt;S1, S2&gt; implements ObjectMapper&lt;DestinationClazz&gt; {\n</code></pre>\n\n<p>but then your constructor is:</p>\n\n<pre><code>private JMapperImpl(Class&lt;DestinationClazz&gt; destination, Class&lt;S1&gt; source1, Class&lt;S2&gt; source2) {\n final String mappingFile = getMappingFile(destination);\n</code></pre>\n\n<p>This makes no sense because since you have declared the ObjectMapper as an exactly typed value, you may as well have a constructor that knows it is production <code>DestinationClazz</code> instances... no need to pass in the class:</p>\n\n<pre><code>private JMapperImpl(Class&lt;S1&gt; source1, Class&lt;S2&gt; source2) {\n final String mappingFile = getMappingFile(DestinationClazz.class);\n</code></pre>\n\n<p>So, because of this inconsistency, I imagine that you really want the <code>DestinationClazz</code> to be a generic type.... and you should specify it as part of the class signature:</p>\n\n<pre><code>public class JMapperImpl&lt;S1, S2, D&gt; implements ObjectMapper&lt;D&gt; {\n private JMapperImpl(Class&lt;D&gt; destination, Class&lt;S1&gt; source1, Class&lt;S2&gt; source2) {\n final String mappingFile = getMappingFile(destination);\n ....\n\n @Override\n public D getDestination(Object source) {\n ....\n</code></pre>\n\n<h2>Static Singleton</h2>\n\n<p>This code is broken for a number of reasons:</p>\n\n<pre><code>public static &lt;S1, S2&gt; ObjectMapper&lt;DestinationClazz&gt; getJMapperInstance(Class&lt;DestinationClazz&gt; destination, Class&lt;S1&gt; source1, Class&lt;S2&gt; source2) {\n if(INSTANCE == null) {\n INSTANCE = new JMapperImpl&lt;S1, S2&gt;(destination, source1, source2); \n }\n return INSTANCE;\n}\n</code></pre>\n\n<p>Here you have a lot of pretty complicated problems going on. I will try to address them in a sensible way....</p>\n\n<ul>\n<li><strong>synchronization</strong> - you are vulnerable to having multiple instances of the same JMapper since multiple threads could be calling this at any one time, and ending up with different instances.</li>\n<li><strong>misleading generics</strong> - This is a <a href=\"http://docs.oracle.com/javase/tutorial/extra/generics/methods.html\">generic method</a> and not a method with generic arguments. What I am saying is that the <code>&lt;S1, S2&gt;</code> here are not the same ones as those on the class (<code>public class JMapperImpl&lt;S1, S2&gt; implements ....</code>). Your code implies that this static method takes the same generic arguments as the <code>INSTANCE</code> instance, but this static method is not related to any particular class instance anywhere.</li>\n<li><strong>Generic Erasure</strong> - when a class with Generics is compiled, the compiler uses the generics to do compile-time validation of the code. Once the compile is validated though, the generic information is completely erased. The effect of this is that there is actually only one class called <code>JMapperImpl</code>. You can create many instances of this class each with different generic types: <code>new JMapperImpl&lt;Double, Long&gt;(Double.class, Long.class)</code>, or <code>new JMapperImpl&lt;String, StringBuilder&gt;(String.class, StringBuilder.class)</code>, etc.... but only the first one you create using the static method will be the <code>INSTANCE</code>, and the others will never exist.... ;-)</li>\n</ul>\n\n<h2>Where to, Sir?</h2>\n\n<p>In your actual mapping method you loop through the input <code>source</code> variables, and, if they match one of your defined source classes, you create a <code>destination</code> instance using the JMapper.</p>\n\n<p>Unfortunately, you keep going until you run out of input source values.... If the user supplies 100 source values, you map them all! and only return the last one....</p>\n\n<p>Which one is the right <code>destination</code> (what's the destination? ... where to, Sir)?</p>\n\n<h2>Conclusion....</h2>\n\n<p>You should:</p>\n\n<ul>\n<li>add the <code>D</code> Destination generic type to your class definition</li>\n<li>completely remove the static INSTANCE and factory method</li>\n<li>make the constructor public.... these are light-weight classes, and you can easily have multiple instances.</li>\n<li>change the mapping method name to something more meaningful.</li>\n<li>change the mapping argument to a single <code>source</code> parameter which is the only thing to map.</li>\n<li>throw an exception if the source does not match one of the anticipated sources.</li>\n</ul>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-01-21T23:51:59.657", "Id": "66726", "Score": "0", "body": "Jmapper will enrich the destination if I pass the destination as a parameter. The source classes are different and destination has different parameters mapped to source parameters. Thank you for the detailed critique of the code. That's a learning lesson." } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-01-21T22:29:29.293", "Id": "39769", "ParentId": "39749", "Score": "6" } }, { "body": "<p>All you need is <code>RelationalJMapper</code>. You must map <code>Destination</code> class towards other classes, in your case towards <code>s1</code> and <code>s2</code>.</p>\n\n<p>For example, suppose that your <code>Destination</code> class is the following:</p>\n\n<pre><code>class Destination {\n String name;\n String surname;\n}\n</code></pre>\n\n<p>and <code>S1</code>, <code>S2</code> classes:</p>\n\n<pre><code>class S1{ class S2{\n String name; String name;\n String surname; String surname;\n} }\n</code></pre>\n\n<p>You only need to configure the <code>Destination</code> class towards <code>S1</code> and <code>S2</code>:</p>\n\n<pre><code>@JGlobalMap(classes={S1.class, S2.class})\nclass Destination {\n String name;\n String surname;\n}\n</code></pre>\n\n<p>And put the <code>Destination</code> class to <code>RelationalJMapper</code> as follows:</p>\n\n<pre><code>RelationalJMapper&lt;Destination&gt; mapper = new RelationalJMapper&lt;&gt;(Destination.class);\n</code></pre>\n\n<p>with the function <code>manyToOne</code> you can obtain an instance of <code>Destination</code> from any source defined in the configuration. In your case:</p>\n\n<pre><code>Destination destination = mapper.manyToOne(new S1(\"S1name\",\"S1surname\"));\n\nassertEqual(destination.getName(), \"S1name\");\nassertEqual(destination.getSurname(), \"S1surname\");\n\ndestination = mapper.manyToOne(new S2(\"S2name\",\"S2surname\"));\n\nassertEqual(destination.getName(), \"S2ame\");\nassertEqual(destination.getSurname(), \"S2surname\");\n</code></pre>\n\n<p>For more information visit the <a href=\"https://code.google.com/p/jmapper-framework/wiki/ExplicitRelations\" rel=\"nofollow\">Explicit relations</a> wiki page.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2015-05-20T09:56:43.067", "Id": "91259", "ParentId": "39749", "Score": "6" } } ]
{ "AcceptedAnswerId": "91259", "CommentCount": "1", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-01-21T16:52:54.100", "Id": "39749", "Score": "8", "Tags": [ "java", "generics" ], "Title": "Mapping from multiple sources to destination using JMapper" }
39749
<p><strong>Question</strong></p> <blockquote> <p>Suppose we have two sorts of classes</p> <ul> <li>an input class <code>Input</code> <ul> <li>defines a type <code>result_type</code></li> <li>defines <code>set(result_type)</code></li> </ul></li> <li>an output class <code>Output</code> <ul> <li>defines a type <code>result_type</code></li> <li>defines <code>result_type get() const</code></li> <li>has a number of <code>Input</code> classes as member variables, on which its output depends</li> </ul></li> </ul> <p>Given an output class and several input classes (arbitrary number), consider the following procedure:</p> <ul> <li>loop over each input class and call <code>set()</code> with an appropriate value (defined beforehand)</li> <li>call the <code>get()</code> on the ouput class and collect the result.</li> </ul> <p>This procedure can be seen as a call to a function taking the input's values as arguments an returning the output value.</p> <p><strong>Write the functor that constructs such a variadic function in the general case.</strong></p> <p>Constraints are: C++ (most likely C++11), arbitrary number of input classes of possibly different <code>Input::result_type</code>s. Note that <code>Input::result_type</code> is not necessarily related to <code>Output::result_type</code>. Aim should first be efficiency, but there's a big bonus if the code is elegant and readable.</p> <p><em>Details</em>: For those who wonder how <code>Output</code> is related to <code>Input</code>, one could imagine that <code>Input</code> has a <code>result_type get() const</code> method as well, which returns whatever you provided via <code>set()</code>. <code>Output</code> then has a constructor that takes various <code>Input</code>s, and stores them (or their reference) as member variables. <code>Output::get()</code> then does some math by using the return values of its input's <code>get()</code> methods, and returns some result of type <code>Output::result_type</code>.</p> </blockquote> <p><strong>Proposed solution</strong></p> <pre><code>#include &lt;functional&gt; template &lt;class Output, class... Inputs&gt; std::function&lt;typename Output::result_type(typename Inputs::result_type...)&gt; make_function(const Output&amp; output, Inputs&amp;... inputs) { return[&amp;](typename Inputs::result_type... input_vals) { int dummy[]{0, (inputs.set(input_vals),0)...}; return output.get(); }; } </code></pre> <p>The <code>int dummy[]</code> line is due to <a href="https://stackoverflow.com/a/12515637/958110">@ecatmur's answer</a>.</p>
[ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-01-22T01:46:10.777", "Id": "66731", "Score": "0", "body": "Just as a question, how are the arbitrary number of `Inputs` stored in `Output`?" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-01-22T09:22:10.053", "Id": "66747", "Score": "0", "body": "there are multiple classes that have a fixed number of inputs, and each store them in a similar way (see details section)." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-01-24T00:01:34.223", "Id": "67019", "Score": "0", "body": "Ok. I was asking because if they are all the same type, then I think there is a more elegant solution. Having them be heterogeneous types makes it more difficult, however. I might think about it a bit more, but I will say that if you're looking for efficiency, I'd try and avoid `std::function` if possible." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-01-28T10:55:07.570", "Id": "67688", "Score": "0", "body": "by what would you replace `std::function` then?" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-01-29T01:47:51.120", "Id": "67869", "Score": "2", "body": "In this case, you likely don't have a choice without changing the design significantly. In C++14, this may change with generic lambdas. That being said, having thought about it, I don't think this can really be improved upon." } ]
[ { "body": "<p>Looks to me as if you've already got the most elegant solution in mind.</p>\n\n<p>In C++14 you'd remove the dependency on <code>std::function</code> and simply return a naked lambda, like this:</p>\n\n<pre><code>template &lt;class Output, class... Inputs&gt;\nauto make_function(const Output&amp; output, Inputs&amp;... inputs) {\n return [&amp;](typename Inputs::result_type... input_vals) {\n int dummy[] { 0, ((void)inputs.set(input_vals),0)... };\n return output.get();\n };\n}\n</code></pre>\n\n<p>but in C++11 you can't make a function-that-returns-a-naked-lambda without a ton of boilerplate — if it's even possible at all.</p>\n\n<hr>\n\n<p>Also, a nitpick, with props to @stephan-t-lavavej's talk at CppCon 2014. You wrote</p>\n\n<pre><code>(inputs.set(input_vals),0)...\n</code></pre>\n\n<p>but what you should have written was</p>\n\n<pre><code>((void)inputs.set(input_vals),0)...\n</code></pre>\n\n<p>to avoid accidentally calling <code>MaliciousUserCode::operator,(int)</code>.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-10-04T07:27:36.817", "Id": "64707", "ParentId": "39750", "Score": "2" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "5", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-01-21T16:58:23.980", "Id": "39750", "Score": "7", "Tags": [ "c++", "c++11", "variadic" ], "Title": "Most elegant variadic functor" }
39750
<p>I'm receiving data from a serial port in C, using <a href="http://www.cmrr.umn.edu/~strupp/serial.html">Serial Programming Guide for POSIX Operating Systems</a> as a guide.</p> <p>The data I receive should be always 10 bytes in length but I want to be sure that, if there is any error (more or less bytes received), reading will clear buffer before the next data arrive, so that there is always proper data in the buffer to be processed. I'm using select to monitor serial file descriptor and local socket. I figured out that I can clean serial buffer in case there was something left from previous transmission, when device is not sending for some period of time.</p> <p>Question is: is this the right solution? </p> <p>main.c:</p> <pre><code>loop_num=0; si_processed=0; while(TRUE) { /* copy fd_set for select */ tmp_input=input; n = select(max_fd,&amp;tmp_input,NULL,NULL,NULL/*&amp;timeout*/); /* See if there was an error */ if (n&lt;0) perror("select failed"); else { /* We have input */ if (FD_ISSET(serial_fd, &amp;input)) { if(!process_serial(serial_fd)) loop_num++; } if (FD_ISSET(local_socket, &amp;input)) process_socket(local_socket); } if(loop_num&gt;10) { /* clear buffer */ si_processed=0; loop_num=0; } fflush(stdout); usleep(20000); } </code></pre> <p>serial_port.c</p> <pre><code>char serial_buffer[256]; int process_serial(int serial_fd) { int bytes; int n,i; char tmp_buffer[32]; ioctl(serial_fd, FIONREAD, &amp;bytes); if(!bytes) return 0; n=read(serial_fd, tmp_buffer, sizeof(tmp_buffer)); for(i=0;i&lt;n;i++) { serial_buffer[si_processed+i]=tmp_buffer[i]; } si_processed+=n; if(si_processed&gt;=INPUT_BYTES_NUM/* defined as 10 */) { serial_buffer[si_processed]='\0'; printf("read:%s\n",serial_buffer); si_processed=0; fflush(stdout); } return 1; } </code></pre> <hr> <p>Some more info. I'm querying device every 5 seconds for data, and it should always respond with 10 bytes packets: so data should come fairly quickly into serial buffer, and then a few seconds of silence; sometimes however the device can send data on its own, I don't know when, but also as a 10 bytes packets.</p> <p>I was doing some test with my program and minicom connected on the other side.</p> <p>Until I was sending data like</p> <pre><code>1234567890 1234567890 </code></pre> <p>program was reading what it supposed to read:</p> <pre><code>1234567890 </code></pre> <p>Problem arises when I send on minicom:</p> <pre><code>12345678901234567890 </code></pre> <p>Usually what was read was:</p> <pre><code>1234567890123456 </code></pre> <p>so next, when I wrote on minicom proper data:</p> <pre><code>1234567890 </code></pre> <p>program was reading</p> <pre><code>7890123456 </code></pre> <p>and every next read was bad because of leftovers in buffer from previous read.</p> <p>When I added clearing buffer after 1 or 2 seconds when nothing is read, then I'm sure any leftovers are cleared before next transmission.</p> <p>I read about this VMIN settings but decided against because of this leftovers.</p> <p>Also this data <code>1234567890</code> is just an example. In fact 10 bytes consist of:</p> <ul> <li>Byte #1 - always some constant to mark begining of transmission like 0xA5</li> <li>Byte #2 through #9 byte - data</li> <li>Byte #10 - control sum from all previous bytes.</li> </ul> <p>So after I have 10 bytes packet received I can verify if it has proper data or is somehow corrupted: so if one transmission fails, I should be ok, especially when I can clear the buffer before next data coming in.</p>
[ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-01-21T17:50:15.700", "Id": "66681", "Score": "1", "body": "What do you mean by \"right solution?\" The \"right solution\" is the one that fulfills your particular requirements. What are your requirements?" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-01-21T17:53:31.690", "Id": "66683", "Score": "0", "body": "@Robert Harvey - to be sure that if there was more or less bytes received, next transmission will have all and proper data send by device, and not some leftovers from previous transmission" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-01-21T18:14:21.927", "Id": "66685", "Score": "0", "body": "also if you know the way to accomplish this in simpler, or more elegant way, then your solution is better, and please share it with me." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-01-21T18:43:15.327", "Id": "66687", "Score": "0", "body": "Are you reading from [serial ports](http://en.wikipedia.org/wiki/Serial_port)?" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-01-21T19:13:14.310", "Id": "66691", "Score": "0", "body": "@ChrisW - Yes I'm I was using this howto http://www.cmrr.umn.edu/~strupp/serial.html" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-01-21T20:54:14.197", "Id": "66711", "Score": "0", "body": "What is the reason for `usleep()`?" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-01-22T11:15:30.250", "Id": "66762", "Score": "0", "body": "@200_success - usleep at the end of the loop is to slow program a little bit, select returns if there is non-blocking condition to read file descriptior, regardles if there is any data, without usleep while loop is working so fast, that it takes 100% of cpu" } ]
[ { "body": "<p>The code you posted contains no error-recovery at all. It's a bit off-topic on this site to ask how to implement a new feature (error-recovery); but I'll try.</p>\n<p>It's not clear what your communication protocol looks like. It might be:</p>\n<ol>\n<li>A continuous stream of bytes, to be split into packets of 10</li>\n<li>10-byte packets, with a measurable delay between packets, no reply expected</li>\n<li>10-byte packets, after which silence until there is a reply, perhaps with a retry if there no reply</li>\n</ol>\n<p>I'll assume it isn't <code>1.</code> because that has little opportunity for error-recovery: if a byte were ever lost then you wouldn't know where the boundary is between &quot;packets&quot;, if it's a continuous stream of bytes, unless you use 'framing' and 'escape sequences' in the data.</p>\n<p>So I'll assume that it's <code>2.</code> or <code>3.</code>. In either case, what's important is:</p>\n<ul>\n<li>There are 10 bytes received (probably received quickly with little or no delay between bytes)</li>\n<li>There is then a delay (no bytes received) after those 10 bytes.</li>\n</ul>\n<p><a href=\"http://www.cmrr.umn.edu/%7Estrupp/serial.html#3_1_5\" rel=\"noreferrer\">Setting Read Timeouts</a> looks interesting. It may be your best algorithm: set VMIN to say that you want to receive no more or less than exactly 10 bytes when you read.</p>\n<p>However that may have a problem:</p>\n<blockquote>\n<p>However, the timeout only applies to the first character read, so if for some reason the driver misses one character inside the N byte packet then the read call could block forever waiting for additional input characters.</p>\n</blockquote>\n<p>You don't say why you want error-recovery after losing a character: perhaps you sometimes get overruns in the driver, or bit parity errors from the serial port?</p>\n<p>&quot;Setting Input Parity Options&quot; talks about handling the parity errors:</p>\n<ol>\n<li><p>Replace/mark the byte with an error byte</p>\n<p>If you do this then you can be more sure that you will get 10 bytes; but you can only do it if the protocol allows you to recognize an illegal byte value.</p>\n</li>\n<li><p>Or remove the error byte</p>\n<p>If you do this then you must be able to recover from getting 9 bytes sometimes.</p>\n</li>\n</ol>\n<blockquote>\n<p>The data I receive should be always 10 bytes in length but I want to be sure that, if there is any error (more or less bytes received), reading will clear buffer before the next data arrive, so that there is always proper data in the buffer to be processed.</p>\n</blockquote>\n<p>Reading should empty the buffer, if your <code>sizeof(tmp_buffer)</code> is bigger is the number of bytes queued in the driver. However:</p>\n<ul>\n<li>It depends on the read mode (e.g. a read may block forever instead of clearing the buffer, if VMIN is set to non-zero)</li>\n<li>If there are, somehow, very many received bytes enqueued in the driver, then you may have to read repeatedly until the driver is empty.</li>\n<li>Immediately after you read, there may be more bytes in the driver: for example if the serial port is flow-controlled, reading from the driver allows the device to send again / send more.</li>\n</ul>\n<p>Whether you can clear the buffer &quot;before the next data arrive&quot; is difficult to say: I don't know when the next data is supposed to arrive.</p>\n<p>Depending on how you handle parity errors, maybe bytes are never lost. If bytes are sometimes lost then you may want to implement logic like:</p>\n<pre><code>read_10_bytes:\n read (waiting forever) until some bytes are returned\n if 10 bytes were read then return\n if less than 10 bytes were read, then:\n set an expiry timer\n loop doing the following\n read more bytes\n if you read 10 bytes before the timer expires, then clear the timer and return\n if the timer expires before you read 10 bytes, then discard the bad bytes and return\n</code></pre>\n<p>Instead of actually setting a timer, above, perhaps loop doing a blocking-read-with-timeout (which either reads the bytes, or expires).</p>\n<p>As well as handling too few bytes (above), you could modify the above to check for receiving more than 10 bytes: after you receive 10 bytes, do another blocking-read-with-small-timeout to verify that there are no more bytes to receive. If there are extra bytes, then read them all before returning to the 'waiting-for-next-10-bytes' state (otherwise, these extra bytes will mess up your next 10-byte packet).</p>\n<hr />\n<p>I think there's an obvious bug in the code. After you read 16 bytes, you completely clear your <code>serial_buffer</code> by zeroing <code>si_processed</code>, and you then think &quot;success!&quot; after each next 10 bytes you read.</p>\n<p>Instead you should:</p>\n<ul>\n<li>If you read too much data, don't discard the extra bytes: instead use <code>memmove</code> to move them to the beginning of the buffer (assuming they're the start of the next packet), and then read the subsequent bytes into the vacant space after them.</li>\n</ul>\n<p>Something like:</p>\n<pre><code>// after reading and processing a 10-byte packet\nif (si_processed &gt; 10) // already have the start of the next packet\n{\n // move start of next packet to start of buffer\n memmove(serial_buffer, serial_buffer+10, si_processed - 10);\n // not 0: remember how many start bytes we already have\n si_processed -= 10;\n}\n</code></pre>\n<ul>\n<li>After you read any bytes, verify whether the start byte is your <code>0xA5</code> value, and discard the bytes if not.</li>\n</ul>\n<p>Something like:</p>\n<pre><code>if (si_processed &gt; 0) // have some bytes\n{\n int i;\n for (i = 0; i &lt; si_processed; ++i)\n if (serial_buffer[i] == 0xA5) // found start of packet\n break;\n if (i &gt; 0)\n {\n // start of packet is not start of buffer\n // so discard bad bytes at the start of the buffer\n memmove(serial_buffer, serial_buffer+i, si_processed - i);\n si_processed -= i;\n }\n}\n</code></pre>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-01-21T22:11:41.223", "Id": "39768", "ParentId": "39752", "Score": "8" } }, { "body": "<p>The final version, in case someone was interested.</p>\n\n<p><strong>main.c</strong> </p>\n\n<pre><code> int local_socket;\n int serial_fd;\n int max_fd;\n fd_set input;\n fd_set tmp_input;\n char *serial_output_buffer;\n serial_output_buffer=malloc(11 * sizeof(char));\n\n serial_fd=open_port();\n local_socket=open_local_socket();\n\n FD_ZERO(&amp;input);\n FD_SET(serial_fd, &amp;input);\n FD_SET(local_socket, &amp;input);\n max_fd = (local_socket &gt; serial_fd ? local_socket : serial_fd) + 1;\n\n si_processed=0;\n serial_output_buffer[10]='\\0';\n while(TRUE) {\n tmp_input=input;\n\n n = select(max_fd,&amp;tmp_input,NULL,NULL,NULL);\n\n /* See if there was an error */\n if (n&lt;0)\n perror(\"select failed\");\n else {\n /* We have input */\n if (FD_ISSET(serial_fd, &amp;input)) {\n if(process_serial(serial_fd,serial_output_buffer)) {\n printf(\"read:%s\\n\",serial_output_buffer);\n fflush(stdout);\n }\n }\n if (FD_ISSET(local_socket, &amp;input))\n process_socket(local_socket);\n }\n usleep(20000);\n}\nreturn 0;\n</code></pre>\n\n<p><strong>serial_port.h</strong></p>\n\n<pre><code>#ifndef SERIAL_PORT\n#define SERIAL_PORT\n\nint open_port();\nint process_serial(int serial_fd,char *output);\n\nint si_processed;\n\n#endif\n</code></pre>\n\n<p><strong>serial_port.c</strong></p>\n\n<pre><code>char serial_buffer[256];\n\n\nint process_serial(int serial_fd,char *output) {\n int bytes;\n int n,i;\n char tmp_buffer[256];\n\n ioctl(serial_fd, FIONREAD, &amp;bytes);\n if(!bytes &amp;&amp; si_processed&lt;INPUT_BYTES_NUM) //proceed if data still in buffer\n return 0;\n\n n=read(serial_fd, tmp_buffer, sizeof(tmp_buffer));\n for(i=0;i&lt;n;i++) {\n serial_buffer[si_processed+i]=tmp_buffer[i];\n }\n si_processed+=n;\n if(si_processed&gt;=INPUT_BYTES_NUM) {\n for (i = 0; i &lt; si_processed; ++i)\n if (serial_buffer[i] == '1') // found start of packet\n break;\n if (i &gt; 0) {\n // start of packet is not start of buffer\n // so discard bad bytes at the start of the buffer\n\n memmove(serial_buffer, serial_buffer+i, si_processed - i);\n si_processed -= i;\n }\n if(si_processed&gt;=INPUT_BYTES_NUM) {\n memmove(output, serial_buffer, 10);\n\n //move what left to the beginning\n memmove(serial_buffer,serial_buffer+10,si_processed-10);\n si_processed -= 10;\n return 1;\n }\n }\nreturn 0;\n}\n\nint open_port(void) {\n int fd; /* File descriptor for the port */\n struct termios options;\n\n fd = open(\"/dev/ttyS0\", O_RDWR | O_NOCTTY | O_NDELAY);\n\n if (fd == -1) {\n /*\n * Could not open the port.\n */\n error_exit(\"open_port: Unable to open /dev/ttyS0\");\n }\n else\n fcntl(fd, F_SETFL, 0);\n\n /*\n * Get the current options for the port...\n */\n\n tcgetattr(fd, &amp;options);\n\n /*\n * Set the baud rates to 19200...\n */\n\n cfsetispeed(&amp;options, B38400);\n cfsetospeed(&amp;options, B38400);\n\n /*\n * Enable the receiver and set local mode...\n */\n\n options.c_cflag |= (CLOCAL | CREAD);\n\n //set 8N1\n options.c_cflag &amp;= ~PARENB;\n options.c_cflag &amp;= ~CSTOPB;\n options.c_cflag &amp;= ~CSIZE;\n options.c_cflag |= CS8;\n\n /*\n * Set the new options for the port...\n */\n\n tcsetattr(fd, TCSANOW, &amp;options);\n\n\n return (fd);\n}\n</code></pre>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-01-22T13:43:48.140", "Id": "39806", "ParentId": "39752", "Score": "3" } }, { "body": "<p>You shouldn't need to call <code>usleep()</code> to throttle the loop. If you need <code>usleep()</code> prevent the loop from consuming 100% of the CPU, then something is wrong, since <code>select()</code> is supposed to be the gatekeeper that lets the loop continue when input is available to be processed. Perhaps you are <a href=\"https://stackoverflow.com/q/9164848/1157100\">failing to drain the socket or serial port completely</a> in your input handlers, so that <code>select()</code> always returns immediately.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-01-22T21:54:29.843", "Id": "66835", "Score": "0", "body": "The serial port can receive several new bytes per millisecond; and, the way it's setup, select will return as soon as the first byte is received ... he reads that (emptying the driver) and then the next byte arrives almost immediately: isn't that so?" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-01-24T19:03:11.447", "Id": "67129", "Score": "0", "body": "I had a problem with socket monitored by select, wrong socket given to select. It wasn't socket from actual connection, but socket created to listen for connections, that's why select returned immediately and I had to throttle program with usleep" } ], "meta_data": { "CommentCount": "2", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-01-22T20:49:26.830", "Id": "39839", "ParentId": "39752", "Score": "3" } }, { "body": "<p>I would modify your serial reading function in a few ways, firstly by changing\nits name to reflect what it does. I would also move the accumulation buffer\ninto the function, making it and its position counter <code>static</code> (which means\nthey stick around without losing their value between calls) . Also define the\ndetails of the packet in <code>#define</code>s.</p>\n\n<p>More extensive changes are required to recover from a loss of synchronization\nto the data or on failure of the check-sum. If the check-sum fails, I don't\nthink it is safe to discard the whole packet unless you can guarantee that the\nsentinel value (0xA5 or whatever) never occurs within the packet or its\ncheck-sum. As you don't mention it, I'm assuming we can't guarantee this,\nalthough it is clearly possible to arrange the data protocol to provide such a\nguarantee. </p>\n\n<p>Without the guarantee, we need to check the check-sum within the reading\nfunction and to re-sync to the next sentinel on error.</p>\n\n<p>I think this might be easier to achieve by making the file descriptor\nnon-blocking and reading one byte at a time. As your data rate is slow, this\nis not a great overhead. And as your baud rate is slow (compared to processor\nspeed) the chances are that your <code>select</code> will unblock after each received\ncharacter.</p>\n\n<p>You should also check for errors in the <code>read</code> call and return an error unless\nthe read was interrupted (EINTR) - in which case the <code>fd</code> will still select\navailable and the function will be called again - or no data was available\n(EAGAIN).</p>\n\n<p>Here is some untested code to do this.</p>\n\n<pre><code>#define SENTINEL ((char)0xA5)\n#define PACKET_SIZE 10\n\nint read_serial(int fd, char *out)\n{\n static char buf[PACKET_SIZE * 2];\n static int in;\n char ch;\n ssize_t err;\n\n while ((err = read(fd, &amp;ch, 1)) &gt; 0) { /* non-blocking read */\n buf[in++] = ch;\n if (buf[0] == SENTINEL) {\n if (in &lt; PACKET_SIZE) {\n continue;\n }\n if (checksum_ok(buf)) {\n memcpy(out, buf+1, PACKET_SIZE-2); /* copy only the data */\n in = 0;\n return 1;\n }\n }\n /* resynchronise */\n const char *s = memchr(buf + 1, SENTINEL, (size_t) in);\n if (!s) {\n in = 0;\n } else {\n in -= s - buf;\n memmove(buf, s, in);\n }\n }\n return ((err == EINTR) || (err == EAGAIN)) ? 0 : -1;\n}\n</code></pre>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-01-23T19:24:44.147", "Id": "39907", "ParentId": "39752", "Score": "3" } }, { "body": "<p>You pass <code>&amp;tmp_input</code> to select but then pass <code>&amp;input</code> to the <code>FD_ISSET</code>s. These two <code>fd_set</code> objects are different. The input <code>fd_set</code> is set once, so <code>FD_ISSET</code> may well lie to you and your reads will fail.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-07-18T05:04:03.523", "Id": "57358", "ParentId": "39752", "Score": "0" } } ]
{ "AcceptedAnswerId": "39768", "CommentCount": "7", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-01-21T17:47:30.837", "Id": "39752", "Score": "11", "Tags": [ "c", "stream", "error-handling", "timeout", "serial-port" ], "Title": "Reading from a serial port" }
39752
<p><strong>Accordion plugin</strong></p> <p>As I don't use jQuery (because I just have fun with Chrome and iOS/Android) and I prefer to write my own functions, I decided to write a simple Accordion function some time ago:</p> <ul> <li>Short code</li> <li>High performance</li> <li>Latest JS CSS3 HTML5 technologies</li> </ul> <p>I don't want to add many classes and ids, and many eventhandlers. (My iPad 1 is very sensitive with too many eventhandlers and they are also a pain to delete if needed)</p> <blockquote> <p>This function adds no ids, no extra classes and uses only one eventhandler.</p> </blockquote> <h3>Single Accordion:</h3> <p>Code for single Accordions (you can apply this function to more elements but you can't put accordions inside accordions.):</p> <pre><code>function acsf(e) { var Accordion = e.target.parentNode; if (Accordion.parentNode == this &amp;&amp; Accordion.firstChild == e.target) { if (this.CurrentAccordion == Accordion) { this.CurrentAccordion.style.height = ''; delete this.CurrentAccordion } else { !this.CurrentAccordion || (this.CurrentAccordion.style.height = ''); this.CurrentAccordion = Accordion; this.CurrentAccordion.style.height = (Accordion.firstChild.offsetHeight + this.CurrentAccordion.childNodes[1].offsetHeight) + 'px' } } } </code></pre> <p>Structure (no new lines or spaces between <code>&lt;&gt;</code>):</p> <pre><code>&lt;div class="accordion"&gt; &lt;div&gt; &lt;div&gt;Title&lt;/div&gt; &lt;div&gt;Content&lt;/div&gt; &lt;/div&gt; &lt;div&gt; &lt;div&gt;Title&lt;/div&gt; &lt;div&gt;Content&lt;/div&gt; &lt;/div&gt; &lt;/div&gt; </code></pre> <p>Usage:</p> <pre><code>document.getElementsByClassName('accordion')[0].addEventListener('click',acsf,false); </code></pre> <p>The above code works perfectly.</p> <p><a href="http://jsfiddle.net/zhD5L/" rel="nofollow">http://jsfiddle.net/zhD5L/</a></p> <p><strong>But</strong> I want to create a plugin that adds this function to every element with the accordion class and include it as a script:</p> <pre><code>(function() { function acsf() { //the code above } function init(){ var acs = D.getElementsByClassName('accordion'), acsl = acs.length; while(acsl--){ acs[acsl].addEventListener('click',acsf,false); } window.removeEventListener('load',init,false); } window.addEventListener('load',init,false); })() </code></pre> <p>Is this correct, or are the better ways to do that?</p> <p>Should this remove the possibility of creating problems with other variable or function names?</p> <hr> <p>I also want to be able to put accordions inside accordions, so I wrote this next script, but there is a delay and I totally don't know how to remove that.</p> <p>I also don't want to use settimeout. That was just the only way I knew to get it work vs <code>webkitAnimationEnd</code> which just needs a little more code. But I need to get the next height before the animation or timeout ends.</p> <pre><code>(function (D) { function acsf(e) { var a = e.target.parentNode, h; if (a.parentNode == this &amp;&amp; a.firstChild == e.target) { h = a.firstChild.offsetHeight; !this.c || (this.c.style.height = h + 'px'); this.c != a ? (this.c = a, this.c.style.height = (h + this.c.childNodes[1].offsetHeight) + 'px') : (this.c.style.height = h + 'px', delete this.c); setTimeout(acscf.bind(this), 350); } } function acscf(x) { x = this; if (x.parentNode &amp;&amp; x.parentNode.parentNode &amp;&amp; x.parentNode.parentNode.parentNode &amp;&amp; x.parentNode.parentNode.parentNode.classList) { var y = x.parentNode.parentNode.parentNode; if (y.classList.contains('accordion')) { console.log(x.offsetHeight); y.c.style.height = (48 + (x.offsetHeight)) + 'px'; setTimeout(acscf.bind(y), 350); } } } function acsinit() { var acs = D.getElementsByClassName('accordion'), acsl = acs.length; while (acsl--) { acs[acsl].addEventListener('click', acsf, false); } window.removeEventListener('load', acsinit, false); } window.addEventListener('load', acsinit, false); })(document) </code></pre> <p>Example to play with:</p> <p><a href="http://jsfiddle.net/x8dzh/" rel="nofollow">http://jsfiddle.net/x8dzh/</a></p> <p>^ the latest accordion title contains other 2 accordions</p> <hr> <p>And now to make things difficult I'm trying to find a way to interact with the closed function outside of it. So basically toggle elements with another function created inside another script.</p> <hr> <h3>To resume the questions:</h3> <ol> <li>Create a plugin to include that does not create problems with other scripts. (I'm totally new to JS classes)</li> <li>Remove the delay</li> <li>I want to be able to toggle the elements outside with a function outside of the plugin.</li> </ol> <p><strong>EDIT</strong></p> <p>I just found out that I could use <code>try</code> <code>catch</code> vs the long check on the <code>parentNode</code>s.</p> <pre><code>if(x.parentNode &amp;&amp; x.parentNode.parentNode &amp;&amp; x.parentNode.parentNode.parentNode &amp;&amp; x.parentNode.parentNode.parentNode.classList.. </code></pre> <p>to</p> <pre><code>try{ y=x.parentNode.parentNode.parentNode.classList.contains('accordion') }catch(e){ y=false } </code></pre> <p>But what about performance?</p>
[ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-01-21T19:39:07.323", "Id": "66693", "Score": "0", "body": "What happened to the indentation? You really use 1 space and no whitespace? It reads like minified code." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-01-21T19:41:00.117", "Id": "66694", "Score": "0", "body": "i personally use only 1 space and no white spaces .. but in this case i also use it so there is no need to scroll." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-01-21T19:43:24.860", "Id": "66695", "Score": "0", "body": "this is how i wrote it first http://jsfiddle.net/zhD5L/1/ i use notepad." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-01-21T19:45:30.897", "Id": "66697", "Score": "1", "body": "But this is a code review site, the indentation is the very first thing I'd notice, plus the name of your variables, it doesn't help either. Many people will pass on your question after a first glance at the code." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-01-21T19:46:18.087", "Id": "66698", "Score": "0", "body": "so you think i should delete the question?" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-01-21T19:47:30.263", "Id": "66699", "Score": "1", "body": "I think you could just name your variables right, and use this service to indent your code http://jsbeautifier.org/. Unless of course, you want people to comment on those things. No need to close the question." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-01-21T19:54:33.773", "Id": "66701", "Score": "0", "body": "better now ? what you think?" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-01-21T20:01:17.290", "Id": "66702", "Score": "0", "body": "Yes, I submitted a little edit for review, but it looks much better. I suppose the problematic variable names are up for review." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-01-21T20:04:05.743", "Id": "66703", "Score": "0", "body": "And what you think about the questions?" } ]
[ { "body": "<p>Your code has a lot of style problems, so many style problems that it would take a long time to figure out what it does. Well written code does not pose this problem. I can really only point out what you are doing wrong style wise and after the code is cleaned up, perhaps we ( or you yourself ) can figure out your questions.</p>\n\n<ul>\n<li>There is not a single comment</li>\n<li><code>Accordion</code> starts with an uppercase, that should be reserved for constructors</li>\n<li><p>This is a shortcut for <code>if</code>, do not use this unless you are code golfing:</p>\n\n<pre><code>!this.CurrentAccordion || (this.CurrentAccordion.style.height = '');\n</code></pre></li>\n<li>Over the top abbreviations like <code>acsf</code> should be avoided</li>\n<li>One character variables should be avoided ( except perhaps for the common <code>i</code>,<code>s</code> and <code>e</code> )</li>\n<li><p>This makes my eyes bleed, what does it do?? :</p>\n\n<pre><code>this.c != a ?\n (this.c = a, this.c.style.height = (h + this.c.childNodes[1].offsetHeight) + 'px') :\n (this.c.style.height = h + 'px', delete this.c);\n</code></pre>\n\n<p>using comma's to chain statements is plain wrong in a ternary</p></li>\n<li><p>I have no idea why you would need to do this:</p>\n\n<pre><code>if (x.parentNode &amp;&amp; x.parentNode.parentNode &amp;&amp;\n x.parentNode.parentNode.parentNode &amp;&amp;\n x.parentNode.parentNode.parentNode.classList) {\n</code></pre>\n\n<p>this is extremely brittle, at the very least I would do a recursive lookup on <code>parentNode</code> until I find something on the element that identifies it as the right level. Or build a function that gives the n-th level parent, but then it's brittle again. ( Meaning that a change in HTML layout will break your function ).</p></li>\n</ul>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-04-17T09:02:49.237", "Id": "83118", "Score": "0", "body": "After reading what code golfing means, well yes i always do that.I want a short performant code. http://stackoverflow.com/a/21353032/2450730 ,http://codereview.stackexchange.com/q/45335/33435. i use shorthand or/& bitwise operators over standard one as they perform faster on most browsers. btw i see no examples in you answer. your just criticizing my code. actually there is no answer in your response that i could apply to my code.reguarding the last answers that checks the parentnode: brittle but performant. i already answered that with another solution with is shorter but loses in performance" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-04-17T09:04:17.013", "Id": "83119", "Score": "0", "body": "http://jsperf.com/parseint-multihttp://jsperf.com/bw-math http://jsperf.com/multiple-functions http://jsperf.com/store-array-vs-obj/2 http://jsperf.com/if-short here are some performance tests." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-04-17T09:06:38.343", "Id": "83121", "Score": "0", "body": "and explain why using commas to chain is wrong pls." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-04-17T13:18:12.450", "Id": "83160", "Score": "0", "body": "Given that you know how to write code golf code, I did not think it was necessary to tell you how to write your code with `if` statements instead. Comma chained statements in a ternary should be handled by an `if` statement" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-04-17T13:24:36.703", "Id": "83164", "Score": "0", "body": "Furthermore, criticizing code actually is an answer on CodeReview. What I am telling you in my review is that your code is too hard to grok, and hence too hard to fix. Write your code first in a readable manner, and then perhaps you will find the trouble. I am sorry if I hurt your feelings, but know that this code is a maintenance nightmare (you cannot fix it yourself!)." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-04-17T14:39:30.823", "Id": "83189", "Score": "0", "body": "\"Comma chained statements in a ternary should be handled by an if statement\" why?" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-04-17T15:00:38.823", "Id": "83197", "Score": "0", "body": "Readability & maintainability, there is no technical reason." } ], "meta_data": { "CommentCount": "7", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-04-16T20:04:19.263", "Id": "47391", "ParentId": "39755", "Score": "3" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "9", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-01-21T19:34:42.437", "Id": "39755", "Score": "2", "Tags": [ "javascript", "classes" ], "Title": "Accordion JS plugin, CSS3 webkit" }
39755
<p>A while back I wrote the following code (target is embedded C code on an 8 bit atmel device):</p> <pre><code> bool received; tryAgain: received = radioReceive(radiogram, MatchTree, CycleClock, duration); if (received &amp;&amp; radiogram-&gt;timeSlit == SolicitMask) goto tryAgain; // not interested in recursion and the (stack) problems that could come with it return received; </code></pre> <p>I rarely rarely use a goto. Sometimes in embedded land, I talk myself into it. I'm aware that goto is bad, let's skip that issue. The real goal of the code flow was to capture 3 cases:</p> <ol> <li>the <code>radioReceive</code> timed out, so we pass the <code>false</code> back up</li> <li>it returned, but what was heard was basically a false positive, so try some more (this is somewhat exceptional)</li> <li>otherwise it was good and we return true</li> </ol> <p>Then we refacatored the <code>timeSlit</code> test to include some other conditions that we felt were false positives (new function named <code>radiogramIsValidSync()</code>), but we got the logic backwards. At which point, we concluded this code was screwy and should be rewritten. But we diverged on how to best express those 3 conditions.</p> <p>We came up with:</p> <pre><code>do { bool received = radioReceive(radiogram, MatchTree, CycleClock, duration); if (received == false) return false; else if (radiogramIsValidForSync(radiogram)) return true; } while (1); </code></pre> <p>This is terse, but I'm not a fan of meaningless <code>while()</code>'s (would rather use empty <code>for</code> conditions). I also don't care for the fact that 2 of the 3 conditions are explicit, but the other is implicit.</p> <p>A more explicit version is</p> <pre><code> bool received tryAgain: received = radioReceive(radiogram, MatchTree, CycleClock, duration); if (received) { if (radiogramIsValidForSync(radiogram)) return true; else goto tryAgain; } else { return false; } </code></pre> <p>But this still includes the <code>goto</code>. A terse version is:</p> <pre><code>do { if (!radioReceive(radiogram, MatchTree, CycleClock, duration)) return false; } while (!radiogramIsValidForSync(radiogram)); return true; </code></pre> <p>It gets rid of a named variable (which could be good or bad), my real issue with this is that it has multiple logic negation points, so you have to think "backwards" in both of the important points. Finally, a <code>for</code> variant:</p> <pre><code>for ( ; ; ) { received = radioReceive(radiogram, MatchTree, CycleClock, duration); if (received == false) return false; else if (radiogramIsValidForSync(radiogram)) return true; } </code></pre> <p>But this isn't really any better than the <code>do/while(1)</code> variant. And at the end of that we found ourselves feeling unexcited about any of them. Is this just a case of the Law of Conservation of Ugly? Or is there a good/clear way to write this?</p>
[ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-01-21T21:00:20.780", "Id": "66712", "Score": "2", "body": "`Is this just a case of the Law of Conservation of Ugly?` .... thank you kind sir. Much appreciated. I can use that frequently." } ]
[ { "body": "<p>If you can do without the <code>received</code> variable...just make the <code>radioReceive(...)</code> the condition of a <code>while</code> loop. You get rid of <code>received</code>, and your loop condition now has a purpose. :)</p>\n\n<pre><code>while (radioReceive(radiogram, MatchTree, CycleClock, duration)) {\n if (radiogramIsValidForSync(radiogram)) return true;\n}\nreturn false;\n</code></pre>\n\n<p>The only real drawback is that it gets a bit awkward if you need to do anything at both exit points, other than return.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-01-21T20:27:53.520", "Id": "39760", "ParentId": "39757", "Score": "5" } } ]
{ "AcceptedAnswerId": "39760", "CommentCount": "1", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-01-21T19:54:00.363", "Id": "39757", "Score": "5", "Tags": [ "c", "embedded" ], "Title": "Better way to write this branch with an exceptional retry in an embedded C environment?" }
39757
<p>I'm writing my first JavaScript application (no 3rd party libraries used) and looking for some high-level guidance on how to better organize the code into separate classes &amp; files.</p> <p>Here is a simplified/contrived example to illustrate my current organizational layout/problems:</p> <p>game.js:</p> <pre><code>/* Lots of constants, enums, etc defined here. Can't define them inside Game function as they are used by Graphics and ui_player classes too. */ function Game(ui) { /* Lots of things defined here which are exclusive to Game class. */ var graphics = new Graphics(); graphics.load(); ui.setCanvas(graphics.canvas); this.start = function() { mainLoop(); }; function mainLoop() { /* ... */ ui.player.updateAbc(abc); /* ... */ paint(); } function paint() { graphics.renderAll() } /* ... */ } </code></pre> <p>graphics.js:</p> <pre><code>function Graphics() { /* Some constants defined here that are exclusive to Graphics class. */ var canvas = this.canvas = ...; var ctx = canvas.getContext("2d"); /* ... */ this.renderAll = function() { ctx.drawImage(...); }; /* ... */ } </code></pre> <p>ui.js:</p> <pre><code>/* Lots of constants related to UI classes here. */ function ui() { var div = this.div = ...; var canvas; /* ... */ var player = this.player = new ui_player(); div.appendChild(player.div); this.setCanvas(c) { if (canvas) div.removeChild(canvas); canvas = c; div.appendChild(canvas); }; /* ... */ } </code></pre> <p>ui_player.js:</p> <pre><code> function ui_player() { var div = this.div = ...; /* ... */ this.updateAbc = function(abc) { div.innerHTML = abc; }; } </code></pre> <p>main.js:</p> <pre><code> ui = new ui(); game = new Game(ui); game.start(); </code></pre> <p>What I dislike about this:</p> <ul> <li>I feel that my scopes are clumsy.</li> <li>I dislike the fact that I have constants in global scope because they are shared across multiple classes.</li> <li>I dislike the fact that I have to pass ui to Game and then to Graphics, but I'm not sure if this is bad or if allowing every class to access others would be worse.</li> </ul> <p>How can I improve my code structure? How can/should I put it all into a namespace hierarchy where classes can access classes above (and maybe even below) them?</p> <p>P.S. - I'm compiling with Google Closure Compiler (advanced) if that makes any difference. No 3rd party libraries are used.</p>
[]
[ { "body": "<h1>Using a closure</h1>\n\n<p>You can avoid putting constants in the global scope by wrapping <em>everything</em> in another closure, i.e. the code produced after the compiling process should look something like this:</p>\n\n<pre><code>(function() {\n/* all your definitions here */\nfunction ui() {\n // code here\n}\n\nfunction Game(ui) {\n // code here\n}\n\nfunction Graphics(ui) {\n // code here\n}\n}).call(this);\n</code></pre>\n\n<p>Thereby all the functions have access to your constants without cluttering the global namespace.</p>\n\n<h1>Supporting RequireJS/AMD</h1>\n\n<p>RequireJS is a library that aims to give you the possibility to import modules, something JavaScript lacks by default. It does so using 'dependency injection', i.e. passing all the things code requires to execute as parameters to a wrapping function. (You're already doing this in your code - kudos! Even though you seem not to like it, definitely stick to it!) This is considered a best practice in many programming languages - including JavaScript, duh - as it allows for nice modularization of code and great testability by replacing other modules that you don't want to test by mock implementations that might always return the same input, thereby you are able to test just parts of your code and locate errors more quickly. This is called unit testing - something you will never want to miss again.</p>\n\n<p>By supporting RequireJS natively you will save your users from a lot headaches figuring out how exactly to get references to your code.<br>\nDoing so is quite easy, you check if the <code>define</code> function exists and use it or release everything to the global scope if it doesn't:</p>\n\n<pre><code>var lib = {\n ui: ui,\n Game: Game,\n Graphics: Graphics\n}\n\nif (typeof define === \"function\") {\n define(\"mylib\", [], function() { return lib; });\n} else {\n window.mylib = lib;\n}\n</code></pre>\n\n<p><strong>EDIT:</strong> When I wrote this I thought you wrote that you were creating your first library - not application. That being the case you can ignore the last paragraph, the first in this section still applies, though.</p>\n\n<h1>Building your library as a set of AMD modules</h1>\n\n<p>You can leverage the power of RequireJS/AMD for your own application. Just use any directory structure you like and use dependency injection to seperate them into files nicely. The RequireJS optimizer can then put them in a single file, you would still need RequireJS, though. Meet <a href=\"https://github.com/jrburke/almond\" rel=\"nofollow\">almond</a>! It is only about 1kb minified+gzipped and defines a subset of the functionality of RequireJS that suffices to still use AMD modules inside a single file, which is ultimately what you want: a single file you can include in their HTML or load using Require. Now, unfortunately, this introduces another step in going from your source to a distributable JS file.</p>\n\n<h1>Using a sophisticated build tool</h1>\n\n<p>Because nobody wants to do 10 steps manually each time you change your code and want a new build, sophisticated build tools were created that invoke the compiler(s), do code linting, etc. I personally recommend Grunt. It is IMHO the best and most flexible option out there and big libraries, e.g. jQuery, use it as well. </p>\n\n<h1>Don't reinvent the wheel</h1>\n\n<p>There already are great libraries that can do some of the heavy lifting for you. While for a first application it is a good idea to do things yourself to learn how they work internally, once you start working on production code you want to rely on existing libraries, because</p>\n\n<ol>\n<li>that leaves you more time to work on your app and make it better</li>\n<li>they make your code more error proof:\n<ul>\n<li>many libraries have been around for quite a long time and hardly have bugs</li>\n<li>bugs that are found will most likely be fixed quickly (and by other people, see (1))</li>\n</ul></li>\n<li>many libraries will make some design decisions for you. While you might think that cuts your freedom as a programmer (it certainly does), it also has a great advantage: Other people have spent a great deal on working out a good concept that will probably make your app easier to maintain in the end. So just choose one you like and go with it...</li>\n<li>let's face it: people who dedicate their whole time to working on a library probably have better implementations of stuff than you, so that might make your app faster</li>\n</ol>\n\n<h1>Additional Points</h1>\n\n<p>I will add further points here with edits, but wanted to give you access to existing sections asap ;)</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-01-21T21:23:16.440", "Id": "66713", "Score": "3", "body": "Thanks in advance, I look forward to what you might add." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-01-21T21:32:30.257", "Id": "66714", "Score": "0", "body": "I started writing this when the question was still on StackOverflow... I just forgot to delete that first sentence :D" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-01-21T21:39:49.430", "Id": "66715", "Score": "1", "body": "I thought Closure Compiler already did this (can't remember if by default or with an option)?" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-01-21T21:52:28.170", "Id": "66716", "Score": "0", "body": "I am honestly not sure if it does that by default, though it probably can with a switch..." } ], "meta_data": { "CommentCount": "4", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-01-21T21:19:03.800", "Id": "39762", "ParentId": "39761", "Score": "5" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-01-21T21:17:17.573", "Id": "39761", "Score": "8", "Tags": [ "javascript", "game" ], "Title": "Graphical game application" }
39761
<p>How can I simplify this in Delphi?</p> <pre><code>Procedure colori1 Begin if Temperatura&lt;=15 then begin Form1.Label1.Font.Color:=clBlue; Form1.Label2.Font.Color:=clBlue; Form1.Label3.Font.Color:=clBlue; Form1.Label4.Font.Color:=clBlue; Form1.Label5.Font.Color:=clBlue; end; if (Temperatura&gt;=16) and (Temperatura&lt;=18) then begin Form1.Label1.Font.Color:=clAqua; Form1.Label2.Font.Color:=clAqua; Form1.Label3.Font.Color:=clAqua; Form1.Label4.Font.Color:=clAqua; Form1.Label5.Font.Color:=clAqua; end; if (Temperatura&gt;=19) and (Temperatura&lt;=22) then begin Form1.Label1.Font.Color:=clLime; Form1.Label2.Font.Color:=clLime; Form1.Label3.Font.Color:=clLime; Form1.Label4.Font.Color:=clLime; Form1.Label5.Font.Color:=clLime; end; if (Temperatura&gt;=23) and (Temperatura&lt;=26) then begin Form1.Label1.Font.Color:=clYellow; Form1.Label2.Font.Color:=clYellow; Form1.Label3.Font.Color:=clYellow; Form1.Label4.Font.Color:=clYellow; Form1.Label5.Font.Color:=clYellow; end; if (Temperatura&gt;=27) and (Temperatura&lt;=29) then begin Form1.Label1.Font.Color:=$000080FF; Form1.Label2.Font.Color:=$000080FF; Form1.Label3.Font.Color:=$000080FF; Form1.Label4.Font.Color:=$000080FF; Form1.Label5.Font.Color:=$000080FF; end; if Temperatura&gt;=30 then begin Form1.Label1.Font.Color:=clRed; Form1.Label2.Font.Color:=clRed; Form1.Label3.Font.Color:=clRed; Form1.Label4.Font.Color:=clRed; Form1.Label5.Font.Color:=clRed; end; end; </code></pre> <p>If I use "for cycle" like this:</p> <pre><code>For i:=0 to n do label[i].font.color:=clRed </code></pre> <p>I'll obviously get an error, because Delphi doesn't know what <code>label[i]</code> means. Any suggestions?</p>
[]
[ { "body": "<p>Declare a local variable to hold the color:</p>\n\n<pre><code>var\n Color: TColor;\n</code></pre>\n\n<p>Then decide what the color should be:</p>\n\n<pre><code>if Temperatura&lt;=15 then\n Color:=clBlue;\nelse if Temperatura&lt;=18 then\n Color:=clAqua;\nelse ...\n</code></pre>\n\n<p>Then assign the color to the controls:</p>\n\n<pre><code>Form1.Label1.Font.Color:=Color;\nForm1.Label2.Font.Color:=Color;\n....\n</code></pre>\n\n<p>The labels could be stored in an array or a list. So that you can iterate over them to assign the color. You could declare the array like this, in the form class:</p>\n\n<pre><code>FLabels: TArray&lt;TLabel&gt;;\n</code></pre>\n\n<p>In the constructor assign it like this:</p>\n\n<pre><code>FLabels := TArray&lt;TLabel&gt;.Create(Label1, Label2, Label3, Label4, Label5);\n</code></pre>\n\n<p>To iterate over it setting the color do this:</p>\n\n<pre><code>var\n lbl: Tlabel;\n....\nfor lbl in FLabels do\n lbl.Font.Color:=Color;\n</code></pre>\n\n<p>You appear to be using a global variable <code>Form1</code>. Your code will be better without that global variable, and having this procedure (and others like it) converted into a method of the form.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-01-21T21:26:53.213", "Id": "39764", "ParentId": "39763", "Score": "11" } }, { "body": "<p>Set the ParentFont property of each label to true in the IDE object inspector. </p>\n\n<p>Then just set the Font property of their parent control (i.e. the Form or Panel they live in ). E.g:</p>\n\n<pre><code>if Temperatura &lt;= 15 then\n Form1.Font.Color := clBlue;\n\nif (Temperatura &gt;= 16) and (Temperatura &lt;= 18) then\n Form1.Font.Color:=clAqua;\n</code></pre>\n\n<p>etc.</p>\n\n<p>Put them in a Panel if you like, to separate these labels from other controls which should not be affected.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2016-08-24T13:02:57.323", "Id": "139521", "ParentId": "39763", "Score": "1" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-01-21T21:26:30.283", "Id": "39763", "Score": "11", "Tags": [ "delphi" ], "Title": "Make it easier with color changing" }
39763
<p>I have coded a webpage and it looks exactly how I want, but I think there could be improvements, possible as unnecessary floats, etc...</p> <p>Could anybody please review my <strong>CSS</strong> code? Its not difficult or vague, I guess.</p> <p>DEMO: <a href="http://jsfiddle.net/dqC8t/2364/" rel="nofollow noreferrer">http://jsfiddle.net/dqC8t/2364/</a></p> <p>CSS:</p> <pre><code>body{ background: url("http://i.imgur.com/cQhlsYZ.png") repeat-x; } h1{ font-size: 18px; font-weight: bold; color: #444; } h2{ font-size: 16px; font-weight: bold; color: #444; } #wrapper{ width: 980px; margin: 0 auto; } /*************START HEAD CONTENT*************/ #header{ width: 100%; float: left; } #headerLogo{ float: left; margin-top: 20px; margin-left: 20px; margin-right: 70px; } #menu { font-family: 'ProximaNova-Bold'; font-size: 16px; margin-top:40px; } #menu ul { list-style-type: none; } #menu li { display: inline-block; width: 150px; border-bottom-style: solid; border-bottom-width: 4px; margin: -5px ; padding: 0 15px 0 0 ; } .item-1 { border-bottom-color: #0099CC; } .item-2 { border-bottom-color: #FF4444; } .item-3 { border-bottom-color: #669900; } .item-4 { border-bottom-color: #FFBB33; } .item a { text-decoration: none; } #headContent{ float: left; margin-top: 20px } .hnItem{ width: 242px; height: 184px; float: left; margin-right: 4px; } .hnItem img { display: block; } #hnItemLast{ width: 242px; height: 184px; float: left; } #hnItemLast img{ display: block; } .hnTextContainer{ height: 40px; padding: 10px 15px; font-family: 'ProximaNova-Regular'; font-size: 14px; line-height: 21px; color: #c8cbcb; background-image: linear-gradient(#262828,#1c1e1e); } /*************END HEAD CONTENT***************/ /*************START MAIN CONTENT*************/ #mainContent{ width: 980px; height: 800px; float: left; margin-top: 20px; background-color: #FFF; } /*************START NEWS LIST CONTENT********/ #nlContainer{ width:660px; float:left; font-family: 'ProximaNova-Regular'; } #nlContainer p{ font-size:14px; } #nlContainer a{ text-decoration: none; } #nlHeader{ float: left; width:100%; margin-top: 15px; margin-bottom: 5px; margin-left: 20px; } .nlItem{ width: 100%; float: left; margin-top: 10px; margin-left: 20px; } .nlImageContainer{ width: 200px; height: 100px; float: left; padding: 3px; border: 1px solid #e3e3e3; background-color: #efefef; } .nlTextContainer{ float:left; margin-top: 10px; margin-left: 20px; } .rmLink a{ font-size: 14px; color: #069; } .rmLink span{ font-size: 10px; color: #c73f20; } /*************END NEWS LIST CONTENT**********/ /*************START SIDEBAR CONTENT**********/ #sidebar{ width: 300px; height: 400px; float:left; margin-right: 20px; } #scBanner{ margin-top: -10px; } </code></pre> <p>HTML:</p> <pre><code> &lt;div id="wrapper"&gt; &lt;div id="header"&gt; &lt;div id="headerLogo"&gt; &lt;a href="index.html"&gt;&lt;img alt="myDr logo" height="50" width="134" src="http://i.imgur.com/w4FYag7.png"&gt;&lt;/a&gt; &lt;/div&gt; &lt;div id="menu"&gt; &lt;ul&gt; &lt;li class="item item-1"&gt;&lt;a href=""&gt;GEZONDHEID A-Z&lt;/a&gt;&lt;/li&gt; &lt;li class="item item-2"&gt;&lt;a href=""&gt;MEDICIJNEN&lt;/a&gt;&lt;/li&gt; &lt;li class="item item-3"&gt;&lt;a href=""&gt;GEZOND LEVEN&lt;/a&gt;&lt;/li&gt; &lt;li class="item item-4"&gt;&lt;a href=""&gt;NEWS &amp;amp; EXPERTS&lt;/a&gt;&lt;/li&gt; &lt;/ul&gt; &lt;/div&gt; &lt;/div&gt; &lt;div id="headContent"&gt; &lt;div class="hnItem"&gt; &lt;a href="#"&gt;&lt;/a&gt; &lt;div class="hnImageContainer"&gt;&lt;img alt="#" height="124" src="http://i.imgur.com/w4FYag7.png" width="242"&gt;&lt;/div&gt; &lt;div class="hnTextContainer"&gt;Lorem ipsum dolor sit amet, consectetur adipisicing elit&lt;/div&gt; &lt;/div&gt; &lt;div class="hnItem"&gt; &lt;a href="#"&gt;&lt;/a&gt;&lt;div class="hnImageContainer"&gt;&lt;img alt="#" height="124" src="http://i.imgur.com/w4FYag7.png" width="242"&gt;&lt;/div&gt; &lt;div class="hnTextContainer"&gt;Lorem ipsum dolor sit amet, consectetur adipisicing elit&lt;/div&gt; &lt;/div&gt; &lt;div class="hnItem"&gt; &lt;a href="#"&gt;&lt;/a&gt;&lt;div class="hnImageContainer"&gt;&lt;img alt="#" height="124" src="http://i.imgur.com/w4FYag7.png" width="242"&gt;&lt;/div&gt; &lt;div class="hnTextContainer"&gt;Lorem ipsum dolor sit amet, consectetur adipisicing elit&lt;/div&gt; &lt;/div&gt; &lt;div id="hnItemLast"&gt; &lt;a href="#"&gt;&lt;/a&gt;&lt;div id="hnImageContainer"&gt;&lt;img alt="#" height="124" src="http://i.imgur.com/w4FYag7.png" width="242"&gt;&lt;/div&gt; &lt;div class="hnTextContainer"&gt;Lorem ipsum dolor sit amet, consectetur adipisicing elit&lt;/div&gt; &lt;/div&gt; &lt;/div&gt; &lt;div id="mainContent"&gt; &lt;div id="nlContainer"&gt; &lt;div id="nlHeader"&gt; &lt;h1&gt;Laatste nieuws&lt;/h1&gt; &lt;/div&gt; &lt;div class="nlItem"&gt; &lt;div class="nlImageContainer"&gt; &lt;a href="#"&gt;&lt;img alt="#" height="100" src="http://i.imgur.com/w4FYag7.png" width="200"&gt;&lt;/a&gt; &lt;/div&gt; &lt;div class="nlTextContainer"&gt; &lt;h2&gt;&lt;a href="#"&gt;Lorem ipsum dolor sit amet consectetur&lt;/a&gt;&lt;/h2&gt; &lt;p&gt;Lorem ipsum dolor sit amet consectetur dolor sit&lt;br&gt;amet consectetur amet&lt;/p&gt; &lt;p class="rmLink"&gt;&lt;a href="#"&gt;Lees meer&lt;span&gt;&amp;gt;&amp;gt;&lt;/span&gt;&lt;/a&gt;&lt;/p&gt; &lt;/div&gt; &lt;/div&gt; &lt;div class="nlItem"&gt; &lt;div class="nlImageContainer"&gt; &lt;a href="#"&gt;&lt;img alt="#" height="100" src="http://i.imgur.com/w4FYag7.png" width="200"&gt;&lt;/a&gt; &lt;/div&gt; &lt;div class="nlTextContainer"&gt; &lt;h2&gt;&lt;a href="#"&gt;Lorem ipsum dolor sit amet consectetur&lt;/a&gt;&lt;/h2&gt; &lt;p&gt;Lorem ipsum dolor sit amet consectetur dolor sit&lt;br&gt;amet consectetur amet&lt;/p&gt; &lt;p class="rmLink"&gt;&lt;a href="#"&gt;Lees meer&lt;span&gt;&amp;gt;&amp;gt;&lt;/span&gt;&lt;/a&gt;&lt;/p&gt; &lt;/div&gt; &lt;/div&gt; &lt;div class="nlItem"&gt; &lt;div class="nlImageContainer"&gt; &lt;a href="#"&gt;&lt;img alt="#" height="100" src="http://i.imgur.com/w4FYag7.png" width="200"&gt;&lt;/a&gt; &lt;/div&gt; &lt;div class="nlTextContainer"&gt; &lt;h2&gt;&lt;a href="#"&gt;Lorem ipsum dolor sit amet consectetur&lt;/a&gt;&lt;/h2&gt; &lt;p&gt;Lorem ipsum dolor sit amet consectetur dolor sit&lt;br&gt;amet consectetur amet&lt;/p&gt; &lt;p class="rmLink"&gt;&lt;a href="#"&gt;Lees meer&lt;span&gt;&amp;gt;&amp;gt;&lt;/span&gt;&lt;/a&gt;&lt;/p&gt; &lt;/div&gt; &lt;/div&gt; &lt;div class="nlItem"&gt; &lt;div class="nlImageContainer"&gt; &lt;a href="#"&gt;&lt;img alt="#" height="100" src="http://i.imgur.com/w4FYag7.png" width="200"&gt;&lt;/a&gt; &lt;/div&gt; &lt;div class="nlTextContainer"&gt; &lt;h2&gt;&lt;a href="#"&gt;Lorem ipsum dolor sit amet consectetur&lt;/a&gt;&lt;/h2&gt; &lt;p&gt;Lorem ipsum dolor sit amet consectetur dolor sit&lt;br&gt;amet consectetur amet&lt;/p&gt; &lt;p class="rmLink"&gt;&lt;a href="#"&gt;Lees meer&lt;span&gt;&amp;gt;&amp;gt;&lt;/span&gt;&lt;/a&gt;&lt;/p&gt; &lt;/div&gt; &lt;/div&gt; &lt;/div&gt; &lt;div id="sidebar"&gt; &lt;div id="scBanner"&gt; &lt;a href="#"&gt;&lt;img alt="#" height="140" src="http://i.imgur.com/w4FYag7.png" width="300"&gt;&lt;/a&gt; &lt;/div&gt; &lt;/div&gt; &lt;/div&gt; &lt;/div&gt; </code></pre>
[]
[ { "body": "<p>Font:</p>\n\n<pre><code>font-family: 'ProximaNova-Regular';\n</code></pre>\n\n<p>You need a fallback font (or two). If this one doesn't exist then it needs to find another appropriate font. Usually I will put serif, san-serif or monospace last. For example:</p>\n\n<pre><code>font-family: 'ProximaNova-Regular, Arial, sans-serif';\n</code></pre>\n\n<p><code>width: 100%</code> and <code>margin-left</code> is not doing what you think it is doing. Using the content box sizing model your items are 20px outside the parent to the right. Instead put the parent as <code>padding-left: 20px</code> and no <code>margin-left</code> on the item.</p>\n\n<pre><code> #nlContainer\n {\n width:660px;\n // ...\n padding-left: 20px;\n }\n\n .nlItem\n {\n width:100%;\n //...\n margin-left: 0;\n } \n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-01-22T13:02:39.437", "Id": "66768", "Score": "0", "body": "Do I have to change the width of nlContainer?\nI am also not sure if the floats of the #header #headContent and #mainContent are needed?" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-01-23T02:11:20.283", "Id": "66860", "Score": "0", "body": "@user3104933 The width of `nlContainer` doesn't have to change, just its `padding`." } ], "meta_data": { "CommentCount": "2", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-01-22T02:32:49.620", "Id": "39775", "ParentId": "39770", "Score": "3" } }, { "body": "<p><strong>HTML:</strong></p>\n\n<ul>\n<li>For prototyping, you should include the <code>#</code> for links to actually trigger link behavior in browsers: <code>&lt;a href=\"#\"&gt;Link&lt;/a&gt;</code></li>\n<li>Instead of placing <code>&lt;span&gt;&amp;gt;&amp;gt;&lt;/span&gt;</code> in your HTML, you should use&hellip;</li>\n<li>If you page is not dynamically generated, you may consider using the CSS properties <code>width</code> and <code>height</code> instead of the HTML attributes</li>\n</ul>\n\n<p><strong>CSS:</strong></p>\n\n<ul>\n<li><p>&hellip;the <code>:after</code> pseudo element:</p>\n\n<pre><code>.rmLink:after {\n /* puts a space and two `&amp;gt;` after rmLink */\n content: \"\\00A0\" \"\\003E\" \"\\003E\";\n}\n</code></pre></li>\n<li><p>If you're not using some kind of CSS reset, you don't need to set <code>font-weight: bold;</code> on headings; All browsers should have User Agent Styles for them.</p></li>\n<li>As already suggested, you should atleast provide <code>sans-serif</code> in your <code>font-family</code> declaration as a fallback, especially if you're not using web fonts (which you should consider)</li>\n<li>When you define hex-based color values, keep in mind you can write <code>#fff</code> instead of <code>#ffffff</code> and so on; There are several occurences in your code where you could change that</li>\n</ul>\n\n<p><strong>Note:</strong></p>\n\n<p>You have a lot of similar margin declarations which can be simplified and stripped down. Think about where you rather should use padding on a parent instead of margin on several child elements.</p>\n\n<p>Check out <code>nlItem</code> and <code>nlTextContainer</code>. You're repeating yourself.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-01-27T20:22:12.277", "Id": "67577", "Score": "1", "body": "Height/width attributes on images should *not* be replaced with their CSS equivalents. These attributes are not in danger of being deprecated." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-01-27T20:23:39.833", "Id": "67578", "Score": "0", "body": "@cimmanon You're right. I'm not talking about deprecation. It's just a maintainance nightmare when instead you could have them in your CSS." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-01-27T20:26:58.120", "Id": "67579", "Score": "1", "body": "How is placing it in the CSS any less of a maintenance nightmare? The OP's code looks like it is potentially dynamically generated, meaning the dimensions of the images could be dynamically generated as well. If this is the case, shoving it into the CSS would be the maintenance nightmare since it would have to be regenerated whenever the content is changed." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-01-27T20:39:18.833", "Id": "67581", "Score": "0", "body": "@cimmanon Although it seems pretty unlikely to me, that this page is generated in such a manner, I agree with you. If this is the case, leaving the attributes where they are is the right thing to do. Thank you. __Updated__ my answer." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-01-27T23:16:29.027", "Id": "67611", "Score": "0", "body": "This page is not generated yet, but thats my goal. So you both are right :)" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-01-27T23:19:45.213", "Id": "67613", "Score": "0", "body": "Is it a nice/professional way to use \"position: absolute\", \"left: 150px\", \"top: 40px\" to place the main menu where I want inside the header div?" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-01-28T06:02:29.317", "Id": "67665", "Score": "0", "body": "@user3104933 Generally, people would avoid using absolute positioning. There are more reliable methods. For example `float: right;` or using `display: inline-block;`." } ], "meta_data": { "CommentCount": "7", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-01-26T18:53:52.283", "Id": "40113", "ParentId": "39770", "Score": "5" } }, { "body": "<p>You have in the image an inline style</p>\n\n<pre><code>&lt;img alt=\"#\" height=\"100\" src=\"http://i.imgur.com/w4FYag7.png\" width=\"200\"&gt;\n</code></pre>\n\n<p>And all the images will have the same size. I would set that in the container class (since you have already that in the CSS:</p>\n\n<pre><code>.hnItem img {\n display: block;\n width: 242px;\n height: 124px;\n}\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-02-01T17:44:56.573", "Id": "68492", "Score": "0", "body": "Just to be precise: These are not CSS inline styles. These are HTML attributes. ;-)" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-02-01T19:30:30.167", "Id": "68505", "Score": "0", "body": "@kleinfreund Yes, you are right. !!" } ], "meta_data": { "CommentCount": "2", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-01-26T19:21:27.013", "Id": "40116", "ParentId": "39770", "Score": "3" } } ]
{ "AcceptedAnswerId": "40113", "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-01-21T23:01:35.467", "Id": "39770", "Score": "7", "Tags": [ "optimization", "html", "css" ], "Title": "Removing unnecessary floats, height, widths" }
39770
<p>I'm writing a service to parse machine log files as they are written to a central directory and push them to a web service. Each machine generates several log files at a time, with each file encapsulating a particular domain of operational information (e.g. user login sessions, errors, statistics, etc.).</p> <p>The log files are written by different models of machines from different manufacturers. All the machines generate the same kinds of information, but the structure of the log files differs according to the manufacturer of the machine and the type of information the log file contains. Below is a sketch of a set of factories that will create Log classes for each type of log file and configure them with a Parser appropriate for that manufacturer (Strategy Pattern). </p> <p>Over time new machines will be added to the logging pool and it should be straightforward to add support for these. The proposed design is arranged around the manufacturer and it makes it simple to add support for new manufacturers. However, I am concerned about a scenario in which a new model from an existing manufacturer does not adhere to that manufacturer's existing log format. </p> <p>Is there a better design?</p> <pre><code>public interface ILogFactory { ISessionLog CreateSessionLog(); ITipLog CreateTipLog(); IStatisticsLog CreateStatisticsLog(); } public class SmithsLogFactory : ILogFactory { public ISessionLog CreateSessionLog() { return new SessionLog() { Parser = new SmithsSessionStrategy(); } } public ITipLog CreateTipLog() { return new TipLog() { Parser = new SmithsTipStrategy(); } } public IStatisticsLog CreateStatisticsLog() { return new StatisticsLog() { Parser = new SmithsStatsStrategy(); } } } public class L3LogFactory : ILogFactory { public ISessionLog CreateSessionLog() { return new SessionLog() { Parser = new L3SessionStrategy(); } } public ITipLog CreateTipLog() { return new TipLog() { Parser = new L3TipStrategy(); } } public IStatisticsLog CreateStatisticsLog() { return new StatisticsLog() { Parser = new L3StatsStrategy(); } } } public class VividFactory : ILogFactory { public ISessionLog CreateSessionLog() { return new SessionLog() { Parser = new VividSessionStrategy(); } } public ITipLog CreateTipLog() { return new TipLog() { Parser = new VividTipStrategy(); } } public IStatisticsLog CreateStatisticsLog() { return new StatisticsLog() { Parser = new VividStatsStrategy(); } } } </code></pre>
[ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-01-22T06:02:06.960", "Id": "66741", "Score": "0", "body": "What is your issue with worst-case scenario you proposed? If you encounter new log format - you simply create a new strategy. Why does it matter if format changes due to new manufacturer or due to new model of existing manufacturer?" } ]
[ { "body": "<p>Few thoughts about your code:</p>\n\n<ul>\n<li><p>your case resembles more <a href=\"http://en.wikipedia.org/wiki/Abstract_factory_pattern\" rel=\"nofollow\"><code>Abstract Factory</code></a> pattern more than <code>Strategy</code> pattern. <code>ILogFactory</code> is your <code>Abstract Factory</code> while <code>SmithsLogFactory</code>, <code>VividFactory</code> etc are yours <code>Concrete Factories</code>. <code>ISessionLog</code>, <code>ITipLog</code> and <code>IStatisticsLog</code> are <code>Abstract Products</code> and, for example, <code>TipLog</code> with <code>L3TipStrategy</code> inside is your <code>Product</code>.</p></li>\n<li><p>Because I see this case as <code>Abstract Factory</code>, I would add derived versions of <code>ISessionLog</code>, <code>ITipLog</code> and <code>IStatisticsLog</code> for each manufacturer. Constructor of each of those classes should take care of details - like creating proper version of <code>Parser</code> subclass. </p></li>\n<li><p>When using <code>Abstract Factory</code> I always like to provide * construction parameters* to the methods, which can be used to control concrete products creation - and here is the place where I would handle issue with different versions of the logs from the same manufacturer.</p></li>\n</ul>\n\n<p>Draft summarizing my thoughts:</p>\n\n<pre><code> public class LogFactoryParameters\n {\n // ... for example, Version\n }\n\n public class L3LogFactory : ILogFactory\n {\n public ISessionLog CreateSessionLog(LogFactoryParameters parameters)\n {\n return new L3SessionLog(parameters);\n }\n\n public ITipLog CreateTipLog(LogFactoryParameters parameters)\n {\n return new L3TipLog(parameters);\n }\n\n public IStatisticsLog CreateStatisticsLog(LogFactoryParameters parameters)\n {\n return new L3StatisticsLog(parameters);\n }\n }\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-01-22T12:03:48.923", "Id": "66766", "Score": "0", "body": "I would say that an Abstract Factory pattern also **is** a Strategy pattern (`AbstractFactoryPattern` **extends** `StrategyPattern`)" } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-01-22T10:03:32.667", "Id": "39793", "ParentId": "39772", "Score": "3" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "1", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-01-22T00:39:07.270", "Id": "39772", "Score": "4", "Tags": [ "c#", "design-patterns" ], "Title": "Abstract Factory + Strategy pattern for parsing log files in multiple formats — improvement suggestions?" }
39772
<p>At this point I've written a fair amount of code to deal with dynamic line items. I've slowly refactored most of the code into an Order object that's created at page load which contains the methods for various actions within the table.</p> <p>I'm hoping to get some feedback from another set of eyes as to how to further optimize this code:</p> <pre><code>&lt;table class="line-items editable table table-bordered"&gt; &lt;thead class="panel-heading"&gt; &lt;tr class="panel-heading"&gt; &lt;th&gt;ITC Part&lt;/th&gt; &lt;th&gt;Description&lt;/th&gt; &lt;th&gt;Vendor&lt;/th&gt; &lt;th&gt;Vendor Part&lt;/th&gt; &lt;th&gt;Cost&lt;/th&gt; &lt;th&gt;Price&lt;/th&gt; &lt;th&gt;Qty&lt;/th&gt; &lt;th&gt;Subtotal&lt;/th&gt; &lt;th&gt;&lt;span class="glyphicon glyphicon-list-alt"&gt;&lt;/span&gt;&lt;/th&gt; &lt;/tr&gt; &lt;/thead&gt; &lt;tfoot&gt; &lt;tr&gt; &lt;th&gt;&lt;input type="text" class="form-control input-sm" id="itc_part_input" name="itc_part_input"&gt;&lt;/th&gt; &lt;th&gt;&lt;textarea class="form-control input-sm" id="description_input" name="description_input" rows="2"&gt;&lt;/textarea&gt;&lt;/th&gt; &lt;th&gt;&lt;input type="text" class="form-control input-sm" id="vendor_input" name="vendor_input"&gt;&lt;/th&gt; &lt;th&gt;&lt;input type="text" class="form-control input-sm" id="vendor_part_input" name="vendor_part_input"&gt;&lt;/th&gt; &lt;th&gt;&lt;input type="text" class="form-control input-sm" id="cost_input" name="cost_input"&gt;&lt;/th&gt; &lt;th&gt;&lt;input type="text" class="form-control input-sm" id="price_input" name="price_input"&gt;&lt;/th&gt; &lt;th&gt;&lt;input type="text" class="form-control input-sm" id="qty_input" name="qty_input" value="1"&gt;&lt;/th&gt; &lt;th&gt;&lt;input type="text" class="form-control input-sm" id="subtotal_input" name="subtotal_input" disabled="disabled"&gt;&lt;/th&gt; &lt;th&gt;&lt;span class="glyphicon glyphicon-plus add-line-item" title="Add Line Item"&gt;&lt;/span&gt;&lt;/th&gt; &lt;/tr&gt; &lt;tr&gt; &lt;th colspan="9"&gt; &lt;div class="row"&gt; &lt;div class="col-sm-6 order-number"&gt;Order Number: 80071&lt;/div&gt; &lt;div class="col-sm-6 text-right order-total"&gt;Total: $0.00&lt;/div&gt; &lt;/div&gt; &lt;/th&gt; &lt;/tr&gt; &lt;/tfoot&gt; &lt;tbody&gt; &lt;/tbody&gt; &lt;/table&gt; </code></pre> <p>JS Code:</p> <pre><code>var Order = function() { this.addLineItem = function() { // build new table row from line item inputs var newRow = '&lt;tr&gt;'+ '&lt;td&gt;'+$('#itc_part_input').val()+'&lt;/td&gt;'+ '&lt;td&gt;'+$('#description_input').val()+'&lt;/td&gt;'+ '&lt;td&gt;'+$('#vendor_input').val()+'&lt;/td&gt;'+ '&lt;td&gt;'+$('#vendor_part_input').val()+'&lt;/td&gt;'+ '&lt;td&gt;'+$('#cost_input').val()+'&lt;/td&gt;'+ '&lt;td&gt;'+$('#price_input').val()+'&lt;/td&gt;'+ '&lt;td&gt;'+$('#qty_input').val()+'&lt;/td&gt;'+ '&lt;td&gt;'+$('#subtotal_input').val()+'&lt;/td&gt;'+ '&lt;td&gt;&lt;span class="glyphicon glyphicon-remove remove-line-item" title="Remove Line Item"&gt;&lt;/span&gt;&lt;/td&gt;'+ '&lt;/tr&gt;'; // add the new row to the table $('.line-items &gt; tbody:last').append(newRow); // scroll to the bottom of the page to compensate for the new table row $('html, body').animate({ scrollTop: $(document).height() }, 'fast'); // clear line item inputs $('.line-items tfoot input, .line-items tfoot textarea').each(function() { $(this).val(''); }); // set default qty to 1 for convenience $('.line-items &gt; tfoot &gt; tr &gt; th:nth-child(7) input').each(function() { $(this).val('1'); }); // return focus to first input field after adding line item, // specifically useful when tabbing out of qty_input $('.line-items &gt; tfoot &gt; tr &gt; th:first-child input').focus(); // recalculate total this.updateTotal(); } this.removeLineItem = function(row) { // remove row from table row.remove(); // to delete an existing line item we have to pass its id to the model with an action =&gt; delete flag new LineItem(); $('&lt;input&gt;').attr({ type: 'hidden', name: 'data[OrderLineItem]['+LineItem.count+'][id]', value: row.attr('data-line-item-id'), }).appendTo('form'); $('&lt;input&gt;').attr({ type: 'hidden', name: 'data[OrderLineItem]['+LineItem.count+'][action]', value: 'delete', }).appendTo('form'); // recalculate total this.updateTotal(); } // calculate order total from subtotals this.calculateTotal = function() { var total = 0; $('.line-items &gt; tbody &gt; tr &gt; td:nth-child(8)').each(function() { total += parseFloat($(this).html()) || 0; }); return total.toFixed(2); } // write order total to table footer this.updateTotal = function() { var amount = this.calculateTotal(); $('.order-total').html('Total: $' + amount); } // adds hidden form fields for dynamically created line items this.processLineItems = function() { // add form fields for each line item in Model.{0..n}.field naming convention $('.line-items &gt; tbody &gt; tr').each(function() { // increments counter for Model.{0..n}.field naming convention new LineItem(); // OrderLineItem id is needed to update records $('&lt;input&gt;').attr({ type: 'hidden', name: 'data[OrderLineItem]['+LineItem.count+'][id]', value: $(this).attr('data-line-item-id'), }).appendTo('form'); // line item fields var colCount = 0; var fields = ['itc_part', 'description', 'vendor', 'vendor_part', 'cost', 'price', 'qty', 'subtotal']; $.each(this.cells, function(){ $('&lt;input&gt;').attr({ type: 'hidden', name: 'data[OrderLineItem]['+LineItem.count+']['+fields[colCount]+']', value: $(this).html() }).appendTo('form'); colCount++; }); }); } this.save = function(afterSaveAction) { // disable any action buttons on the page to prevent double submit $('.btn').button('loading'); // turn line items table into form fields before submit this.processLineItems(); // afterSaveAction tells controller what to do after save // stay on page by default, controller will refresh page // this default action is also set inside the controller if (typeof(afterSaveAction) === 'undefined') afterSaveAction = 'continue'; $('&lt;input&gt;').attr({ type: 'hidden', name: 'data[Order][action]', value: afterSaveAction, }).appendTo('form'); // submit the form $('form[id^=Order]').submit(); } // calculate order total when Order is initialized this.updateTotal(); } Order = new Order(); // helper to keep count of dynamic line items on page function LineItem() { if (typeof LineItem.count == 'undefined') { LineItem.count = 0; } else { LineItem.count++; } } // force numeric input function $.fn.ForceNumeric = function() { return this.each(function() { $(this).keydown(function(event) { var key = event.charCode || event.keyCode || 0; // allow backspace, tab, delete, arrows, numbers and keypad numbers ONLY // home, end, period, and numpad decimal return ( key == 8 || key == 9 || key == 46 || key == 110 || key == 190 || (key &gt;= 35 &amp;&amp; key &lt;= 40) || (key &gt;= 48 &amp;&amp; key &lt;= 57) || (key &gt;= 96 &amp;&amp; key &lt;= 105) ); }); }); }; $(function() { // set datepicker defaults globally $.fn.datepicker.defaults.autoclose = true; $.fn.datepicker.defaults.todayHighlight = true; $('#itc_part_input').change(function(){ this.value = this.value.toUpperCase(); }); // force numeric input $('#cost_input, #price_input, #qty_input').ForceNumeric(); // format number to two decimal points on change $('#cost_input, #price_input').change(function () { $(this).val( parseFloat($(this).val()).toFixed(2) ); }); // calculate subtotal during input $('#price_input, #qty_input').change(function () { var subtotal = $('#price_input').val() * $('#qty_input').val(); $('#subtotal_input').val( parseFloat(subtotal).toFixed(2) ); }); // tabbing out of #qty_input automatically adds line item $("#qty_input").on('keydown', function(e) { var keyCode = e.keyCode || e.which; if (keyCode == 9) { e.preventDefault(); Order.addLineItem(); } }); // add line item to table $('.add-line-item').click(function(event) { Order.addLineItem(); }); // make table cell editable when clicked function enableLineItemEdit() { $('.line-items').on('click', 'tbody td:not(:last-child)', function(event) { if (event.currentTarget.cellIndex == 1) { $(this).html('&lt;textarea class="form-control input-sm" id="description_input" name="description_input"&gt;'+$(this).text()+'&lt;/textarea&gt;'); $(this).find('textarea').focus(); } else { $(this).html('&lt;input type="text" class="form-control input-sm" value="'+$(this).text()+'"&gt;'); $(this).find('input').focus(); } $(this).off(event); }); }; enableLineItemEdit(); // turn line item cell input back into text when clicked out of $('.line-items').on('blur', 'tbody input, tbody textarea', function(event) { $(this).replaceWith(this.value); enableLineItemEdit(); }); // remove line item from table $('.line-items').on('click', '.remove-line-item', function(event) { Order.removeLineItem($(this).closest('tr')); }); // save buttons $('.save-continue').click(function(event) { Order.save('continue'); }); $('.save-close').click(function(event) { Order.save('close'); }); }); </code></pre> <p>Specific areas of concern:</p> <ol> <li><p>I moved most functionality into the Order object and then use jQuery after DOM-ready to bind event handlers. How might I go about replacing most (if not all) the code in the DOM-ready function with an <code>Order.init()</code> or similar?</p></li> <li><p>I had to comment out the <code>$.fn.datepicker.defaults</code> lines in the bootply because the associated js file isn't available. Is there a better place to put these default settings for the datepicker?</p></li> <li><p>This code is functional, but one of the users is reporting what sounds like a possible memory leak (though I cannot recreate it). How much of this code can be refactored away as being redundant?</p></li> <li><p>The more field-specific functionality I add, the more spaghetti-ish this is becoming, so I'm looking for suggestions on how to better organize the code for maintainability.</p></li> </ol>
[ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-01-22T03:12:07.563", "Id": "66734", "Score": "3", "body": "Post JS code here, please." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-01-22T03:16:29.637", "Id": "66735", "Score": "0", "body": "In absence of JS being here, I can take a really wild stab at your memory leak. Usually it happens when you give something a unique ID and store some object with that ID as its key in another object. What you really want there is a weak reference, but you don't have one, so your object can never be GCed." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-01-22T18:43:48.190", "Id": "66814", "Score": "1", "body": "Ted, the code ends very abruptly, it is not valid JavaScript." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-01-22T19:15:35.010", "Id": "66820", "Score": "0", "body": "Fixed the cut-off JS" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-01-23T15:57:45.983", "Id": "66925", "Score": "0", "body": "Do these inputs have a defaultValue property set to what you want their default to be? for example, the quantity input, is it's defaultValue set to 1? (defaultValue typically contains the *original* value of the value attribute.)" } ]
[ { "body": "<p>You could generate your row string using .map to eliminate selecting each input one by one by id.</p>\n\n<pre><code>// build new table row from line item inputs\nvar newRow = \"&lt;tr&gt;\";\nnewRow += $(\".line-items tfoot\").find(\":input\").map(function(_,obj) {\n return \"&lt;td&gt;\" + $(obj).val() + \"&lt;/td&gt;\";\n}).join(\"\");\nnewRow += \"&lt;/tr&gt;\";\n\n// add the new row to the table\n$('.line-items &gt; tbody:last').append(newRow);\n</code></pre>\n\n<p>This causes the code to be more maintainable because you no longer need to modify this section of code when a new column is added or one is removed.</p>\n\n<p>While you're iterating over the inputs already, you reset the value of the inputs to their default value (assuming they have the desired default value)</p>\n\n<pre><code>// build new table row from line item inputs\nvar newRow = \"&lt;tr&gt;\";\nnewRow += $(\".line-items tfoot\").find(\":input\").map(function(i,el) {\n var $el = $(el), val = $el.val();\n // clear line item input\n $el.val(el.defaultValue);\n return \"&lt;td&gt;\" + val + \"&lt;/td&gt;\";\n}).join(\"\");\nnewRow += \"&lt;/tr&gt;\";\n\n// add the new row to the table\n$('.line-items &gt; tbody:last').append(newRow);\n</code></pre>\n\n<p>Other Thoughts:</p>\n\n<ul>\n<li>Why does the <code>enableLineItemEdit</code> function exist? Why can't you just execute that code immediately? (this is likely where your <em>\"memory leak\"</em> is coming from, you keep binding the same event to the table, never removing it)</li>\n<li>When wiring up your delegated events on <code>$('.line-items')</code>, you should use chaining so that you aren't repeatedly calling <code>$('.line-items')</code></li>\n</ul>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-01-23T21:34:59.133", "Id": "66989", "Score": "0", "body": "Kevin, I believe I created the `enableLineItemEdit` function because I couldn't get .one() to work correctly. So I used .on(click), wrapped it in a function and used .off() to disable the event listener after a cell was selected for edit. Otherwise clicking in the cell while in edit state would populate the input with the table cell contents <input> and multiple cells could be in edit mode simultaneously with no way to change them back to a normal table cell. Hence the blur even listener below it reenables the edit mode click listener. I know there must be a better way, but I'm not seeing it.." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-01-23T21:35:35.163", "Id": "66990", "Score": "0", "body": "My issue with that is the fact that your usage of .off in fact does not remove the event. `$(this)` is the clicked element, not the element that the event is bound to (which just so happens to be the table)" } ], "meta_data": { "CommentCount": "2", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-01-23T15:45:34.707", "Id": "39878", "ParentId": "39774", "Score": "1" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "5", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-01-22T02:26:17.417", "Id": "39774", "Score": "4", "Tags": [ "javascript", "optimization", "jquery" ], "Title": "Refactor jQuery code to use fewer selectors" }
39774
<p><a href="http://mustache.github.io/" rel="nofollow">Mustache</a> is a simple template language for preprocessing text templates.</p>
[]
[]
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-01-22T02:50:15.863", "Id": "39777", "Score": "0", "Tags": null, "Title": null }
39777
Mustache is a "logic-less" templating library available in a range of languages.
[]
[]
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-01-22T02:50:15.863", "Id": "39778", "Score": "0", "Tags": null, "Title": null }
39778
<p>I have written some code for one of my assignments. However, I feel that I am repeating myself slightly in a few places. I have that niggling feeling that there is a better way to do things.</p> <p>Here is the code in full:</p> <pre><code>#include &lt;stdio.h&gt; #include &lt;string.h&gt; #define ARR_SIZE 256 int main(void) { //Declare char arrays char arcInputString5[ARR_SIZE]; char arcInputString10[ARR_SIZE]; char arcInputString15[ARR_SIZE]; char arcInputString20[ARR_SIZE]; int clean1, clean2, clean3, clean4, nCount; char buffer[ARR_SIZE]; printf("\nPlease Input String 1 - Max Length 5: "); //gets(arcInputString5); fgets(arcInputString5, ARR_SIZE, stdin); for(clean1 = 0; clean1 &lt; strlen(arcInputString5); clean1++) { if(arcInputString5[clean1] == '\n' || arcInputString5[clean1] == '\r') { arcInputString5[clean1] = '\0'; break; } } printf("\nPlease Input String 2 - Max Length 10: "); //gets(arcInputString10); fgets(arcInputString10, ARR_SIZE, stdin); for(clean1 = 0; clean1 &lt; strlen(arcInputString10); clean1++) { if(arcInputString10[clean1] == '\n' || arcInputString10[clean1] == '\r') { arcInputString10[clean1] = '\0'; break; } } printf("\nPlease Input String 3 - Max Length 15: "); //gets(arcInputString15); fgets(arcInputString15, ARR_SIZE, stdin); for(clean1 = 0; clean1 &lt; strlen(arcInputString15); clean1++) { if(arcInputString15[clean1] == '\n' || arcInputString15[clean1] == '\r') { arcInputString15[clean1] = '\0'; break; } } printf("\nPlease Input String 4 - Max Length 20: "); //gets(arcInputString20); fgets(arcInputString20, ARR_SIZE, stdin); for(clean1 = 0; clean1 &lt; strlen(arcInputString20); clean1++) { if(arcInputString20[clean1] == '\n' || arcInputString20[clean1] == '\r') { arcInputString20[clean1] = '\0'; break; } } printf("\nThankyou For Your Inputs - They Are Shown Back To You Below\n\n"); puts(arcInputString5); puts(arcInputString10); puts(arcInputString15); puts(arcInputString20); printf("\nThe String Lengths For Each Input Are Listed Below. \nIt is also indicated below if you have typed too many characters in"); printf("\n%d", strlen(arcInputString5)); printf("\n%d", strlen(arcInputString10)); printf("\n%d", strlen(arcInputString15)); printf("\n%d", strlen(arcInputString20)); if(strlen(arcInputString5) &gt; 5) { printf("\n\nString Length: %d - Exceeded Allowed Characters", strlen(arcInputString5)); } else { printf("\n\nString Length: %d - NOT Exceeded Allowed Characters", strlen(arcInputString5)); } if(strlen(arcInputString10) &gt; 10) { printf("\n\nString Length: %d - Exceeded Allowed Characters", strlen(arcInputString10)); } else { printf("\n\nString Length: %d - NOT Exceeded Allowed Characters", strlen(arcInputString10)); } if(strlen(arcInputString15) &gt; 15) { printf("\n\nString Length: %d - Exceeded Allowed Characters", strlen(arcInputString15)); } else { printf("\n\nString Length: %d - NOT Exceeded Allowed Characters", strlen(arcInputString15)); } if(strlen(arcInputString20) &gt; 20) { printf("\n\nString Length: %d - Exceeded Allowed Characters", strlen(arcInputString20)); } else { printf("\n\nString Length: %d - NOT Exceeded Allowed Characters", strlen(arcInputString20)); } //printf("\n\nBelow are the strings Concatenated: \n"); sprintf(buffer, "\n\nBelow are the strings Concatenated: \n\n&gt;%s&lt;&gt;%s&gt;&lt;%s&lt;&gt;%s&lt;", arcInputString5, arcInputString10, arcInputString15, arcInputString20); printf("%s", buffer); //puts(buffer) } </code></pre> <p>I feel that the 4 sections of this code:</p> <pre><code>for(clean1 = 0; clean1 &lt; strlen(arcInputString20); clean1++) { if(arcInputString20[clean1] == '\n' || arcInputString20[clean1] == '\r') { arcInputString20[clean1] = '\0'; break; } } </code></pre> <p>And this code:</p> <pre><code>if(strlen(arcInputString5) &gt; 5) { printf("\n\nString Length: %d - Exceeded Allowed Characters", strlen(arcInputString5)); } else { printf("\n\nString Length: %d - NOT Exceeded Allowed Characters", strlen(arcInputString5)); } </code></pre> <p>Could be shortened somehow, but I am unsure how to do this. They may not be able to, but that's why I'm posting here!</p> <p>Any hints/tips are appreciated. </p>
[ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-01-22T03:33:00.660", "Id": "66738", "Score": "5", "body": "Hi Dr.Pepper. On CodeReview we rollback edits if they invalidate answers that have already been given... just a head's up." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-01-22T15:45:59.810", "Id": "66787", "Score": "1", "body": "\"mate\" is ok, \"primate\" is more appropriate in @rolfl's case :)" } ]
[ { "body": "<p>You currently have separate variables for each input. You could instead have a two-dimensional array:</p>\n\n<pre><code>char inputs[4][ARR_SIZE];\n</code></pre>\n\n<p>You have variables <code>clean1</code>, <code>clean2</code>, …, <code>nCount</code>, but only use <code>clean1</code>. Since they're only used as index variables in non-nested loops, you only need one.</p>\n\n<p>Then you can refactor the reading parts to have a <code>for</code> loop that reads each input in turn. You can do something similar when printing the strings out.</p>\n\n<p>For checking their lengths, you can also do something similar, but you might want to have an array of maximum lengths to check against, e.g.:</p>\n\n<pre><code>static const int max_lengths[] = { 5, 10, 15, 20 };\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-01-22T03:32:21.197", "Id": "66737", "Score": "0", "body": "The clean2 and ncount etc were left in there from some testing. Thanks for noticing! took them out and updated OP. Thanks for your input, ill have a proper read over it and do some testing now." } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-01-22T03:26:35.383", "Id": "39780", "ParentId": "39779", "Score": "6" } }, { "body": "<p>Whenever you have a self-contained chunk of code that serves an identifiable purpose, it's a good idea to package it in a function. That's true even if you aren't repeating yourself four times. The fact that all the code appears in quadruplicate makes it even more urgent to define some functions to make your code reusable.</p>\n\n<p>To decide how to break up your code, the key questions to ask are:</p>\n\n<ol>\n<li>What is the purpose of this chunk of code? Can you give it a name? If you have a hard time naming the operation, maybe you need to decompose it further into smaller operations.</li>\n<li>What could vary? Those will be your parameters. What are the operation's outputs?</li>\n</ol>\n\n<p>Here's how I recommend decomposing your <code>main()</code> function:</p>\n\n<pre><code>/**\n * Prints the prompt, then writes a '\\0'-terminated string of user input to buf. \n */\nvoid input(const char *prompt, char *buf, int bufsize) {\n /* TODO: Exercise for you */\n}\n\n/**\n * Truncates str at the first '\\n' or '\\r' character.\n */\nvoid chomp(char *str) {\n str[strcspn(str, \"\\n\\r\")] = '\\0';\n}\n\n/**\n * Prints either \"String Length: N - Exceeded Allowed Characters\\n\"\n * OR \"String Length: N - NOT Exceeded Allowed Characters\\n\"\n */\nvoid report_whether_length_exceeded(const char *str, int maxlen) {\n /* TODO: Exercise for you */\n}\n\nint main() {\n char str5[ARR_SIZE], str10[ARR_SIZE], str15[ARR_SIZE], str20[ARR_SIZE];\n char buffer[ARR_SIZE];\n\n input(\"Please Input String 1 - Max Length 5:\", str5, sizeof(str5));\n input(\"Please Input String 2 - Max Length 10:\", str10, sizeof(str10));\n input(\"Please Input String 3 - Max Length 15:\", str15, sizeof(str15));\n input(\"Please Input String 4 - Max Length 20:\", str20, sizeof(str20));\n\n chomp(str5);\n chomp(str10);\n chomp(str15);\n chomp(str20);\n\n printf(\"Thank you for your inputs - they are:\\n\\n\"\n \"%s\\n%s\\n%s\\n%s\\n\",\n str5, str10, str15, str20);\n\n printf(\"Their string lengths are:\\n\\n\"\n \"%d\\n%d\\n%d\\n%d\\n\",\n strlen(str5), strlen(str10), strlen(str15), strlen(str20));\n\n report_whether_length_exceeded(str5, 5); \n report_whether_length_exceeded(str10, 10);\n report_whether_length_exceeded(str15, 15);\n report_whether_length_exceeded(str20, 20);\n\n /* I assume you want to append all the strings to a buffer for fun. Otherwise,\n you could achieve the same effect more easily just with printf().\n It would be a good habit to use snprintf() instead of sprintf() if\n it's available on your system. */\n sprintf(buffer, \"&gt;%s&lt;&gt;%s&gt;&lt;%s&lt;&gt;%s&lt;\", str5, str10, str15, str20);\n printf(\"\\nHere are the strings concatenated:\\n\\n%s\\n\", buffer);\n}\n</code></pre>\n\n<p>Once you accomplish that, you could go one step further: instead of storing four strings in separate <code>char</code> arrays, you could hold them all in a single array of strings (that is, a two-dimensional <code>char</code> array). However, I consider it more important to understand how to decompose your code into functions, so I'll leave it at that.</p>\n\n<p>A final note: you'll give yourself fewer headaches if you consistently end each printout with a trailing newline. Sometimes putting it at the end of the previous line, and sometimes putting it at the beginning of the next line makes your code harder to work with.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-01-22T14:37:50.927", "Id": "66778", "Score": "0", "body": "Thanks for the help mate, ill sit down and have a look at your answer properly later this evening" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-01-23T22:06:35.323", "Id": "66994", "Score": "1", "body": "I think `chomp()` should be part of `input()` and `input()` should return the string length (since it has to compute it to trim the `\\n` and `\\r`. Also `report_whether_length_exceeded()` is an odd function - a simple boolean `length_exceeded()` and a `printf` would make more sense to me. Also the final unbounded `sprintf` is asking for trouble and seems unnecessary (just use `printf` to concatenate)." } ], "meta_data": { "CommentCount": "2", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-01-22T07:05:30.930", "Id": "39783", "ParentId": "39779", "Score": "4" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "2", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-01-22T03:11:31.727", "Id": "39779", "Score": "8", "Tags": [ "c", "strings", "homework", "validation" ], "Title": "Inputting and displaying strings" }
39779
<p>Search an element in a n-ary tree. Looking for good code practices, optimizations etc. If question is ambiguous, let me know and I will reply ASAP.</p> <p>Note - <code>SearchInANAryTree</code> name of class is for personal maintenance reason, so please ignore feedback as that name does not sound good. Also, help me with three questions:</p> <ol> <li><p>Constructor takes Array <code>T[] items</code>. Since we are using generics, is it considered good practice to use a list instead of an array?</p></li> <li><p>As a corollary <code>TreeNode nested static class</code> is using a list, should it be replaced by an array?</p></li> <li><p>Do we need exception-checking in <code>TreeNode</code> to ensure that its <code>childNode</code> is not greater than <code>branching factor</code>? Or can we trust private functions calling it no more than <code>n-arry</code> times?</p></li> </ol> <p></p> <pre><code> public final class SearchInANAryTree&lt;T&gt; { private TreeNode&lt;T&gt; root; /** * Constructs a tree with given branching factor (n-ary). * The integer arrays, which is specified in the BFS order. * For example, the children of the current node are * in position "nary * i + k" in the array, where i is the position of the current / parent node. * n-ary (nary) is the branching factor and k is the kth / count of the child. * * @param items the list of items, to be parsed according to branching factor. * @param nary n-ary, the branching factor. */ public SearchInANAryTree(T[] items, int nary) { if (nary &lt;= 0) throw new NullPointerException("The branching factor : " + nary + ", should be greater than zero."); constructTree(items, nary); } private void constructTree(T[] items, int nary) { root = new TreeNode&lt;T&gt;(items[0], new ArrayList&lt;TreeNode&lt;T&gt;&gt;(nary)); final Queue&lt;TreeNode&lt;T&gt;&gt; nodeQueue = new LinkedList&lt;TreeNode&lt;T&gt;&gt;(); nodeQueue.add(root); for (int i = 0; i &lt; (items.length / nary); i++) { if (items[i] != null) { final TreeNode&lt;T&gt; node = nodeQueue.poll(); for (int k = 1; k &lt;= nary; k++) { if (items[nary * i + k] != null) { TreeNode&lt;T&gt; childNode = new TreeNode&lt;T&gt;(items[nary * i + k], new ArrayList&lt;TreeNode&lt;T&gt;&gt;(nary)); nodeQueue.add(childNode); node.childNodes.add(childNode); } } } } } /** * Search an element in the n-ary tree * * @param x x is the item to search. * @return true is item is found else false. */ public boolean searchElement(T x) { final Queue&lt;TreeNode&lt;T&gt;&gt; nodeQueue = new LinkedList&lt;TreeNode&lt;T&gt;&gt;(); nodeQueue.add(root); while (!nodeQueue.isEmpty()) { final TreeNode&lt;T&gt; node = nodeQueue.poll(); if (node.item.equals(x)) return true; for (TreeNode&lt;T&gt; childNode : node.childNodes) { if (childNode != null) { nodeQueue.add(childNode); } } } return false; } private static class TreeNode&lt;T&gt; { T item; List&lt;TreeNode&lt;T&gt;&gt; childNodes; public TreeNode(T item, List&lt;TreeNode&lt;T&gt;&gt; childNodes) { this.item = item; this.childNodes = childNodes; } } public static void main(String[] args) { /* * 1 * / | \ * 2 3 4 * / | | \ * 5 6 8 10 * */ Integer[] m1 = {1, 2, 3, 4, null, null, null, 5, 6, null, null, 8, null}; SearchInANAryTree&lt;Integer&gt; sian2 = new SearchInANAryTree&lt;Integer&gt;(m1, 3); System.out.print("Expect: true, Actual: "); boolean result = true; for (Integer i : m1) { if (i != null) result = result &amp;&amp; sian2.searchElement(i); // test case in a for loop. } System.out.println(result); System.out.println("Expect: false, Actual: " + sian2.searchElement(7)); } } </code></pre>
[]
[ { "body": "<p>I am taking a very broad stab at this, answering your questions along the way but with additional comments on the code in general.</p>\n\n<pre><code> public SearchInANAryTree(T[] items, int nary) {\n if (nary &lt;= 0) throw new NullPointerException(\"The branching factor : \" + nary + \", should be greater than zero.\");\n constructTree(items, nary);\n }\n</code></pre>\n\n<p>This is an incorrect use of NPE, consider using IllegalArgumentException. Given that you have included this in your code, did you consider the case where items is a null array?</p>\n\n<p>Answer to question 1, There is no need to use a list, <code>T[]</code> is perfectly fine.</p>\n\n<pre><code> private void constructTree(T[] items, int nary) {\n root = new TreeNode&lt;T&gt;(items[0], new ArrayList&lt;TreeNode&lt;T&gt;&gt;(nary));\n\n final Queue&lt;TreeNode&lt;T&gt;&gt; nodeQueue = new LinkedList&lt;TreeNode&lt;T&gt;&gt;();\n nodeQueue.add(root);\n\n for (int i = 0; i &lt; (items.length / nary); i++) {\n if (items[i] != null) {\n final TreeNode&lt;T&gt; node = nodeQueue.poll();\n\n for (int k = 1; k &lt;= nary; k++) {\n if (items[nary * i + k] != null) {\n TreeNode&lt;T&gt; childNode = new TreeNode&lt;T&gt;(items[nary * i\n + k], new ArrayList&lt;TreeNode&lt;T&gt;&gt;(nary));\n nodeQueue.add(childNode);\n node.childNodes.add(childNode);\n }\n }\n }\n }\n}\n</code></pre>\n\n<p>This code generally is more complicated than it needs to be, when you are aware of the tree arity, the array is your tree representation, there is no needs to create the conceptual equivalent of how trees are represented on paper in code.</p>\n\n<p>This code also has the following errors, using the example in the main function you have written</p>\n\n<p>The array representation</p>\n\n<pre><code>Integer[] m1 = {1, 2, 3, 4, null, null, null, 5, 6, null, null, 8, null};\n</code></pre>\n\n<p>of the tree</p>\n\n<pre><code> /*\n * 1 \n * / | \\\n * 2 3 4 \n * / | | \\\n * 5 6 8 10\n * \n */\n</code></pre>\n\n<p>is converted to the tree</p>\n\n<pre><code> /*\n * 1 \n * / | \\\n * 2 3 4 \n * / | / |\n * 5 6 8 10\n * \n */\n</code></pre>\n\n<p>by the code. You went from a correct literal representation on the tree in array form to an incorrect conceptual representation in code. You can correctly handle this with a <code>NullObject</code> tree node.</p>\n\n<p>The remainder of the comments make the assumption that a <code>node</code> representation is desired over an <code>array</code> representation of the tree, as both your questions and my comments are not necessarily valid for an <code>array</code> representation.</p>\n\n<p>A second error in your code is the case where you do not handle array representation where <code>null</code> root has children, did you consider error handling code for this scenario.</p>\n\n<p>A third error is in the case of zero length array, since you have taken the care to address invalid values for <code>nary</code>, do you not want to handle 0 length arrays, which are valid trees with <code>null</code> root.</p>\n\n<pre><code> private static class TreeNode&lt;T&gt; {\n T item;\n List&lt;TreeNode&lt;T&gt;&gt; childNodes;\n\n public TreeNode(T item, List&lt;TreeNode&lt;T&gt;&gt; childNodes) {\n this.item = item;\n this.childNodes = childNodes;\n }\n}\n</code></pre>\n\n<p>Answer to the second question, Since you know the specific <code>nary</code> there isn't a need to use an array list. In practice however for small <code>nary</code> values less than <code>10</code> there is no great drawback or performance penalty for using an <code>ArrayList</code>, there is tho greater memory usage.</p>\n\n<pre><code>/**\n * Constructs an empty list with the specified initial capacity.\n *\n * @param initialCapacity the initial capacity of the list\n * @throws IllegalArgumentException if the specified initial capacity\n * is negative\n */\npublic ArrayList(int initialCapacity) {\n super();\n if (initialCapacity &lt; 0)\n throw new IllegalArgumentException(\"Illegal Capacity: \"+\n initialCapacity);\n this.elementData = new Object[initialCapacity];\n}\n\n/**\n * Constructs an empty list with an initial capacity of ten.\n */\npublic ArrayList() {\n this(10);\n}\n</code></pre>\n\n<p>That is the constructor implementation from the JDK source and it is initialized with an array of size 10. </p>\n\n<p>Brooks in his book <code>Mythical man month</code> says <code>premature optimization is the root of all evil in programming</code>, and it has long been the refuge of code that has been written without good understanding, in this case, I would definitely use an array, premature optimization claims or otherwise.</p>\n\n<p>I did like that you made sure that TreeNode was static which is a common error that even experienced java programmers make.</p>\n\n<p>On the 3'rd question, using an array will cause a runtime exception (<code>ArrayIndexOutOfBoundsException</code>) if one were to write code that attempts to insert more child nodes than the branching factor. </p>\n\n<p>However, to answer your question, you can develop confidence that your private function behaves correctly with regards to branching factor. The way to develop this confidence is via writing some unit tests.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-01-23T14:38:09.230", "Id": "39874", "ParentId": "39784", "Score": "4" } } ]
{ "AcceptedAnswerId": "39874", "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-01-22T07:31:00.580", "Id": "39784", "Score": "1", "Tags": [ "java", "tree", "binary-search" ], "Title": "Search an element/item in an n-ary tree" }
39784
<p>As part of learning more C, I wrote this extremely trivial C program that takes Student scores from <code>stdin</code> and, upon termination, prints out the minimum score/maximum score and the average score. Can somebody review my code and tell me how I might be able to improve my code?</p> <pre><code>#include &lt;stdio.h&gt; int main() { int currentEntry; int startValue = 0; int counter = 0; int currentMax; int currentMin; double average; printf("Enter scores one-by-one, exit by entering -1\n"); while(currentEntry != -1){ if((scanf("%d",&amp;currentEntry) == 1) &amp;&amp; (currentEntry != -1)){ printf("Current score is %d\n",currentEntry); counter++; startValue += currentEntry; average = startValue/counter; if(counter == 1){ currentMax = currentEntry; currentMin = currentEntry; } if(currentEntry &gt; currentMax){ currentMax = currentEntry; } if(currentEntry &lt; currentMin){ currentMin = currentEntry; } } } printf("The average is %lf\n",average); printf("The maximum score is %d\n",currentMax); printf("The minimum score is %d\n",currentMin); return 0; } </code></pre>
[]
[ { "body": "<p>You should get into the habit of initialising variables whenever possible. It's a little more difficult here, since <code>currentMax</code>, <code>currentMin</code>, and <code>currentEntry</code> may seem not to have a sensible default value. However, all arithmetic values have an upper and a lower bound (these can be found in <code>limits.h</code>). It would make sense to initialise <code>currentMax</code> and <code>currentMin</code> based on these:</p>\n\n<pre><code>int currentMax = INT_MIN;\nint currentMin = INT_MAX;\n</code></pre>\n\n<p>Note that if the user inputs <code>-1</code> straight away, <code>currentMax</code> and <code>currentMin</code> will now print out predictable values. If you leave them uninitialised, they will print out whatever bits happen to be on the stack at that point in time (effectively, they will print out a random value).</p>\n\n<p>Also, note that because these are now initialised with the min/max integer values respectively, you can remove the check for <code>counter</code> being <code>1</code>.</p>\n\n<p>I'd also initialise <code>currentEntry</code> and <code>average</code>, <code>0</code> and <code>0.0</code> seem like relatively reasonable defaults.</p>\n\n<p>The name <code>startValue</code> is accurate at the beginning, but by the end, doesn't really reflect the starting value as you've been adding to it each time. Hence, I'd rather call it something like <code>currentTotal</code>. </p>\n\n<p>Integer division in <code>C</code> can trip beginners up, the line:</p>\n\n<pre><code>average = startValue/counter;\n</code></pre>\n\n<p>isn't doing quite what you want it to be. Since <code>startValue</code> and <code>counter</code> are both integers, this will do an integer division, and then convert that to a double. Hence this will actually be the <strong>floor</strong> of the average. To fix this, you need to cast the numerator or denominator to a <code>double</code>:</p>\n\n<pre><code>average = (double)startValue / counter;\n</code></pre>\n\n<p>In the end, the code is pretty similar, but looks something like:</p>\n\n<pre><code>#include &lt;stdio.h&gt;\n#include &lt;limits.h&gt;\n\nint main()\n{\n int currentEntry = 0;\n int currentTotal = 0;\n int counter = 0;\n int currentMax = INT_MIN;\n int currentMin = INT_MAX;\n double average = 0.0;\n\n printf(\"Enter scores one-by-one, exit by entering -1\\n\");\n\n while(currentEntry != -1) {\n if((scanf(\"%d\", &amp;currentEntry) == 1) &amp;&amp; (currentEntry != -1)) {\n printf(\"Current score is %d\\n\", currentEntry);\n counter++;\n currentTotal += currentEntry;\n average = (double)currentTotal/counter;\n\n if(currentEntry &gt; currentMax) {\n currentMax = currentEntry;\n }\n\n if(currentEntry &lt; currentMin) {\n currentMin = currentEntry;\n }\n }\n }\n\n printf(\"The average is %lf\\n\",average);\n printf(\"The maximum score is %d\\n\", currentMax);\n printf(\"The minimum score is %d\\n\", currentMin);\n return 0;\n}\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-01-23T04:16:53.567", "Id": "66877", "Score": "0", "body": "Thanks a lot. I feel like I am learning more from Code Review than from any of the C books that are on my shelf." } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-01-22T07:53:13.290", "Id": "39788", "ParentId": "39785", "Score": "2" } }, { "body": "<p>Adding to what @Yuushi said, I would make some more changes.</p>\n\n<p><strong>Variable Names</strong></p>\n\n<p>Your variable names mostly contain the word 'current'. Does that improve\nreadability or make it more understandable? I think not, so I would rename\nthe variables <code>total</code>, <code>count</code>, <code>min</code>, <code>max</code> and <code>average</code>. <code>currentEntry</code>\nholds a 'score' so I would call it <code>score</code>. And <code>counter</code> can be shortened to\n<code>count</code> with no loss. Once you change these names in your code it will\nimmediately look less dense and more readable. </p>\n\n<p>Note that variable name length is often best if related to variable scope. So\na variable that has large scope (ie. is used in many places) should be\nrelatively long; ones that have small scope (and that is often most) may be\nshort.</p>\n\n<p><strong>User input</strong></p>\n\n<p>Using <code>scanf</code> can cause problems. For example if you type a letter instead of\na number your program will fail to recognize any subsequent input (the letter\nremains in the input stream and <code>scanf</code> (which was expecting a number) will\nnot remove it. I hardly ever use <code>scanf</code>.</p>\n\n<p>I would rewrite your loop to use <code>fgets</code> instead. This function reads a\nstring from the input. You can then extract the score from the string using\nlibrary function <code>strtol</code>. When you do this you can allow the user to type\n(for example) 'q' to quit instead of the somewhat contrived -1. </p>\n\n<p>Here is the code:</p>\n\n<pre><code>int main(void)\n{\n int total = 0;\n int count = 0;\n int max = INT_MIN;\n int min = INT_MAX;\n char buf[20];\n\n printf(\"Enter scores one-by-one, exit by entering 'q'\\n\");\n\n while (fgets(buf, sizeof buf, stdin) != NULL) {\n if (buf[0] == 'q') {\n break;\n }\n char *end;\n int score = (int) strtol(buf, &amp;end, 0);\n if (end != buf) {\n count++;\n total += score;\n if (score &gt; max) {\n max = score;\n }\n if (score &lt; min) {\n min = score;\n }\n }\n }\n if (count) {\n double average = (double)total/count;\n printf(\"The average is %lf\\n\",average);\n printf(\"The maximum score is %d\\n\", max);\n printf(\"The minimum score is %d\\n\", min);\n }\n return 0;\n}\n</code></pre>\n\n<p>Notice that the loop now exist when <code>fgets</code> returns <code>NULL</code>, which it does when\nthe user closes the input stream (for example by typing ctrl-d on UNIXy\nsystems). And there is an explict check for 'q' in the input. </p>\n\n<p>The <code>strtol</code> call takes the buffer holding user input and also the address of\na pointer <code>&amp;end</code>. It places a pointer to the first character that is not part\nof a number in <code>end</code>. So if the user entered '123p', <code>end</code> would point to the 'p'.\nAlso if <code>buf</code> does not contain a number at the beginning, <code>strtol</code> sets <code>end</code>\nto point to <code>buf</code>. Hence we can check whether a number was read by checking\nthat equivalence.</p>\n\n<p>Finally note that the average need not be computed on every loop so I have\nmoved that outside the loop, protected by a check for <code>count</code> being non-zero. </p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-01-23T23:47:33.487", "Id": "39924", "ParentId": "39785", "Score": "2" } } ]
{ "AcceptedAnswerId": "39788", "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-01-22T07:35:30.307", "Id": "39785", "Score": "4", "Tags": [ "c", "stream" ], "Title": "Processing student scores from the stdin" }
39785
<p>In my Android application, I have two types of filters: search filters and sorting filters.</p> <p>I need to read filters from view, display filter on view, and save them into and from memory. I should include these needed features into one class to help myself add new filters in the future. I also need to divide filters by their type.</p> <p>Filters in my app represented via:</p> <ul> <li><code>Comparator&lt;T&gt;</code> interface from Java SDK (for sorting filters)</li> <li><p><code>SearchCriterion&lt;T&gt;</code> interface (for search filters)</p> <pre><code>public interface SearchCriterion&lt;T&gt; { boolean meetCriterion(T obj); } </code></pre></li> </ul> <p>To do something needed I wrote an <code>interface</code>:</p> <pre><code>public interface Filter { void readFrom(View view); void displayOn(View view); void restoreFrom(SharedPreferences sharedPreferences); void saveInto(SharedPreferences.Editor editor); void includeInIfNeed(Filters filters); } </code></pre> <p>Example of <code>Filter</code> subclass:</p> <pre><code>class SearchFilterByDiscountType implements Filter { private static class KeysOfDiscountTypes { public static final String BONUS = getClassName() + "Bonus"; public static final String DISCOUNT = getClassName() + "Discount"; public static final String CASH_BACK = getClassName() + "Cash Back"; } private static String getClassName() { return SearchFilterDiscountType.class.getSimpleName(); } private static final boolean DEFAULT_BONUS = true; private static final boolean DEFAULT_DISCOUNT = true; private static final boolean DEFAULT_CASH_BACK = true; private boolean bonus; private boolean discount; private boolean cashBack; public SearchFilterDiscountType() { bonus = DEFAULT_BONUS; discount = DEFAULT_DISCOUNT; cashBack = DEFAULT_CASH_BACK; } @Override public void readFrom(View view) { bonus = findCheckBox(view, R.id.bonusCheckBox).isChecked(); discount = findCheckBox(view, R.id.discountCheckBox).isChecked(); cashBack = findCheckBox(view, R.id.cashBackCheckBox).isChecked(); } @Override public void displayOn(View view) { findCheckBox(view, R.id.bonusCheckBox).setChecked(bonus); findCheckBox(view, R.id.discountCheckBox).setChecked(discount); findCheckBox(view, R.id.cashBackCheckBox).setChecked(cashBack); } private CheckBox findCheckBox(View view, int idOfCheckBox) { return (CheckBox) view.findViewById(idOfCheckBox); } @Override public void restoreFrom(SharedPreferences sharedPreferences) { bonus = sharedPreferences.getBoolean(KeysOfDiscountTypes.BONUS, DEFAULT_BONUS); discount = sharedPreferences.getBoolean(KeysOfDiscountTypes.DISCOUNT, DEFAULT_DISCOUNT); cashBack = sharedPreferences.getBoolean(KeysOfDiscountTypes.CASH_BACK, DEFAULT_CASH_BACK); } @Override public void saveInto(SharedPreferences.Editor editor) { editor.putBoolean(KeysOfDiscountTypes.BONUS, bonus); editor.putBoolean(KeysOfDiscountTypes.DISCOUNT, discount); editor.putBoolean(KeysOfDiscountTypes.CASH_BACK, cashBack); } @Override public void includeInIfNeed(Filters filters) { filters.add(new DiscountTypeSearchCriterion(bonus, discount, cashBack)); } } </code></pre> <p>To divide filters by their type I wrote this class:</p> <pre><code>public class Filters implements Serializable { public final List&lt;SearchableListing.SearchCriterion&lt;PartnerPoint&gt;&gt; searchCriteria; public final List&lt;Comparator&lt;PartnerPoint&gt;&gt; comparators; public static Filters from(List&lt;Filter&gt; filters) { Filters result = new Filters(); for (Filter filter : filters) { filter.includeInIfNeed(result); } return result; } public Filters() { searchCriteria = new ArrayList&lt;SearchableListing.SearchCriterion&lt;PartnerPoint&gt;&gt;(); comparators = new ArrayList&lt;Comparator&lt;PartnerPoint&gt;&gt;(); } public void add(SearchableListing.SearchCriterion&lt;PartnerPoint&gt; searchCriterion) { searchCriteria.add(searchCriterion); } public void add(Comparator&lt;PartnerPoint&gt; comparator) { comparators.add(comparator); } public void add(Filters other) { searchCriteria.addAll(other.searchCriteria); comparators.addAll(other.comparators); } } </code></pre> <p>But in my opinion, <code>Filter</code> and <code>Filters</code> are confusing names for these very different interfaces.</p>
[]
[ { "body": "<p>You have presented similar code to this before, and while some of the recommendations I had have been implemented, others have not... ;-) This is fine, presumably you have your reasons, but the one that sticks out is the <code>public void includeInIfNeed(Filters filters)</code> method, which is redundant....</p>\n\n<p>As for naming, I have a few recommendations:</p>\n\n<ul>\n<li><code>Filter</code> is a fine name for it. No need to change.</li>\n<li><code>SearchFilterByDiscountType</code> does not search, it is used to search. I use the convention that a specialization of a class/implementation should (normally) use the base class as a suffix. So, here the <code>Filter</code> should go to the end, and become <code>DiscountTypeFilter</code>. This is somewhat standard, think of <code>List</code>, <code>ArrayList</code>, <code>LinkedList</code>, etc.</li>\n<li><code>Filters</code> is not a completely bad name, I agree it could be better, but if this was 'production' code I probably would not change it because the mess in the change logs would not be worth it. On the other hand, it is simple enough to change now, and I have a number of suffixes I use.... <code>Set</code>, <code>List</code>, <code>Array</code>, <code>Chain</code>, <code>Pack</code>, <code>Group</code> and some others I forget right now. I use the suffix that most closely represents the structure and data access mechanism of the data in the collection. In this case, I would probably use <code>FilterChain</code>.</li>\n</ul>\n\n<p>There are two other suggestions I have:</p>\n\n<ul>\n<li><code>Filters</code> is not actually Serializable, so why is it declared to be?</li>\n<li>It woul dbe really convenient if the <code>Filters</code> (<code>FilterChain</code>?) class also implements the <code>Filter</code> interface which would allow you to apply filters in a batched fashion.</li>\n</ul>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-01-22T12:47:03.853", "Id": "39802", "ParentId": "39786", "Score": "2" } } ]
{ "AcceptedAnswerId": "39802", "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-01-22T07:47:59.217", "Id": "39786", "Score": "3", "Tags": [ "java", "android" ], "Title": "Search filters and sorting filters" }
39786
<p>I have just started to use PHP OOP and I would like to write a class to make a multi-language website. I started from <a href="http://www.bitrepository.com/php-how-to-add-multi-language-support-to-a-website.html" rel="nofollow">this</a> but I wanted to use OOP so I came up with this:</p> <p><strong>Language.php</strong></p> <pre><code>&lt;?php class Language { private $UserLng; private $langSelected; public $lang = array(); public function __construct($userLanguage){ $this-&gt;UserLng = $userLanguage; } public function userLanguage(){ switch($this-&gt;UserLng){ /* ------------------ Language: English ------------------ */ case "en": $lang['PAGE_TITLE'] = 'My website page title'; $lang['HEADER_TITLE'] = 'My website header title'; $lang['SITE_NAME'] = 'My Website'; $lang['SLOGAN'] = 'My slogan here'; $lang['HEADING'] = 'Heading'; // Menu $lang['MENU_LOGIN'] = 'Login'; $lang['MENU_SIGNUP'] = 'Sign up'; $lang['MENU_FIND_RIDE'] = 'Find Ride'; $lang['MENU_ADD_RIDE'] = 'Add Ride'; $lang['MENU_LOGOUT'] = 'Logout'; return $lang; break; /* ------------------ Language: Italian ------------------ */ case "it": $lang['PAGE_TITLE'] = 'Il titolo della mia pagina'; $lang['HEADER_TITLE'] = 'Il mio titolo'; $lang['SITE_NAME'] = 'Il nome del mio sito'; $lang['SLOGAN'] = 'Uno slogan'; $lang['HEADING'] = 'Heading'; // Menu $lang['MENU_LOGIN'] = 'Entra'; $lang['MENU_SIGNUP'] = 'Registrati'; $lang['MENU_FIND_RIDE'] = 'Trova gruppi'; $lang['MENU_ADD_RIDE'] = 'Aggiungi gruppo'; $lang['MENU_LOGOUT'] = 'Esci'; return $lang; break; /* ------------------ Default Language ------------------ */ default: $lang['PAGE_TITLE'] = 'My website page title'; $lang['HEADER_TITLE'] = 'My website header title'; $lang['SITE_NAME'] = 'My Website'; $lang['SLOGAN'] = 'My slogan here'; $lang['HEADING'] = 'Heading'; // Menu $lang['MENU_LOGIN'] = 'Login'; $lang['MENU_SIGNUP'] = 'Sign up'; $lang['MENU_FIND_RIDE'] = 'Find Ride'; $lang['MENU_ADD_RIDE'] = 'Add Ride'; $lang['MENU_LOGOUT'] = 'Logout'; return $lang; break; } } } </code></pre> <p><strong>index.php</strong></p> <pre><code>&lt;?php $lang = substr($_SERVER['HTTP_ACCEPT_LANGUAGE'], 0, 2);//Detecting Default Browser language $language = New Language($lang); $langArray = array(); $langArray = $language-&gt;userLanguage(); ?&gt; &lt;div class="cssmenu"&gt; &lt;ul&gt; &lt;li&gt; class="active"&gt;&lt;a href="/login"&gt;&lt;?php echo $langArray['MENU_LOGIN']?&gt;&lt;/a&gt;&lt;/li&gt; &lt;li&gt;&lt;a href="/rides"&gt;&lt;?php echo $langArray['MENU_FIND_RIDE']?&gt;&lt;/a&gt;&lt;/li&gt; &lt;li&gt;&lt;a id ="btnShow"&gt;&lt;?php echo $langArray['MENU_ADD_RIDE']?&gt;&lt;/a&gt;&lt;/li&gt; &lt;li&gt;&lt;a href="/logout.php"&gt;&lt;?php echo $langArray['MENU_LOGOUT']?&gt; &lt;/a&gt;&lt;/li&gt; &lt;li&gt;&lt;a href="/register"&gt;&lt;?php echo $langArray['MENU_SIGNUP']?&gt;&lt;/a&gt;&lt;/li&gt; &lt;/ul&gt; &lt;/div&gt; </code></pre> <p>While this works perfectly, I am not sure this is the correct way to do it. I didn't find many tutorials on how to do this using OOP so I have the following doubts:</p> <ol> <li>Is this a correct way to do it?</li> <li>is this code maintainable?</li> <li>would it make more sense to create a table in the database with all the different languages?</li> <li>I am still struggling to understand "abstract classes". Would this be the case to create an abstract class <code>language.php</code> and then extend(I hope this is the correct terminology) that class with other languages class (<code>english.php</code>, <code>italian.php</code> etc).</li> </ol>
[ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-01-22T14:50:19.583", "Id": "66780", "Score": "0", "body": "this isn't really an answer, but Google will Translate your site into many common languages, you shouldn't waste your time reinventing this. I mean that anyone can navigate to a site in Italian and have Google Translate it for them. if you use Chrome it asks you if you want to translate the site if it detects the site in a language it is able to translate." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-01-22T15:00:25.147", "Id": "66781", "Score": "3", "body": "@Malachi Defining your own translations is not reinventing, it's providing a **decent translation**. Humans are normally better than google at translating things." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-01-22T15:13:11.523", "Id": "66782", "Score": "0", "body": "I would say that Google is pretty good at translation, but that Humans are not very good at spelling or grammar. but I see your point @SimonAndréForsberg" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-01-22T15:49:02.873", "Id": "66789", "Score": "1", "body": "@Malachi thank you for your comments. While I agree with you that humans are not very good at spelling or grammar, I found google translation quite funny sometimes. English is not my first language but I want to have full control over the way the website will be translated in other languages (English will be the default language)." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-01-22T15:54:09.323", "Id": "66791", "Score": "0", "body": "@mattia, you might want to look into how Google will Translate your website as well. there might be something where Google will use your Translation when someone wants your page translated through them. does that make sense?" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-01-23T12:38:47.913", "Id": "66901", "Score": "2", "body": "I'm a stickler in terms of variable names. Keep whatever format you use the same so it's consistent across your code base. Having $UserLng and then other variables like $langSelected will start to become difficult to figure out both for yourself and other developers. EG: Make them all start lowercase." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-01-23T13:30:34.457", "Id": "66908", "Score": "0", "body": "@StevenLeggett thanks. I will work on that. I need to improve the indentation as well. ;)" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-01-23T20:03:18.253", "Id": "66966", "Score": "0", "body": "Returning anything, in your case `$this->UserLng`, in a class constructor doesn't make much sense. Constructors don't get return values, they serve entirely to instantiate the class." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-01-25T11:31:01.833", "Id": "67257", "Score": "0", "body": "@user555 thanks for pointing that out. I fixed the code. As I said, I have just started to use OOP." } ]
[ { "body": "<p>You've made a good start, but the switch statement in <code>userLanguage()</code> just doesn't feel right from an Object orientated perspective:</p>\n\n<p>A class called <code>Language</code> should represent a single language which is generic enough to fit all cases: however at the moment, whatever language it represents, it has the definitions of all of them just jammed into that one method.</p>\n\n<p><strong>Is it maintainable?</strong>\nNot really, no. At the moment you have two languages, which I assume you know. However, should you ever want to translate it into another language (perhaps using another Charset, you're going to run into issues of space in the file, saving the file correctly, and merging in translations provided by other people for your site.</p>\n\n<p>As to whether to use databases, abstract classes et cetera: You may want to, though there are other solutions.</p>\n\n<p><strong>Solution 1: Simple Configuration File</strong></p>\n\n<p><a href=\"http://php.net/parse_ini_file\"><code>parse_ini_file()</code></a> is a very powerful little tool that does exactly what you expect. Using a simple file like this which we'll call <strong>en.ini</strong>:</p>\n\n<pre><code>PAGE_TITLE = My website page title\nHEADER_TITLE = My website header title\nSITE_NAME = My Website\nSLOGAN = My slogan here\nHEADING = Heading\nMENU_LOGIN = Login\nMENU_SIGNUP = Sign up\nMENU_FIND_RIDE = Find Ride\nMENU_ADD_RIDE = Add Ride\nMENU_LOGOUT = Logout\n</code></pre>\n\n<p>You can simply use: <code>parse_ini_file('en.ini')</code> to return an array exactly as in your switch statement, which will be much easier for other (non-programmers) to read and write for you. And if you were to then continue naming the files with this style, you could reduce <code>userLanguage()</code> to something like:</p>\n\n<pre><code>public function userLanguage()\n{\n $file = '/path/to/language/config/' . $this-&gt;UserLng . '.ini';\n if(!file_exists($file))\n {\n //Handle Error\n }\n return parse_ini_file($file);\n}\n</code></pre>\n\n<p><strong>Solution 2: Abstract class</strong></p>\n\n<p>As your array is basically acting as getter methods, an abstract Language class should have all the language components you need in it, like so:</p>\n\n<pre><code>interface Language\n{\n public function getPageTitle();\n public function getHeaderTitle();\n public function getSiteName();\n public function getSlogan();\n public function getHeading();\n public function getMenuLogin();\n public function getMenuSignup();\n public function getMenuFindRide();\n public function getMenuAddRide();\n public function getMenuLogout();\n}\n</code></pre>\n\n<p>Though the interface is small, implementing it may produce a big file, though it would arguably be clearer than the array style:</p>\n\n<pre><code>class English implements Language\n{\n public function getHeaderTitle()\n {\n return 'My website header title';\n }\n\n public function getHeading()\n {\n return 'Heading';\n }\n\n // etc...\n}\n</code></pre>\n\n<p><strong>Alternative</strong></p>\n\n<p>Alternatively, you could combine these styles and have a singleton Language with getter methods accessing that array, i.e.:</p>\n\n<pre><code>class Language\n{\n private $languageArray;\n private $userLanguage;\n\n public function __construct($language)\n {\n $this-&gt;userLanguage = $language;\n $this-&gt;languageArray = self::userLanguage();\n }\n\n private static function userLanguage()\n {\n $file = '/path/to/language/config/' . $this-&gt;userLanguage . '.ini';\n if(!file_exists($file))\n {\n //Handle Error\n }\n return parse_ini_file($file);\n }\n\n public function getPageTitle()\n {\n return $this-&gt;languageArray['PAGE_TITLE'];\n }\n\n public function getHeaderTitle()\n {\n return $this-&gt;languageArray['HEADER_TITLE'];\n }\n\n //etc...\n}\n</code></pre>\n\n<p>Which will provide the benefits of both. Personally though, unless you're planning on adding more languages in the very near future, I believe solution #2 would suit you best.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-01-22T11:45:43.597", "Id": "39799", "ParentId": "39787", "Score": "10" } }, { "body": "<p>I have done translation of one of my sites into English, French and German \nand what I found is that maintaining a class with getter's and setter's for a handful of phrases works, but anything more, just becomes hard work</p>\n\n<p>I like @MrLore parse_ini_file() approach.</p>\n\n<p>with a few differences</p>\n\n<p>For example instead of using made up constants like PAGE_TITLE, use the real string in your native language.</p>\n\n<p>So my en_nz.ini file looks like this</p>\n\n<pre><code>My website page title = My website page title\n</code></pre>\n\n<p>My fr_fr.ini file looks like this</p>\n\n<pre><code>My website page title = Mon site web page de titre\n</code></pre>\n\n<p>The advantages of the ini format style, as @MrLore said, you can give a file to someone (not a programmer) and they can do the translation for you.</p>\n\n<p>Another advantage is if you use multiple programming languages, the ini file is independent of those.</p>\n\n<p>You can also do more advanced stuff like including arguments into the strings</p>\n\n<pre><code>I am %d years old today = I am %d years old today\n</code></pre>\n\n<p>Then when you render the string in your page</p>\n\n<pre><code>&lt;?php\n\nclass lang {\n\n private $lang = null;\n\n function __construct($lang) {\n $this-&gt;lang = parse_ini_file(\"{$lang}.ini\");\n }\n\n\n public function xlate($str) {\n\n $arg_count = func_num_args();\n\n if ($arg_count &gt; 1) {\n $params = func_get_args();\n\n // strip first arg\n array_shift($params);\n } else {\n $params = array();\n }\n\n $out_str = isset($this-&gt;lang[$str]) ? $this-&gt;lang[$str] : null;\n\n // if you string doesn't exist or is mistyped, then blow up, so we know about it\n // or you could even go away to google translate and perform the translation for\n // any missing strings\n if (!$out_str) {\n throw new exception(\"Lang String Not Found: $str\");\n }\n\n return vsprintf($out_str, $params);\n }\n}\n\n$lang = new lang('fr_fr');\n\necho $lang-&gt;xlate('Thank you my friend');\n\necho $lang-&gt;xlate('My website page title for %d', 2014);\n\necho $lang-&gt;xlate('made up string');\n</code></pre>\n\n<p>fr_fr.ini</p>\n\n<pre><code>My website page title for %d = Mon site web page de titre pour %d\nThank you my friend = Merci mon ami\n</code></pre>\n\n<p>On a final note $lang->xlate may sound like a nice function name, but after a while you will get sick of typing it, $l->x is cryptic but shorter</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-01-22T20:56:52.293", "Id": "39840", "ParentId": "39787", "Score": "7" } } ]
{ "AcceptedAnswerId": "39799", "CommentCount": "9", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-01-22T07:50:43.857", "Id": "39787", "Score": "12", "Tags": [ "php", "object-oriented", "php5", "i18n" ], "Title": "Multi-language website management" }
39787
<p>I have 18 <code>RadioGroup</code>. I am declaring the <code>RadioGroup</code> like this way </p> <pre><code>private RadioGroup kn1RadioGroup, kn2RadioGroup, kn4aRadioGroup, kn4bRadioGroup, kn4cRadioGroup, kn4dRadioGroup, kn4eRadioGroup, kn4fRadioGroup, kn4gRadioGroup, kn4hRadioGroup, kn4iRadioGroup,kn4jRadioGroup,ap2aRadioGroup,ap2bRadioGroup, ap2cRadioGroup,ap2dRadioGroup,ap2eRadioGroup,pr1RadioGroup; </code></pre> <p>I have created getter and setter for these <code>RadioGroup</code>. And I am setting the RadioGroup id like this way </p> <pre><code>fragment.setKn1RadioGroup((RadioGroup) findViewById(R.id.kn1_radio_group)); fragment.setKn2RadioGroup((RadioGroup) findViewById(R.id.kn2_radio_group)); fragment.setPr1RadioGroup((RadioGroup) findViewById(R.id.pr1_radio_group)); fragment.setKn4aRadioGroup((RadioGroup) findViewById(R.id.kn4a_radio_group)); fragment.setKn4bRadioGroup((RadioGroup) findViewById(R.id.kn4b_radio_group)); fragment.setKn4cRadioGroup((RadioGroup) findViewById(R.id.kn4c_radio_group)); fragment.setKn4dRadioGroup((RadioGroup) findViewById(R.id.kn4d_radio_group)); fragment.setKn4eRadioGroup((RadioGroup) findViewById(R.id.kn4e_radio_group)); fragment.setKn4fRadioGroup((RadioGroup) findViewById(R.id.kn4f_radio_group)); fragment.setKn4gRadioGroup((RadioGroup) findViewById(R.id.kn4g_radio_group)); fragment.setKn4hRadioGroup((RadioGroup) findViewById(R.id.kn4h_radio_group)); fragment.setKn4iRadioGroup((RadioGroup) findViewById(R.id.kn4i_radio_group)); fragment.setKn4jRadioGroup((RadioGroup) findViewById(R.id.kn4j_radio_group)); fragment.setAp2aRadioGroup((RadioGroup) findViewById(R.id.ap2a_radio_group)); fragment.setAp2bRadioGroup((RadioGroup) findViewById(R.id.ap2b_radio_group)); fragment.setAp2cRadioGroup((RadioGroup) findViewById(R.id.ap2c_radio_group)); fragment.setAp2dRadioGroup((RadioGroup) findViewById(R.id.ap2d_radio_group)); fragment.setAp2eRadioGroup((RadioGroup) findViewById(R.id.ap2e_radio_group)); </code></pre> <p>Is there any easy way to do it? </p>
[ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-01-22T11:15:49.513", "Id": "66763", "Score": "2", "body": "So...can you explain why this question is different [to your previous one](http://codereview.stackexchange.com/questions/39468/refactoring-radiogroup-setter-code)?" } ]
[ { "body": "<p>The easiest way would be to define a constant integer array holding the ids:</p>\n\n<pre><code>private static final int[] ids = { R.id.kn1_radio_group, R.id.kn2_radio_group, R.id.pr1_radio_group, /* and so on... */};\n</code></pre>\n\n<p>And then using the same method as in my answer to <a href=\"https://codereview.stackexchange.com/questions/39468/refactoring-radiogroup-setter-code\">your previous question</a>.</p>\n\n<p>However, your naming of these RadioGroups tells me that there <strong>might be another structure here.</strong> And I also suspect that there is more to your application than what we see here. So what you really should do is to <strong>think about the structure of your variables;</strong> Should a <code>kn</code> be a class? Should <code>kn4</code> be an array on it's own, or should perhaps <code>kn</code> be a two-dimensional array (one dimension for the number and one for the letter. <strong>These are questions that none of us currently can answer considering the lack of context we have about your application</strong>. If you would explain a bit more about <strong>What your application is for</strong> and what a <code>kn</code> / <code>ap</code> RadioGroup is, then we might help you more. You probably have some reasons for naming the radio groups the way that you do, in which case a different structure than an array might be more useful.</p>\n\n<p>Also, I would like to add something: Why not let the fragment take care of it's own initialization of the RadioGroups? Is perhaps the RadioGroups a part of the fragment's view already? If so, then there is no need to use all these setter methods for it.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-01-22T11:45:15.830", "Id": "39798", "ParentId": "39790", "Score": "2" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "1", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-01-22T09:04:19.567", "Id": "39790", "Score": "1", "Tags": [ "java", "android" ], "Title": "How to reduce this RadioGroup Code?" }
39790
<p>We have multiple scripts which write into XLSX with the same format, into a different format or slide variation. I am trying to write an API which saves time for other programs, but I need input on restructuring the file.</p> <pre><code>import openpyxl from xlsxwriter.workbook import Workbook class xlsx_extend(object): """This class contain api of xlsx functionality""" def __init__(self, name): """create xls file""" self.xlsx_name = Workbook(name) self.create_format('blue', 12) def create_format(self, color, size): """write header""" self.xlsx_format = self.xlsx_name.add_format() self.xlsx_format.set_font_size(size) self.xlsx_format.set_bold() self.xlsx_format.set_color(color) self.xlsx_format.set_border() self.xlsx_format.set_center_across() self.xlsx_format.set_align('center') self.xlsx_format.set_rotation(90) def add_sheet(self, ws_name): """Adding worksheet name""" return self.xlsx_name.add_worksheet(ws_name) def rotate_text_format(self, angle): """rotate the text data""" self.xlsx_format.set_rotation(angle) def get_xlsx_name(self): """Returing xlsx name for derive class""" return self.xlsx_name def close_xlsx(self): """close xlsx File""" self.xlsx_name.close() class xlsx_sheet: """This is xlsx worksheet class""" def __init__(self, excel_sheet, ws_name): """Initialze Base function and Create Worksheet""" self.excel_sheet = excel_sheet self.ws_name_worksheet = excel_sheet.add_sheet(ws_name) self.ws_name_worksheet.set_column(0, 0, 40) def write(self, row, col, data, format=None): """write Add in xlsx File""" self.ws_name_worksheet.write(row, col, data) def write_column(self, row, col, data, format=None): """write data in column than need pass data as list""" self.ws_name_worksheet.write_column(row, col, data) def write_row(self, row, col, data, format=None): """write data in row than need to pass as list""" self.ws_name_worksheet.write_row(row, col, data, self.excel_sheet.xlsx_format) def write_comment(self, row, col, data): """write comment in cell""" self.ws_name_worksheet.write_comment(row, col, data, {'width': 400, 'height': 400}) def text_condition_format(self, first_row, first_col, last_row, last_col, value, format): """Adding text condition format""" self.ws_name_worksheet.conditional_format(first_row, first_col, last_row, last_col, {'type': 'text', 'criteria': 'containing', 'value': value, 'format': format }) </code></pre> <p>And another module with it's call API like:</p> <pre><code>report_xlsx = xlsxutils.xlsx_extend("report.xlsx") red_format = report_xlsx.xlsx_name.add_format({'bg_color': '#FF0000'}) green_format = report_xlsx.xlsx_name.add_format({'bg_color':'#99CC32'}) gray_format = report_xlsx.xlsx_name.add_format({'bg_color':'#53868B'}) blue_format = report_xlsx.xlsx_name.add_format({'bg_color':'#3298FE'}) light_red_format = report_xlsx.xlsx_name.add_format({'bg_color':'#FF9999'}) report_worksheet = xlsxutils.xlsx_sheet(report_xlsx, "Report") report_worksheet.text_condition_format(1, 1, row, col, 'P', green_format) report_worksheet.text_condition_format(1, 1, row, col, 'F', red_format) report_worksheet.text_condition_format(1, 1, row, col, 'AB', red_format) report_worksheet.text_condition_format(1, 1, row, col, 'RU', light_red_format) report_worksheet.text_condition_format(1, 1, row, col, 'QU', light_red_format) report_worksheet.text_condition_format(1, 1, row, col, 'M', gray_format) report_worksheet.text_condition_format(1, 1, row, col, 'UN', blue_format) report_xlsx.close_xlsx() </code></pre> <p>Can you do code review and provide your input?</p>
[]
[ { "body": "<h2>Naming Conventions</h2>\n\n<p>According to the official Python style guide, class names should be in <code>PascalCase</code>:</p>\n\n<pre><code>No:\n class my_class():\nYes:\n class MyClass():\n</code></pre>\n\n<p>In your case, I would capitalize the entire <code>xlsx</code> because it is an acroynm:</p>\n\n<pre><code>class XSLXExtend():\n</code></pre>\n\n<hr>\n\n<p>There also seems to be some redundancy in some of your names:</p>\n\n<pre><code># worksheet_name_worksheet?\nself.ws_name_worksheet\n</code></pre>\n\n<hr>\n\n<p>This next point may be speaking on an intentional design measure, but I would take a look at what properties are supposed to be 'public' and which are meant to be 'private'. Even though Python <a href=\"https://stackoverflow.com/questions/1641219/does-python-have-private-variables-in-classes\">doens't truly have private variables</a>, it is still convention to use a single underscore ('_') at the start of any intended private variables.</p>\n\n<pre><code>self._i_should_be_private = 'No touching!'\n</code></pre>\n\n<hr>\n\n<p>Some of your names are misleading:</p>\n\n<pre><code># Wait. This stores the actual Workbook not its name?\nself.xlsx_name = Workbook(name)\n</code></pre>\n\n<h2>Structure</h2>\n\n<p>I am not a big fan of declaring instance variables outside of the <code>__init__</code> method. In lieu of this, I would refactor your <code>create_format()</code> method as such:</p>\n\n<pre><code>def create_format(self, color, size):\n format = self.xlsx_name.addFormat()\n format.set_font_size(size)\n format.set_bold()\n format.set_color(color)\n format.set_border()\n format.set_center_across()\n format.set_align('center')\n format.set_rotation(90)\n\n return format\n</code></pre>\n\n<p>Then just put this line in the <code>__init__</code> method: <code>self.format = create_format('blue', 12)</code>.</p>\n\n<hr>\n\n<p>Also, you have an accessor method (which is nice) for <code>xlsx_name</code>. However, in your code that actually uses your classes, you just directly access it:</p>\n\n<pre><code># Why even have `get_xlsx_name()` if you don't use it?\nred_format = report_xlsx.xlsx_name.add_format(...)\n</code></pre>\n\n<p>The same goes for your <code>create_format()</code> method. You use it once in <code>__init__</code> but don't when you <strong>actually use</strong> your class. You skip straight to the <code>Workbook</code>:</p>\n\n<pre><code>red_format = report_xlsx.xlsx_name.add_format({'bg_color': '#FF0000'})\n</code></pre>\n\n<p>Essentially you are circumventing all the work you did wrapping the <code>Workbook</code> class in another class.</p>\n\n<hr>\n\n<p>Since your <code>xlsx_extend</code> class is supposed to store data about and manipulate a <code>Workbook</code> why not store all of the formats there? Here is what I would do:</p>\n\n<pre><code>class XLSXExtension(object):\n def __init__(self, name):\n self.xlsx_name = Workbook(name)\n self.formats = {}\n\n self.create_format('blue', 'blue')\n\n def create_format(self, name, color, size=12):\n format = self.xlsx_name.addFormat()\n format.set_font_size(size)\n format.set_bold()\n format.set_color(color)\n format.set_border()\n format.set_center_across()\n format.set_align('center')\n format.set_rotation(90)\n\n self.formats[name] = format\n\n def __getattr__(self, key):\n try:\n return self.formats[key]\n except KeyError:\n print('Format \"{}\" not found.'.format(key))\n\n\nreport_xlsx = xlsxutils.xlsx_extend(\"report.xlsx\")\nreport_xlsx.create_format('red', '#FF0000')\nreport_xlsx.create_format('green', '#99CC32', 24)\n\nreport_worksheet = xlsxutils.xlsx_sheet(report_xlsx, \"Report\") \nreport_worksheet.text_condition_format(1, 1, row, col, 'P', report_xlsx['green'])\nreport_worksheet.text_condition_format(1, 1, row, col, 'F', report_xlsx['red'])\n</code></pre>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-05-19T15:32:34.860", "Id": "51151", "ParentId": "39792", "Score": "3" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-01-22T09:46:26.137", "Id": "39792", "Score": "5", "Tags": [ "python", "api", "python-3.x", "excel" ], "Title": "XLSX writer implementation" }
39792
<p>The assignment is very open and we have only 4 things it needs to cover:</p> <ol> <li>File write and read</li> <li>Use a Struct</li> <li>Export into HTML format</li> <li>use a common sorting algorithm</li> </ol> <p>so I've decided to create a little "Library" with following features:</p> <ul> <li>read the input file "Library.dat"</li> <li>List the books on the console</li> <li>Sort the books by name</li> <li>Add new book</li> <li>delete a book by ID</li> <li>check a book in / out</li> </ul> <p>So I'm a beginner at C and would be very happy for a review and some tips on how to improve my project.</p> <p>Input File:</p> <pre><code>1;v;121212;121212;1 2;a;121212;121212;0 4;e;121212;121212;1 6;d;121212;121212;1 7;w;121212;121212;0 8;x;121212;121212;1 9;c;121212;121212;1 </code></pre> <p>My Config.h file:</p> <pre><code>// // Library.config // // Created by Me on 03.12.13. // Copyright (c) 2013 Me. All rights reserved. // // DEFINE #define MAX_STR_LEN 256 #define MAX_BOOKS 10 #define DATE_LEN 8 #define PATH "/users/xxxxxxx/desktop/Library/Library.dat" </code></pre> <p>My Code:</p> <pre><code>/************************************************* * Library Application * * Author: Me * Date: 26.11.2013 * Version: BETA * * *************************************************/ /**************************** * OSX: fpurge(stdin) insted of fflush(stdin) * * * *****************************/ /* TODOs: * * Search Function * Colors (conio.h)? * * */ /* header files for access to specialized functions*/ #include &lt;stdio.h&gt; #include &lt;string.h&gt; #include &lt;stdlib.h&gt; #include "config.h" typedef struct { int ID; char name[MAX_STR_LEN]; char dateIn[DATE_LEN]; char dateOut[DATE_LEN]; int isIn; }book; struct book{ int ID; char name[MAX_STR_LEN]; char dateIn[DATE_LEN]; char dateOut[DATE_LEN]; int isIn; }; /* array of my books */ struct book books[MAX_BOOKS]; /* PROTOTYPE OF FUNCTIONS */ int readBookFile(); void printBookList(); void addBook(); void mutateBook(book b); //TODO int getNextID(); book enterBookData(); void delBook(); int writeBookFile(); void menu(); void checkOut(); void checkIn(); void sort(); /**************************************************** * Function: main() * * Description: What is there to explain.. * * Parameters: argv (the string of all parameters), * argc (the count of all input aruments) * * return parameters: int, 0 = OK, 1 = Error ****************************************************/ int main(int argc, char **argv) { /* declaration of the return parameter */ int isOK = 0; /* first read the input file for the Library */ isOK = readBookFile(); /* the menu is the main controll structure */ menu(); /* last write the changes made to the Library file */ isOK = writeBookFile(); /* pause the system, so we see its over */ //system("pause"); system( "read -n 1 -s -p \"Press any key to continue...\"" ); /* return 1 = Error, 0 = ok */ return isOK; } /********************************************* * Function: readBookFile() * * Description: Read the csv file into a books arrray * * Parameters: none * * Return parameters: none * ********************************************/ int readBookFile() { /* FileStream for the Library File */ FILE *bookFile; /* allocation of the buffer for every line in the File */ char *buf = malloc(MAX_STR_LEN); char *tmp; /* if the space could not be allocaed, return an error */ if (buf == NULL) { printf ("No memory\n"); return 1; } /* chack if the file can really be loaded into the stream */ if ( ( bookFile = fopen( PATH , "r" ) ) == NULL ) //Reading a file { printf( "File could not be opened.\n" ); return 1; } int i = 0; /* read every line of the inputfile to an element of the books array */ while (fgets(buf, 255, bookFile) != NULL) { /* this is to check if the files last line was reached last turn */ if(ferror(bookFile)) { break; } /* if we don't chech for newline we skip every second line */ if ((strlen(buf)&gt;0) &amp;&amp; (buf[strlen (buf) - 1] == '\n')) buf[strlen (buf) - 1] = '\0'; /* read the ID and cast it to an Integer */ tmp = strtok(buf, ";"); books[i].ID = atoi(tmp); /* to give the value of the tmp part of the csv string to books[i] we need to copy the string! */ tmp = strtok(NULL, ";"); strcpy( books[i].name, tmp); tmp = strtok(NULL, ";"); strcpy(books[i].dateIn, tmp); tmp = strtok(NULL, ";"); strcpy(books[i].dateOut, tmp); tmp = strtok(NULL, ";"); books[i].isIn = atoi(tmp); // printf("index i= %i ID: %i, %s, %s, %s \n",i, books[i].ID , books[i].name, books[i].dateIn , books[i].dateOut); /* increment for next book in books[] */ i++; } /* free the buffer */ free(buf); /* close the filestream */ fclose(bookFile); return 0; } /********************************************* * Function: printBookList() * * Description: Print the Array of books to the console * * Parameters: none * * Return parameters: none * ********************************************/ void printBookList() { int i; sort(); printf("ID: \t Title: \t\t Dateout: \tDate in:\tOut? \n"); printf("------------------------------------------------------------------------\n"); for (i = 0; i &lt;= MAX_BOOKS; i++) { /* only do this until the last is printed, as 256 are allocated by default */ if (books[i].ID != 0) /* the %.15s means only the first 15 characters of the string will be printed */ printf("ID: %i\t %.15s \t %s \t%s\t\t%i \n", books[i].ID , books[i].name, books[i].dateIn , books[i].dateOut, books[i].isIn); else break; } printf("------------------------------------------------------------------------\n"); } /********************************************* * Function: addBook() * * Description: add a new book to the books[] array * * Parameters: none * * Return parameters: none * ********************************************/ void addBook() { /* the function enterBookData return the new book */ book bin = enterBookData(); int newID = 0; /* the getNextID returns the next free ID number */ newID = getNextID(); books[newID].ID= newID + 1; strcpy(books[newID].name, bin.name); strcpy(books[newID].dateIn, bin.dateIn); strcpy(books[newID].dateOut, bin.dateOut); books[newID].isIn = bin.isIn; } /********************************************* * Function: getNextID() * * Description: returns the next free index of the books[] array * * Parameters: none * * Return parameters: int, the next free index of books[] * ********************************************/ int getNextID() { int i; for (i = 0; i &lt;= MAX_BOOKS; i++) { if (books[i].ID == 0) break; } return i; } /********************************************* * Function: enterBookData() * * Description: get the user input of every Attribute * * Parameters: none * * Return parameters: the new book * ********************************************/ book enterBookData() { book b1 = {0,"","",""}; char tmp[MAX_STR_LEN]; printf("Titel: "); fgets(tmp, MAX_STR_LEN, stdin); if ((strlen(tmp)&gt;0) &amp;&amp; (tmp[strlen (tmp) - 1] == '\n')) tmp[strlen (tmp) - 1] = '\0'; strcpy(b1.name, tmp); /* free the standard in, ohterwise you will encounter problems if the enterd string is too long */ fpurge(stdin); printf("datein (DDMMYY):"); fgets(tmp, DATE_LEN, stdin); if ((strlen(tmp)&gt;0) &amp;&amp; (tmp[strlen (tmp) - 1] == '\n')) tmp[strlen (tmp) - 1] = '\0'; strcpy(b1.dateIn, tmp); fpurge(stdin); printf("dateout (DDMMYY): "); fgets(tmp, DATE_LEN, stdin); if ((strlen(tmp)&gt;0) &amp;&amp; (tmp[strlen (tmp) - 1] == '\n')) tmp[strlen (tmp) - 1] = '\0'; strcpy(b1.dateOut, tmp); fpurge(stdin); printf("is it in? (1 = yes, 0 = no): "); fgets(tmp, 2, stdin); if ((strlen(tmp)&gt;0) &amp;&amp; (tmp[strlen (tmp) - 1] == '\n')) tmp[strlen (tmp) - 1] = '\0'; b1.isIn= atoi(tmp); fpurge(stdin); return b1; } /********************************************* * Function: delBook() * * Description: deletes the index of the books[] array the user choose * * Parameters: none * * Return parameters: none * ********************************************/ void delBook() { char ids[3]; int id = 0, c; printf("Enter linenumber of book to delete. \n"); fgets(ids, MAX_STR_LEN, stdin); if ((strlen(ids)&gt;0) &amp;&amp; (ids[strlen (ids) - 1] == '\n')) ids[strlen (ids) - 1] = '\0'; id= atoi(ids); if (id &gt; MAX_BOOKS) id = MAX_BOOKS; for ( c = id - 1 ; c &lt; MAX_BOOKS - 1 ; c++ ) books[c] = books[c+1]; fflush(stdin); } /********************************************* * Function: writeBookFile() * * Description: writes the array of books[] to the file (overwrites) * * Parameters: none * * Return parameters: int, could the file be written? 1 = no, 0 = yes * ********************************************/ int writeBookFile() { /* FileStream for the Library File */ FILE *bookFile; if ( ( bookFile = fopen( PATH, "w" ) ) == NULL ) //Reading a file { printf( "File could not be opened.\n" ); return 1; } int i; for(i = 0; i &lt; MAX_BOOKS;i++) { if(books[i].ID != 0) { fprintf(bookFile, "%i;%s;%s;%s;%i\n", books[i].ID, books[i].name, books[i].dateIn, books[i].dateOut, books[i].isIn); } } fclose(bookFile); return 0; } /********************************************* * Function: menu() * * Description: the main menu, logic and printfs * * Parameters: none * * Return parameters: none * ********************************************/ void menu() { char choice[1]; while(choice[0] != '5') { system("clear"); //printf("\33[2J"); printBookList(); printf("1. Add book \n"); printf("2. Delete book \n"); printf("3. Check out book \n"); printf("4. Check in book \n"); printf("5. Quit \n"); printf("Please enter the number of your choice: "); fgets(choice, 2, stdin); fpurge(stdin); switch(choice[0]) { case '1': { addBook(); break; } case '2': { delBook(); break; } case '3': { checkOut(); break; } case '4': { checkIn(); break; } } } } /********************************************* * Function: checkOut() * * Description: To check out a book, the user chooses the ID and then sets the isIn attribute of the book to 0 * * Parameters: none * * Return parameters: none * ********************************************/ void checkOut() { char tmp[3]; int i = 0; printf("Please enter the ID of the book beeing checked out: "); fgets(tmp, 4, stdin); if ((strlen(tmp)&gt;0) &amp;&amp; (tmp[strlen (tmp) - 1] == '\n')) tmp[strlen (tmp) - 1] = '\0'; fflush(stdin); for (i = 0; i &lt; MAX_BOOKS;i++) { if(books[i].ID == atoi(tmp)) { if (books[i].isIn == 0) { printf("Book allready checked out!\n"); system("pause"); } else { books[i].isIn = 0; } break; } } } /********************************************* * Function: checkIn() * * Description: To check in a book, the user chooses the ID and then sets the isIn attribute of the book to 1 * * Parameters: none * * Return parameters: none * ********************************************/ void checkIn() { char tmp[3]; int i = 0; printf("Enter ID of the book beeing returned: "); fgets(tmp, 4, stdin); if ((strlen(tmp)&gt;0) &amp;&amp; (tmp[strlen (tmp) - 1] == '\n')) tmp[strlen (tmp) - 1] = '\0'; fflush(stdin); for (i = 0; i &lt; MAX_BOOKS;i++) { if(books[i].ID == atoi(tmp)) { if (books[i].isIn == 1) { printf("Book allready checked here!\n"); system("pause"); } else { books[i].isIn = 1; } break; } } } /********************************************* * Function: sort() * * Description: sorts the Array of books by ID * Algorythmus: Bubblsort * Parameters: none * * Return parameters: none * ********************************************/ void sort() { /* first find out how many indexes there are */ int h; for (h = 0; h&lt; MAX_BOOKS; h++) { if (books[h].ID == 0) { break; } } int j = 0; int swaped = 1; struct book temp; while (swaped == 1) //bubble sort on the book name { swaped = 0; for(j=0;j&lt; h -1 ;j++) { if(books[j].ID &gt; books[j + 1].ID) { //copy to temp val temp.ID = books[j].ID; strcpy(temp.name,books[j].name); strcpy(temp.dateIn,books[j].dateIn); strcpy(temp.dateOut,books[j].dateOut); temp.isIn = books[j].isIn; //copy next val books[j].ID = books[j + 1].ID; strcpy(books[j].name,books[j + 1].name); strcpy(books[j].dateIn,books[j + 1].dateIn); strcpy(books[j].dateOut,books[j + 1].dateOut); books[j].isIn = books[j + 1].isIn; //copy back temp val books[j + 1].ID = temp.ID; strcpy(books[j+ 1].name,temp.name); strcpy(books[j + 1].dateIn,temp.dateIn); strcpy(books[j + 1].dateOut,temp.dateOut); books[j + 1].isIn = temp.isIn; swaped = 1; } } } } void mutateBook(book b) { printf("What do you want to change?\n"); } </code></pre>
[]
[ { "body": "<p>You don't need the two definitions of book:</p>\n\n<pre><code>typedef struct {..} book ;\nstruct book {..} ;\n</code></pre>\n\n<p>What I would normally do is:</p>\n\n<pre><code>typedef struct Book {\n...\n} Book ;\n</code></pre>\n\n<p>This allows you to write either:</p>\n\n<pre><code>struct Book b1 ;\nBook b1 ;\n</code></pre>\n\n<p>and in both cases get a Book structure. it also means i can refer to a Book structure within a Book structure:</p>\n\n<pre><code>typedef struct Book {\n ...\n struct Book* prequel ;\n} Book ;\n</code></pre>\n\n<p>I'd change the name of the structure and typedef to Book as most coding standards call for structs and typedefs to have an initial capital letter.</p>\n\n<p>In a lot of places you'll see the typedef and the structure given different names, </p>\n\n<pre><code>typedef struct Book_ {...} Book_T ;\n</code></pre>\n\n<p>it's up to you to decide what you find easiest to use; I said I like to use the same name for both.</p>\n\n<p>Another thing to look at is the readBookFile function, from reading the code I think you need to look at the following:</p>\n\n<p>You use malloc() to allocate the buffer that the file is read into; however you never free the memmory that is allocated by malloc. It's good practice to make sure that every malloc ends up being freed in every route through the function.</p>\n\n<p>You don't check the return value of malloc; in a program like yours it's very unlikely that the malloc call will fail; however you should check the return value.</p>\n\n<p>Do you even need to use malloc here? If you allocate the buffer on the stack then you don't need to worry about freeing it.</p>\n\n<p>The call to fgets() has the magic number 255 in it, you can and should just use the MAX_STR_LEN #define that you created and used in the malloc. Read the man page for fgets(), it tells you that the function already knows that the last char is resevered for a terminating NULL.</p>\n\n<p>The strtok() function call returns NULL if there are no more tokens, again this is something you should check. </p>\n\n<p>You have virtually identical code repeated several times when you call strtok() for each field, you should consider extracting this out into it's own function.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-01-22T17:19:31.433", "Id": "66802", "Score": "0", "body": "This is so cool.. I've been asking myself why it didn't work before I had both decinitions. Now I know :-)" } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-01-22T15:26:40.920", "Id": "39819", "ParentId": "39795", "Score": "4" } }, { "body": "<pre><code>#define MAX_STR_LEN 256\n#define MAX_BOOKS 10\n#define DATE_LEN 8\n</code></pre>\n\n<p>How do you choose these numbers? Does you code ensure that data in the file doesn't exceed these numbers?</p>\n\n<p>In fact your readBookFile function has a bug: if the title of a book is nearly MAX_STR_LEN then the length of the whole file-line is greater than MAX_STR_LEN and won't fit into buffer.</p>\n\n<hr>\n\n<pre><code>/* array of my books */\n</code></pre>\n\n<p>See @Jackson's answer.</p>\n\n<hr>\n\n<pre><code>/* PROTOTYPE OF FUNCTIONS */\n</code></pre>\n\n<p>If you define main at the end of the file, then you may not need these functional <em>declarations</em> because instead you'll have the function <em>definitions</em> already defined, above main, before they're used from main.</p>\n\n<hr>\n\n<pre><code> * Description: What is there to explain..\n *\n * Parameters: argv (the string of all parameters),\n * argc (the count of all input aruments)\n</code></pre>\n\n<p>Too many useless comments?</p>\n\n<hr>\n\n<pre><code>isOK = readBookFile();\n</code></pre>\n\n<p>You don't test isOK or do anything to recover or exit gracefully (for example, print an error message and return early before trying to write), if readBookFile fails.</p>\n\n<p>In general, assigning to a variable and then not reading/using the value in the variable is suspicious: if you don't read/use it, why assign/remember it in the first place?</p>\n\n<hr>\n\n<pre><code>system( \"read -n 1 -s -p \\\"Press any key to continue...\\\"\" );\n</code></pre>\n\n<p>I don't know the <code>system</code> function. Why not <code>printf</code> instead?</p>\n\n<hr>\n\n<pre><code>FILE *bookFile;\n</code></pre>\n\n<p>I like to delay my variable definition until the later line of code (immediately before the <code>if ( ( bookFile</code> statement) when I can actually assign a value to it. In general, any uninitialized variable is dangerous.</p>\n\n<hr>\n\n<pre><code>printf (\"No memory\\n\");\n</code></pre>\n\n<p>You use whitespace inconsistently: normal style is no whitespace between the function name and its open parenthesis.</p>\n\n<hr>\n\n<pre><code>while (fgets(buf, 255, bookFile) != NULL)\n</code></pre>\n\n<p>I think you meant MAX_STR_LEN not <code>255</code>. What if you change the definition of MAX_STR_LEN? You don't want to hunt through the rest of your source code looking for other <code>255</code> instances to change.</p>\n\n<p>Also to fix the bug I mentioned earlier, buf and fgets should use MAX_BOOK_LEN not MAX_STR_LEN:</p>\n\n<pre><code>#define MAX_BOOK_LEN sizeof(Book) + 1\n</code></pre>\n\n<p>This expression for MAX_BOOK_LEN based on sizeof(Book) assumes that Book.title is an array inside Book (which, it is at the moment), not a pointer to a variable/infinite length title allocated via malloc (which, you might change it to sometime in the future).</p>\n\n<hr>\n\n<pre><code> /* if we don't chech for newline we skip every second line */\n if ((strlen(buf)&gt;0) &amp;&amp; (buf[strlen (buf) - 1] == '\\n'))\n buf[strlen (buf) - 1] = '\\0';\n</code></pre>\n\n<p>You're calling <code>strlen(buf)</code> several times. If you want it to be (very slightly) faster then only call it once:</p>\n\n<pre><code> size_t buflen = strlen(buf);\n if ((buflen &gt; 0) &amp;&amp; (buf[buflen - 1] == '\\n'))\n buf[buflen - 1] = '\\0';\n</code></pre>\n\n<hr>\n\n<pre><code>if(ferror(bookFile))\n</code></pre>\n\n<p>This isn't necessary according to my reading of <a href=\"http://www.cplusplus.com/reference/cstdio/fgets/\" rel=\"nofollow\">some documentation</a>: because if there is any error then <code>fgets</code> would return null.</p>\n\n<p>You might like to call it before you return, so that you can use its return code to say whether there was an error reading from the input file:</p>\n\n<pre><code>/* check for error */\nint returncode = ferror(bookFile);\n\n/* free the buffer */\nfree(buf);\n\n/* close the filestream */\nfclose(bookFile);\n\nreturn returncode; /* 0 if all reads were successful */\n</code></pre>\n\n<hr>\n\n<pre><code>/* the getNextID returns the next free ID number */\nnewID = getNextID();\n\nbooks[newID].ID= newID + 1;\n</code></pre>\n\n<p>This was confusing: I wondered, why do you increment the next ID before using it? Don't you want to increment the current ID, or not increment to next ID?</p>\n\n<p>To avoid this confusion, perhaps rename the getNextID() function to getEmptyIndex(), and add a comment to your <code>newID = getEmptyIndex() + 1;</code> statement to say that indexes are 0-based whereas IDs are 1-based.</p>\n\n<hr>\n\n<pre><code>printf(\"datein (DDMMYY):\");\n</code></pre>\n\n<p>Perhaps you should verify the format and length of what was entered, and ask the user to retry or quit if it's the wrong syntax.</p>\n\n<hr>\n\n<p>There are several places, i.e. in addBook and in sort, where you use a series of statements like:</p>\n\n<pre><code>books[newID].ID= newID + 1;\nstrcpy(books[newID].name, bin.name);\nstrcpy(books[newID].dateIn, bin.dateIn);\nstrcpy(books[newID].dateOut, bin.dateOut);\nbooks[newID].isIn = bin.isIn;\n</code></pre>\n\n<p>What happens if you add a new field to Book (for example, author) in the future? You'd have to change these statements in several places. Better to have a new common subroutine,</p>\n\n<pre><code>void memcpyBook(Book* toBook, const Book* fromBook) { ... }\n</code></pre>\n\n<hr>\n\n<p>I'm worried about linking ID to index. If you do the following:</p>\n\n<ol>\n<li>Create or read several books</li>\n<li>Delete some books from the middle of the array</li>\n<li>Sort the books</li>\n</ol>\n\n<p>Then the IDs no longer match the array indexes. If you then add another book, you'll find the empty index and maybe create a duplicate Book ID.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-01-23T13:44:35.960", "Id": "39872", "ParentId": "39795", "Score": "3" } } ]
{ "AcceptedAnswerId": "39872", "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-01-22T10:46:01.060", "Id": "39795", "Score": "6", "Tags": [ "c", "beginner", "parsing", "library" ], "Title": "Educational \"Library\" project" }
39795
<p>I'm new to jQuery/JSON and I've build an dynamic toggle system. It work fine, but I'm not sure about my code and I want a better way of building this.</p> <p>Could you please see my code and give comments/solutions/explanations for a better structure for this system?</p> <p>NOTE: All JSON files are the same build</p> <pre><code>$(document).ready(function() { $(".color-list.one li:nth-child(2)").on('click', function() { $.getJSON("json/a2.json", function(data) { //Handle my response $('ul.elements-list').html( '&lt;li class="elements-item"&gt;&lt;span class="tog"&gt;' + data.Atitle + '&lt;/span&gt;'+ '&lt;div class="togcont hidden"&gt;'+ '&lt;ul class="elements-link"&gt;'+ '&lt;li&gt;&lt;a href=' + data.AAurlElement + '&gt;' + data.AAnameElement + '&lt;/a&gt;&lt;/li&gt;'+ '&lt;li&gt;&lt;a href=' + data.ABurlElement + '&gt;' + data.ABnameElement + '&lt;/a&gt;&lt;/li&gt;'+ '&lt;/ul&gt;'+ '&lt;/div&gt;&lt;/li&gt;'); $('ul.elements-list').append( '&lt;li class="elements-item"&gt;&lt;span class="tog"&gt;' + data.Btitle + '&lt;/span&gt;'+ '&lt;div class="togcont hidden"&gt;'+ '&lt;ul class="elements-link"&gt;'+ '&lt;li&gt;&lt;a href=' + data.BAurlElement + '&gt;' + data.BAnameElement + '&lt;/a&gt;&lt;/li&gt;'+ '&lt;/ul&gt;'+ '&lt;/div&gt;&lt;/li&gt;'); }); }); $(".color-list.one li:nth-child(3)").on('click', function() { $.getJSON("json/a3.json", function(data) { //Handle my response $('ul.elements-list').html( '&lt;li class="elements-item"&gt;&lt;span class="tog"&gt;' + data.Btitle + '&lt;/span&gt;'+ '&lt;div class="togcont hidden"&gt;'+ '&lt;ul class="elements-link"&gt;'+ '&lt;li&gt;&lt;a href=' + data.BAurlElement + '&gt;' + data.BAnameElement + '&lt;/a&gt;&lt;/li&gt;'+ '&lt;li&gt;&lt;a href=' + data.BBurlElement + '&gt;' + data.BBnameElement + '&lt;/a&gt;&lt;/li&gt;'+ '&lt;/ul&gt;'+ '&lt;/div&gt;&lt;/li&gt;'); }); }); $(".color-list.one li:nth-child(4)").on('click', function() { $.getJSON("json/a4.json", function(data) { //Handle my response $('ul.elements-list').html( '&lt;li class="elements-item"&gt;&lt;span class="tog"&gt;' + data.Atitle + '&lt;/span&gt;'+ '&lt;div class="togcont hidden"&gt;'+ '&lt;ul class="elements-link"&gt;'+ '&lt;li&gt;&lt;a href=' + data.AAurlElement + '&gt;' + data.AAnameElement + '&lt;/a&gt;&lt;/li&gt;'+ '&lt;li&gt;&lt;a href=' + data.ABurlElement + '&gt;' + data.ABnameElement + '&lt;/a&gt;&lt;/li&gt;'+ '&lt;li&gt;&lt;a href=' + data.ACurlElement + '&gt;' + data.ACnameElement + '&lt;/a&gt;&lt;/li&gt;'+ '&lt;/ul&gt;'+ '&lt;/div&gt;&lt;/li&gt;'); $('ul.elements-list').append( '&lt;li class="elements-item"&gt;&lt;span class="tog"&gt;' + data.Btitle + '&lt;/span&gt;'+ '&lt;div class="togcont hidden"&gt;'+ '&lt;ul class="elements-link"&gt;'+ '&lt;li&gt;&lt;a href=' + data.BAurlElement + '&gt;' + data.BAnameElement + '&lt;/a&gt;&lt;/li&gt;'+ '&lt;/ul&gt;'+ '&lt;/div&gt;&lt;/li&gt;'); }); }); $(".color-list.one li:nth-child(5)").on('click', function() { $.getJSON("json/a5.json", function(data) { //Handle my response $('ul.elements-list').html( '&lt;li class="elements-item"&gt;&lt;span class="tog"&gt;' + data.Atitle + '&lt;/span&gt;'+ '&lt;div class="togcont hidden"&gt;'+ '&lt;ul class="elements-link"&gt;'+ '&lt;li&gt;&lt;a href=' + data.AAurlElement + '&gt;' + data.AAnameElement + '&lt;/a&gt;&lt;/li&gt;'+ '&lt;li&gt;&lt;a href=' + data.ABurlElement + '&gt;' + data.ABnameElement + '&lt;/a&gt;&lt;/li&gt;'+ '&lt;li&gt;&lt;a href=' + data.ACurlElement + '&gt;' + data.ACnameElement + '&lt;/a&gt;&lt;/li&gt;'+ '&lt;/ul&gt;'+ '&lt;/div&gt;&lt;/li&gt;'); $('ul.elements-list').append( '&lt;li class="elements-item"&gt;&lt;span class="tog"&gt;' + data.Btitle + '&lt;/span&gt;'+ '&lt;div class="togcont hidden"&gt;'+ '&lt;ul class="elements-link"&gt;'+ '&lt;li&gt;&lt;a href=' + data.BAurlElement + '&gt;' + data.BAnameElement + '&lt;/a&gt;&lt;/li&gt;'+ '&lt;/ul&gt;'+ '&lt;/div&gt;&lt;/li&gt;'); }); }); $('ul.elements-list').on("click", ".tog", function(){ var obj = $(this).next(); if(obj.hasClass("hidden")){ obj.removeClass("hidden").slideDown(); $(this).addClass("bounce"); } else { obj.addClass("hidden").slideUp(); $(this).removeClass("bounce"); } }); }); </code></pre> <p>The structure of my json files :</p> <pre><code>{ "Atitle": "Master Title A", "AAnameElement": "name 1", "ABnameElement": "name 2", "ACnameElement": "name 3", "AAurlElement" : "url1.html", "ABurlElement" : "url2.html", "ACurlElement" : "url3.html", "Btitle": "Master Title B", "BAurlElement" : "urlB1.html", "BAnameElement": "name B1" } </code></pre>
[]
[ { "body": "<p>You are definitely repeating a ton of code, as far as I can tell the following is true</p>\n\n<ul>\n<li>You always set the html <code>$('ul.elements-list')</code> to show either an <code>.A</code> or <code>.B</code> list</li>\n<li>The amount of elements varies, but it seems to be never more than 3</li>\n<li>Optionally if the <code>.A</code> is shown, you might also show a <code>.B</code> list</li>\n<li>The <code>.A</code> list always comes before the <code>.B</code> list</li>\n</ul>\n\n<p>From there you could build a function that takes the amount of A and B list entries to display</p>\n\n<pre><code>function buildTable(data, config) {\n var title = data[config.prefix + 'title'],\n output = '&lt;li class=\"elements-item\"&gt;' +\n '&lt;span class=\"tog\"&gt;' + title + '&lt;/span&gt;' +\n '&lt;div class=\"togcont hidden\"&gt;' +\n '&lt;ul class=\"elements-link\"&gt;',\n i, rowId,url,name;\n\n for( i = 0 ; i &lt; config.rows ; i++)\n {\n //ASCII, 65 -&gt; A, 66 -&gt; B etc.\n rowId = config.prefix + String.fromCharCode( 65+i );\n url = data[rowId + 'urlElement'];\n name = data[rowId + 'nameElement'];\n output += ' &lt; li &gt; &lt; a href = ' + url + ' &gt; ' + name + ' &lt; /a&gt;&lt;/li &gt; '\n }\n\n output += ' &lt; /ul&gt;&lt;/div &gt; &lt; /li&gt;';\n return output\n}\n\nfunction buildTables( data , config )\n{\n var html = \"\"\n for( var i = 0; i &lt; config.length ; i++ ){\n html += buildTable( data , config[i] );\n }\n $('ul.elements-list').html( html );\n}\n</code></pre>\n\n<p>From there you can simply change your listeners to </p>\n\n<pre><code>$.getJSON(\"json/a2.json\", function(data) {\n buildTables( data , [ { prefix : \"A\" , rows : 2 } , { prefix : \"B\" , rows : 1 } ] );\n});\n\n$.getJSON(\"json/a3.json\", function(data) {\n buildTables( data , [ { prefix : \"B\" , rows : 2 } ] );\n});\n\n$.getJSON(\"json/a4.json\", function(data) {\n buildTables( data , [ { prefix : \"A\" , rows : 3 } , { prefix : \"B\" , rows : 1 } ] );\n});\n</code></pre>\n\n<p>etc. etc. </p>\n\n<p>I did not test the code, however it should give you an insight how to build this yourself.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-01-22T19:37:35.397", "Id": "66821", "Score": "0", "body": "Waouhh, thanks but i'm newbies and i'm not sure to understand the synthax and the close tag! I've test your code and i can't do work it!" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-01-22T19:48:31.227", "Id": "66823", "Score": "0", "body": "I've edited my code with add the structure of my json files!" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-01-22T19:51:16.600", "Id": "66824", "Score": "1", "body": "Thanks, I cleaned up my code so that at least there are no more syntax errors. Still, this might be too big a jump for you :\\ Is there any part that needs to be explained better/extra ?" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-01-22T20:01:26.920", "Id": "66826", "Score": "0", "body": "Thanks, I've a hard time with endings (parenthesis, brackets, semi-colons ... etc). so, where i must put the $(document)ready (function () { and my toggle system function please?" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-01-23T15:04:19.413", "Id": "66922", "Score": "0", "body": "Hi, Thanks for the great help @konijn but i tried to use your code but I don't organize! I can't put well my \"toggle\" function and all others code neccessary!" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-01-23T15:39:31.077", "Id": "66924", "Score": "0", "body": "Hmmm, since you are dealing with JSON, it is tricky to set up a fiddle.. I am not sure I can help you out there, if my advice is too advanced then you will have trouble maintaining it.. I would say leave your code as is for now and come back to it once you feel more comfortable in JavaScript." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-01-23T17:18:16.113", "Id": "66932", "Score": "0", "body": "Ok lot of thanks ! ;-) i've resolved push" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-01-23T17:24:23.670", "Id": "66933", "Score": "0", "body": "Just one more question ! is that the spaces in the html tags (in your code) are very important?" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-01-23T17:28:11.857", "Id": "66934", "Score": "0", "body": "OHHHHH !!!!! WAOUHHHHHHHH !!!! IT WORKS PERFECTLY !!! I finally managed to make focntionner your code!" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-01-23T17:30:28.633", "Id": "66935", "Score": "0", "body": "Happy to make it fonctionne ;)" } ], "meta_data": { "CommentCount": "10", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-01-22T14:21:12.733", "Id": "39807", "ParentId": "39796", "Score": "4" } } ]
{ "AcceptedAnswerId": "39807", "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-01-22T10:47:10.380", "Id": "39796", "Score": "6", "Tags": [ "javascript", "jquery", "beginner", "json" ], "Title": "Dynamic toggle system" }
39796
<p>Currently working on writing out some test for an iOS enterprise application. My concern is in this set up of my overloaded constructor.</p> <pre><code>- (id)init { CRMHttpClient *client = [CRMHttpClient sharedClient]; NSOperationQueue *queue = [NSOperationQueue new]; UIApplication *application = [UIApplication sharedApplication]; return [self initWithCRMHttpClient:client operationQueue:queue application:application]; } - (id) initWithCRMHttpClient:(CRMHttpClient *)client operationQueue:(NSOperationQueue *)operationQueue application:(UIApplication *)application { self = [super init]; if(self) { self.client = client; self.queue = operationQueue; self.queue.name = [[NSBundle.mainBundle bundleIdentifier] stringByAppendingString:@".CRMDataProcessingQueue"]; self.queue.maxConcurrentOperationCount = 2; self.application = application; self.backgroundTask = UIBackgroundTaskInvalid; } return self; } </code></pre> <p><code>-(id)init</code> is called by the other classes in the project. <code>-(id)initWithCRMHttpClient:...</code> is called in my test class so I can inject my mocks to unit test my class. (I know I could use partial mocks for the singleton classes, but I prefer to explicitly inject the class) What bothers me about this approach is the few lines of code where I'm configuring my <code>NSOperationQueue</code>'s name and operation count. This requires me to write this up in my <code>-(void)setup</code> method of my testing class.</p> <pre><code>- (void)setUp { [super setUp]; self.mockCRMHttpClient = [OCMockObject mockForClass:[CRMHttpClient class]]; self.mockOperationQueue = [OCMockObject mockForClass:[NSOperationQueue class]]; [[self.mockOperationQueue stub] setName:OCMOCK_ANY]; [[self.mockOperationQueue stub] setMaxConcurrentOperationCount:2]; self.mockApplication = [OCMockObject mockForClass:[UIApplication class]]; } </code></pre> <p>I need to stub out the calls for those set up methods so that I don't get failed calls. I my options are:</p> <ol> <li>Leave it as is, stubbing in the <code>-setup</code></li> <li>Configure the operation queue in the <code>-init</code> method instead.</li> <li>Create a nice mock for <code>mockOperationQueue</code></li> <li>Am I forgetting something?</li> </ol> <p>I'm unsure of which approach to take.</p>
[]
[ { "body": "<p>Go with #3, \"Create a nice mock for <code>mockOperationQueue</code>.\" The only reason you're having to do that stubbing is that OCMock creates \"strict\" mocks by default. Strict mocks used to be the standard, but mock object frameworks have evolved. The problem with strict mocking is that they make tests more brittle.</p>\n\n<p>For example, let's say you find the need to add another \"this needs to happen when I'm setting up the operation queue\" call. Suddenly, your tests will break, because the strict mock will complain, \"I don't know what this new call is.\" You've coded things well by setting up the mock operation queue in one place, so fixing it wouldn't be hard; you'd just add another stub in your <code>-setUp</code>. But the test failure isn't a failure; it's noise.</p>\n\n<p>OCMock was originally written when strict mocks were the norm. It was also the norm then to state expectations first, call the method of interest, then ask the mock to verify itself:</p>\n\n<pre><code>[mockView expect] addTweet:[OCMArg any];\n\n[controller displayTweets];\n\n[mockView verify];\n</code></pre>\n\n<p>But mock object frameworks have evolved since then. People figured out that <a href=\"https://stackoverflow.com/a/3135022/246895\">having non-strict mocks was almost never a problem</a>. And new frameworks came along that state the expectation after calling the method of interest. Using <a href=\"https://github.com/jonreid/OCMockito\" rel=\"nofollow noreferrer\">OCMockito</a>, the example above changes to:</p>\n\n<pre><code>[controller displayTweets];\n\n[verify(mockView) addTweet:anything()];\n</code></pre>\n\n<p>This restores the standard order of unit tests: \"Arrange - Act - Assert\" (or if you prefer, \"Given - When - Then\"). The verification of expectations now happens in the Assert phase, rather than sitting up in the Arrange phase. So now the test code reads more naturally, like a DSL.</p>\n\n<p>The author of OCMock recognizes the importance of this evolution, and <a href=\"https://twitter.com/erikdoe/status/424904652115959809\" rel=\"nofollow noreferrer\">has stated</a>: </p>\n\n<blockquote>\n <p>The next major version of OCMock is planned to support nice-by-default\n and verification of specific calls after the fact.</p>\n</blockquote>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-04-12T00:36:03.013", "Id": "82266", "Score": "0", "body": "To answer your now deleted comment, I was one of the first downvoters; then you changed your answer to include more helpful information. Sorry for any anxiety that may have been caused. You should join us in [our chat room](http://chat.stackexchange.com/rooms/8595/the-2nd-monitor) sometime, we need another Objective-C guru!" } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-02-16T06:38:58.263", "Id": "41778", "ParentId": "39808", "Score": "5" } } ]
{ "AcceptedAnswerId": "41778", "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-01-22T14:24:01.643", "Id": "39808", "Score": "5", "Tags": [ "unit-testing", "objective-c", "ios", "http" ], "Title": "Configuring Constructor Parameters and Unit Testing" }
39808
<p>I'm looking to simplify the initialisation of the second constant, preferably to just one line. Any ideas? Anything from Guava or JDK (up to 1.6) is ok to use.</p> <pre><code>enum Box { PROMO_HEADER, FREEMIUM, EXTRA_STORIES, TOP_STORIES, TOP_CHARACTERS, TOP_THEMES, TOP_ARTISTS, TOP_ISSUES // several more ... } final static List&lt;Box&gt; FREEMIUM_BOXES = ImmutableList.copyOf(Box.values()); final static List&lt;Box&gt; DEFAULT_BOXES = initDefaultBoxes(); // All except FREEMIUM static List&lt;Box&gt; initDefaultBoxes() { List&lt;Box&gt; boxes = Lists.newArrayList(FREEMIUM_BOXES); boxes.remove(Box.FREEMIUM); return ImmutableList.copyOf(boxes); } </code></pre> <p>Granted, it's not <em>that</em> bad, but still I'd like to get rid of the init method. :-) (Static initialiser wouldn't be any better.) </p> <p>NB: I want to define the <em>order</em> of boxes only once, in the enum definition itself, so <code>ImmutableList.of(PROMO_HEADER, EXTRA_STORIES, ...)</code> is not considered a good solution for the purposes of this refactoring.</p> <hr> <p>A single-statement Guava solution would be this, using <code>filter()</code> and a Predicate, but arguably this is less clean than the original, because this kind of stuff is verbose in Java...</p> <pre><code>final static List&lt;Box&gt; DEFAULT_BOXES = ImmutableList.copyOf(Iterables.filter(FREEMIUM_BOXES, new Predicate&lt;Box&gt;() { @Override public boolean apply(Box box) { return box != Box.FREEMIUM; } })); </code></pre> <h2>Resolution</h2> <p>Went with this, which is the cleanest option considering I indeed need the constants defined as Lists:</p> <pre><code>final static List&lt;Box&gt; FREEMIUM_BOXES = ImmutableList.copyOf(Box.values()); final static List&lt;Box&gt; DEFAULT_BOXES = Sets.immutableEnumSet(EnumSet.complementOf(EnumSet.of(Box.FREEMIUM))).asList(); </code></pre> <p><a href="https://codereview.stackexchange.com/a/39821/5665">Props to Xaerxess</a>!</p>
[]
[ { "body": "<p>Use <a href=\"http://docs.oracle.com/javase/7/docs/api/java/util/EnumSet.html\"><code>EnumSet</code></a> for that. From docs:</p>\n\n<blockquote>\n <p>A specialized Set implementation for use with enum types. (...) The iterator returned by the iterator method traverses the elements in their natural order (the order in which the enum constants are declared).</p>\n</blockquote>\n\n<p>It's also very efficent:</p>\n\n<blockquote>\n <p>Implementation note: All basic operations execute in constant time.\n They are likely (though not guaranteed) to be much faster than their\n HashSet counterparts. Even bulk operations execute in constant time if\n their argument is also an enum set.</p>\n</blockquote>\n\n<p>So in your case:</p>\n\n<pre><code>final static Set&lt;Box&gt; DEFAULT_BOXES = \n EnumSet.complementOf(EnumSet.of(Box.FREEMIUM));\n</code></pre>\n\n<p>or if you prefer immutable one, use <a href=\"http://docs.guava-libraries.googlecode.com/git-history/release/javadoc/com/google/common/collect/Sets.html#immutableEnumSet%28java.lang.Iterable%29\"><code>Sets.immutableEnumSet(Iterable)</code></a>:</p>\n\n<pre><code>final static ImmutableSet&lt;Box&gt; DEFAULT_BOXES = \n Sets.immutableEnumSet(EnumSet.complementOf(EnumSet.of(Box.FREEMIUM)));\n</code></pre>\n\n<p>or if you insist for <code>List</code> (but why would you?):</p>\n\n<pre><code>final static ImmutableList&lt;Box&gt; DEFAULT_BOXES = \n Sets.immutableEnumSet(EnumSet.complementOf(EnumSet.of(Box.FREEMIUM))).asList();\n</code></pre>\n\n<p>P.S. All constants can be represented as:</p>\n\n<pre><code>final static Set&lt;Box&gt; FREEMIUM_BOXES = EnumSet.allOf(Box.class); // or wrap it with Sets.immutableEnumSet to make it ImmutableSet\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-01-22T15:44:18.883", "Id": "66786", "Score": "0", "body": "Why List? Simple: **order matters**. This affects the order of UI elements and that *must* be correct. It might work with some Sets too, but when the constant is defined as List, it's explicit and guaranteed that the order will be right." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-01-22T15:46:11.977", "Id": "66788", "Score": "0", "body": "`ImmutableSet` also has defined order (insertion order), so does `Sets.immutableEnumSet` (_The iteration order of the returned set follows the enum's iteration order_, so this is what you want), you can always use `.asList()` on it which is a view (does not copy elements). Anyway, I agree with you, and that said I'd use `.asList()` with `ImmutableList`." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-01-22T15:52:04.250", "Id": "66790", "Score": "0", "body": "Yes, I might actually define it as ImmutableSet, since it has \"reliable, user-specified iteration order\". Good call on `EnumSet.complementOf()` and `EnumSet.allOf()`, thanks!" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-01-22T15:59:06.973", "Id": "66792", "Score": "0", "body": "Ah, actually I will stick with List as the type, because what I need from these constants is `get(int index)` (in a method called `createView(int position)`). Using Set would unnecessarily complicate that code." } ], "meta_data": { "CommentCount": "4", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-01-22T15:38:41.930", "Id": "39821", "ParentId": "39811", "Score": "8" } } ]
{ "AcceptedAnswerId": "39821", "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-01-22T14:40:31.767", "Id": "39811", "Score": "5", "Tags": [ "java", "collections", "enum", "guava" ], "Title": "One-line initialisation for a constant list with all entries except one from another list" }
39811
<p>I wrote this code many years ago to analyze Excel data coming in from the clipboard.</p> <p>Please review for performance and maintainability concerns.</p> <p>One minor note, from an OO perspective, a class level property is pretty much global level as every method has access, so these are prefixed with <code>G_</code></p> <pre class="lang-none prettyprint-override"><code>class ZCL_RM_EXCEL_DATA definition public final create public . public section. *"* public components of class ZCL_RM_EXCEL_DATA *"* do not include other source files here!!! methods CONSTRUCTOR importing !P_DATA type ZRMTT_ALSMEX_TABLINE . methods RANGE_TO_LIST importing !P_RANGE type STRING !P_VECTOR type I default 1 preferred parameter P_RANGE returning value(P_OUT) type STRINGTAB . class-methods DERIVE_LOCATION importing value(P_CELL) type STRING exporting !P_COL type I !P_ROW type I . class-methods COLUMN_TO_INT importing !P_COL type STRING returning value(P_OUT) type I . class-methods INT_TO_COLUMN importing !P_COL type I returning value(P_OUT) type STRING . methods GET_BOUNDARIES exporting !P_TOP_ROW type I !P_BOTTOM_ROW type I !P_LEFT_MOST_COL type I !P_RIGHT_MOST_COL type I . methods RANGE importing !P_FROM_ROW type I !P_TO_ROW type I !P_FROM_COL type I !P_TO_COL type I returning value(P_RANGE) type STRING . methods GET_CELL_VALUE importing !P_CELL type STRING returning value(P_VALUE) type STRING . protected section. *"* protected components of class ZCL_RM_EXCEL_DATA *"* do not include other source files here!!! private section. *"* private components of class ZCL_RM_EXCEL_DATA *"* do not include other source files here!!! data G_DATA type ZRMTT_ALSMEX_TABLINE . data G_TOP_ROW type I . data G_BOTTOM_ROW type I . data G_LEFT_MOST_COL type I . data G_RIGHT_MOST_COL type I . ENDCLASS. CLASS ZCL_RM_EXCEL_DATA IMPLEMENTATION. * &lt;SIGNATURE&gt;---------------------------------------------------------------------------------------+ * | Static Public Method ZCL_RM_EXCEL_DATA=&gt;COLUMN_TO_INT * +-------------------------------------------------------------------------------------------------+ * | [---&gt;] P_COL TYPE STRING * | [&lt;-()] P_OUT TYPE I * +--------------------------------------------------------------------------------------&lt;/SIGNATURE&gt; METHOD column_to_int. ***************************************************************************** * Description : Convert a column ( D ) into '4' * ***************************************************************************** DATA: l_col_char(3) TYPE c. DATA: l_length TYPE i. DATA: l_char TYPE c. DATA: l_index TYPE i. "This magic is required to achieve what ASC &amp; CHR would do in VBa FIELD-SYMBOLS: &lt;dummy&gt; TYPE x. "Cast from string to char so that we can use positional offsets l_col_char = p_col. TRANSLATE l_col_char TO UPPER CASE. l_length = strlen( l_col_char ). "We require to do this l_length times to support columns like 'AZ' DO l_length TIMES. l_index = sy-index - 1. l_char = l_col_char+l_index(1). ASSIGN l_char TO &lt;dummy&gt; CASTING TYPE x. "26 because there are 26 letters in the alphabet "256 because we need to shift the 2byte value to the right "64 because 65 -&gt; A in ASCII, and 65-64 = 1, is column 1 p_out = p_out * 26 + ( ( &lt;dummy&gt; / 256 ) - 64 ). ENDDO. ENDMETHOD. * &lt;SIGNATURE&gt;---------------------------------------------------------------------------------------+ * | Instance Public Method ZCL_RM_EXCEL_DATA-&gt;CONSTRUCTOR * +-------------------------------------------------------------------------------------------------+ * | [---&gt;] P_DATA TYPE ZRMTT_ALSMEX_TABLINE * +--------------------------------------------------------------------------------------&lt;/SIGNATURE&gt; METHOD constructor. ***************************************************************************** * Description : This class provides helper methods to analyze data coming * * from an excel sheet that was copied into the buffer and then* * read from the buffer into an internal table of type * * alsmex_tabline. * * * * The standard SAP does not promise to give the data sorted in* * any way, hence the silly looping over all the data to find * * the bottom row, top row, left most and right most column * * * ***************************************************************************** DATA: wa_data TYPE alsmex_tabline. "ROW,COL,VALUE "Take over the data g_data = p_data. "Sane defaults for cell boundaries g_bottom_row = g_right_most_col = 0. g_top_row = g_left_most_col = 2147483647. "MAXINT "We will loop over this once LOOP AT g_data INTO wa_data. IF wa_data-row GT g_bottom_row. g_bottom_row = wa_data-row. ENDIF. IF wa_data-col GT g_right_most_col. g_right_most_col = wa_data-col. ENDIF. IF wa_data-row LT g_top_row. g_top_row = wa_data-row. ENDIF. IF wa_data-col LT g_left_most_col. g_left_most_col = wa_data-col. ENDIF. ENDLOOP. ENDMETHOD. * &lt;SIGNATURE&gt;---------------------------------------------------------------------------------------+ * | Static Public Method ZCL_RM_EXCEL_DATA=&gt;DERIVE_LOCATION * +-------------------------------------------------------------------------------------------------+ * | [---&gt;] P_CELL TYPE STRING * | [&lt;---] P_COL TYPE I * | [&lt;---] P_ROW TYPE I * +--------------------------------------------------------------------------------------&lt;/SIGNATURE&gt; METHOD derive_location. ***************************************************************************** * Description : This method will derive from a string a column and a row * * This string can contain several formats: * * '123' -&gt; Row 123 , Column -1 * * 'AB' -&gt; Column 27 , Row -1 * * 'AB123' -&gt; Row 123 , Column 25 * ***************************************************************************** DATA: l_len TYPE i. DATA: l_row TYPE string. DATA: l_col TYPE string. TRANSLATE p_cell TO UPPER CASE. "We are having a row indicator IF p_cell CO '0123456789'. p_row = p_cell. p_col = -1. RETURN. ENDIF. "We are having a col indicator IF p_cell NA '0123456789'. p_row = -1. p_col = column_to_int( p_cell ). RETURN. ENDIF. "We having a colum/row cell, the hardest case IF p_cell CA '123456789'. "This is just to get the row into SY-FDPOS p_row = p_cell+sy-fdpos. l_col = p_cell(sy-fdpos). p_col = column_to_int( l_col ). ENDIF. ENDMETHOD. * &lt;SIGNATURE&gt;---------------------------------------------------------------------------------------+ * | Instance Public Method ZCL_RM_EXCEL_DATA-&gt;GET_BOUNDARIES * +-------------------------------------------------------------------------------------------------+ * | [&lt;---] P_TOP_ROW TYPE I * | [&lt;---] P_BOTTOM_ROW TYPE I * | [&lt;---] P_LEFT_MOST_COL TYPE I * | [&lt;---] P_RIGHT_MOST_COL TYPE I * +--------------------------------------------------------------------------------------&lt;/SIGNATURE&gt; METHOD get_boundaries. ***************************************************************************** * Description : This method simply exposes private properties to the caller * ***************************************************************************** "Just pass it! p_top_row = g_top_row. p_bottom_row = g_bottom_row. p_left_most_col = g_left_most_col. p_right_most_col = g_right_most_col. ENDMETHOD. * &lt;SIGNATURE&gt;---------------------------------------------------------------------------------------+ * | Instance Public Method ZCL_RM_EXCEL_DATA-&gt;GET_CELL_VALUE * +-------------------------------------------------------------------------------------------------+ * | [---&gt;] P_CELL TYPE STRING * | [&lt;-()] P_VALUE TYPE STRING * +--------------------------------------------------------------------------------------&lt;/SIGNATURE&gt; METHOD get_cell_value. ***************************************************************************** * Description : This method will parse the string-location into row, column,* * read the table entry and pass the value back * * As in a real excel file, cells that are not filled in, are * * considered/returned as blank * ***************************************************************************** DATA: wa_data TYPE alsmex_tabline. "ROW,COL,VALUE DATA: l_row TYPE i. DATA: l_col TYPE i. derive_location( EXPORTING p_cell = p_cell IMPORTING p_col = l_col p_row = l_row ). READ TABLE g_data INTO wa_data WITH KEY row = l_row col = l_col. p_value = wa_data-value. ENDMETHOD. * &lt;SIGNATURE&gt;---------------------------------------------------------------------------------------+ * | Static Public Method ZCL_RM_EXCEL_DATA=&gt;INT_TO_COLUMN * +-------------------------------------------------------------------------------------------------+ * | [---&gt;] P_COL TYPE I * | [&lt;-()] P_OUT TYPE STRING * +--------------------------------------------------------------------------------------&lt;/SIGNATURE&gt; METHOD int_to_column. ***************************************************************************** * Description : This method is the opposite of COLUMN_TO_INT and will * * convert an integer into a character. 2 -&gt; B * ***************************************************************************** "CHR , ASC functionality must pass through hex magic FIELD-SYMBOLS: &lt;dummy&gt; TYPE c. DATA: i(4) TYPE x. DATA: l_target TYPE i. DATA: l_rest TYPE string. "We are doing this in a recursive manner, "to understand recursive coding, one must start by understanding recursive coding IF p_col LT 27. " 64 because A starts at 65 and is value 1, 256 because now we need to shift to the left i = ( 64 + p_col ) * 256. ASSIGN i TO &lt;dummy&gt; CASTING TYPE c. p_out = &lt;dummy&gt;+1. ELSE. i = ( 64 + p_col MOD 26 ) * 256. ASSIGN i TO &lt;dummy&gt; CASTING TYPE c. p_out = &lt;dummy&gt;+1. "26 because there are 26 characters in the alphabet l_target = ( p_col - p_col MOD 26 ) / 26. l_rest = int_to_column( l_target ). CONCATENATE l_rest p_out INTO p_out. ENDIF. ENDMETHOD. * &lt;SIGNATURE&gt;---------------------------------------------------------------------------------------+ * | Instance Public Method ZCL_RM_EXCEL_DATA-&gt;RANGE * +-------------------------------------------------------------------------------------------------+ * | [---&gt;] P_FROM_ROW TYPE I * | [---&gt;] P_TO_ROW TYPE I * | [---&gt;] P_FROM_COL TYPE I * | [---&gt;] P_TO_COL TYPE I * | [&lt;-()] P_RANGE TYPE STRING * +--------------------------------------------------------------------------------------&lt;/SIGNATURE&gt; METHOD range. ***************************************************************************** * Description : This method will convert any a topleft and bottomright * * coordinate into the correct Excel range notations to * * Note the assumptions in the code, the caller has some * * responsability in calling this correctly. * ***************************************************************************** DATA: l_left TYPE string. DATA: l_right TYPE string. DATA: l_max_left TYPE string. DATA: l_max_right TYPE string. DATA: l_top_row TYPE string. DATA: l_bottom_row TYPE string. DATA: l_from_row TYPE string. DATA: l_to_row TYPE string. l_left = int_to_column( p_from_col ). l_right = int_to_column( p_to_col ). l_max_left = int_to_column( g_left_most_col ). l_max_right = int_to_column( g_left_most_col ). l_top_row = g_top_row. l_bottom_row = g_bottom_row. l_from_row = p_from_row. l_to_row = p_to_row. CONDENSE: l_bottom_row , l_top_row , l_from_row , l_to_row . "4 cases, everything, row to row, col to col, row/col to row/col "Case 1, everything IF p_from_col EQ -1 AND p_from_row EQ -1 AND p_to_col EQ -1 AND p_to_row EQ -1. CONCATENATE l_max_left l_top_row ':' l_max_right l_bottom_row INTO p_range. RETURN. ENDIF. "Case 2, row to row, ASSUMING that from is smaller than to IF p_from_col EQ -1 AND p_to_col EQ -1 AND p_from_row NE -1 AND p_to_row NE -1. CONCATENATE l_from_row ':' l_to_row INTO p_range. RETURN. ENDIF. "Case 3, col to col, ASSUMING that from is smaller than to IF p_from_col NE -1 AND p_to_col NE -1 AND p_from_row EQ -1 AND p_to_row EQ -1. CONCATENATE l_left ':' l_right INTO p_range. RETURN. ENDIF. "Case 4, cell to cell, ASSUMING that from is smaller than to IF p_from_col NE -1 AND p_to_col NE -1 AND p_from_row NE -1 AND p_to_row NE -1. CONCATENATE l_left l_from_row ':' l_right l_to_row INTO p_range. ENDIF. ENDMETHOD. * &lt;SIGNATURE&gt;---------------------------------------------------------------------------------------+ * | Instance Public Method ZCL_RM_EXCEL_DATA-&gt;RANGE_TO_LIST * +-------------------------------------------------------------------------------------------------+ * | [---&gt;] P_RANGE TYPE STRING * | [---&gt;] P_VECTOR TYPE I (default =1) * | [&lt;-()] P_OUT TYPE STRINGTAB * +--------------------------------------------------------------------------------------&lt;/SIGNATURE&gt; METHOD range_to_list. ***************************************************************************** * Description : This method will collect all cells in a given range * ***************************************************************************** DATA: l_from TYPE string, l_to TYPE string. DATA: l_from_row TYPE i, l_from_col TYPE i, l_to_row TYPE i, l_to_col TYPE i. DATA: wa_data TYPE alsmex_tabline. "ROW,COL,VALUE SPLIT p_range AT ':' INTO l_from l_to. IF sy-subrc NE 0. RETURN. ENDIF. derive_location( EXPORTING p_cell = l_from IMPORTING p_col = l_from_col p_row = l_from_row ). derive_location( EXPORTING p_cell = l_to IMPORTING p_col = l_to_col p_row = l_to_row ). "4 cases, everything, row to row, col to col, row/col to row/col "Case 1, everything IF l_from_col EQ -1 AND l_from_row EQ -1 AND l_to_col EQ -1 AND l_to_row EQ -1. LOOP AT g_data INTO wa_data. APPEND wa_data-value TO p_out. ENDLOOP. RETURN. ENDIF. "Case 2, row to row, ASSUMING that from is smaller than to IF l_from_col EQ -1 AND l_to_col EQ -1 AND l_from_row NE -1 AND l_to_row NE -1. LOOP AT g_data INTO wa_data WHERE row GE l_from_row AND row LE l_to_row. APPEND wa_data-value TO p_out. ENDLOOP. RETURN. ENDIF. "Case 3, col to col, ASSUMING that from is smaller than to IF l_from_col NE -1 AND l_to_col NE -1 AND l_from_row EQ -1 AND l_to_row EQ -1. LOOP AT g_data INTO wa_data WHERE col GE l_from_col AND col LE l_to_col. APPEND wa_data-value TO p_out. ENDLOOP. RETURN. ENDIF. "Case 4, cell to cell, ASSUMING that from is smaller than to IF l_from_col NE -1 AND l_to_col NE -1 AND l_from_row NE -1 AND l_to_row NE -1. LOOP AT g_data INTO wa_data WHERE col GE l_from_col AND col LE l_to_col AND row GE l_from_row AND row LE l_to_row. APPEND wa_data-value TO p_out. ENDLOOP. RETURN. ENDIF. ENDMETHOD. ENDCLASS. </code></pre>
[]
[ { "body": "<p>I would recommend using CALL FUNCTION 'ALSM_EXCEL_TO_INTERNAL_TABLE'</p>\n\n<p>I do not think there is an option to use field symbols though.</p>\n\n<p>If a field symbol contains internal table data you can use ASSIGN COMPONENT sy-index. The values are retrieved one by one as well. </p>\n\n<p>This is one example to convert the data to internal table from excel sheet.Using 'ALSM_EXCEL_TO_INTERNAL_TABLE' function module internal table contains the data like ROW, COL,VALUE. So now we have to convert it to the actual internal table structure.</p>\n\n<p>Below is the internal table structure.</p>\n\n<pre><code>BEGIN OF WA_BKPF,\n BUKRS LIKE BKPF-BUKRS, \" company Code\n BELNR LIKE BKPF-BELNR, \" Accounting Document Number\n GJAHR LIKE BKPF-GJAHR, \" Fiscal Year\n BLART LIKE BKPF-BLART, \" Document type\n BLDAT LIKE BKPF-BLDAT, \" Document Date in Document\n BUDAT LIKE BKPF-BUDAT, \" Posting Date in the Document\n MONAT LIKE BKPF-MONAT, \" Fiscal Period\n CPUDT LIKE BKPF-CPUDT, \" Accounting Document Entry Date\nEND OF WA_BKPF.\n</code></pre>\n\n<p>Below is how to convert the excel sheet data to internal table. You need to take the entire ROW with all the columns one by one and move it to one variable . Here I took LW_LINE . LW_LINE contains the values of the one ROW of actual internal table structure .After getting all the ROW values append it to the actual internal table.</p>\n\n<pre><code>FORM UPLOAD .\n\n DATA:\n LW_ROW TYPE I, \" Index to read t_value table\n LW_LINE(100) TYPE C, \" Holds VALUE from t_rowcol\n LW_COMPONENTS TYPE I, \" Nimber of fields in t_bkpf\n LW_TYPE TYPE C, \" Holds Field type of fs_bkpf\n LW_TIMES TYPE I. \" No of rows in internal table\n\n* finding no.of fields in fs_bkpf structure\n DESCRIBE FIELD FS_BKPF TYPE LW_TYPE COMPONENTS LW_COMPONENTS.\n\n*describe table t_bkpf.\n\n CALL FUNCTION 'ALSM_EXCEL_TO_INTERNAL_TABLE'\n EXPORTING\n FILENAME = W_FNAME1\n I_BEGIN_COL = 1\n I_BEGIN_ROW = 1\n I_END_COL = LW_COMPONENTS\n I_END_ROW = 50\n TABLES\n INTERN = T_ROWCOL\n EXCEPTIONS\n INCONSISTENT_PARAMETERS = 1\n UPLOAD_OLE = 2\n OTHERS = 3.\n IF SY-SUBRC &lt;&gt; 0.\n* MESSAGE ID SY-MSGID TYPE SY-MSGTY NUMBER SY-MSGNO\n* WITH SY-MSGV1 SY-MSGV2 SY-MSGV3 SY-MSGV4.\n ENDIF. \" IF SY-SUBRC &lt;&gt; 0.\n\n* Finding no.of rows in T_ROWCOL internal table\n DESCRIBE TABLE T_ROWCOL.\n\n LW_TIMES = SY-TFILL DIV LW_COMPONENTS.\n\n LW_ROW = 0.\n\n\n DO LW_TIMES TIMES.\n LW_ROW = LW_ROW + 1.\n LOOP AT T_ROWCOL WHERE ROW = LW_ROW .\n\n CONCATENATE LW_LINE\n T_ROWCOL-VALUE\n INTO LW_LINE\n SEPARATED BY SPACE.\n ENDLOOP. \" LOOP AT T_ROWCOL...\n\n SHIFT LW_LINE LEFT.\n\n* Separating w_line into fields of T_BKPF\n SPLIT LW_LINE AT SPACE INTO FS_BKPF-BUKRS\n FS_BKPF-BELNR\n FS_BKPF-GJAHR\n FS_BKPF-BLART\n FS_BKPF-BLDAT\n FS_BKPF-BUDAT\n FS_BKPF-MONAT\n FS_BKPF-CPUDT.\n* Appending each row value from excel file to t_bkpf\n\n APPEND FS_BKPF TO T_BKPF.\n\n CLEAR : LW_LINE,\n FS_BKPF.\n ENDDO. \" DO LW_TIMES TIMES.\n\n* Displaying data from internal table\n LOOP AT T_BKPF INTO FS_BKPF.\n WRITE :/\n FS_BKPF-BUKRS UNDER TEXT-001,\n FS_BKPF-BELNR UNDER TEXT-002,\n FS_BKPF-GJAHR UNDER TEXT-003,\n FS_BKPF-BLART UNDER TEXT-004,\n FS_BKPF-BLDAT UNDER TEXT-005,\n FS_BKPF-BUDAT UNDER TEXT-006,\n FS_BKPF-MONAT UNDER TEXT-007,\n FS_BKPF-CPUDT UNDER TEXT-008.\n ENDLOOP. \" LOOP AT T_BKPF INTO FS_BKPF.\n\nENDFORM. \" UPLOAD\n</code></pre>\n\n<p><strong>Examples came from Rajitha</strong> </p>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-08-24T06:17:58.790", "Id": "440833", "Score": "0", "body": "How `ALSM_EXCEL_TO_INTERNAL_TABLE` is related to the question?" } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2017-10-17T11:35:34.910", "Id": "178107", "ParentId": "39813", "Score": "1" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-01-22T14:48:56.387", "Id": "39813", "Score": "23", "Tags": [ "excel", "abap" ], "Title": "ABAP Excel data analyzer" }
39813
<p>ABAP (Advanced Business Application Programming, originally Allgemeiner Berichts-Aufbereitungs-Prozessor, German for "general report creation processor"[3]) is a high-level programming language created by the German software company SAP. It is currently positioned, alongside the more recently introduced Java, as the language for programming the SAP Application Server, part of its NetWeaver platform for building business applications. The syntax of ABAP is somewhat similar to COBOL.</p>
[]
[]
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-01-22T14:51:11.100", "Id": "39814", "Score": "0", "Tags": null, "Title": null }
39814
ABAP is a high-level programming language created by the German software company SAP. The syntax of ABAP is somewhat similar to COBOL.
[]
[]
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2014-01-22T14:51:11.100", "Id": "39815", "Score": "0", "Tags": null, "Title": null }
39815
<p>I'm working on the ui for an application which uses a custom ui control that is loosly related to a treeview.</p> <p>This treeview has two levels:</p> <ol> <li>Top level which has a number of different geographical regions as well as a 'select all' item</li> <li>Second level which has a number of countries in those geographical regions </li> </ol> <p>The user is able to use the checkboxes in the top level to select whole regions at once or they can select individual countries by going into any of the regions. Using the 'select all' checkbox allows the user to select everything.</p> <p>The number of selected countries in each given region is also shown because the countries for only one region can be shown at any one time. The actual number of countries in each of the regions is a lot higher, I cut them out for the purposes of the demo. Most of this code is generated server side but I have full control over the html structure should it need to be changed.</p> <p><strong><a href="http://jsfiddle.net/HV5Z5/">http://jsfiddle.net/HV5Z5/</a></strong> - is a jsfiddle of it working.</p> <p>Here is my code:</p> <pre><code>regionLabelClick = function () { $('.vcs-cb-asset-wizard-region:eq(0)').addClass('vcs-cb-asset-wizard-region-selected'); $('.vcs-cb-asset-wizard-region-select label').click(function () { var index = $('.vcs-cb-asset-wizard-region-select label').index($(this)); $('.vcs-cb-asset-wizard-region').removeClass('vcs-cb-asset-wizard-region-selected'); $(this).parent('li').addClass('vcs-cb-asset-wizard-region-selected'); $('.vcs-cb-asset-wizard-regions &gt; div').hide(); $('.vcs-cb-asset-wizard-regions &gt; div:eq('+ index +')').show(); }); } areaSelect = function () { // count up how many checkboxes have been checked initially areaCount(); $('.vcs-cb-asset-wizard-region-select-container input').change(function () { var val = $(this).val(); var isChecked = $(this).prop('checked'); var isMain = false; // if the changed checkbox is a top level one if ($(this).parent('li').hasClass('vcs-cb-asset-wizard-region')) { isMain = true; } if (isMain) { if (isChecked) { // if one of the top level checkboxes is checked if (val == 0) { // check the 'all regions' one $('.vcs-cb-asset-wizard-choose-region input').prop('checked', true); } else { // otherwise check all of the checkboxes associated with the selected region $('.vcs-cb-asset-wizard-regions &gt; div:eq(' + parseInt(val - 1) + ') input').prop('checked', true); } } else { // if one of the top level checkboxes is unchecked if (val == 0) { // unchecked 'all regions' $('.vcs-cb-asset-wizard-choose-region input').prop('checked', false); } else { // uncheck the checkboxes associated with the unchecked top level checkbox $('.vcs-cb-asset-wizard-regions &gt; div:eq(' + parseInt(val - 1) + ') input').prop('checked', false); } } } else { // if one of the second level checkboxes is checked checkCurrentArea($(this), isChecked); } // has the 'all regions' checkbox been checked? if (checkAllSelection()) { // check all of the checkboxes $('.vcs-cb-asset-wizard-all-regions input').prop('checked', true); } else { // uncheck all of the checkboxes $('.vcs-cb-asset-wizard-all-regions input').prop('checked', false); } // count up how many checkboxes are now checked areaCount(); }); } areaCount = function () { var totalNumber = 0; var numberOfChecked = 0; // loop through each of the 5 top levels and count the number of checked second level checkboxes // append the values to a span top level &lt;ul&gt; $('.vcs-cb-asset-wizard-region-select &gt; li').each(function (i) { totalNumber = $('.vcs-cb-asset-wizard-regions &gt; div:eq(' + parseInt(i - 1) + ') input').length; numberOfChecked = $('.vcs-cb-asset-wizard-regions &gt; div:eq(' + parseInt(i - 1) + ') input:checked').length; $('.vcs-cb-asset-wizard-region-select &gt; li:eq(' + parseInt(i - 1) + ') span').text(numberOfChecked + ' / ' + totalNumber); }); } checkAreaSelection = function (index) { var result = true; // loop through a given div containing second level checkboxes // return false if any of them are unchecked $('.vcs-cb-asset-wizard-region-countries:eq(' + index + ') input').each(function () { if (!$(this).prop('checked')) { result = false; } }); return result; } checkAllSelection = function () { var result = true; // loop through the top level checkboxes // return false if any of them are unchecked $('.vcs-cb-asset-wizard-regions input').each(function () { if (!$(this).prop('checked')) { result = false; } }); return result; } checkCurrentArea = function (elem, isChecked) { // store index value of the parent div that contains this second level checkbox var index = $('.vcs-cb-asset-wizard-region-countries').index(elem.parents('.vcs-cb-asset-wizard-region-countries')); // if all of the second level checkboxes in this div are checked if (checkAreaSelection(index)) { // check the associated top level checkbox $('.vcs-cb-asset-wizard-region-select li:eq(' + index + ') input').prop('checked', true); } else { // uncheck the associated top level checkbox $('.vcs-cb-asset-wizard-region-select li:eq(' + index + ') input').prop('checked', false); } } $(function () { regionLabelClick(); areaSelect(); }); </code></pre> <p>I don't like the messy if statement in my <code>areaSelect()</code> method and there must be a better way to keep track of which checkboxes are checked without having to loop through them all after each one has been changed.</p> <p>Can anyone offer some pointers as to how the code can be improved?</p>
[]
[ { "body": "<p>Your code looks very busy;</p>\n\n<p>if there is one thing you should take away from this review : do not namespace your css classes, it makes for hard to read code. </p>\n\n<p><strong>regionLabelClick</strong></p>\n\n<p>You mention the same CSS class a few times, you should extract those in to a <code>var</code> both for readability and maintainability. You could merge the last two statements since the only difference is <code>eq</code> which is a jQuery function anyway.</p>\n\n<p>I would counterpropose this:</p>\n\n<pre><code>regionLabelClick = function () {\n var cssSelected = 'vcs-cb-asset-wizard-region-selected',\n cssSelectedSelector = '.' + cssSelected,\n cssWizardRegionSelector = '.vcs-cb-asset-wizard-region';\n cssWizardRegionDivSelector = '.vcs-cb-asset-wizard-regions &gt; div';\n\n $(cssWizardSelector).eq(0).addClass(cssSelected);\n\n $(cssSelectedSelector + ' label').click(function () {\n var index = $(cssSelectedSelector + ' label').index($(this));\n\n $(cssWizardSelector).removeClass(cssSelected);\n $(this).parent('li').addClass(cssSelected);\n\n $( cssWizardRegionDivSelector ).hide().eq(index).show();\n });\n};\n</code></pre>\n\n<p><strong>areaSelect</strong></p>\n\n<p>I agree with you that the code is messy, the root cause, in my mind, is that the selector you use is too generic, and then you need too much code to figure out what specifically was selected and deal with it in a ton of <code>if</code>s.</p>\n\n<p>I would counter-propose something like</p>\n\n<pre><code>areaSelect = function () {\n\n // count up how many checkboxes have been checked initially\n areaCount();\n\n $( selector uniquely identifying the all regions checkbox).change(function(){})\n $( selector identifying the other top level checkboxes ).change(function(){})\n $( selector identifying the 2nd level checkboxes ).change(function(){})\n\n\n}\n</code></pre>\n\n<p><strong>The looping</strong></p>\n\n<p>You actually only loop over the top-level checkboxes to set the labels ( x/y ) with a smart jQuery to get the count of selected boxes, I like it, not sure how that can be improved.</p>\n\n<p><strong>The rest</strong></p>\n\n<p>The other functions are moderately size and well commented. They could benefit as well from extracting css selector strings into <code>var</code>, but that is optional in my mind.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-01-30T16:45:48.000", "Id": "68119", "Score": "0", "body": "Thanks for taking the time to go through my code soup. One question though, what do you mean by `do not namespace your css classes`?" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-01-30T17:07:35.403", "Id": "68127", "Score": "0", "body": "You prefix everything with `vcs-cb-`, I call this type of prefixing namespacing." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-01-30T17:10:52.167", "Id": "68128", "Score": "0", "body": "Ah I see. It's kind of out of the scope of this question but I am dealing with an extremely large web app with multiple components. The only way i could guarantee not to have duplicate classes is to go down that route. Hopefully, it will eliminate some of the 'where is this class used?' questions in a few years from now." } ], "meta_data": { "CommentCount": "3", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-01-30T14:42:25.877", "Id": "40463", "ParentId": "39816", "Score": "1" } } ]
{ "AcceptedAnswerId": "40463", "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-01-22T15:07:02.183", "Id": "39816", "Score": "7", "Tags": [ "javascript", "jquery" ], "Title": "A better looking 'treeview' - dealing with lots of checkboxes" }
39816
<p>Attempting to jump into the Windows Server ServiceBus 1.1 code-base along with adopting the new TPL async methods. But I could not find an easy way to just spin up N number of handlers for message sessions (might have 100 or so concurrent sessions). So it would be great to get some feedback on the following code, any suggestions on an easier way would be great... note tried to keep code sample simple for the questions purpose.</p> <pre><code>///============================================================== /// SAMPLE USAGE SubClient = SubscriptionClient.Create(TopicName, SubscriptionName); SessionsMessagingOptions opts = new SessionsMessagingOptions() { NumberOfSesssions = 5, ReceiveTimeOut = TimeSpan.FromSeconds (5), AutoMarkMessageComplete = true, MessageHandler = msg =&gt; { _logger.Log(string.Format("Processing recived Message: SessionId = {0}, Body = {1}", msg.SessionId, msg.GetBody&lt;string&gt;())); } }; SubClient.HandleSessions(opts); ///============================================================== public class SessionsMessagingOptions { public Int32 NumberOfSesssions { get; set; } public TimeSpan ReceiveTimeOut { get; set; } public Boolean AutoMarkMessageComplete { get; set; } public Action&lt;BrokeredMessage&gt; MessageHandler { get; set; } } ///============================================================== public static class SubscriptionClientExtensions { public static void HandleSessionsV2(this SubscriptionClient sc, SessionsMessagingOptions opts) { for (Int32 nIndex = 0; nIndex &lt; opts.NumberOfSesssions; nIndex++) { HandleSession(sc, opts); } } public static async Task&lt;MessageSession&gt; HandleSession(SubscriptionClient sc, SessionsMessagingOptions opts) { do { MessageSession ms = null; try { ms = await sc.AcceptMessageSessionAsync().ConfigureAwait(false); foreach (var msg in await ms.ReceiveBatchAsync(5, opts.ReceiveTimeOut).ConfigureAwait(false)) { if (msg == null) break; try { opts.MessageHandler(msg); if (opts.AutoMarkMessageComplete) msg.Complete(); } catch (Exception) { // log the exception } } } catch (TimeoutException) { // log timeout occurred } catch (Exception) { // look into other exception types to handle here } finally { if (ms != null) { if (!ms.IsClosed) ms.Close(); } } } while (true); } public static void HandleSessions(this SubscriptionClient sc, SessionsMessagingOptions opts) { Action&lt;Task&lt;MessageSession&gt;&gt; sessionAction = null; Action&lt;Task&lt;BrokeredMessage&gt;&gt; msgHandler = null; sessionAction = new Action&lt;Task&lt;MessageSession&gt;&gt;(tMS =&gt; { if (tMS.IsFaulted) // session timed out - repeat { sc.AcceptMessageSessionAsync().ContinueWith(sessionAction); return; } MessageSession msgSession = null; try { msgSession = tMS.Result; } catch (Exception) { return; // task cancelation exception } msgHandler = new Action&lt;Task&lt;BrokeredMessage&gt;&gt;(taskBM =&gt; { if (taskBM.IsFaulted) return; BrokeredMessage bMsg = null; try { bMsg = taskBM.Result; } catch (Exception) { return; // task cancelation exception } if (bMsg == null) { sc.AcceptMessageSessionAsync().ContinueWith(sessionAction); // session is dead return; } opts.MessageHandler(bMsg); // client code to handle the message if (opts.AutoMarkMessageComplete) bMsg.Complete(); msgSession.ReceiveAsync(opts.ReceiveTimeOut).ContinueWith(msgHandler); // repeat }); msgSession.ReceiveAsync(opts.ReceiveTimeOut).ContinueWith(msgHandler); // start listening }); for (Int32 nIndex = 0; nIndex &lt; opts.NumberOfSesssions; nIndex++) { sc.AcceptMessageSessionAsync().ContinueWith(sessionAction); } } } </code></pre>
[]
[]
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-01-22T15:07:22.077", "Id": "39817", "Score": "2", "Tags": [ "c#", "task-parallel-library" ], "Title": "Easy way to handle AcceptMessageSessionAsync and ReceiveAsync - Windows Server ServiceBus" }
39817
<p>I am programming with Java (server side) and JavaScript a card game and I do not know how to give properties (on server side) to every card that I create. For a match I need 20 different cards from a complete set of cards (52). Now I want that these 20 cards get a value (Ace, 2, 3, 4, 5, 6, 7, 8, 9, 10, Jack, Queen, King) and a symbol (like Spades, Hearts, Diamonds and Clubs).</p> <p>How should I approach this? I thought using if clauses like I used on client side would be ok (JavaScript):</p> <pre><code>p.initialize = function (id) { this.card= new createjs.Bitmap(images[id]); // HEARTS if (id &gt; 0 &amp;&amp; id &lt; 14) { this.symbol = Card.HEARTS; } // DIAMONDS else if (id &gt; 13 &amp;&amp; id &lt; 28) { this.symbol = Card.DIAMONDS; } // CLUBS else if(id &gt; 27 &amp;&amp; id &lt;42) { this.symbol = Card.CLUBS; } // SPADES else if(id &gt; 41 &amp;&amp; id &lt;53) { this.symbol = Card.SPADES; } this.VALUE = id%13; }; </code></pre> <p>This is the way I did it on client side. Should I do the same with Java or are there better possibilities?</p>
[ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-01-22T16:57:55.163", "Id": "66801", "Score": "0", "body": "Is this the only piece of code that you can provide? From just this one can not really review your code. You should at least include your Card class. Also if you do not have a class to encapsulate a set/deck logic you're doing it wrong. Well, may not be wrong, but major of card game (like yours) relies on having at least one set. So there is no point of not having one.." } ]
[ { "body": "<p>Can't help but think that a trick with integer division and clever Card enum setup would help a lot:</p>\n\n<pre><code>this.symbol = Card.values()[(id - 1) / 13];\n</code></pre>\n\n<p>Replace all your code with the above 1-liner ;-)</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-01-22T17:05:30.123", "Id": "39826", "ParentId": "39823", "Score": "4" } }, { "body": "<h3>Slight improvements of your current code</h3>\n\n<ul>\n<li>Get rid of the comments and read three lines below which symbol you are currently declaring the conditions for. Your code is very self-documenting, no need to add comments.</li>\n<li><p>You should know that there is a <code>more than or equal to</code> operator, which can be used to make your code a lot more readable (here I have also removed the braces since your statement is only one line) </p>\n\n<pre><code>if (id &gt;= 1 &amp;&amp; id &lt;= 13) this.symbol = Card.HEARTS;\nelse if (id &gt;= 14 &amp;&amp; id &lt;= 28) this.symbol = Card.KARO;\nelse if (id &gt;= 28 &amp;&amp; id &lt;= 41) this.symbol = Card.CLUBS;\nelse if (id &gt;= 42 &amp;&amp; id &lt;= 52) this.symbol = Card.SPADES;\n</code></pre></li>\n</ul>\n\n<p>This can in turn also be simplified to:</p>\n\n<pre><code> if (id &lt;= 0) { /* mega-super-error-should-probably-not-happen-and-if-it-does-then-it's-no-symbol */ }\n else if (id &lt;= 13) this.symbol = Card.HEARTS;\n else if (id &lt;= 28) this.symbol = Card.KARO;\n else if (id &lt;= 41) this.symbol = Card.CLUBS;\n else if (id &lt;= 52) this.symbol = Card.SPADES;\n</code></pre>\n\n<h3>Weird King</h3>\n\n<p>Are you aware that in your current code, you will have the values <code>1 2 3 4 5 6 7 8 9 10 11 12 0</code>? This feels weird. If Ace is 1 then 0 is king I assume? But using 0 as king does not make sense.</p>\n\n<h3>Adding a parameter to the function</h3>\n\n<p>Even though @rolfl provides a short way to do this, I just want to object to one thing: <strong>The use of the id parameter</strong>.</p>\n\n<p>It seems like you are creating a card from an ID. Now what if you some day totally forget about how to calculate these IDs from a specified suite and rank? (or vice versa). I would instead <strong>use a function with two parameters: Suite and rank.</strong> I'm not sure how you are calling this method today, but to me it feels cleaner to create cards by using a nested for-loop to loop first over suite and then over rank, rather than looping from 1 to 52.</p>\n\n<p>Also, I wouldn't use an uppercase property <code>VALUE</code> when the others, <code>symbol</code> and <code>card</code> is lowercase. It's better to use lowercase <code>value</code> also. Or, you could call it <code>rank</code> instead. And you might want to rename the <code>card</code> property to <code>picture</code>.</p>\n\n<p>As for how to do it in Java, I would say that you should try to make it the same in both Java and JavaScript. Tidy up the JavaScript and then make it the same in Java.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-01-22T17:53:48.037", "Id": "39830", "ParentId": "39823", "Score": "5" } }, { "body": "<p>I did the Java server side of a Go Fish card game a while back, with a second person doing a Javascript client and a third one doing an AS3 client. The way that we implemented it was similar to rolfl's suggestion.</p>\n\n<p>Java, in the Card object class:</p>\n\n<pre><code>public int getRank() {\n return id % 13;\n}\n\npublic int getSuit() {\n return id / 13;\n}\n</code></pre>\n\n<p>Javascript, in the Card object class. I'm not sure why Steve used Math.floor on the % results.</p>\n\n<pre><code>this.rank = Math.floor(id % 13);\nthis.suit = Math.floor(id/13);\n</code></pre>\n\n<p>AS3, in the Card object class. </p>\n\n<pre><code>static public function getRankForId(id:int):int {\n var rank:int = (id % 13);\n //trace(\"id \" + id + \" rank: \" + rank);\n return rank;\n}\n\nstatic public function getSuitForId(id:int):int {\n var suit:int = Math.floor(id / 13);\n //trace(\"id \" + id + \" suit: \" + suit);\n return suit;\n}\n</code></pre>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-01-23T01:31:41.467", "Id": "39850", "ParentId": "39823", "Score": "3" } } ]
{ "AcceptedAnswerId": "39830", "CommentCount": "1", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-01-22T16:13:49.267", "Id": "39823", "Score": "4", "Tags": [ "java", "javascript", "game", "playing-cards" ], "Title": "Turn-based game setting properties for playcards" }
39823
<p>New to Ruby here. I just made a script that print some metrics from a Windows machine about its disk. The script works fine and as I wanted it to. Now, since I'm new to the ruby and programming world, I'd like to ask you if anyone could help me to make to code look better or if there's other more efficient way I could have wrote it.</p> <pre><code>require 'rubygems' if RUBY_VERSION &lt; '1.9.0' require 'sensu-plugin/metric/cli' require 'socket' class LogicalDiskMetric &lt; Sensu::Plugin::Metric::CLI::Graphite option :scheme, :description =&gt; "Metric naming scheme, text to prepend to .$parent.$child", :long =&gt; "--scheme SCHEME", :default =&gt; "#{Socket.gethostname}" #Run a wmic command to get some stats about the disks usage def get_logical_disk_metrics tmp = `wmic logicaldisk get caption, drivetype, freespace, size`.split("\n") logical_disk = [] bytes_to_gbytes = 1073741824 #Convert data from bytes to gigabytes and find the used space (size-free) tmp.each do |disk| disk = disk.split(" ") if disk[1].to_i == 3 disk[2] = (disk[2].to_f/bytes_to_gbytes).round(2) disk[3] = (disk[3].to_f/bytes_to_gbytes).round(2) disk.push((disk[3].to_f - disk[2].to_f).round(2)) logical_disk.push(disk) end end return logical_disk end #Add the disks usage in % def get_logical_disk_usage_percentage(logical_disk) logical_disk.each do |disk| disk.push(((disk[2].to_f/disk[3].to_f)*100).round(2)) disk.push(100.00-disk[5]) end return logical_disk end def run timestamp = Time.now.utc.to_i logical_disk = get_logical_disk_metrics() logical_disk = get_logical_disk_usage_percentage(logical_disk) logical_disk.each do |disk| metrics = { :"logical_disk_#{disk[0]}" =&gt; { :"size(Gb)" =&gt; disk[3], :"free_space(Gb)" =&gt; disk[2], :"free_space(%)" =&gt; disk[5], :"used_space(Gb)" =&gt; disk[4], :"used_space(%)" =&gt; disk[6] } } metrics.each do |parent, children| children.each do |child, value| output [config[:scheme], parent, child].join("."), value, timestamp end end end ok end end </code></pre>
[ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-01-23T12:52:45.840", "Id": "66904", "Score": "0", "body": "Magic, but you can just delete line `return logical_disk`" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-01-23T15:00:12.910", "Id": "66921", "Score": "0", "body": "Did no try it, but even if I can do it, are you sure it's a good thing to do? I mean, to me it only adds a bit of complexity to understand the code." } ]
[ { "body": "<p>Some general pointers:</p>\n\n<p>Refrain from using <code>tmp</code> as variable names. <code>raw_output</code> will do the job better.</p>\n\n<p>Working with arrays as object replacement (<code>x[0]</code> is the caption, <code>x[1]</code> is the type...) is cumbersome, unreadable, and difficult to maintain. I suggest moving to Hash:</p>\n\n<pre><code>tmp.map(&amp;:split).select { |_, drivetype, _, _| drivetype.to_i == 3 }.map do |caption, drivetype, freespace, size|\n {\n caption: caption,\n drivetype: drivetype,\n freespace: (freespace.to_f/bytes_to_gbytes).round(2),\n size: (size.to_f/bytes_to_gbytes).round(2),\n usedspace: ((size.to_f - freespace.to_f)/bytes_to_gbytes).round(2)\n }\nend\n</code></pre>\n\n<p>This code returns an array of hashes, one for each disk with drivetype '3'. The variables (<code>caption</code>, <code>drivetype</code>, etc...) are created when ruby translates the array to the list of variables declared, so actually the <code>tmp.map(&amp;:split).map { |caption, drivetype, freespace, size| ... }</code> is like saying:</p>\n\n<pre><code>tmp.map do |disk|\n disk = disk.split\n caption = data[0]\n drivetype = data[1]\n freespace = data[2]\n size = data[3]\n ...\nend\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-02-04T14:16:14.983", "Id": "69940", "Score": "0", "body": "Wow Uri, many thanks for that awesome answer! I look into it!" } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-02-04T08:03:00.257", "Id": "40831", "ParentId": "39824", "Score": "2" } } ]
{ "AcceptedAnswerId": "40831", "CommentCount": "2", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-01-22T16:15:44.130", "Id": "39824", "Score": "4", "Tags": [ "ruby", "beginner", "windows" ], "Title": "Printing some metrics from a Windows machine" }
39824
<blockquote> <p>Adapt the ideas of <code>printd</code> to write recursive version of <code>itoa</code>; that is, convert integer into a string by calling a recursive routine</p> </blockquote> <p>Here is the implementation of printd:</p> <pre><code>void printd(int n) { if(n &lt; 0) putchar('-'); if(n / 10) printd(n / 10); putchar(n % 10 + '0')l } </code></pre> <p>And here is my solution: </p> <pre><code>int itoa(int n, char s[]) { int i; if(n &lt; 0) { n *= -1; } i = 0; if(n / 10) { i = itoa(n / 10, s); } s[i] = n % 10 + '0'; s[++i] = '\0'; return i; /* next free slot in array */ } </code></pre> <p>As you can see, my version of <code>itoa</code> is a little bit different than the one presented in the book. It returns a variable <code>i</code> that represents the index of the next free slot in array, at every step it fills the next empty slot with the null character. At the deepest level of recursion, it returns 1.</p> <p>Could you review my exercise?</p>
[]
[ { "body": "<p>There are two bugs in <code>printd()</code>:</p>\n\n<ol>\n<li>The last character is an <code>l</code> instead of a semicolon.</li>\n<li>If <code>n</code> is negative, it prints a negative sign before each digit.</li>\n</ol>\n\n<p>Your <code>itoa()</code> also has a bug in handling negative input. It always stringifies the absolute value of <code>n</code>.</p>\n\n<p>Your strategy to use the return value to determine which array element to write to seems like a good idea. I think it would be more user friendly, though, to say that you are returning the <code>strlen()</code> of the output.</p>\n\n<pre><code>int itoa(int n, char s[]) {\n int i = 0;\n\n if (n &lt; 0) {\n s[0] = '-';\n return 1 + itoa(-n, s + 1);\n }\n\n if (n / 10) {\n i = itoa(n / 10, s);\n }\n s[i] = n % 10 + '0';\n s[++i] = '\\0';\n\n return i; /* strlen(s), i.e. the next free slot in array */\n}\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-01-23T16:15:35.310", "Id": "66927", "Score": "0", "body": "This is the first time when I see this kind of expression in this context `s + 1`. I understand what it does, but I don't understand how it works." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-01-24T00:41:34.870", "Id": "67023", "Score": "1", "body": "`s + 1` is equivalent to `&(s[1])`, but written using [pointer arithmetic](http://en.wikipedia.org/wiki/Pointer_\\(computer_programming\\)#C_arrays)." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-02-08T03:53:17.637", "Id": "70703", "Score": "1", "body": "Fatal infinite loop with 2's complement `itoa(INT_MIN, s)`" } ], "meta_data": { "CommentCount": "3", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-01-23T00:58:42.227", "Id": "39848", "ParentId": "39825", "Score": "6" } }, { "body": "<p>The signature of <code>itoa</code> <a href=\"http://www.cplusplus.com/reference/cstdlib/itoa/\">is supposed to look like this</a>:</p>\n\n<pre><code>char* itoa( int value, char* str, int base);\n</code></pre>\n\n<p>Therefore, if you want your recursing function to return a int, then you can call it as a private subroutine (a non-public implementation detail of your public itoa function).</p>\n\n<pre><code>static int itoa_implementation(int n, char s[]) { ... }\n\nchar* itoa( int value, char* str, int base)\n{\n itoa_implementation(value, str); // don't care about the int return code\n return str; // as expected/required of the standard itoa function\n}\n</code></pre>\n\n<p>You should also modify your implementation to support the <code>int base</code> parameter (which you'll probably find easy to do):</p>\n\n<ul>\n<li>Your current implementation assumes the base is (hard-coded) <code>10</code></li>\n<li>Your current <code>n % 10 + '0'</code> expression should be modified to potentially return 'a', 'b', etc., if the base is larger than 10.</li>\n</ul>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-01-23T01:37:10.410", "Id": "39851", "ParentId": "39825", "Score": "5" } }, { "body": "<ol>\n<li><p><code>printd()</code> look fine except for negative numbers (@200_success). Following may fix</p>\n\n<pre><code> putchar((abs(n) % 10 + '0');\n</code></pre></li>\n<li><p>@ChrisW well pointed out that if one is to use the name of a common function like <code>itoa()</code>, code should function in a similar fashion.</p></li>\n<li><p><code>if(n / 10) { i = itoa(n / 10, s);</code> computes <code>n/10</code> twice. Suggest calculating once and saving the result. Being a <code>/</code> operation, I`d expect a slight performance improvement.</p></li>\n<li><p><code>if(n &lt; 0) { n *= -1; }</code> has problems when <code>n == INT_MIN</code> and 2's complement (which is the usual signed integer format). The only <em>portable</em> solution I can think of is to embrace the negative side instead of the positive side as follows:</p>\n\n<pre><code>// value is &lt;= 0\nstatic char *itoa_recursive_helper(int value, char* str, int base) {\n if (value &lt;= -base) {\n str = itoa_recursive_helper(value / base, str, base);\n value %= base;\n }\n *str++ = \"0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ\"[-value];\n *str = '\\0';\n return str;\n}\n\nchar* itoa_recursive(int value, char* str, int base) {\n // Could add checks here for str == NULL, base &lt; 2 or &gt; 36\n char *original = str;\n if (value &lt; 0) {\n *str++ = '-';\n } else {\n value = -value;\n }\n itoa_recursive_helper(value, str, base);\n return original;\n}\n</code></pre></li>\n<li><p>If you care about portability with ASCII <em>and</em> non-ASCII character sets and need to work in bases > 10, the following works well.</p>\n\n<pre><code>*str++ = \"0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ\"[digit];\n</code></pre></li>\n</ol>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-02-08T04:35:11.883", "Id": "41202", "ParentId": "39825", "Score": "1" } } ]
{ "AcceptedAnswerId": "39848", "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-01-22T16:42:13.670", "Id": "39825", "Score": "8", "Tags": [ "c", "recursion", "converting" ], "Title": "Integer-to-string conversion using recursion" }
39825
<p>I've made a small class whose purpose is to generate dynamic HTML. However, it seems that my implementation turned into a state machine algorithm. And so here am I seeking help on a possible design pattern that I may apply, so my code can be more readable, objected oriented and more maintainable.</p> <pre><code>public interface IViewContext { object GetContent(); } public delegate object BindingModelToHtmlEh(object sender, BindingModelToHtmlArgs args); public class BindingModelToHtmlArgs : EventArgs { public BindingModelToHtmlArgs(Type hint, Type domain) { this.Hint = hint; this.Domain = domain; } public Type Hint { get; private set; } public Type Domain { get; set; } } public class HtmlViewContext : IViewContext { private readonly List&lt;object&gt; htmlList; private HtmlViewContext parent; public event BindingModelToHtmlEh ProvideValue; protected virtual object OnProvideValue(BindingModelToHtmlArgs args) { BindingModelToHtmlEh handler = ProvideValue; if (handler != null) return handler(this, args); return null; } public HtmlViewContext() { htmlList = new List&lt;object&gt;(); } public HtmlViewContext(HtmlViewContext ctx): this() { parent = ctx; } public void AddContent(string html) { if (parent != null) { parent.AddContent(html); return; } htmlList.Add(html); } public void AddContent(Type type, Func&lt;object, string&gt; html) { if (parent != null) { parent.AddContent(type, html); return; } htmlList.Add(new Tuple&lt;Type, Func&lt;object, string&gt;&gt;(type, html)); } public void AddContent(Type type, Func&lt;IEnumerable&lt;object&gt;, string&gt; html) { if (parent != null) { parent.AddContent(type, html); return; } htmlList.Add(new Tuple&lt;Type, Func&lt;IEnumerable&lt;object&gt;, string&gt;&gt;(type, html)); } public object GetContent() { HtmlViewResult result = new HtmlViewResult(this); result.GetResult(); while (result.Continues) { object value = OnProvideValue(new BindingModelToHtmlArgs(result.Hint, result.Domain)); result.GetResult(value); } return result.GetResult(); } } private class HtmlViewResult { private readonly HtmlViewContext htmlView; private readonly IEnumerator&lt;object&gt; it; private object currentState; private readonly StringBuilder builder; public HtmlViewResult(HtmlViewContext htmlView) { this.htmlView = htmlView; Continues = true; this.builder = new StringBuilder(); it = GetHtmlContent(); } private object GetResult() { while (it.MoveNext()) { if (it.Current != null) { builder.Append(it.Current); } else { break; } } return builder.ToString(); } internal object GetResult(object context) { currentState = context; it.MoveNext(); builder.Append(it.Current); builder.Append(GetResult()); return builder.ToString(); } public bool Continues { get; set; } public Type Hint { get; private set; } public Type Domain { get; private set; } public IEnumerator&lt;string&gt; GetHtmlContent() { foreach (object obj in htmlView.htmlList) { string html = obj as string; if (html != null) { yield return html; } else { Hint = obj.GetType(); if (currentState != null) { throw new InvalidOperationException("invalid state"); } var f1 = obj as Tuple&lt;Type, Func&lt;object, string&gt;&gt;; if (f1 != null) { Domain = f1.Item1; } var f2 = obj as Tuple&lt;Type, Func&lt;IEnumerable&lt;object&gt;, string&gt;&gt;; if (f2 != null) { Domain = f2.Item1; } yield return null; if (f1 != null) { yield return f1.Item2(currentState); } if (f2 != null) { yield return f2.Item2(currentState as IEnumerable&lt;object&gt;); } currentState = null; Hint = null; Domain = null; } } Continues = false; } } </code></pre>
[ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-01-23T02:55:46.187", "Id": "66866", "Score": "1", "body": "Please read [What makes a good question?](http://meta.codereview.stackexchange.com/a/76/34757) I hope this code might get better review answers, if you added some introduction to the question to say what the code is supposed to do (what problem you are trying to solve)." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-01-23T14:35:38.010", "Id": "66916", "Score": "0", "body": "On my further questions I'll try to provide more context. That being said I think there is no value on editing my question since I already accepted an answer." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-12-19T18:30:21.740", "Id": "134923", "Score": "0", "body": "I'd say there is value on improving the question, even now that there's an accepted answer: even if you're all set now, this thread might be useful for others and it would be better if Q&A are clear for most users. After all, isn't that what editors & reviewers do all the time here on SO/SE ?" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-12-19T20:35:26.137", "Id": "134958", "Score": "0", "body": "@superjos I'm on it but please remind that I am not able to update the code due to asking policy." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-12-21T11:28:35.100", "Id": "135249", "Score": "0", "body": "sorry, I was not aware of this policy. Just my thoughts on keeping this place as a good source for help." } ]
[ { "body": "<p><code>BindingModelToHtmlEh</code> - really, an <code>Eh</code> suffix for a delegate?</p>\n\n<blockquote>\n<pre><code>public delegate object BindingModelToHtmlEh(object sender, BindingModelToHtmlArgs args);\n</code></pre>\n</blockquote>\n\n<p>Wait a minute. This <em>looks</em> like an event handler, it's got the <code>sender</code> and <code>EventArgs</code>-derived <code>args</code> parameters, but it returns an <code>object</code>. This is rather surprising. Events shouldn't need to <em>return</em> anything, they carry all the needed data in the <code>EventArgs</code> instance; relying on events' return value can cause nasty unsuspected bugs when/if you start having more than a single subscriber to your event.</p>\n\n<p>I think you can drop that delegate and declare your event as: </p>\n\n<pre><code>public event EventHandler&lt;BindingModelToHtmlArgs&gt; ProvideValue;\n</code></pre>\n\n<p>And then you can fix your <code>EventArgs</code> class to include whatever <code>object</code> you wanted your event handler to return. Also the naming for the event isn't terrific, I'd expect something more in line with the framework, like <code>ValueProvided</code>.</p>\n\n<p>Aside from that, the first thing that really caught my attention was that the <code>GetContent</code> method you're worried about, is returning an <code>object</code>. I strongly believe a public API that exposes <code>object</code> better have a very, <em>very</em>, <strong>very</strong> good reason to do so.</p>\n\n<p><code>GetContent</code> returns the result of <code>GetResult</code>:</p>\n\n<pre><code>internal object GetResult(object context)\n{\n currentState = context;\n it.MoveNext();\n builder.Append(it.Current);\n builder.Append(GetResult());\n return builder.ToString();\n}\n</code></pre>\n\n<p>And that is undeniably a <code>string</code>. Why are you throwing away type safety like this? Any method that requires an <code>object</code> will be more than happy to take your <code>string</code>, you don't have to \"downgrade\" it any sooner. In fact, you should be holding on to your types for as long as it's possible to do so.</p>\n\n<p>The setter for <code>HtmlViewResult.Continues</code> should be <code>private</code>. The way you have it, it's possible for a caller to mess with it, and that doesn't look like it would do any good.</p>\n\n<p>I think there's a lot more to review, but that's a start :)</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-01-23T03:22:52.873", "Id": "66870", "Score": "0", "body": "You stated that events shall carry all the data needed, does that also applies for fields that the subscribers shall fill(that's why I used return)? I wasn't also expecting any cenario where that event has multiple subscribers but you got the point. My GetContent method returns object because other implementations of IViewContext for Winforms are expected and those would return a Control." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-01-23T03:35:27.177", "Id": "66871", "Score": "2", "body": "Yup. Think of a `CancelEventArgs`: the handler sets the `Cancel` value to `true` and when the call returns to the sender, `e.Cancel` is acted upon - the handler doesn't return a `bool`. With multiple subscribers, the returned value would be that of the last handler that executed, which I believe would be the last handler that was registered with the event. I think I'd try to see what I can get out of generics before resorting to `object`, but you got a fair point here, a WinForms `Control` and a HTML string have little in common..." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-01-23T03:39:33.147", "Id": "66872", "Score": "0", "body": "Sorry I thought you were talking about GetContent but you were talking about GetResult. I believe it just slipped away because I really do care about type safety and I try to only drop it if absolutly needed and as late as possible." } ], "meta_data": { "CommentCount": "3", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-01-23T02:43:05.330", "Id": "39856", "ParentId": "39827", "Score": "6" } }, { "body": "<p>Apart from the comments provided by @lol.upvote:</p>\n\n<p>The code as you have posted it does not compile for two reasons:</p>\n\n<ul>\n<li><p><code>htmlList</code> is a private member of <code>HtmlViewContext</code> so <code>HtmlViewResult</code> cannot access it. I can only assume that <code>HtmlViewResult</code> is actually a nested class within <code>HtmlViewContext</code> (oin which case it can access the private member of the outer class).</p></li>\n<li><p>In <code>HtmlViewContext</code> you call <code>result.GetContent()</code> however <code>GetContent()</code> is a private method in <code>HtmlViewResult</code> so it cannot be accessed (be it a n inner class or not)</p></li>\n</ul>\n\n<p>Now, we only review working code but because the above things are mostly access modifier problems rather than actual code bugs I'll continue with the review anyway. However you should test that your code compiles and work first before posting here.</p>\n\n<p><strong>Review:</strong></p>\n\n<p>First off: The idiomatic way to create tuples is to use <code>Tuple.Create()</code>. This way the compiler can infer the generic types automatically which saves you some typing work. In your case this means: <code>Tuple.Create(type, html)</code> - much shorter.</p>\n\n<hr>\n\n<p>Your code in <code>HtmlViewContext.GetContent()</code> and the <code>HtmlViewResult</code> classes is so heavily intertwined that I'm having trouble actually figuring out what is going on there and what is supposed to happen. In the long run this is unmaintainable code. The next developer which comes along in 2 years time and tries to make a change here will just bang his head against the desk for a while until he can figure it out.</p>\n\n<p>So what to do about it? Let's see if we can decipher the intend of the code:</p>\n\n<p>You build a list of what I'd call content providers. Then you process that list by appending all straight html providers together until you hit a function based provider, at that point you stop, raise an event which returns an object which is the used to execute the provider returning a string (presumably dynamically generated html).</p>\n\n<p>Now your problem is that you don't have a common interface for your content providers which results in a lot of type checking and casting which is a bit nasty in OO. So let's see what they have in common.</p>\n\n<p>For one thing they all produce a string but while one provider can produce the string immediately others require external context. So I'd suggest something like this:</p>\n\n<pre><code> private interface IContentProvider\n {\n BindingModelToHtmlArgs GetContextRequest(); \n string GetContent(object context);\n }\n\n private class StringContentProvider : IContentProvider\n {\n private string _Content;\n\n public StringContentProvider(string content)\n {\n _Content = content;\n }\n\n public BindingModelToHtmlArgs GetContextRequest()\n {\n return null; // need no context\n }\n\n public string GetContent(T context)\n {\n return _Content;\n }\n }\n\n private class SingleObjectResolverContentProvider : IContentProvider\n {\n private Tuple&lt;Type, Func&lt;object, string&gt;&gt; _Provider;\n\n public SingleObjectResolverContentProvider(Tuple&lt;Type, Func&lt;object, string&gt;&gt; provider)\n {\n _Provider = provider;\n }\n\n public BindingModelToHtmlArgs GetContextRequest()\n {\n return new BindingModelToHtmlArgs(_Provider.GetType(), _Provider.Item1);\n }\n\n public string GetContent(object context)\n {\n return _Provider.Item2(context);\n }\n }\n\n private class ObjectCollectionResolverContentProvider : IContentProvider\n {\n private Tuple&lt;Type, Func&lt;IEnumerable&lt;object&gt;, string&gt;&gt; _Provider;\n\n public ObjectCollectionResolverContentProvider(Tuple&lt;Type, Func&lt;IEnumerable&lt;object&gt;, string&gt;&gt; provider)\n {\n _Provider = provider;\n }\n\n public BindingModelToHtmlArgs GetContextRequest()\n {\n return new BindingModelToHtmlArgs(_Provider.GetType(), _Provider.Item1);\n }\n\n public string GetContent(object context)\n {\n return _Provider.Item2((IEnumerable&lt;object&gt;)context);\n }\n }\n</code></pre>\n\n<p>These are nested classes inside <code>HtmlViewContext</code>.</p>\n\n<p>You need to change your <code>htmlList</code> and <code>Add</code> methods:</p>\n\n<pre><code> private readonly List&lt;IContentProvider&gt; htmlList;\n\n ...\n\n public void AddContent(string html)\n {\n if (parent != null)\n {\n parent.AddContent(html);\n return;\n }\n htmlList.Add(new StringContentProvider(html));\n }\n\n public void AddContent(Type type, Func&lt;object, string&gt; html)\n {\n if (parent != null)\n {\n parent.AddContent(type, html);\n return;\n }\n htmlList.Add(new SingleObjectResolverContentProvider(Tuple.Create(type, html)));\n }\n\n public void AddContent(Type type, Func&lt;IEnumerable&lt;object&gt;, string&gt; html)\n {\n if (parent != null)\n {\n parent.AddContent(type, html);\n return;\n }\n htmlList.Add(new ObjectCollectionResolverContentProvider(Tuple.Create(type, html));\n }\n</code></pre>\n\n<p>Next thing is that you need to build the contents. The weird thing is that in your code you actually discard all the strings being returned except for the last call. I'll assume this is a bug for now.</p>\n\n<pre><code> public string GetContent()\n {\n StringBuilder sb = new StringBuilder();\n\n foreach (var provider in htmlList)\n {\n object context = null;\n var contextRequest = provider.GetContextRequest();\n if (contextRequest != null)\n {\n context = OnProvideValue(contextRequest);\n }\n sb.Append(provider.GetContent(context));\n }\n\n return sb.ToString();\n }\n</code></pre>\n\n<p>And we are done. The <code>HtmlViewRequest</code> class is gone and the code is much more straight forward to read and extend in the future.</p>\n\n<p>What I don't like is that the context is just an <code>object</code> - next thing I'd check is if that can't be refactored somehow to provide a stronger type.</p>\n\n<p>For reference - the <code>HtmlViewContext</code> class now looks like this (I've renamed <code>htmlList</code> to reflect the intend better):</p>\n\n<pre><code>public class HtmlViewContext : IViewContext\n{\n private readonly List&lt;IContentProvider&gt; contentProviders;\n private HtmlViewContext parent;\n public event BindingModelToHtmlEh ProvideValue;\n\n protected virtual object OnProvideValue(BindingModelToHtmlArgs args)\n {\n BindingModelToHtmlEh handler = ProvideValue;\n if (handler != null) return handler(this, args);\n return null;\n }\n\n public HtmlViewContext()\n {\n contentProviders = new List&lt;IContentProvider&gt;();\n }\n\n public HtmlViewContext(HtmlViewContext ctx)\n : this()\n {\n parent = ctx;\n }\n\n public void AddContent(string html)\n {\n if (parent != null)\n {\n parent.AddContent(html);\n return;\n }\n contentProviders.Add(new StringContentProvider(html));\n }\n\n public void AddContent(Type type, Func&lt;object, string&gt; html)\n {\n if (parent != null)\n {\n parent.AddContent(type, html);\n return;\n }\n contentProviders.Add(new SingleObjectResolverContentProvider(Tuple.Create(type, html)));\n }\n\n public void AddContent(Type type, Func&lt;IEnumerable&lt;object&gt;, string&gt; html)\n {\n if (parent != null)\n {\n parent.AddContent(type, html);\n return;\n }\n contentProviders.Add(new ObjectCollectionResolverContentProvider(Tuple.Create(type, html));\n }\n\n public string GetContent()\n {\n StringBuilder sb = new StringBuilder();\n\n foreach (var provider in contentProviders)\n {\n object context = null;\n var contextRequest = provider.GetContextRequest();\n if (contextRequest != null)\n {\n context = OnProvideValue(contextRequest);\n }\n sb.Append(provider.GetContent(context));\n }\n\n return sb.ToString();\n }\n\n private interface IContentProvider\n {\n BindingModelToHtmlArgs GetContextRequest(); \n string GetContent(object context);\n }\n\n private class StringContentProvider : IContentProvider\n {\n private string _Content;\n\n public StringContentProvider(string content)\n {\n _Content = content;\n }\n\n public BindingModelToHtmlArgs GetContextRequest()\n {\n return null; // need no context\n }\n\n public string GetContent(object context)\n {\n return _Content;\n }\n }\n\n private class SingleObjectResolverContentProvider : IContentProvider\n {\n private Tuple&lt;Type, Func&lt;object, string&gt;&gt; _Provider;\n\n public SingleObjectResolverContentProvider(Tuple&lt;Type, Func&lt;object, string&gt;&gt; provider)\n {\n _Provider = provider;\n }\n\n public BindingModelToHtmlArgs GetContextRequest()\n {\n return new BindingModelToHtmlArgs(_Provider.GetType(), _Provider.Item1);\n }\n\n public string GetContent(object context)\n {\n return _Provider.Item2(context);\n }\n }\n\n private class ObjectCollectionResolverContentProvider : IContentProvider\n {\n private Tuple&lt;Type, Func&lt;IEnumerable&lt;object&gt;, string&gt;&gt; _Provider;\n\n public ObjectCollectionResolverContentProvider(Tuple&lt;Type, Func&lt;IEnumerable&lt;object&gt;, string&gt;&gt; provider)\n {\n _Provider = provider;\n }\n\n public BindingModelToHtmlArgs GetContextRequest()\n {\n return new BindingModelToHtmlArgs(_Provider.GetType(), _Provider.Item1);\n }\n\n public string GetContent(object context)\n {\n return _Provider.Item2((IEnumerable&lt;object&gt;)context);\n }\n }\n}\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-01-23T14:31:01.320", "Id": "66914", "Score": "1", "body": "I just have a word for this: \"fantastic!\". I think it is incredible to find a pattern like that one by only viewing a not so understandable method. Thank you very much for your effort! On my further questions I'll try to provide more context as well as to make really sure that the code I provide is totally compilabe (I made some in-place changes and ended up with the visibility problem, I also forgot that `HtmlViewResult` was a inner class). That being said I think there is no value on editing this question since you figured out what I was doing and your answer is accepted." } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-01-23T08:50:57.137", "Id": "39865", "ParentId": "39827", "Score": "4" } } ]
{ "AcceptedAnswerId": "39865", "CommentCount": "5", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-01-22T17:27:02.147", "Id": "39827", "Score": "5", "Tags": [ "c#", "html" ], "Title": "Generating dynamic HTML" }
39827
<p>I would really like something to replace all of these <code>REPLACE</code> Statements.</p> <pre><code>SELECT DISTINCT CAH.CaseNbr , REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE( (SELECT table1.Degree FROM SDUJS.dbo.fnWorstDegreeCharge(CB.CaseID) AS table1), 'F1', 'F') ,'F2','F'),'F3','F'),'F4','F'),'F5','F'),'F6','F'),'FA','F'),'FB','F') ,'FC','F') AS Degree , dbo.fncasecounty(CB.CaseID) AS County FROM Justice.dbo.CaseBase AS CB INNER JOIN Justice.dbo.xCaseBaseChrg AS xCBC WITH (NOLOCK) ON xCBC.CaseID = CB.CaseID INNER JOIN Justice.dbo.Chrg AS Chrg WITH (NOLOCK) ON Chrg.ChargeID = xCBC.ChargeID INNER JOIN Justice.dbo.CaseAssignHist AS CAH WITH (NOLOCK) ON CAH.CaseID = CB.CaseID INNER JOIN Justice.dbo.ClkCaseHdr AS CCH WITH (NOLOCK) ON CCH.CaseID = CB.CaseID WHERE CCH.DtFile BETWEEN '07/01/2010' AND '06/30/2011' AND CCH.CaseUTypeID IN (858,4330,865,4329,6362,5112) ORDER BY CaseNbr </code></pre> <p>All possible entries for that column</p> <blockquote> <p>M1, M2, MO, PO, CHINS, F1, F2, F3, F4, F5, F6, FA, FB, FC, 00</p> </blockquote> <p>I want all the Felonies to be represented by <code>F</code></p> <hr> <h1>Code after the review</h1> <p>I decided not to do this as a follow up question because there isn't much that I think can be done to this query now to make it faster, except for get rid of the <code>DISTINCT</code> which I don't feel comfortable doing right now.</p> <pre><code>SELECT DISTINCT CAH.CaseNbr , (SELECT table1.Degree FROM SDUJS.dbo.fnWorstDegreeCharge(CB.CaseID) AS table1) AS Degree , dbo.fncasecounty(CB.CaseID) AS County FROM Justice.dbo.CaseBase AS CB INNER JOIN Justice.dbo.CaseAssignHist AS CAH WITH (NOLOCK) ON CAH.CaseID = CB.CaseID INNER JOIN Justice.dbo.ClkCaseHdr AS CCH WITH (NOLOCK) ON CCH.CaseID = CB.CaseID WHERE CCH.DtFile BETWEEN '07/01/2010' AND '06/30/2011' AND CCH.CaseUTypeID IN (858,4330,865,4329,6362,5112) </code></pre> <p><strong>Missing <code>REPLACE</code> statement</strong></p> <p>I moved the "<code>REPLACE</code>" to the function that I am calling, but I used <strong>@rolfl</strong>'s wonderful Case Statement idea to get rid of all the <code>REPLACE</code> statements inside that function.</p>
[ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-01-22T19:38:48.190", "Id": "66822", "Score": "0", "body": "Are there, or can there be, other values starting with 'F' that would be broken if you selected the first leftmost character instead? It might be useful to include a few possible values of that field." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-01-24T17:43:43.820", "Id": "67112", "Score": "0", "body": "Warning: with nolock is dangerous: http://stackoverflow.com/a/5469238" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-01-24T17:51:18.910", "Id": "67113", "Score": "0", "body": "@ChrisMathews, this is something that the Vendor told us to do, in order to speed things up. I am pulling data from a report server. if I put a lock on all these tables then I can't run concurrent reports, this can cause issues. that is the purpose of using `NOLOCK` but thank you for that information." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-01-24T17:52:15.897", "Id": "67114", "Score": "0", "body": "@ChrisMathews, in other words there shouldn't be too much going on in terms of things being changed here, so the dangers are less than what you are thinking because of the way that the Databases are set up." } ]
[ { "body": "<p>This strikes me as best being done by using a temp table, or <code>with</code> clause.</p>\n\n<p>Also, the DISTINCT part worries me.... why is that needed? Are your joins not good?</p>\n\n<p>Still, I think you may have some more contentment with:</p>\n\n<pre><code>SELECT DISTINCT\n CAH.CaseNbr,\n (SELECT CASE WHEN Degree in ('F1','F2','F3','F4','F5','F6','FA','FB','FC')\n THEN 'F'\n ELSE Degree\n END\n FROM SDUJS.dbo.fnWorstDegreeCharge(CB.CaseID)) AS Degree,\n dbo.fncasecounty(CB.CaseID) AS County\n....\n</code></pre>\n\n<p>You should still consider a better mechanism for joining. The procedure route seems 'klunky'</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-01-22T22:17:37.203", "Id": "66838", "Score": "0", "body": "it's a really bad Data Retrieval (PITA Report). I am labeling a case with one Charge's degree, a case can have many charges and they can all be different degrees. the data is good but what they want isn't always good for the data... does that even make sense?" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-01-22T22:33:13.830", "Id": "66840", "Score": "0", "body": "the database tables are connected all over the place so I could end up with duplicated data. I almost always throw it in there on this Database. I probably don't need it on this query because it isn't bringing back more than a couple of columns" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-01-23T13:47:08.057", "Id": "66910", "Score": "0", "body": "I like the `CASE` statement. I will see if I need the `DISTINCT or not while at work today." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-01-23T22:47:05.167", "Id": "67004", "Score": "0", "body": "I will wait until the Question is Eligible for a bounty and then accept your answer. I need the `DISTINCT` I am either not as good of a SQL Dev that I need to be, or the Database is really screwy....or both. I can't believe that I didn't think of a Case Statement...Sigh." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-01-23T22:49:46.637", "Id": "67005", "Score": "2", "body": "That's why CodeReview is a Good Thing™ .... pulls on different people's eyes, experience, and opinions." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-01-23T22:52:05.490", "Id": "67006", "Score": "0", "body": "its for a report that has been stressing me out since I started. finally got it whittled down to what the user actually needs and not \"*what the legacy report returned*\"" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-01-24T14:40:19.017", "Id": "67086", "Score": "0", "body": "I ended up using the `CASE` statement inside the function instead of outside in this Query. think I will post another Question, I have a lot of SQL to learn." } ], "meta_data": { "CommentCount": "7", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-01-22T22:03:30.323", "Id": "39842", "ParentId": "39828", "Score": "6" } } ]
{ "AcceptedAnswerId": "39842", "CommentCount": "4", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-01-22T17:38:49.593", "Id": "39828", "Score": "8", "Tags": [ "sql", "sql-server" ], "Title": "Can you replace a REPLACE statement, or 9?" }
39828
<p>I've seen a similar question to this but mine's a little more specific. I have the below</p> <pre><code>File f = new File("./data.txt"); if(f.isFile()) { try { FileChannel fc = new RandomAccessFile(f,"r").getChannel(); //Get information and return it } catch(FileNotFoundException e) { System.out.println("FileNoFoundException: "+e.getMessage()); } } else { //If the file wasn't found, return default values } </code></pre> <p>I was wondering, should I just put the default returning of the information in the catch block?<br/> I assumed that'd be a no because you're not really supposed to use it to control flow. But having the both the if and the try catch just looks too redundant to me.</p>
[ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-01-22T18:07:37.353", "Id": "66805", "Score": "3", "body": "Exceptions control flow whether you like it or not. You shouldn't **throw** Exceptions to control **normal** program flow, that doesn't mean that you should avoid controlling the program flow when you **catch** the exception." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-01-23T02:39:58.513", "Id": "66865", "Score": "0", "body": "The `if(f.isFile())` statement looks redundant to the `FileNotFoundException`. Also, what if `f` is `null`?" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-01-23T14:21:14.520", "Id": "66912", "Score": "0", "body": "Yeah, the redundancy was what I was unsure of. Whether I should do things based on if an exception is thrown or if I should take steps using the if statement (perhaps proactive is the right word) to check the file because having both looks weird. I did not consider f being null. What might go wrong to cause that? Out of memory or something similar?" } ]
[ { "body": "<p>In cases like this, I like taking a default-unless-better approach... Consider this re-working of your code to do the same thing in a different order.</p>\n\n<p>The basic premise is:</p>\n\n<ol>\n<li>set up a default value (or null if it is a complicated thing to do).</li>\n<li>do the hard work which may be missing dependencies or may fail</li>\n<li>if the hard work completes successfully, return that result.</li>\n</ol>\n\n<p>The reason this works well is because you can exit from the hard work at any point, and have the default standing by to continue.....</p>\n\n<p>... also, as an exercise, use the try-with-resources and new NIO2 features in Java7</p>\n\n<pre><code>// set up the default value...\nSomeValue result = null;\nPath path = Paths.get(\"./data.txt\");\nif (Files.isRegularFile(path)) {\n try (SeekableByteChannel channel =\n Files.newByteChannel(path, StandardOpenOptions.READ)) {\n\n // do the work required for your file....\n ...\n\n // after everything is successful... set the result:\n result = new SomeValue(....real arguments ....);\n } catch (IOException ioe) {\n System.out.println(\"FileNoFoundException: \" + e.getMessage());\n }\n}\nresult == null ? new SomeValue(defaults...) : result;\n</code></pre>\n\n<p>Additionally, there is no reason, if you are in a method that builds these things, that you can't return immediately with the right answer.</p>\n\n<p>Often if you are doing things like the above, it indicates that what you are doing <strong>should</strong> be in a sub-method, with an early-return when you have a successful setup, and a default return value when things fail.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-01-23T14:24:09.167", "Id": "66913", "Score": "0", "body": "It actually is in a submethod and after reworking it a bit I found that this was the best option. Thanks! Very similar to the answer below but I understood this one more." } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-01-22T19:18:42.367", "Id": "39835", "ParentId": "39829", "Score": "4" } }, { "body": "<p>My usual pattern here is to set the default values first, then replace the defaults with the expected values in the happy path.</p>\n\n<pre><code>int resultA = DEFAULT_FOR_A;\nString resultB = DEFAULT_FOR_B;\n\n File f = new File(\"./data.txt\");\n if(f.isFile())\n {\n try\n {\n FileChannel fc = new RandomAccessFile(f,\"r\").getChannel();\n resultA = computeA(fc);\n resultB = readB(fc);\n }\n catch(FileNotFoundException e)\n {\n // TODO: replace with a logging framework\n System.out.println(\"FileNoFoundException: \"+e.getMessage());\n }\n}\n\n// use resultA and resultB as required.\n</code></pre>\n\n<p>If <code>computeA()</code> and <code>readB()</code> can also throw, then you need to think about whether the results are coupled or not. If they are coupled, then I would advise storing the results of the functions in variables scoped to the try block, and only overwriting the results after you are certain that no further exceptions will be thrown.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-01-22T19:20:13.493", "Id": "39836", "ParentId": "39829", "Score": "4" } } ]
{ "AcceptedAnswerId": "39835", "CommentCount": "3", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-01-22T17:45:59.703", "Id": "39829", "Score": "6", "Tags": [ "java" ], "Title": "Flow control with try catch to reduce redundancy" }
39829
<p>This functionality is for a Monopoly board game. In particular, when the player lands on Chance or Community Chest, a random card is drawn with a particular set of instruction, a bonus could be paid out, or perhaps the player is fined. The two cards are different in that one is a set of 16 cards and the other a set of 14. How would you make this code more efficient?</p> <h3>Chance</h3> <pre><code>function chanceCard() { var x = Math.floor(Math.random() * ((16 - 1) + 1) + 1); var title = chancecards['chance' + x].title; var type = chancecards['chance' + x].type; var bill = chancecards['chance' + x].bill; var bonus = chancecards['chance' + x].bonus; if (type == "bill") { updateBalance("-", bill); } else if (type == "bonus") { updateBalance("+", bonus); } else if (type == "move") { var newposition = chancecards['chance' + x].newposition; var currentposition = players[player].currentpos; if (newposition == 40) { //this if the player has to "advance to go" updateBalance("+", 200); } else if (newposition &lt; currentposition) { //if the new position is less than the current one it means the player has to go past go updateBalance("+", 200); } players[player].prevpos = players[player].currentpos; players[player].currentpos = newposition; players[player].startpos = players[player].currentpos; movePiece(); checkForSale(); } else if (title == "Go back 3 spaces") { players[player].prevpos = players[player].currentpos; players[player].currentpos -= -3; players[player].startpos = players[player].currentpos; movePiece(); checkForSale(); } flipCard("Chance"); } </code></pre> <h3>Community Chest</h3> <pre><code>function chestCard() { var x = Math.floor(Math.random() * ((14 - 1) + 1) + 1); var title = chestcards['chest' + x].title; var chesttype = chestcards['chest' + x].type; var bill = chestcards['chest' + x].bill; var bonus = chestcards['chest' + x].bonus; if (chesttype == "bill") { updateBalance("-", bill); } else if (chesttype == "bonus") { updateBalance("+", bonus); } else if (chesttype == "move") { var newposition = chestcards['chest' + x].newposition; var currentposition = players[player].currentpos; if (newposition == 40) { //this if the player has to "advance to go" updateBalance("+", 200); } else if (newposition &lt; currentposition) { //if the new position is less than the current one it means the player has to go past go updateBalance("+", 200); } players[player].prevpos = players[player].currentpos; players[player].currentpos = newposition; players[player].startpos = players[player].currentpos; movePiece(); checkForSale(); } flipCard("Community Chest"); } </code></pre> <h3>CreateCards</h3> <pre><code>function createCards() { chancecards = { chance1: { title: "Advance to go", type: "move", newposition: 40 }, chance2: { title: "Advance to London", type: "move", newposition: 39 }, chance4: { title: "Your ass is going to jail", type: "move", newposition: 10 }, chance9: { title: "Advance to Rome", type: "move", newposition: 24 }, chance10: { title: "Advance to Charles de Gaulle", type: "move", newposition: 15 }, chance11: { title: "Advance to Amsterdam", type: "move", newposition: 11 }, chance6: { title: "Go back 3 spaces", type: "movex", newposition: -3 }, chance14: { title: "No drink and driving mate1", type: "bill", bill: 20 }, chance15: { title: "Get out of Jail free card", type: "bill", bill: 150 }, chance7: { title: "Pay school fees", type: "bill", bill: 150 }, chance12: { title: "Speeding fine", type: "bill", bill: 150 }, chance5: { title: "Bank pays you dividend", type: "bonus", bonus: 40 }, chance13: { title: "You have won the competition", type: "bonus", bonus: 200 }, chance16: { title: "Your building loan matures", type: "bonus", bonus: 200 }, chance3: { title: "You are assessed for street repairs $40 per house $115 per hotel", type: "billx" }, chance8: { title: "House repairs $25 per house $100 per hotel", type: "billx" } }; chestcards = { chest1: { title: "Advance to go", type: "move", newposition: 40, bonus: 200 }, chest2: { title: "Advance to Cairo", type: "move", newposition: 1 }, chest3: { title: "Go to Jail", type: "move", newposition: 10 }, chest4: { title: "Pay hospital fees", type: "bill", bill: 100 }, chest5: { title: "Pay doctor fees", type: "bill", bill: 50 }, chest6: { title: "Pay insurance premium", type: "bill", bill: 50 }, chest7: { title: "Bank error. Collect $200", type: "bonus", bonus: 200 }, chest8: { title: "Annuity matures. Collect $100", type: "bonus", bonus: 100 }, chest9: { title: "You inherit $100", type: "bonus", bonus: 100 }, chest10: { title: "From sale of stock you get $50", type: "bonus", bonus: 50 }, chest11: { title: "Preference shares: $25", type: "bonus", bonus: 25 }, chest12: { title: "You have won second prize in a beauty contest. Collect $10.", type: "bonus", bonus: 10 }, chest13: { title: "It is your birthday. Collect $10.", type: "bonus", bonus: 10 }, chest14: { title: "You win the lottery. Collect $10", type: "bonus", bonus: 10 } }; } </code></pre>
[ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-01-22T18:09:47.063", "Id": "66806", "Score": "0", "body": "1. `chanceCards()` , 2. `chestCards()` , 3. `createCards()`.\n\nI want to DRY 1 and 2." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-01-22T20:12:48.830", "Id": "66832", "Score": "0", "body": "I can help you out a bit but I want to stay DRY myself. Do you care if I write my answer using a lightweight framework?" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-01-23T14:49:09.980", "Id": "66917", "Score": "0", "body": "@pllee no i don't mind." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-01-23T14:50:29.887", "Id": "66918", "Score": "0", "body": "@AlienArrays haha yes ofcourse. This is just for educational purpose, I think the best way to learn is to actually build stuff" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-01-30T17:51:13.127", "Id": "68132", "Score": "3", "body": "Please don't make massive edits to your posts which invalidates answers. If you want to show the result, you can edit and add the text below your original question or post it as an answer stating that it is the result of the reviews. If you want more code reviewed, ask a new question." } ]
[ { "body": "<p>The first thing I would suggest to DRY your code, is to organize your cards in collections (arrays of objects), rather than nested objects. The reason is: arrays have order, and JavaScript has many built-in methods to work with collections, like <code>sort</code>, <code>map</code>, and many others:</p>\n\n<pre><code>var cards = {\n // Collection of chance cards\n chance: [\n {\n title: 'Advance to go',\n type: 'move',\n position: 40\n },\n {\n title: 'Advance to London',\n type: 'move',\n position: 39\n },\n {\n title: 'Your ass is going to jail',\n type: 'move',\n position: 10\n },\n // more\n ],\n // Collection of chest cards\n chest: [\n // chest cards\n ]\n};\n</code></pre>\n\n<p>That way you can you get rid of <code>chance1, chance2, chance3</code> and use array indices instead.</p>\n\n<p>Now that you're working with a nicer data structure, let's rethink our steps, and what we can do to solve them:</p>\n\n<ol>\n<li>Grab a random card. Now that we have an array, we can simply shuffle it, and grab an element.</li>\n<li>Determine the type of card. We can use a dictionary approach, instead of multiple <code>if..else</code>.</li>\n<li>Update the game (balance, position, etc...)</li>\n</ol>\n\n<p>I can't run this code obviously I'm missing many parts, but hopefully it'll give you an idea of how to simplify it and improve readability.</p>\n\n<pre><code>// Naive shuffle implementation\nvar shuffle = function(xs) {\n return xs.slice(0).sort(function() {\n return .5 - Math.random();\n });\n};\n\nfunction getCard(from) {\n var card = shuffle(cards[from]).pop(); // a random card\n\n // A dictionary\n var types = {\n bill: function() {\n updateBalance('-', card.bill);\n },\n bonus: function() {\n updateBalance('+', card.bonus);\n },\n move: function() {\n var current = players[player].currentpos;\n var player = players[player]; // cache for convenience\n\n // We can shorten this statment as you were doing\n // the same thing in both clauses\n if (card.position == 40 || card.position &lt; current) {\n updateBalance(\"+\", 200);\n }\n\n player.prevpos = player.currentpos;\n player.currentpos = card.position;\n player.startpos = player.currentpos;\n\n movePiece();\n checkForSale();\n },\n // \"Go back 3 spaces\" is the only one of type `movex`\n // so we can use that in the same way as the others\n // without the need to compare by string\n movex: function() {\n var player = players[player];\n player.prevpos = player.currentpos;\n player.currentpos -= -3;\n player.startpos = player.currentpos;\n\n movePiece();\n checkForSale();\n }\n };\n\n // Run the code for the type if it exists\n if (types[card.type]) {\n types[card.type]();\n }\n\n // To be able to use the type, and for consistency\n // modify `filpCard` so it takes the types as `chest` and `chance`\n flipCard(from);\n}\n</code></pre>\n\n<p>But if you look up closesly there's a pattern that's still repeats itself a couple times:</p>\n\n<pre><code>player.prevpos = player.currentpos;\nplayer.currentpos = card.position;\nplayer.startpos = player.currentpos;\n\nmovePiece();\ncheckForSale();\n</code></pre>\n\n<p>This is related to point 3 (Update the game), it's harder to abstract. The main issue I see is that <code>player</code> is coupled to the function that creates the cards, and <code>updateBalance</code> also affects <code>player</code> but it's hidden away in the details. In an object oriented way you'd have <code>Board</code>, <code>Player</code> and <code>Card</code> classes, with their own methods and properties. Your current code as-is is hard to DRY up more. You could separate that repeating pattern into a function, but I'd argue that it will make your logic harder to follow.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-01-22T22:26:44.270", "Id": "66839", "Score": "2", "body": "Your last suggestion is really what needs to happen here. The effect of a card on a player should be one of the properties on card, so you'd have `card.applyTo(player)` with an `applyTo` method (for a specific example card) like `function applyTo(player) { player.moveTo(HOME) }`. Currently this key responsibility of a card has been moved elsewhere. \"A George divided against himself cannot stand!\"" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-01-22T22:47:13.057", "Id": "66841", "Score": "0", "body": "I agree, but at that point I'd rather build from scratch I suppose, in an object oriented way." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-01-23T14:57:05.177", "Id": "66919", "Score": "1", "body": "@elclanrs I went out to build this game without extensive planning, I am not very imaginative, but it is good to write bad code and then later realise why it is bad. I will finnish the game with bad code, just to get it working for now then." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-01-26T07:37:25.163", "Id": "67329", "Score": "0", "body": "I'd like to reemphasize your casual mention that shuffling an array by passing a non-deterministic comparator to `.sort()` is a naïve approach. It's a hack that can [yield unsatisfactory results](http://sroucheray.org/blog/2009/11/array-sort-should-not-be-used-to-shuffle-an-array/)." } ], "meta_data": { "CommentCount": "4", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-01-22T21:22:33.473", "Id": "39841", "ParentId": "39831", "Score": "14" } }, { "body": "<h3>Card representation</h3>\n\n<p>I offer three important tips to improve the representation of the cards:</p>\n\n<ol>\n<li>The draw-a-card-from-the-deck functions should have nothing to do with updating balances, moving pieces, etc. (In technical terms, <code>chanceCard()</code> and <code>chestCard()</code> violate the Single Responsibility Principle.)</li>\n<li>JavaScript lets you store code as a kind of data. (In technical terms, \"functions are first-class objects in JavaScript.\")</li>\n<li>Giant switch blocks (like the if-elseif-elseif-… chain in <code>chanceCard()</code>) are a hint to use objects instead. (In technical terms, apply the \"<a href=\"http://refactoring.com/catalog/replaceConditionalWithPolymorphism.html\">Replace Conditionals With Polymorphism</a>\" refactoring rule.)</li>\n</ol>\n\n<p>These indicators suggest that the action for the cards should be encoded in the cards themselves. Since you don't want to write a function per card, though, you'll want to classify the cards into several types, and define the functions in their prototypes.</p>\n\n<p>Note that \"bill\" and \"bonus\" cards are really just the same thing, except that bills have a negative impact on the player's balance and bonuses have a positive impact.</p>\n\n<h3>Code</h3>\n\n<pre><code>function updateBalance(player, amount) {\n player.balance += amount;\n}\n\nfunction movePiece(player, direction, destination) {\n if (direction &gt; 0 &amp;&amp; destination != \"jail\" &amp;&amp; destination &lt; player.currentpos) {\n // Moving forward to or past Go, but not going to jail\n updateBalance(player, +200);\n }\n player.currentpos = destination;\n checkForSale();\n}\n\nfunction drawCard(player, deck) {\n var card = deck.shift();\n // console.log(card.title);\n card.act(player);\n deck.push(card);\n}\n\nfunction shuffle(deck) {\n // Fisher-Yates shuffle\n for (var i = deck.length - 1; i &gt; 0; i--) {\n var j = Math.floor((i + 1) * Math.random());\n var swap = deck[i];\n deck[i] = deck[j];\n deck[j] = swap;\n }\n}\n\n//////////////////////// CARD TYPES ////////////////////////\n\nfunction AbsMoveCard(title, destination) {\n this.title = title;\n this.destination = destination;\n}\n\nAbsMoveCard.prototype.act = function(player) {\n // All logic about current position, bonus for passing Go, and checking\n // for property sale should be included in movePiece().\n movePiece(player, +1, this.destination);\n};\n\nfunction RelMoveCard(title, distance) {\n this.title = title;\n this.distance = distance;\n}\n\nRelMoveCard.prototype.act = function(player) {\n // All logic about current position, bonus for passing Go, and checking\n // for property sale should be included in movePiece().\n movePiece(player, this.distance, (player.currentpos + 40 + this.distance) % 40);\n}\n\nfunction MoneyCard(title, amount) {\n this.title = title;\n this.amount = amount;\n}\n\nMoneyCard.prototype.act = function(player) {\n updateBalance(player, this.amount);\n}\n\nfunction AssessmentCard(title, perHouse, perHotel) {\n this.title = title;\n this.perHouse = perHouse;\n this.perHotel = perHotel;\n}\n\nAssessmentCard.prototype.act = function(player) {\n updateBalance(player, player.houseCount * this.perHouse +\n player.hotelCount * this.perHotel);\n}\n\n/////////////////////////// CARDS ///////////////////////////\n\nvar chanceCards = [\n // \"Go\" should be position 0 rather than 40\n new AbsMoveCard(\"Advance to go\", 0),\n new AbsMoveCard(\"Advance to London\", 39),\n new AbsMoveCard(\"Your ass is going to jail\", \"jail\"),\n new AbsMoveCard(\"Advance to Rome\", 24),\n new AbsMoveCard(\"Advance to Charles de Gaulle\", 15),\n new AbsMoveCard(\"Advance to Amsterdam\", 11),\n new RelMoveCard(\"Go back 3 spaces\", -3),\n new MoneyCard(\"No drink and driving mate!\", -20),\n new MoneyCard(\"Get out of Jail free card\", -150),\n new MoneyCard(\"Pay school fees\", -150),\n new MoneyCard(\"Speeding fine\", -150),\n new MoneyCard(\"Bank pays you dividend\", +40),\n new MoneyCard(\"You have won the competition\", +200),\n new MoneyCard(\"Your building loan matures\", +200),\n new AssessmentCard(\"You are assessed for street repairs $40 per house $115 per hotel\", -40, -115),\n new AssessmentCard(\"House repairs $25 per house $100 per hotel\", -25, -100),\n];\n\nvar chestCards = [\n new AbsMoveCard(\"Advance to go\", 0),\n new AbsMoveCard(\"Advance to Cairo\", 1),\n new AbsMoveCard(\"Go to Jail\", \"jail\"),\n new MoneyCard(\"Pay hospital fees\", -100),\n new MoneyCard(\"Pay doctor fees\", -50),\n new MoneyCard(\"Pay insurance premium\", -50),\n new MoneyCard(\"Bank error. Collect $200\", +200),\n new MoneyCard(\"Annuity matures. Collect $100\", +100),\n new MoneyCard(\"You inherit $100\", +100),\n new MoneyCard(\"From sale of stock you get $50\", +50),\n new MoneyCard(\"Preference shares: $25\", +25),\n new MoneyCard(\"You have won second prize in a beauty contest. Collect $10.\", +10),\n new MoneyCard(\"It is your birthday. Collect $10.\", +10),\n new MoneyCard(\"You win the lottery. Collect $10\", +10),\n];\n\nshuffle(chanceCards);\nshuffle(chestCards);\n</code></pre>\n\n<h3>Example usage</h3>\n\n<pre><code>var player1 = { currentpos: 0, balance: 200, houseCount: 0, hotelCount: 0 };\ndrawCard(player1, chanceCards);\n</code></pre>\n\n<h3>Additional remarks</h3>\n\n<p>It would be more natural to represent Go as position 0 rather than position 40. You could then use the modulo 40 operation to maintain the illusion of a cyclical board.</p>\n\n<p>You designated board position 10 as the jail. However, I would prefer to think of board position 10 as the \"Just Visiting\" space rather than the \"In Jail\" portion. One or the other will need special treatment, and since the jail requires special handling anyway, it seems appropriate that it should be the exceptional case. Here, I've used the string <code>\"jail\"</code> to represent that position, but deeper consideration may be worthwhile.</p>\n\n<p>Picking a random element from the array to doesn't accurately simulate a card draw in a board game. I think it would be more appropriate to <a href=\"http://en.wikipedia.org/wiki/Fisher%E2%80%93Yates_shuffle\">shuffle</a> the cards initially, draw from the \"top\" of the deck, and replace the cards at the \"bottom\" after use.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-01-26T13:30:07.587", "Id": "67361", "Score": "0", "body": "Wow I really appreciate the tips, but it is way beyond the scope of my understanding of JS, I am still a beginner. I will definitely refer back to your tips once I learned more. It would be nice if a collection of Stack contributors do a tutorial of the Monopoly board game." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-01-27T22:50:39.567", "Id": "67604", "Score": "0", "body": "Hi, could you show me how you would call the different prototype methods depending on the card picked?" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-01-27T22:58:39.520", "Id": "67606", "Score": "0", "body": "The _Example usage_ already does everything. You don't call the prototype methods explicitly — that's what makes it elegant. Setting `AbsMoveCard.prototype.act = function() { … }` just means that every object created using `var card = new AbsMoveCard(…)` automatically gets that `act` function attached to it. You can then invoke that function with `card.act(player)`. Furthermore, you don't care what kind of card is drawn. Whatever card you pick, just call `card.act(player)` on it, and the card \"knows\" how to do the right thing." } ], "meta_data": { "CommentCount": "3", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-01-26T07:25:40.020", "Id": "40077", "ParentId": "39831", "Score": "8" } } ]
{ "AcceptedAnswerId": "40077", "CommentCount": "5", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-01-22T18:07:59.850", "Id": "39831", "Score": "14", "Tags": [ "javascript", "game" ], "Title": "Monopoly game cards" }
39831
<p>I am writing a function to filter a "dictionary" by the "subject" of its definitions.</p> <p>The dictionary data structure is a hash-map of this kind:</p> <pre><code>{ "word1" {:foo :bar :definitions [{:definition "def1" :subject ["Subject1" "Subject2"]} {:definition "def2" :subject ["Subject3" "Subject1"]}]} "word2" {:foo :baz :definitions [{:definition "def3" :subject "Subject2"} {:definition "def4" :subject ["Subject2" "Subject3"]}]} </code></pre> <p>The function needs to return a new dictionary with only definitions of the specified subject (no word entry if no definition available).</p> <p>I came up with two (working) different functions that returns the same exact result.<br> The first version uses <code>map</code>, the second version uses <code>loop/recur</code>.</p> <p><code>map</code> version:</p> <pre><code>(defn filter-by-subject [dict subject] (apply hash-map (flatten (map (fn [[word entry]] (let [definitions (definitions-for-subject entry subject)] (if (&gt; (count definitions) 0) [word (assoc entry :definitions definitions)] []))) dict)))) </code></pre> <p><code>loop/recur</code> version:</p> <pre><code>(defn filter-by-subject2 [dict subject] (loop [old-dict dict new-dict {}] (if-let [[word entry] (first old-dict)] ;; then (recur (dissoc old-dict word) (let [definitions (definitions-for-subject entry subject)] (if (&gt; (count definitions) 0) (assoc new-dict word (assoc entry :definitions definitions)) new-dict))) ;; else new-dict))) </code></pre> <p>Supporting functions:</p> <pre><code>(defn subjects-of-definition [definition] (let [sbjs (:subject definition)] (if (coll? sbjs) sbjs [sbjs]))) (defn definitions-for-subject [entry subject] (into [] (filter (fn [definition] (some #{subject} (subjects-of-definition definition))) (:definitions entry)))) </code></pre> <p>I would like to hear your opinion on these functions.</p> <ol> <li>Do they follow the common "functional style"? </li> <li>Which version of the two do you find more readable, clear, understandable or even faster?</li> </ol> <hr> <p><strong>UPDATE</strong></p> <p>A little clarification.<br> If a word has two definitions, one of subjects A and B, and one of subjects B and C, and we filter by subject A, the resulting dictionary will have only the first definition of word (the one of subjects A and B). </p> <p>Some examples:</p> <pre><code>=&gt; (def dictionary { "Bit" { :definitions [ { :definition "A unit of information storage on a computer" :subject "IT" } { :definition "Beijing Institute of Technology" :subject ["Acronyms" "Education"] }] } "Matrix" { :definitions [ { :definition "A rectangular array of numbers, symbols or expressions" :subject "Mathematics"} { :definition "A 1999 science fiction film" :subject "Movies"}]}}) #'user/dictionary =&gt; (filter-by-subject dictionary "Education") {"Bit" {:definitions [{:subject ["Acronyms" "Education"], :definition "Beijing Institute of Technology"}]}} =&gt; (filter-by-subject dictionary "IT") {"Bit" {:definitions [{:subject "IT", :definition "A unit of information storage on a computer"}]}} =&gt; (filter-by-subject dictionary "Movies") {"Matrix" {:definitions [{:subject "Movies", :definition "A 1999 science fiction film"}]}} </code></pre> <p>(note that, for example, filtering by "Education" deletes the "IT" definition of "Bit".)</p>
[]
[ { "body": "<p>Updated answer:</p>\n\n<p>Thanks for clarifying the question, the examples helped. Here is my new attempt:</p>\n\n<pre><code>(defn update-subjects [dict subj]\n (map (fn [[k {val :definitions}]]\n [k {:definitions\n (filter (fn [{s :subject}] \n ((into #{} (flatten [s])) subj)) val)}]) dict))\n\n(defn my-filter [dict subj]\n (into {} (-&gt;&gt; (update-subjects dict subj)\n (remove (comp empty? :definitions second)))))\n\n(= (my-filter dictionary \"IT\") (filter-by-subject dictionary \"IT\"))\n=&gt; true\n</code></pre>\n\n<p>in this solution, I first remove all the definitions which subjects do not match, and then I remove all the entries with empty definitions. I used the <a href=\"http://clojuredocs.org/clojure_core/clojure.core/-%3E%3E\" rel=\"nofollow\">threading macro (->>)</a> for readability.</p>\n\n<hr>\n\n<p>original answer:</p>\n\n<p>Here is another way of implementing your subject filter:</p>\n\n<pre><code>(defn subject-filter [p m]\n (filter (fn[[k {v :definitions}]]\n (some (fn [{x :subject}] \n ((into #{} (flatten [x])) p)) v)) m))\n</code></pre>\n\n<p>This implementation makes use of two important features:</p>\n\n<ol>\n<li><strong>Destructuring</strong> - an idiomatic method of extracting items from a data structure in clojure. I highly recommend keeping the following link handy at all times <a href=\"http://blog.jayfields.com/2010/07/clojure-destructuring.html\" rel=\"nofollow\">http://blog.jayfields.com/2010/07/clojure-destructuring.html</a></li>\n<li><strong>Sets as a predicate</strong> - in clojure, if a set is in a function position, it acts as a function that returns true iff the first argument is in the set. So it is very idiomatic to write <code>(if (#{1 2 3} i) .. ..)</code> to know if <code>i</code> is either 1, 2 or 3. Perhaps you could even use sets instead of arrays in your data definition for <code>:subject</code>, which will make this code even shorter and faster, and your DS more \"correct\" - you could never keep two identical subjects and <code>:subject</code> will be a predicate of a query subject.</li>\n</ol>\n\n<hr>\n\n<p>Just a note, you could also do without so much destructuring, and get a more concise function:</p>\n\n<pre><code>(defn my-filter [p m] \n (filter (fn[[k v]] (some (fn [x] ((into #{} (flatten [(:subject x)])) p)) (:definitions v))) m))\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-01-23T09:14:54.773", "Id": "66886", "Score": "0", "body": "Thanks for the good information! Unfortunately I already came up with a similar solution but filtering on the dictionary is not the solution. In fact if a word has two definitions, e.g. `{ \"word\" { :definitions [{:definition \"One\" :subject [\"foo\" \"bar\"]} {:definition \"Two\" :subject [\"bar\" \"baz\"]}]}}`, filtering by subject \"baz\" this code would return the same exact dictionary while the correct solution would be `{ \"word\" { :definitions [{:definition \"Two\" :subject [\"bar\" \"baz\"]}]}}`, i.e. only the definition with subject \"baz\" must be there. I'm updating the question to better clarify this." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-01-23T14:19:40.333", "Id": "66911", "Score": "0", "body": "Hey, you are right. I gave it another shot, check the updated answer" } ], "meta_data": { "CommentCount": "2", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-01-22T19:44:19.120", "Id": "39837", "ParentId": "39832", "Score": "1" } } ]
{ "AcceptedAnswerId": "39837", "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-01-22T18:21:58.623", "Id": "39832", "Score": "2", "Tags": [ "functional-programming", "clojure" ], "Title": "Filtering a dictionary by subject of definitions" }
39832
<p>I am just now learning Scala a bit on my own time. I wrote some code that works, but was wondering if you could eyeball it to see if its structure can be improved. It is a partial octree implementation.</p> <pre><code>class octree(min_x:Double, min_y:Double, min_z:Double, max_x:Double, max_y:Double, max_z:Double ){ var children:Array[octree] = new Array[octree](8) val min = (min_x,min_y,min_z) val max = (max_x,max_y,max_z) def side(x:Double,y:Double):Int={ if(x&lt;y) 1 else 0 } def index(x:Double,y:Double,z:Double):Int={ val center=(0.5*(max._1+min._1),0.5*(max._2+min._2), 0.5*(max._3+min._3)) (side(center._1,x))|(side(center._2,y)&lt;&lt;1)| (side(center._3,z)&lt;&lt;2) } def add(x:Double,y:Double,z:Double):octree={ var i=index(x,y,z) print(" "+i) if(children(i)==null){ var min2_x=min._1 var min2_y=min._2 var min2_z=min._3 var max2_x=max._1 var max2_y=max._2 var max2_z=max._3 val center=(0.5*(max._1+min._1),0.5*(max._2+min._2), 0.5*(max._3+min._3)) if((i&amp;1)==0) max2_x=center._1 else min2_x=center._1 if((i&amp;2)==0) max2_y=center._2 else min2_y=center._2 if((i&amp;4)==0) max2_z=center._3 else min2_z=center._3 children(i) = new octree(min2_x,min2_y,min2_z,max2_x,max2_y,max2_z) children(i) } else children(i).add(x,y,z) } def find(x:Double,y:Double,z:Double):octree={ var i=index(x,y,z) print(" "+i) if(children(i)==null){ this } else children(i).find(x,y,z) } } </code></pre>
[]
[ { "body": "<p>Some ideas:</p>\n\n<ul>\n<li>Properly indent your code and strictly adhere to some style guide. (For example it's very uncommon to have class name starting with a lowercase letter.) I recommend you to read some style guide or study the code of some publicly available libraries. This is very important for readability and future maintainability of your code. It doesn't matter if you will be reading it or somebody else. Code is written once but read many times.</li>\n<li>Define a custom class for vectors. (Having a function with 6 arguments is inconvenient and error prone and it is a signal for looking for alternative solutions).</li>\n<li>Use this class to implement vector operations on it.</li>\n<li>Variables that aren't modified should be declared <code>val</code>.</li>\n<li><code>side</code> could be made local to the <code>index</code> method.</li>\n<li><code>center</code> can be precomputed and reused.</li>\n<li>Instead of modifying variables when computing adding a node, it's often more idiomatic to describe the new cell declaratively. Using a helper function can shorten the code.</li>\n<li>Optimize recursive functions using <code>tailrec</code>, if possible.</li>\n</ul>\n\n<p>After some refactoring:</p>\n\n<pre><code>case class Vector(x: Double, y: Double, z: Double) {\n def +(that: Vector) = Vector(this.x + that.x,\n this.y + that.y,\n this.z + that.z);\n def *(scalar: Double) = Vector(this.x * scalar,\n this.y * scalar,\n this.z * scalar);\n}\n\nclass Octree(min: Vector, max: Vector) {\n val children: Array[Octree] = new Array[Octree](8)\n val center = (max + min) * 0.5\n\n def index(p: Vector): Int = {\n @inline\n def side(x: Double, y: Double): Int =\n if (x &lt; y) 1\n else 0\n (side(center.x, p.x)) |\n (side(center.y, p.y)&lt;&lt;1) |\n (side(center.z, p.z)&lt;&lt;2)\n }\n\n @annotation.tailrec\n final def add(point: Vector): Octree = {\n var i = index(point)\n debug(i)\n if (children(i) == null) {\n @inline\n def pick(b: Int, f: Vector =&gt; Double, l: Vector, r: Vector): Double =\n if (b == 0) f(l)\n else f(r)\n def split(v1: Vector, v2: Vector): Vector =\n Vector(pick(i &amp; 1, _.x, v1, v2),\n pick(i &amp; 2, _.y, v1, v2),\n pick(i &amp; 4, _.z, v1, v2));\n children(i) = new Octree(\n split(center, min),\n split(max, center));\n children(i)\n } else\n children(i).add(point)\n }\n\n @annotation.tailrec\n final def find(p: Vector): Octree = {\n var i = index(p)\n debug(i)\n if(children(i) == null)\n this\n else\n children(i).find(p)\n }\n\n private def debug(message: =&gt; Any) {\n // if you comment out the print statement, `message`\n // won't be evaluated, so even if it's computationally intensive,\n // you don't need to comment out `debug` from the code.\n print(message.toString)\n }\n}\n</code></pre>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-02-05T21:27:48.690", "Id": "41003", "ParentId": "39833", "Score": "1" } }, { "body": "<p>Just a few remarks on your implementation.</p>\n\n<p>(0) Define a vector type!</p>\n\n<p>(1) The whole <code>side</code> thing and using bit patterns to guide your logic is very hard to follow.</p>\n\n<p>(2) Usually an octree just forms a tree from the vertices contained within; your implementation works by representing the bounding cuboid at each level, which makes your code more complex.</p>\n\n<p>Here's a C# sketch of what I mean in point (2):</p>\n\n<pre><code>public class Vec {\n double[] XYZ;\n public Vec(double x, double y, double z) { XYZ = new double[3] { x, y, z }; }\n public double X { get { return XYZ[0]; } }\n public double Y { get { return XYZ[1]; } }\n public double Z { get { return XYZ[2]; } }\n public double this[int i] { get { return XYZ[i]; } }\n public bool Eq(Vec v) { return v.X == X &amp;&amp; v.Y == Y &amp;&amp; v.Z == Z; }\n}\n\npublic class Octree {\n int Idx;\n Vec Item;\n Octree L;\n Octree R;\n public static Octree Ins(Octree t, Vec v, int idx = 0) {\n if (t == null) return new Octree { Idx = idx, Item = v };\n if (t.Item.Eq(v)) return t;\n return (0 &lt;= v[t.Idx] - t.Item[t.Idx])\n ? new Octree { Idx = t.Idx, Item = t.Item, L = Octree.Ins(t.L, v, (idx + 1) % 3), R = t.R }\n : new Octree { Idx = t.Idx, Item = t.Item, L = t.L, R = Octree.Ins(t.R, v, (idx + 1) % 3) };\n }\n public static bool Contains(Octree t, Vec v) {\n if (t == null) return false;\n if (t.Item.Eq(v)) return true;\n return Octree.Contains(0 &lt;= v[t.Idx] - t.Item[t.Idx] ? t.L : t.R, v);\n }\n}\n</code></pre>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-02-06T02:33:04.447", "Id": "41025", "ParentId": "39833", "Score": "1" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-01-22T18:41:09.727", "Id": "39833", "Score": "3", "Tags": [ "beginner", "tree", "scala" ], "Title": "Partial octree implementation" }
39833
<p>I want you to give me some tips on what I could have done better and is considered "bad practice". The code works, but I think there are better ways to do stuff, so please let me know.</p> <pre><code>var Artikel = Backbone.Model.extend({ urlRoot: 'api/items.json', defaults: { titel: 'Titel niet opgegeven', url_titel: 'unieke sleutel urltitel', img_path: 'geen image toegevoegd', commentaar: 'Commentaar niet opgegeven', categorie: 'Categorie niet opgegeven', waardering: 0, artikel: 'Artikel niet opgegeven' }, initialize: function() { if (!this.get('description')) { var lazy = 'This user was too lazy too add a description'; this.set('description', lazy); } } }); //Mijn collection wordt voorzien van een sorteerfunctie om niet met 'asc' en 'desc' te moeten werken kan ik gebruik maken van 1 en -1 var Artikels = Backbone.Collection.extend({ model: Artikel, sortAttribute: "categorie", sortDirection: 1, sortArtikels: function(attr) { this.sortAttribute = attr; this.sort(); }, comparator: function(a, b) { var a = a.get(this.sortAttribute), b = b.get(this.sortAttribute); if (a == b) return 0; if (this.sortDirection == 1) { return a &gt; b ? 1 : -1; } else { return a &lt; b ? 1 : -1; } }, url: 'api/items.json' }); //Eerste view dat wordt weergegeven en geeft een lijst van al de artikels. var ArtikelLijst = Backbone.View.extend({ el: '#app', initialize: function() { _.bindAll(this, "render"); this.model.bind('change', this.render); }, render: function(zoekterm) { this.render; var that = this; artikels.fetch({ success: function(artikels) { if (artikels.sortDirection == -1) { artikels.sortDirection = 1; } else { artikels.sortDirection = -1; } artikels.sortArtikels(zoekterm); var template = _.template($('#artikel-overzicht-template').html(), { artikels: artikels.models }); that.$el.html(template); return this; } }); } }); //Geeft een detail view van de artikels, in de detailweergave wordt de foto bijvoorbeeld weergegeven als extraatje var ArtikelDetail = Backbone.View.extend({ el: '#app', render: function(options) { var that = this; var artikel = new Artikels(); url = options.id; artikel.fetch({ success: function(artikel, options) { var vindartikel = artikel.where({ url_titel: url }); var artikelcol = Backbone.Collection.extend({ model: Artikels }); var specifiekArtikel = new artikelcol(vindartikel); var template = _.template($('#detail-edit-template').html(), { specifiekArtikel: specifiekArtikel.models }); that.$el.html(template); } }); } }); // de searchview geeft een formulier en zorgt er voor dat de zoekopdracht url-vriendelijk wordt var ArtikelSearchView = Backbone.View.extend({ el: '#app', render: function() { this.$el.html($("#search-form").html()); if (arguments.length &gt; 0) { var querystr = arguments[0].replace(/\+/g, "%20"); $("#searchQuery").val(decodeURIComponent(querystr)); } }, events: { 'submit #searchForm': function(ev) { $form = $(ev.currentTarget); document.location = '#/search/' + encodeURIComponent($("#searchQuery", $form).val()).replace(/%20/g, '+'); return false; } } }); //De resultsview laat de gevonden resultaten zien var ArtikelSearchResultsView = Backbone.View.extend({ el: '#searchResults', render: function(query_encoded) { var query = decodeURIComponent(query_encoded.replace(/\+/g, "%20")); var result_artikels = _.filter(this.model.models, function(artikel_model) { var artikel = artikel_model.attributes; artikel.waardering = "string"; for (var key in artikel) { if (artikel[key].toLowerCase().indexOf(query.toLowerCase()) &gt;= 0) { return true; } } return false; }); var template = $("#search-results").html(); var result_html = _.template(template, { artikels: result_artikels, query: query }); this.$el.html(result_html); } }); var artikels = new Artikels(); var artikelLijst = new ArtikelLijst({ model: Artikels }); var artikelDetail = new ArtikelDetail(); var artikelSearchView = {}; artikelSearchView.search = new ArtikelSearchView(); function sorteer(sortterm) { artikelLijst.render(sortterm); }; var Router = Backbone.Router.extend({ routes: { "": "home", "detail/:id": "detail", "searchform": "searchform", "search/:query": "searchResults" }, home: function() { artikelLijst.render('titel'); }, detail: function(id) { artikelDetail.render({ id: id }); }, searchform: function() { artikelSearchView.search.render(); }, searchResults: function(query) { artikelSearchView.search.render(query); var artikelSearchResultsView = new ArtikelSearchResultsView({ model: artikels }); artikelSearchResultsView.render(query); } }); var router = new Router(); Backbone.history.start(); </code></pre>
[ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-01-22T23:55:59.270", "Id": "66850", "Score": "4", "body": "Seriously, komaan man, don't put Dutch in your code, it makes us Dutch speaking developers look bad!" } ]
[ { "body": "<p>I don't see major refactorings in your code. However:</p>\n\n<ul>\n<li><p>Use triple-equals (see <a href=\"https://stackoverflow.com/questions/359494/does-it-matter-which-equals-operator-vs-i-use-in-javascript-comparisons\">here</a> for more) when doing comparisons with zero or one (and probably the part with <code>a == b</code>, unless you know you want otherwise)</p></li>\n<li><p><a href=\"http://underscorejs.org/#template\" rel=\"nofollow noreferrer\">Pre-compile templates</a> rather than doing them on-the-fly for better performance</p></li>\n<li><p>You are using Backbone, jQuery, and Underscore (or lodash) - re-examine whether you need all of these libraries. Less code means a faster loading page. (On the other hand, you might need the cross-browser compatibility provided by jQuery - your call.)</p>\n\n<ul>\n<li><p><a href=\"http://youmightnotneedjquery.com\" rel=\"nofollow noreferrer\">http://youmightnotneedjquery.com</a></p></li>\n<li><p><a href=\"http://vanilla-js.com/\" rel=\"nofollow noreferrer\">http://vanilla-js.com/</a></p></li>\n</ul></li>\n</ul>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-03-02T00:39:53.673", "Id": "43182", "ParentId": "39843", "Score": "3" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "1", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-01-22T22:14:56.033", "Id": "39843", "Score": "6", "Tags": [ "javascript", "backbone.js" ], "Title": "Managing article information" }
39843
<p>The following class was designed to help create a more detailed error message than what's provided by the repository when a user tries to insert text into a column that is > the column max length. The users would like to be able to track down exactly which column(s) were the issue. Therefore, I created the following, and I would like to know if this is a good approach or not.</p> <p>This class defines the parameters needed and is the context object for each respective strategy class. </p> <pre><code>public class QueryBuilder { public StringBuilder ColumnNames{get;private set;} public StringBuilder ColumnValues{get;private set;} public string TableName{get;private set;} public Database.FactoryType FactoryType {get;private set;} private static Dictionary&lt;Database.FactoryType, IQueryBuilderStrategy&gt; queryBuilderStrategies; public QueryBuilder(StringBuilder columnNames,StringBuilder columnValues,string tableName, Database.FactoryType factoryType) { TableName = tableName; ColumnNames = columnNames; ColumnValues = columnValues; FactoryType = factoryType; LoadStrategies(); } private void LoadStrategies() { queryBuilderStrategies = new Dictionary&lt;Database.FactoryType,IQueryBuilderStrategy&gt;(); queryBuilderStrategies.Add(Database.FactoryType.SqlClient, new SQLErrorQueryStrategy() ); queryBuilderStrategies.Add(Database.FactoryType.OleDb, new AccessErrorQueryStrategy()); } public string Create() { return queryBuilderStrategies[FactoryType].CreateSQLQueryString(this); } public string Read(IDataReader reader) { return queryBuilderStrategies[FactoryType].ParseDataReader(this, reader); } } </code></pre> <p>I created the following interface to decouple all the different strategies needed to communicate with multiple databases that we support.</p> <pre><code>public interface IQueryBuilderStrategy { string CreateSQLQueryString(QueryBuilder queryBuilder); string ParseDataReader(QueryBuilder queryBuilder, IDataReader reader); } </code></pre> <p>I then took it a step further and defined an abstract class because there was alot of duplication of code that only needed to change slightly</p> <pre><code>public abstract class ErrorQueryStrategyBase : IQueryBuilderStrategy { protected Func&lt;DataRow,bool&gt; IsTextField; protected virtual string[] GetFieldNames(QueryBuilder builder) { return builder.ColumnNames.ToString().Replace("\"", string.Empty).Replace("'", string.Empty).Split(','); } protected virtual string[] GetFieldValues(QueryBuilder builder) { return builder.ColumnValues.ToString().Replace("'", string.Empty).Split(','); } protected virtual string GetErrorMessage(string fieldName, int currentFieldLength, string dbColumnName, int columnMaxSize) { string indexErrorMessage = String.Format("Field {0} length is {1}. However Data storage max length for column {2} is {3}{4}"); return string.Format(indexErrorMessage, fieldName, currentFieldLength, dbColumnName, columnMaxSize, System.Environment.NewLine); } public virtual string CreateSQLQueryString(QueryBuilder queryBuilder) { return string.Format("SELECT {0} FROM {1}", queryBuilder.ColumnNames.ToString(), queryBuilder.TableName); } public virtual string ParseDataReader(QueryBuilder builder, IDataReader reader) { string[] userProvidedValues = GetFieldValues(builder); string[] columnNamesSeparated = GetFieldNames(builder); string errorMessage = string.Empty; DataTable dt = reader.GetSchemaTable(); int index = 0; foreach (DataRow row in dt.Rows) { string columnName = row[0].ToString(); int columnSize = (int)row[2]; int len = userProvidedValues[index].Length; if (IsTextField(row) ) { if (len &gt; columnSize) { string fieldName = columnNamesSeparated[index]; errorMessage += GetErrorMessage(fieldName, len, columnName, columnSize); } } index++; } return errorMessage; } } public class SQLErrorQueryStrategy : ErrorQueryStrategyBase { private readonly int textFieldIndex; public SQLErrorQueryStrategy() { this.textFieldIndex = 12; this.IsTextField = delegate(DataRow row) { Type dataType = (Type)row[textFieldIndex]; return dataType.Name == "String"; }; } } public class AccessErrorQueryStrategy : ErrorQueryStrategyBase { private readonly int textFieldIndex; public AccessErrorQueryStrategy() { this.textFieldIndex = 5; this.IsTextField = delegate(DataRow row) { Type dataType = (Type)row[textFieldIndex]; return dataType.Name == "String"; }; } } </code></pre> <p>I instantiate and call the class here:</p> <pre><code>QueryBuilder errorQuery = new QueryBuilder(fieldList,valueList,tableName,capDatabase.Type); message += GetDetailedErrorMessage(capDatabase, errorQuery); private string GetDetailedErrorMessage(IDatabase database, QueryBuilder queryBuilder) { string message = string.Empty; try { using (DbCommand errorQueryCommand = database.CreateCommand(queryBuilder.Create(), CommandType.Text)) { errorQueryCommand.Connection = databaseConnection; using (DbDataReader reader = errorQueryCommand.ExecuteReader(CommandBehavior.SchemaOnly)) { message += queryBuilder.Read(reader); } } } catch (Exception ex) { message += ex.Message; } return message; } </code></pre> <p>Using this approach, I was able to isolate the changes out. It also allows for future changes and additional db support.</p> <p>Please provide constructive comments.</p>
[ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-01-22T23:36:58.863", "Id": "66848", "Score": "1", "body": "Outstanding first post. Welcome!" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-01-23T00:15:47.837", "Id": "66852", "Score": "1", "body": "What's the reasoning behind using a delegate instead of a virtual method?" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-01-23T01:22:18.270", "Id": "66856", "Score": "0", "body": "Well the first pass was just that, two concrete classes implementing the interface IQueryBuilderStrategy then I realized they had a lot more in common then i originally planned. If I would have left them as virtual the concrete classes would have basically been a case of copy and paste. Therefore, I continued to re-factor." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-01-28T07:14:41.747", "Id": "67675", "Score": "0", "body": "Please expand on why you think using a delegate may not be the best choice. I have been getting answers based on functional constructs but i was really in search of OOP critiques." } ]
[ { "body": "<p>I think <code>QueryBuilder</code> can use constructor parameters, and that its auto-properties can be changed to be <code>{ get; private set; }</code>. Otherwise the public setters seem to make an opportunity for some trouble. Actually I'd drop the auto-properties and initialize <code>private readonly</code> fields, exposed by get-only properties.</p>\n\n<p>I don't get the <code>static</code> modifier for a dictionary that is recreated for every instance of the type. I would drop the <code>static</code> modifier altogether.</p>\n\n<blockquote>\n<pre><code>public Database.FactoryType Type {get;set;}\n</code></pre>\n</blockquote>\n\n<p>Might be a nitpick, but I find <code>Type</code> is a confusing name to use here, it clashes with <code>System.Type</code>. <code>FactoryType</code> would be much more appropriate.</p>\n\n<p>Also there are inconsistencies in the way you're dealing with <code>IDisposable</code> in the <code>try</code> block of <code>GetDetailedErrorMessage</code>:</p>\n\n<blockquote>\n<pre><code> DbCommand errorQueryCommand =\n database.CreateCommand(queryBuilder.Create(), CommandType.Text); \n errorQueryCommand.Connection = databaseConnection; \n using (DbDataReader reader = errorQueryCommand.ExecuteReader(CommandBehavior.SchemaOnly))\n {\n message += queryBuilder.Read(reader); \n }\n if (errorQueryCommand != null)\n errorQueryCommand.Dispose();\n</code></pre>\n</blockquote>\n\n<p>I don't see a reason not to do <code>using (var errorQueryCommand = database.CreateCommand(...)</code>; also you're assigning the command's <code>Connection</code> to some <code>databaseConnection</code> which has to be a private field (that would be clearer if the name was <code>_databaseConnection</code> instead, but that could be only me).</p>\n\n<p>One thing though, is that I don't think <code>errorQueryCommand</code> would ever be <code>null</code> where you're testing for it - if it were the case, you'd already be in the <code>catch</code> block over a <code>NullReferenceException</code> caused by accessing the setter of <code>errorQueryCommand.Connection</code>. But that point is moot if you wrap the <code>DbCommand</code> in a <code>using</code> block.</p>\n\n<p>The rest looks ok, except if you're a fan of <code>var</code>, in which case reading your code... tickles. I personally find it very redundant to see <code>string message = string.Empty;</code> when it's obvious that <code>message</code> is a <code>string</code> - not because of its name, but because of the value it's being assigned to.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-01-23T01:53:46.313", "Id": "66858", "Score": "0", "body": "I updated my code to reflect the using statements you suggested. As far as the static dictionary goes i feel that is the pivotal point that makes this more DRY. My point being that as new provider support is requested then I only have to add to this dictionary here at a single point no more." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-01-23T02:01:20.373", "Id": "66859", "Score": "0", "body": "But you're reassigning that dictionary everytime the constructor runs; whether it's `static` or not wouldn't make a difference then... unless you're reusing the same instance and calling these setters. I think it makes more sense for these values to be per-instance, so you can't accidentally miss a property and drag a value from another use. Don't give different meanings to the same variable; this applies to a `string`, just as it applies to a `QueryBuilder` IMHO. Feel free to upvote if any helpful - this isn't StackOverflow, we're a beta site trying to build a hi-rep user base and graduate :)" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-01-23T03:49:45.817", "Id": "66873", "Score": "0", "body": "I am sorry but i don't completely understand how I would be applying new meaning to QueryBuilder. Would you please expand? Can you provide an example how i can achieve my point without the dictionary?" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-01-23T03:58:20.053", "Id": "66874", "Score": "1", "body": "I didn't say *drop the dictionary*, I meant to drop the `static` keyword, it's not really buying you anything, but I see how it might be better off at the type level (vs. instance). By \"new meaning\" I mean, if you have an instance, and then you reuse that same instance later but for a different `TableName` and/or `ColumnNames`, or even a different `Type` - the public setters you have here allow for that instance to be misused and then your can change `TableName` and forget to update `ColumnNames` for example; with private setters and parameterized constructor you avoid that kind of trouble." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-01-23T04:12:04.267", "Id": "66875", "Score": "0", "body": "I hear you. Good point." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-01-23T18:23:42.060", "Id": "66951", "Score": "0", "body": "As great answers trickle in should I update the original to reflect the codes evolution? I would say yes, but then it might take away from the relevance of the answers and comments and perhaps not allow people to see cause and effect." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-01-23T20:58:59.130", "Id": "66982", "Score": "0", "body": "@vmichael take the time you need to \"fix\" your code, and then mark this question as answered and ask a follow-up question (link to this one). More reputation score (/votes) will be generated that way, and you will not *mootinate* any answers here :)" } ], "meta_data": { "CommentCount": "7", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-01-23T01:38:24.153", "Id": "39852", "ParentId": "39844", "Score": "7" } }, { "body": "<p>In addition to what @lol.upvote already said:</p>\n\n<p>I don't really like the way you pass the column names and values around for several reasons:</p>\n\n<ol>\n<li><p>You basically pass them as a string which means that whoever provides them very likely already has a list and needs to concatenate them together and then you have to split them again.</p></li>\n<li><p>You rely on the fact that there are the same number of column names provided as there are column values. Your code will crash if that is not the case.</p></li>\n<li><p>If a column name or value contains a <code>,</code> you are in trouble as well. Probably unlikely to be the case for the names but values might be more likely. From experience it's not a question of \"if\" but of \"when\" this is going to happen.</p></li>\n<li><p>It violates the Single Responsibility Principle to a certain degree. This becomes apparent when you write unit tests because now you have to write unit tests to check that it can parse the names and value correctly - a functionality which is not really related to the actual purpose of the class.</p></li>\n</ol>\n\n<p>So I'd suggest to change the <code>QueryBuilder</code> constructor like this:</p>\n\n<pre><code>public QueryBuilder(KeyValuePair&lt;string, string&gt; columnValues, string tableName, Database.FactoryType factoryType)\n{\n ..\n</code></pre>\n\n<p>You'll have to adapt some code but you can also get rid of the parsing for the names and values.</p>\n\n<p>Instead of a <code>KeyValuePair</code> you might want to consider a <code>Tuple</code> or your own <code>ColumnValue</code> class instead.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-01-23T17:32:24.900", "Id": "66936", "Score": "0", "body": "Excellent point, definitely a sore thumb. In regards to your points {1,3} I guess I was trying to lie to myself by saying if i make the ColumnNames and ColumnValues methods virtual then i will be ok. However, that still doesn't help when the lists are not the same length as you pointed out as well." } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-01-23T09:16:04.950", "Id": "39866", "ParentId": "39844", "Score": "3" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "4", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-01-22T22:24:48.440", "Id": "39844", "Score": "12", "Tags": [ "c#", "object-oriented", "design-patterns" ], "Title": "Implementation of the Strategy Pattern using an interface, abstract class and delegate" }
39844
<p>I'm writing a list of inputs and outputs for to be compared in unit tests.</p> <pre><code>var equals = [ //input //output ["name:(John Smith)", "name:(John~ Smith~)" ], ["name:Jon~0.1", "name:Jon~0.1" ], ["Jon", "Jon~" ], ["Jon Smith~0.1", "Jon~ Smith~0.1" ], ["Jon AND Bob", "Jon~ AND Bob~" ], ["Jon AND Bob~0.1", "Jon~ AND Bob~0.1" ], ["Steve^9 Jon", ] "Steve^9 Jon~" ] ]; </code></pre> <p>I've formatted it as such, so it's easy to compare and read. However, it's unconventional. </p> <p>Is this a bad idea?</p>
[ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-01-23T03:19:05.630", "Id": "66869", "Score": "0", "body": "I imagine one possible problem would be that it might spill over on different editors/screen sizes, and look awful." } ]
[ { "body": "<h1>An argument against table-style alignment in code</h1>\n\n<p><em>Except</em> when the editor/IDE helps maintain alignment with little work from the programmer, <em>and</em> all those who work with the code have that same facility, horizontal, table-like alignment in code is more trouble than it's worth, for these reasons:</p>\n\n<ul>\n<li><p>Search/replace operations on the entire code-base (as when renaming a variable or method) will tend to leave such code in a mess that needs manual cleanup.</p></li>\n<li><p>Anyone whose editor/IDE does not make horizontal alignment easy will spend a lot of time hitting space or DEL to make things line up when adding or deleting an entry.</p></li>\n<li><p>When the entire table needs to be realigned (as when adding a new row that causes a column to grow), the version control system will show that the entire table changed.</p></li>\n</ul>\n\n<p>For those reasons, I'm inclined to put up with a little bit of ugly:</p>\n\n<pre><code> var equals = [ //input, output\n [\"name:(John Smith)\", \"name:(John~ Smith~)\"],\n [\"name:Jon~0.1\", \"name:Jon~0.1\"],\n //...\n ];\n</code></pre>\n\n<p>or, as @ChrisW suggests:</p>\n\n<pre><code> var equals = [ //input, output\n [\n \"name:(John Smith)\",\n \"name:(John~ Smith~)\"\n ],\n [\n \"name:Jon~0.1\",\n \"name:Jon~0.1\"\n ],\n //...\n ];\n</code></pre>\n\n<h1>But maybe data doesn't want to be in the code</h1>\n\n<p>Sometimes data wants its own home, a place where \"rows and columns\" are more natural than in code. Perhaps that's a table in the database. In your case, where the table is input to a test, a .csv file might be good. A non-technical user could then view and edit the data with a spreadsheet program.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-01-22T23:02:18.920", "Id": "66843", "Score": "2", "body": "Is there a second alternative you'd also find acceptable, which left-aligns each output string underneath its input string? IMO that might make it easier to visually compare each output with its input." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-01-22T23:04:27.943", "Id": "66844", "Score": "1", "body": "For example, `[\"Jon\"` _newline_ `, \"Jon~\"]` so that the `,` is under the `[`?" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-01-22T23:06:00.313", "Id": "66845", "Score": "3", "body": "I disagree with this answer. Usually, code is read more often than written, so the extra effort is worth it. Tabular data should have a tabular layout in code. Good formatting makes it easier to spot errors." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-01-22T23:33:04.457", "Id": "66846", "Score": "0", "body": "@ChrisW, Is what I just added to the answer what you had in mind?" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-01-22T23:35:33.610", "Id": "66847", "Score": "0", "body": "@amon, In the code base I maintain, editing of old code is much more common than creation of new code. That might explain why you and I have such a different view of this practice." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-01-22T23:44:14.270", "Id": "66849", "Score": "2", "body": "+1 That looks good (better than my suggestion). You could additionally perhaps save vertical space, by having the `], [` immediately after (on the same line as) each output." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-01-23T21:33:58.147", "Id": "66988", "Score": "1", "body": "Good answer thanks Wayne. Here is a programmers.SE question on the same topic where I mention putting it in to CSV. [Is there a better way of writing unit tests than a series of 'AssertEquals'?](http://programmers.stackexchange.com/questions/225116/is-there-a-better-way-of-writing-unit-tests-than-a-series-of-assertequals)" } ], "meta_data": { "CommentCount": "7", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-01-22T22:55:04.430", "Id": "39846", "ParentId": "39845", "Score": "27" } }, { "body": "<p>An opinion question, always tricky.</p>\n\n<p>From a DRY perspective, your code should be usable to generate documentation, like 'what use cases does this routine support' or 'What are the mapping values between y and z'. </p>\n\n<p>So I definitely align my tables, however I also tend to align the comma's and I tend to align 2 spaces in, not all the way to the right of var.</p>\n\n<p>In other words, something like this : </p>\n\n<pre><code>var equals = \n [ \n //input //output\n [\"name:(John Smith)\", \"name:(John~ Smith~)\"],\n [\"name:Jon~0.1\" , \"name:Jon~0.1\" ],\n [\"Jon\" , \"Jon~\" ],\n [\"Jon Smith~0.1\" , \"Jon~ Smith~0.1\" ],\n [\"Jon AND Bob\" , \"Jon~ AND Bob~\" ],\n [\"Jon AND Bob~0.1\" , \"Jon~ AND Bob~0.1\" ],\n [\"Steve^9 Jon\" , \"Steve^9 Jon~\" ] \n ]; \n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-01-23T00:42:51.170", "Id": "66853", "Score": "0", "body": "Can you state any advantage which this has over the other answer?" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-01-23T03:03:15.350", "Id": "66867", "Score": "0", "body": "@ChrisW Aesthetics (which is subjective and a matter of personal taste). I like this version as well, although I tend to not align commas, because spaces before commas feel like improper punctuation to me and create that annoying pressure point in my head, just like unaligned tables. Not annoying _me_ is an important advantage _my_ code needs to have. :-) I tend to work in very small teams, though. (Objective disadvantages are well-stated in another answer.)" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-01-23T03:04:32.907", "Id": "66868", "Score": "1", "body": "@ChrisW As per my answer, documentation, especially documentation that I provide to non-technical people, they understand this format whereas the other answer is ungrokkable for non-technical people." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-01-23T07:55:05.310", "Id": "66881", "Score": "0", "body": "I do not _generally_ align commas since I do not like how it looks. It does however have the advantage that it makes it much easier to use block-selection to copy any column of the declaration to for example a default assignment or a validation code section." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-01-23T13:38:03.113", "Id": "66909", "Score": "0", "body": "@konijn - Providing code to non-technical people as documentation?" } ], "meta_data": { "CommentCount": "5", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-01-22T23:49:43.040", "Id": "39847", "ParentId": "39845", "Score": "12" } }, { "body": "<p>From a pure code review perspective, not addressing the direct question of \"Should I format my unit test data in a tabular way\", but instead, is this the best way to write this data in the first place?</p>\n\n<p>If you think about writing a unit test, is it more readable/maintainable to do:</p>\n\n<pre><code> var equals = \n [ \n //input //output\n [\"name:(John Smith)\", \"name:(John~ Smith~)\"],\n [\"name:Jon~0.1\" , \"name:Jon~0.1\" ],\n [\"Jon\" , \"Jon~\" ],\n [\"Jon Smith~0.1\" , \"Jon~ Smith~0.1\" ],\n [\"Jon AND Bob\" , \"Jon~ AND Bob~\" ],\n [\"Jon AND Bob~0.1\" , \"Jon~ AND Bob~0.1\" ],\n [\"Steve^9 Jon\" , \"Steve^9 Jon~\" ] \n ]; \n\nforeach(var item in equals){\nAssert.Equal(Sut.Process(item.Key), item.Value)\n}\n</code></pre>\n\n<p>Or perhaps you should simply write out your assertions/tests:</p>\n\n<pre><code>Assert.Equal(Sut.Process(\"name:(John Smith)\"), \"name:(John~ Smith~)\")\nAssert.Equal(Sut.Process(\"name:Jon~0.1\"), \"name:Jon~0.1\")\netc\n</code></pre>\n\n<p>If you feel you should use a list, use a structured type as opposed to an array, as although it's more typing, it's easier to read:</p>\n\n<pre><code> var params =\n [{\n Input: \"name:(John Smith)\",\n Output: \"name:(John~ Smith~)\"\n },{\n Input: \"name:Jon~0.1\",\n Output: \"name:Jon~0.1\"\n }]\n\nfor(var expect in params){\n Assert.Equal(Sut.Process(expect.Input), expect.Output)\n}\n</code></pre>\n\n<p>There is no advantage to formatting your data the way that you do UNLESS you are using an editor that manages this for you. The readability is not greatly enhanced, (considering if I have lower screen resolution than you I may not even see it) and the work to maintain such formatting far outweighs the benefits of doing so. Agreed, tests should be as readable as possible, which is why an array is probably not the best option for writing this data in the first place.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-03-14T22:27:22.280", "Id": "44409", "ParentId": "39845", "Score": "3" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "1", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-01-22T22:44:38.863", "Id": "39845", "Score": "29", "Tags": [ "javascript", "unit-testing", "formatting" ], "Title": "Code indentation for declaring inputs/outputs in an array" }
39845
<p>I don't want any feedback on the regexes as I know what needs to be updated here. Also, don't need any feedback on naming conventions.</p> <p>I'm looking for feedback on the structure and correctness of the class.</p> <pre><code>/*************************************************************************************************** **SForm - validates and manipulates form data */ var SForm = $A.Class.create({ Name: 'SForm', S: { domain: /:\/\/(www\.)?([\.a-zA-Z0-9\-]+)/, url: /:\/\/(www\.)?[\x00-\x7F]{1,1800}\.[\x00-\x7F]{1,200}/, email: /\S{1,64}@[\x00-\x7F]{1,255}\.[\x00-\x7F]{1,255}/, tweet: /\S{1,40}/, title: /\S{1,32}/, name: /\S{1,64}/, pass: /\S{6,20}/, pre_url: /(http:)|(https:)\/\//, full: /\S+/, google: 'https://plus.google.com/_/favicon?domain=' }, constructor : function (form_elements) { this.form = {}; $A.someKey(form_elements, function (val) { if (val.type !== 'checkbox') { this.form[val.name] = val.value; } else if (val.type === 'checkbox') { this.form[val.name] = val.checked; } }, this); }, get: function (key) { return this.form[key]; }, set: function (key, value) { this.form[key] = value; }, getObj: function () { return this.form; }, checkField: function (key) { return this.S[key].test(this.form[key]); }, checkFull: function () { var key; for (key in this.form) { // if it is not a boolean and it is not full if (!$A.isBoolean(this.form[key]) &amp;&amp; !this.S.full.test(this.form[key]) ) { return false; } } return true; }, checkFullAM: function () { var key; for (key in this.form) { // if the fields is empty and it is not the tag field if (key !== "tag" &amp;&amp; !this.S.full.test(this.form[key])) { return false; } // if no tag is set, set one by default if (key === "tag" &amp;&amp; !this.S.full.test(this.form[key])) { this.form[key] = "no-tag"; } } return true; }, addURLPrefix: function () { // if there is no prefix, add http by default if (!this.S.pre_url.test(this.form.url)) { this.form.url = 'http://' + this.form.url; } }, setDomain: function () { var domain = this.form.url.match(this.S.domain); if (domain) { this.form.domain = domain[2]; } }, setFaviconTemp: function () { this.form.favicon = this.S.google + this.form.domain; } }, 'constructor'); </code></pre>
[ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-01-23T02:12:26.843", "Id": "66861", "Score": "0", "body": "I would abstract the validation process from the data, and the data from the DOM. It seems you have to create a validation object with methods and everything for every form, or is it re-usable?" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-01-23T02:14:45.060", "Id": "66862", "Score": "0", "body": "What do you mean? I don't access the DOM in this class." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-01-23T02:18:08.333", "Id": "66863", "Score": "0", "body": "I see that, just as general idea I mean. How do you use your class with the DOM?" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-01-23T20:47:56.513", "Id": "66980", "Score": "0", "body": "did you have a chance to read the code?" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-01-23T20:58:19.130", "Id": "66981", "Score": "0", "body": "I did, that's why I'm asking about it. Are you matching form elements strictly by name to use it in the DOM?. This `return this.S[key].test(this.form[key])` is what looks limited at first sight, but I don't know how you interact with the library." } ]
[ { "body": "<p>A quick review, as the illustrious <code>user34330</code> is no longer with us.</p>\n\n<ul>\n<li><p>This:</p>\n\n<pre><code>if (val.type !== 'checkbox') {\n this.form[val.name] = val.value;\n} else if (val.type === 'checkbox') {\n this.form[val.name] = val.checked;\n}\n</code></pre>\n\n<p>should be </p>\n\n<pre><code>if (val.type !== 'checkbox') {\n this.form[val.name] = val.value;\n} else\n this.form[val.name] = val.checked;\n}\n</code></pre>\n\n<p>because if it is not not a checkbox, then... you know it is checkbox, you could also consider a ternary here:</p>\n\n<pre><code>this.form[val.name] = (val.type === 'checkbox') ? val.checked : val.value;\n</code></pre></li>\n<li><code>getObj</code> should be <code>getForm</code>, since it returns the <code>form</code></li>\n<li><code>checkFullAM</code> the name does not tell me what this does, due to a lack of comments I am mystified at what this function should do. &lt;- That's bad</li>\n<li>I would have expected to be able to pass a prefix to <code>addURLPrefix</code>, so that I could set <code>https</code> if I wanted to</li>\n<li><code>setDomain</code> seems to have no possible use, there are no comments to enlighten the reader why/how this could be useful</li>\n</ul>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-04-04T13:42:00.090", "Id": "80764", "Score": "0", "body": "R.I.P user34330 :(" } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-04-04T13:37:55.563", "Id": "46271", "ParentId": "39853", "Score": "2" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "5", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-01-23T01:59:50.787", "Id": "39853", "Score": "2", "Tags": [ "javascript", "form", "validation" ], "Title": "A class for form data validation" }
39853
<p>Looking for feedback on correctness and code structure.</p> <p>Follow up to:</p> <p><a href="https://codereview.stackexchange.com/questions/19825/sstorage-remember-v0">SStorage (remember) - v0</a></p> <p>Note that b.c. the user can only change the storage type when logging in, there is no need to copy back and forth between storage types.</p> <pre><code>/*************************************************************************************************** **SStorage - handles remember option of logging in and namespaces the domain as well */ var SStorage = $A.Class.create({ Name: 'SStorage', A: { // storage type storage: null, // set the namespace here ns: 'arcmarks_', // storage key which keeps track of storage type indicator: 'arcmarks_h_token' }, // type of storage is set when the user logs in // and called below setType: function (remember) { this.A.storage = remember ? $A.localStorage : $A.sessionStorage; }, // determine type of storage at load MUserAny load: function () { this.setType($A.localStorage[this.A.indicator]); }, // basic setters and getters with namespacing set: function (key, value) { this.A.storage[this.A.ns + key] = value; }, get: function (key) { return this.A.storage[this.A.ns + key]; }, setObj: function (o) { $A.someKey(o, function (val, key) { this.A.storage[this.A.ns + key] = val; }, this); }, getObj: function () { var o = {}, real_key, namespace; $A.someKey(this.A.storage, function (val, key) { // retrieves after the name-space real_key = key.slice(this.A.ns.length); // retrieves the name-space namespace = key.slice(0, this.A.ns.length); if (namespace === this.A.ns) { o[real_key] = val; } }, this); return o; }, // clear only namespaced items clear: function () { var key; for (key in this.A.storage) { if (key.slice(0, this.A.len) === this.A.ns) { this.A.storage.removeItem(key); } } } }, true); </code></pre>
[ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-01-23T07:19:29.897", "Id": "66880", "Score": "0", "body": "Can I get a comment on why the object (presumably becoming a prototype) has `this.A.foo` instead of `this.foo`?" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-01-23T20:08:47.487", "Id": "66968", "Score": "0", "body": "just a choice of style" } ]
[ { "body": "<p>From a once over:</p>\n\n<ul>\n<li>You are a bit overdoing the blank lines in your definition of <code>A</code></li>\n<li>I like the namespace idea, given how you implement <code>getObj</code> and <code>setObj</code>, it would be nice if the caller could set the namespace.</li>\n<li><code>setType</code> -> I get that <code>remember</code> probably means you want to remember info across sessions, hence you choose <code>localStorage</code> and not <code>sessionStorage</code>, still something like <code>persist</code> or <code>persistAcrossSessions</code> could be more informative.</li>\n<li><code>setObj</code> -> does totally not what I would expect it to do, I would expect your code to <code>JSON.stringify()</code> and assign that to a key, however you store each property individually which can make for a very messy retrieval</li>\n<li><code>getObj</code> -> does exactly what I thought i would, give all properties in 1 object, this is very limited functionality. You should consider really consider JSON in your class.</li>\n<li><code>clear</code> -> I would make <code>var key</code> part of the <code>for</code> loop : <code>for (var key in this.A.storage) {</code></li>\n<li>Commenting is uneven, the 2 functions which are most surprising to me have no comments.</li>\n</ul>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-01-23T20:09:21.287", "Id": "66969", "Score": "0", "body": "your first comment is a style choice that I picked up from underscorejs.org" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-01-23T20:10:36.247", "Id": "66970", "Score": "0", "body": "second comment - OK. Will implement setNameSpace or you may if you like :)" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-01-23T20:11:46.723", "Id": "66971", "Score": "0", "body": "third comment - style" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-01-23T20:13:08.887", "Id": "66972", "Score": "0", "body": "4the comment - we can agree to disagree. I think that is fine." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-01-23T20:13:40.703", "Id": "66973", "Score": "0", "body": "5th comment - if I wanted to go the JSON route I would use indexedDB instead." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-01-23T20:14:05.283", "Id": "66974", "Score": "0", "body": "6the comment - style again. I chose jslint style." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-01-23T20:15:07.820", "Id": "66975", "Score": "0", "body": "7th comment - i'll try and add more commenting" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-01-23T20:15:38.433", "Id": "66976", "Score": "0", "body": "Thank you for your feedback, if you are interested in working on this project let me know." } ], "meta_data": { "CommentCount": "8", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-01-23T03:38:59.087", "Id": "39857", "ParentId": "39854", "Score": "2" } } ]
{ "AcceptedAnswerId": "39857", "CommentCount": "2", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-01-23T02:05:54.977", "Id": "39854", "Score": "4", "Tags": [ "javascript" ], "Title": "A class for remember me" }
39854
<p>This class creates dynamic input labels. You give it a pair of elements and it sets up the event listeners and CSS toggles to accomplish this.</p> <p>Looking for feedback on code structure and correctness.</p> <p>Toggle classes do what they say, they toggle one class on and another class off.</p> <pre><code>/*************************************************************************************************** **SDynInput - provides dynamic input for labels and borders */ var SDynInput = $A.Class.create({ Name: 'SDynInput', A: { // CSS classes used to toggle the label toggle_label_hide: 'toggle_label_hide', toggle_label_obscure: 'toggle_label_obscure', toggle_label_show: 'toggle_label_show', // CSS classes used to toggle the border toggle_border_hide: 'toggle_border_hide', toggle_border_obscure: 'toggle_border_obscure', toggle_border_show: 'toggle_border_show', // speed of label expanding speed: 200 }, // elements are passed in as input/label pairs set: function (pair_array) { var index; for (index = 0; index &lt; pair_array.length; index += 2) { this.applyEL(pair_array[index], pair_array[index + 1]); } }, // apply event listeners to the input elements applyEL: function (input_element, label_element) { var self = this; input_element.addEventListener("blur", function () { if (input_element.value === '') { $A.addClass(input_element, self.A.toggle_border_show); $A.addClass(label_element, self.A.toggle_label_show); $A.expandFont(label_element, 'up', self.A.speed); } }, false); input_element.addEventListener("focus", function () { if (input_element.value === '') { $A.addClass(input_element, self.A.toggle_border_obscure); $A.addClass(label_element, self.A.toggle_label_obscure); } }, false); input_element.addEventListener("paste", function () { $A.addClass(label_element, self.A.toggle_label_hide); $A.addClass(input_element, self.A.toggle_border_hide); }, false); input_element.addEventListener("keypress", function () { $A.addClass(label_element, self.A.toggle_label_hide); $A.addClass(input_element, self.A.toggle_border_hide); }, false); input_element.addEventListener("drop", function () { $A.setTimeout(function () { $A.addClass(label_element, self.A.toggle_label_hide); $A.addClass(input_element, self.A.toggle_border_hide); }, 0); }, false); } }, true); </code></pre>
[]
[ { "body": "<p>The code is not bad;</p>\n\n<ul>\n<li>Quite configurable</li>\n<li>Helper functions</li>\n</ul>\n\n<p>However,</p>\n\n<ul>\n<li>There is quite a bit of copy paste code</li>\n<li>Placing the style classes in <code>self.A.</code> makes for verbose code</li>\n<li>The css classes themselves are lengthy as well</li>\n<li><code>onBlur</code> keeps making the font larger, but <code>focus</code> does not make the font smaller, which could cause comically large labels</li>\n<li><code>applyEL</code> -> <code>applyEventListeners</code> reads/parses better </li>\n</ul>\n\n<p>This could be done instead:</p>\n\n<pre><code>/*****************************************************************************************\n **SDynInput - provides dynamic input for labels and borders\n */\nvar SDynInput = $A.Class.create({\n Name: 'SDynInput',\n // elements are passed in as input/label pairs\n set: function (inputLabelPairs) {\n var index;\n for (index = 0; index &lt; inputLabelPairs.length; index += 2) {\n this.applyEventListeners(inputLabelPairs[index], inputLabelPairs[index + 1]);\n }\n },\n // apply event listeners to the input elements\n applyEventListeners: function (input, label) {\n var self = this,\n labelSpeed = 200,\n // CSS classes used to toggle the label\n hideLabel = 'toggle_label_hide',\n obscureLabel = 'toggle_label_obscure',\n showLabel = 'toggle_label_show',\n // CSS classes used to toggle the input border\n hideBorder = 'toggle_border_hide',\n obscureBorder = 'toggle_border_obscure',\n showBorder = 'toggle_border_show',\n applyClasses = function (inputClass, labelClass) {\n $A.addClass(input, inputClass);\n $A.addClass(label, labelClass);\n },\n applyHidingClasses = function () {\n applyClasses(hideBorder, hideLabel);\n };\n input.addEventListener(\"blur\", function () {\n if (input.value === '') {\n applyClasses(borderShow, labelShow);\n $A.expandFont(label, 'up', labelSpeed);\n }\n }, false);\n input.addEventListener(\"focus\", function () {\n if (input.value === '') {\n applyClasses(borderObscure, labelObscure);\n }\n }, false);\n input.addEventListener(\"paste\", applyHidingClasses false);\n input.addEventListener(\"keypress\", applyHidingClasses, false);\n input.addEventListener(\"drop\", function () {\n $A.setTimeout(applyHidingClasses, 0);\n }, false);\n }\n}, true);\n</code></pre>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-04-08T01:46:58.057", "Id": "46604", "ParentId": "39855", "Score": "3" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-01-23T02:17:49.377", "Id": "39855", "Score": "2", "Tags": [ "javascript", "reinventing-the-wheel", "event-handling" ], "Title": "A class for dynamic inputs" }
39855
<p>I am fairly new to web development, and would like some feedback. It is HTML/CSS, with some JS (button hovers, anchor scrolling and image sliders) from elsewhere. Comments on best practices and any other suggestions would be great as I feel I'm probably doing a lot wrong, but specifically:</p> <ol> <li><p>I used different-colored containers that stretch the whole width of the page. Each container is inside a div which specifies the background color. Is this the best way to do it?</p></li> <li><p>Is there an easy way for me to vertically-center my text blocks, instead of adding lots of linebreak tags?</p></li> <li><p>A lot of my divs have multiple classes, e.g. "column last half image" and "centered larger highlight" - should this be avoided and if so what's the best way to go about this?</p></li> </ol> <p><a href="https://dl.dropboxusercontent.com/u/10251831/Training%20Website/index.html">Link</a></p> <p><strong>HTML:</strong></p> <pre><code>&lt;!DOCTYPE html&gt; &lt;html&gt; &lt;head&gt; &lt;title&gt;MVX Training | Welcome to the future of training&lt;/title&gt; &lt;meta name="description" content="3D Interactive Training"&gt; &lt;meta name="keywords" content="3D, interactive, virtual, simulations, training, games, gamification"&gt; &lt;link href='style.css' rel='stylesheet' type='text/css'&gt; &lt;link rel="icon" type="img/ico" href="images/favicon.ico"&gt; &lt;link rel="image_src" href="screenshot.jpg" /&gt; &lt;script src="js/jquery.min.js"&gt;&lt;/script&gt; &lt;script src="js/responsiveslides.min.js"&gt;&lt;/script&gt; &lt;script&gt; $(function() { $(".rslides").responsiveSlides({ auto: true, // Boolean: Animate automatically, true or false speed: 700, // Integer: Speed of the transition, in milliseconds timeout: 4000, // Integer: Time between slide transitions, in milliseconds pager: false, // Boolean: Show pager, true or false nav: false, // Boolean: Show navigation, true or false maxwidth: "", // Integer: Max-width of the slideshow, in pixels }); }); &lt;/script&gt; &lt;/head&gt; &lt;body&gt; &lt;header&gt; &lt;div class="lightgrey"&gt; &lt;div class="navcontainer"&gt; &lt;div class="logo"&gt; &lt;img src="images/logo.png" /&gt; &lt;/div&gt; &lt;div class="navlinks"&gt; &lt;ul&gt; &lt;li&gt;&lt;a class="scroll" data-speed="700" href="#welcome"&gt;Welcome&lt;/a&gt;&lt;/li&gt; &lt;li&gt;&lt;a class="scroll" data-speed="1000" href="#features"&gt;Features&lt;/a&gt;&lt;/li&gt; &lt;li&gt;&lt;a class="scroll" data-speed="1400" href="#casestudies"&gt;Case Studies&lt;/a&gt;&lt;/li&gt; &lt;li&gt;&lt;a class="scroll" data-speed="1500" href="#development"&gt;Development&lt;/a&gt;&lt;/li&gt; &lt;li&gt;&lt;a class="scroll" data-speed="1600" href="#pricing"&gt;Pricing&lt;/a&gt;&lt;/li&gt; &lt;li&gt;&lt;a class="scroll" data-speed="1700" href="#getintouch"&gt;Get in Touch&lt;/a&gt;&lt;/li&gt; &lt;/ul&gt; &lt;/div&gt; &lt;/div&gt; &lt;/div&gt; &lt;/header&gt; &lt;div class="darkgrey"&gt; &lt;div class="container"&gt; &lt;div class="column"&gt; &lt;p&gt;&lt;br /&gt;&lt;br /&gt;&lt;br /&gt;&lt;/p&gt; &lt;a class="anchor" id="welcome"&gt;&lt;/a&gt;&lt;h1 class="light"&gt;&lt;br /&gt;&lt;br /&gt;WELCOME TO THE FUTURE OF TRAINING&lt;/h1&gt; &lt;div class="underline light"&gt;&lt;/div&gt; &lt;p class="centered larger"&gt;MVX is an innovative new technology which leverages 3D gaming engines to provide immersive virtual training. 3D visuals and outcomes-focussed content are combined in a realistic 3D environment, allowing you to teach and assess operational procedures, hazard awareness and emergency scenario responses in an interactive and memorable way.&lt;/p&gt;&lt;br /&gt; &lt;center&gt;&lt;img src="images/reel.png" /&gt;&lt;/center&gt; &lt;a href="#"&gt;&lt;div class="button light"&gt;CONTACT US FOR A FREE DEMO&lt;/div&gt;&lt;/a&gt; &lt;/div&gt; &lt;a class="scroll" data-speed="700" href="#features"&gt;&lt;div class="nextbutton"&gt;NEXT&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&lt;/div&gt;&lt;/a&gt; &lt;/div&gt; &lt;/div&gt; &lt;div class="lightgrey"&gt; &lt;div class="container"&gt; &lt;div class="column"&gt; &lt;a class="anchor" id="features"&gt;&lt;/a&gt;&lt;h1&gt;FEATURES&lt;/h1&gt; &lt;div class="underline"&gt;&lt;/div&gt; &lt;div class="column half"&gt; &lt;h2&gt;SIMULATE EMERGENCY SCENARIOS&lt;/h2&gt; &lt;p&gt;Expose your personnel to realistic emergency and hazard scenarios so they can safely experience the potential consequences and dangers they can cause, and practise the appropriate responses to these emergencies.&lt;/p&gt; &lt;/div&gt; &lt;div class="column half last image"&gt; &lt;img src="images/simulate_emergency_scenarios.png" /&gt; &lt;/div&gt; &lt;/div&gt; &lt;a class="scroll" data-speed="700" href="#features2"&gt;&lt;div class="nextbutton"&gt;NEXT&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&lt;/div&gt;&lt;/a&gt; &lt;/div&gt; &lt;/div&gt; &lt;div class="lightestgrey"&gt; &lt;div class="container"&gt; &lt;div class="column"&gt; &lt;div class="column half image rtl"&gt; &lt;img src="images/teach_consequences_effectively.png" /&gt; &lt;/div&gt; &lt;div class="column half last"&gt; &lt;a class="anchor" id="features2"&gt;&lt;/a&gt;&lt;h2&gt;TEACH CONSEQUENCES EFFECTIVELY&lt;/h2&gt; &lt;p&gt;Users can interact with the virtual 3D environment and make choices that will affect how their virtual character will fare, much like the real world. In these virtual environments, users can experience the consequences of those choices in a memorable way without the risk, and without the need to cease real operations.&lt;/p&gt; &lt;/div&gt; &lt;/div&gt; &lt;a class="scroll" data-speed="700" href="#features3"&gt;&lt;div class="nextbutton"&gt;NEXT&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&lt;/div&gt;&lt;/a&gt; &lt;/div&gt; &lt;/div&gt; &lt;div class="lightgrey"&gt; &lt;div class="container"&gt; &lt;div class="column"&gt; &lt;div class="column half"&gt; &lt;a class="anchor" id="features3"&gt;&lt;/a&gt;&lt;h2&gt;SITE FAMILIARISATION&lt;/h2&gt; &lt;p&gt;Our talented team of 3D artists can create realistic 3D representations of your plant, site or work environment - whether it be existing or conceptual. These can be created using photographs, videos, blueprints or 3D CAD models. Interacting and exploring within this virtual environment will allow users to become familiar with important locations around site, minimising risk and improving efficiency.&lt;/p&gt; &lt;/div&gt; &lt;div class="column half last image rtl"&gt; &lt;br /&gt;&lt;br /&gt; &lt;img src="images/site_familiarisation.png" /&gt; &lt;/div&gt; &lt;/div&gt; &lt;a class="scroll" data-speed="700" href="#features4"&gt;&lt;div class="nextbutton"&gt;NEXT&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&lt;/div&gt;&lt;/a&gt; &lt;/div&gt; &lt;/div&gt; &lt;div class="lightestgrey"&gt; &lt;div class="container"&gt; &lt;div class="column"&gt; &lt;div class="column half image rtl"&gt; &lt;/div&gt; &lt;div class="column half last"&gt; &lt;a class="anchor" id="features4"&gt;&lt;/a&gt;&lt;h2&gt;COMMUNICATE SAFETY CULTURE&lt;/h2&gt; &lt;p&gt;Our training modules are custom-tailored to teach your user outcomes and safety culture in the most effective way. These may be communicated and tested through animated storylines and conversations within the 3D environment, engaging and interactive minigames, and simulated emergency scenarios.&lt;/p&gt; &lt;/div&gt; &lt;/div&gt; &lt;a class="scroll" data-speed="700" href="#features5"&gt;&lt;div class="nextbutton"&gt;NEXT&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&lt;/div&gt;&lt;/a&gt; &lt;/div&gt; &lt;/div&gt; &lt;div class="lightgrey"&gt; &lt;div class="container"&gt; &lt;div class="column"&gt; &lt;div class="column half"&gt; &lt;a class="anchor" id="features5"&gt;&lt;/a&gt;&lt;h2&gt;VISUALISE COMPLEX PROCESSES&lt;/h2&gt; &lt;p&gt;(Removed for StackExchange char limit)&lt;/p&gt; &lt;/div&gt; &lt;div class="column half last image rtl"&gt; &lt;img src="images/visualise_complex_processes.png" /&gt; &lt;/div&gt; &lt;/div&gt; &lt;a class="scroll" data-speed="700" href="#features6"&gt;&lt;div class="nextbutton"&gt;NEXT&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&lt;/div&gt;&lt;/a&gt; &lt;/div&gt; &lt;/div&gt; &lt;div class="lightestgrey"&gt; &lt;div class="container"&gt; &lt;div class="column"&gt; &lt;div class="column half image"&gt; &lt;/div&gt; &lt;div class="column half last"&gt; &lt;a class="anchor" id="features6"&gt;&lt;/a&gt;&lt;h2&gt;DETAILED USER REPORTING&lt;/h2&gt; &lt;p&gt;(Removed for StackExchange char limit)&lt;/p&gt; &lt;/div&gt; &lt;/div&gt; &lt;a class="scroll" data-speed="700" href="#features7"&gt;&lt;div class="nextbutton"&gt;NEXT&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&lt;/div&gt;&lt;/a&gt; &lt;/div&gt; &lt;/div&gt; &lt;div class="lightgrey"&gt; &lt;div class="container"&gt; &lt;div class="column"&gt; &lt;div class="column half"&gt; &lt;a class="anchor" id="features7"&gt;&lt;/a&gt;&lt;h2&gt;DEPLOYMENT OPTIONS&lt;/h2&gt; &lt;p&gt;(Removed for StackExchange char limit)&lt;/p&gt; &lt;/div&gt; &lt;div class="column half last image rtl"&gt; &lt;br /&gt; &lt;img src="images/deployment_options.png" /&gt; &lt;/div&gt; &lt;/div&gt; &lt;a class="scroll" data-speed="700" href="#casestudies"&gt;&lt;div class="nextbutton"&gt;NEXT&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&lt;/div&gt;&lt;/a&gt; &lt;/div&gt; &lt;/div&gt; &lt;div class="lightestgrey"&gt; &lt;div class="container"&gt; &lt;div class="column"&gt; &lt;a class="anchor" id="casestudies"&gt;&lt;/a&gt;&lt;h1&gt;CASE STUDIES&lt;/h1&gt; &lt;div class="underline"&gt;&lt;/div&gt; &lt;h2&gt;WOODSIDE HEAT STRESS&lt;/h2&gt; &lt;ul class="rslides"&gt; &lt;li&gt;&lt;img src="images/case-studies/woodside-1.jpg"&gt;&lt;/li&gt; &lt;li&gt;&lt;img src="images/case-studies/woodside-2.jpg"&gt;&lt;/li&gt; &lt;li&gt;&lt;img src="images/case-studies/woodside-3.jpg"&gt;&lt;/li&gt; &lt;li&gt;&lt;img src="images/case-studies/woodside-4.jpg"&gt;&lt;/li&gt; &lt;li&gt;&lt;img src="images/case-studies/woodside-5.jpg"&gt;&lt;/li&gt; &lt;/ul&gt; &lt;p&gt;To complement their existing Broome induction, Woodside required an additional module to teach inductees about the dangers of heat stress. The module covered several related topics ranging from PPE, alcohol restrictions, real examples of heat stress, assessing personal risk, first aid response, emergency response and incident reporting.&lt;/p&gt; &lt;p class="parabreak"&gt;&amp;nbsp;&lt;/p&gt; &lt;p&gt;Inductees are placed in various realistic scenarios, including emergency scenarios, in which they must apply the knowledge they have learnt throughout the module. They are taught to be aware of their own hydration/heat stress levels, as well as those of their co-workers.&lt;/p&gt; &lt;div class="quote"&gt; &lt;p&gt;"The software developed by Sentient for Woodside's Kimberley induction program has provided workers with a more engaging and effective site induction."&lt;/p&gt; &lt;div class="author"&gt; &lt;p&gt;- Jim McQueenie / Health, Safety &amp; Security Manager / Woodside Browse LNG Development&lt;/p&gt; &lt;/div&gt; &lt;/div&gt; &lt;/div&gt; &lt;a class="scroll" data-speed="700" href="#casestudies2"&gt;&lt;div class="nextbutton"&gt;NEXT&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&lt;/div&gt;&lt;/a&gt; &lt;/div&gt; &lt;/div&gt; &lt;div class="lightgrey"&gt; &lt;div class="container"&gt; &lt;div class="column"&gt; &lt;br /&gt;&lt;br /&gt;&lt;br /&gt; &lt;a class="anchor" id="casestudies2"&gt;&lt;/a&gt;&lt;h2&gt;ACID PLANT FILTER PRESS&lt;/h2&gt; &lt;ul class="rslides"&gt; &lt;li&gt;&lt;img src="images/case-studies/acid-1.jpg"&gt;&lt;/li&gt; &lt;li&gt;&lt;img src="images/case-studies/acid-2.jpg"&gt;&lt;/li&gt; &lt;li&gt;&lt;img src="images/case-studies/acid-3.jpg"&gt;&lt;/li&gt; &lt;li&gt;&lt;img src="images/case-studies/acid-4.jpg"&gt;&lt;/li&gt; &lt;li&gt;&lt;img src="images/case-studies/acid-5.jpg"&gt;&lt;/li&gt; &lt;li&gt;&lt;img src="images/case-studies/acid-6.jpg"&gt;&lt;/li&gt; &lt;li&gt;&lt;img src="images/case-studies/acid-7.jpg"&gt;&lt;/li&gt; &lt;/ul&gt; &lt;p&gt;This training module was developed to teach complex procedures to new and existing staff at a plant dealing with hazardous chemicals. The procedures were taught by utilising three fundamental stages: Show, Interact, and Assess. Trainees were first shown the correct procedure, then were allowed to interact with the virtual scene to practise the procedure, and finally were assessed on what they had learnt.&lt;/p&gt; &lt;p class="parabreak"&gt;&amp;nbsp;&lt;/p&gt; &lt;p&gt;Visual animations, combined with an accurate and immersive 3D representation of the real site allowed trainees to familiarise themselves with the procedure and site before being physically inducted.&lt;/p&gt; &lt;div class="stat"&gt; &lt;p&gt;&amp;nbsp;&lt;/p&gt; &lt;p&gt;The company was able to reduce its training time from 3 days per trainee to just 1.&lt;/p&gt; &lt;/div&gt; &lt;/div&gt; &lt;a class="scroll" data-speed="700" href="#development"&gt;&lt;div class="nextbutton"&gt;NEXT&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&lt;/div&gt;&lt;/a&gt; &lt;/div&gt; &lt;/div&gt; &lt;div class="darkgrey"&gt; &lt;div class="container"&gt; &lt;a class="anchor" id="development"&gt;&lt;/a&gt;&lt;h1 class="light"&gt;DEVELOPMENT&lt;/h1&gt; &lt;div class="underline light"&gt;&lt;/div&gt; &lt;div class="flowbox"&gt;Project start-up meeting (with client) to discuss requirements and deliverables&lt;/div&gt; &lt;div class="flowline"&gt;&lt;/div&gt; &lt;div class="flowbox"&gt;Customer delivers existing training material &amp; other supporting documentation and assets&lt;/div&gt; &lt;div class="flowline"&gt;&lt;/div&gt; &lt;div class="flowbox"&gt;Create pre-visualisation (3D storyboard)&lt;/div&gt; &lt;div class="flowline"&gt;&lt;/div&gt; &lt;div class="flowbox right"&gt;Make adjustments&lt;/div&gt; &lt;div class="flowbox rounded"&gt;Client approves?&lt;/div&gt; &lt;p class="centered"&gt;Yes&lt;/p&gt; &lt;div class="flowline"&gt;&lt;/div&gt; &lt;div class="flowline"&gt;&lt;/div&gt; &lt;div class="flowbox"&gt;Develop any remaining 3D content&lt;/div&gt; &lt;div class="flowline"&gt;&lt;/div&gt; &lt;div class="flowbox"&gt;Implement animations and interactions&lt;/div&gt; &lt;div class="flowline"&gt;&lt;/div&gt; &lt;div class="flowbox"&gt;Implement training outcomes&lt;/div&gt; &lt;div class="flowline"&gt;&lt;/div&gt; &lt;div class="flowbox"&gt;Create a build and deliver to customer&lt;/div&gt; &lt;div class="flowline"&gt;&lt;/div&gt; &lt;div class="flowbox right"&gt;Make adjustments&lt;/div&gt; &lt;div class="flowbox rounded"&gt;Client approves?&lt;/div&gt; &lt;p class="centered"&gt;Yes&lt;/p&gt; &lt;div class="flowline"&gt;&lt;/div&gt; &lt;div class="flowbox"&gt;Project closure&lt;/div&gt; &lt;a class="scroll" data-speed="700" href="#pricing"&gt;&lt;div class="nextbutton"&gt;NEXT&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&lt;/div&gt;&lt;/a&gt; &lt;/div&gt; &lt;/div&gt; &lt;div class="lightestgrey"&gt; &lt;div class="container"&gt; &lt;a class="anchor" id="pricing"&gt;&lt;/a&gt;&lt;h1&gt;PRICING&lt;/h1&gt; &lt;div class="underline"&gt;&lt;/div&gt; &lt;p&gt;As each module is customised, the pricing will vary depending on several factors. Below is an estimation of our average module prices. Please contact us directly for a specific quote.&lt;/p&gt;&lt;br /&gt; &lt;div class="column third lightgrey"&gt; &lt;h2 class="centered"&gt;BASIC&lt;/h2&gt; &lt;div class="price"&gt;&lt;br /&gt;&lt;br /&gt;&lt;br /&gt;15k&lt;/div&gt; &lt;/div&gt; &lt;div class="column third lightgrey"&gt; &lt;h2 class="centered"&gt;MEDIUM&lt;/h2&gt; &lt;div class="price"&gt;&lt;br /&gt;&lt;br /&gt;&lt;br /&gt;50k&lt;/div&gt; &lt;/div&gt; &lt;div class="column third last lightgrey"&gt; &lt;h2 class="centered"&gt;COMPLEX&lt;/h2&gt; &lt;div class="price"&gt;&lt;br /&gt;&lt;br /&gt;&lt;br /&gt;85k&lt;/div&gt; &lt;/div&gt; &lt;div class="column third"&gt; &lt;p class="centered"&gt;10-20 minutes of gameplay&lt;br /&gt; Basic 3D environment and assets&lt;br /&gt; Basic 3D animations&lt;br /&gt; 1-2 non-player characters&lt;br /&gt; In-house voiceovers&lt;/p&gt; &lt;/div&gt; &lt;div class="column third"&gt; &lt;p class="centered"&gt;20-40 minutes of gameplay&lt;br /&gt; Realistic 3D environment and assets&lt;br /&gt; Realistic 3D animations&lt;br /&gt; 3-5 non-player characters&lt;br /&gt; Professional voiceovers&lt;/p&gt; &lt;/div&gt; &lt;div class="column third last"&gt; &lt;p class="centered"&gt;40-60 minutes of gameplay&lt;br /&gt; Realistic 3D environment and assets&lt;br /&gt; Realistic 3D animations&lt;br /&gt; 6-10 non-player characters&lt;br /&gt; Professional voiceovers&lt;/p&gt; &lt;/div&gt; &lt;a class="scroll" data-speed="700" href="#getintouch"&gt;&lt;div class="nextbutton"&gt;NEXT&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&lt;/div&gt;&lt;/a&gt; &lt;/div&gt; &lt;/div&gt; &lt;div class="darkgrey"&gt; &lt;div class="container contact"&gt; &lt;a class="anchor" id="getintouch"&gt;&lt;/a&gt;&lt;h1 class="light"&gt;GET IN TOUCH&lt;/h1&gt; &lt;div class="underline light"&gt;&lt;/div&gt; &lt;p class="centered larger"&gt;See what you can achieve with MVX Training. Contact us for a free demo today.&lt;/p&gt; &lt;a href="#"&gt;&lt;div class="button light"&gt;CONTACT US FOR A FREE DEMO&lt;/div&gt;&lt;/a&gt; &lt;p class="centered larger"&gt;Or call us on&lt;/p&gt; &lt;p class="centered larger highlight"&gt;+61 8 9240 7888&lt;/p&gt; &lt;/div&gt; &lt;/div&gt; &lt;div class="darkestgrey"&gt; &lt;div class="container"&gt; &lt;center&gt;&lt;img src="images/sentient_logo.png" /&gt;&lt;/center&gt; &lt;p class="centered larger"&gt;204 Balcatta Road, Balcatta WA 6021&lt;/p&gt; &lt;p class="centered larger"&gt;&lt;a href="http://sencom.com.au" target="_blank"&gt;www.sencom.com.au&lt;/a&gt;&lt;/p&gt; &lt;/div&gt; &lt;/div&gt; &lt;/body&gt; &lt;script src="js/smooth-scroll.js"&gt;&lt;/script&gt; &lt;/html&gt; </code></pre> <p><strong>CSS:</strong></p> <pre><code>/* --------------------------------------------------------------- MVX TRAINING WEBSITE URL: Company: Year: 2014 ------- SWATCHES USED: -------- Dark backgrounds: #1b1b1b Darkest backgrounds: #090909 Light backgrounds: #eeeeee Lightest backgrounds: #f5f5f5 Dark text: #1b1b1b Light text: #fff Light grey text: #9e9e9e Orange highlights: #f98c0b ------------------------------- --------------------------------------------------------------- */ /* --------------------------- OPEN SANS --------------------------- */ /* Light */ @font-face { font-family: 'Open Sans'; src: url('fonts/OpenSans-Light-webfont.eot'); src: url('fonts/OpenSans-Light-webfont.eot?#iefix') format('embedded-opentype'), url('fonts/OpenSans-Light-webfont.woff') format('woff'), url('fonts/OpenSans-Light-webfont.ttf') format('truetype'), url('fonts/OpenSans-Light-webfont.svg#OpenSansLight') format('svg'); font-weight: 300; font-style: normal; } /* Light Italic */ @font-face { font-family: 'Open Sans'; src: url('fonts/OpenSans-LightItalic-webfont.eot'); src: url('fonts/OpenSans-LightItalic-webfont.eot?#iefix') format('embedded-opentype'), url('fonts/OpenSans-LightItalic-webfont.woff') format('woff'), url('fonts/OpenSans-LightItalic-webfont.ttf') format('truetype'), url('fonts/OpenSans-LightItalic-webfont.svg#OpenSansLightItalic') format('svg'); font-weight: 300; font-style: italic; } /* --------------------------- GENERAL --------------------------- */ body { background-color: #fff; } a { outline: 0; } a.anchor { display: block; position: relative; top: -150px; visibility: hidden; } * { margin: 0; padding: 0; } /* --------------------------- FONTS --------------------------- */ p, body { font-family: 'Open Sans', sans-serif; font-size: 14px; font-weight: 300; text-align: justify; line-height: 28px; color: #1b1b1b; } p a { color: #f98c0b; text-decoration: none; } p a:hover { text-decoration: underline; } .darkgrey p, .darkestgrey p { color: #9e9e9e; } p.larger { font-size: 16px; } p.parabreak { line-height: 14px; } .quote { min-height: 100px; width: 60%; float: right; margin: 10px 120px 10px 10px; font-style: italic; color: #000; background: url('images/quote.png') 1.4em 1.6em no-repeat; padding: 10px 10px 10px 90px; } .author { font-style: normal; } .stat { min-height: 100px; width: 60%; float: right; margin: 10px 120px 10px 10px; font-style: italic; color: #000; background: url('images/stat.png') 1.4em 1.6em no-repeat; padding: 6px 10px 10px 90px; } h1 { letter-spacing: 2px; font-weight: 300; text-align: center; font-size: 36px; color: #1b1b1b; margin-top: 20px; margin-bottom: 20px; } h1 a { text-decoration: inherit; color: inherit; } h1.light { color: #fff; } h2 { letter-spacing: 2px; font-weight: 300; font-size: 22px; text-align: justify; margin-bottom: 20px; } h2.light { color: #fff; } .underline { background-color: #1b1b1b; width: 70px; height: 2px; display: block; margin: 0 auto; margin-top: 20px; margin-bottom: 30px; } .underline.light { background-color: #fff; } .centered { text-align: center; } .highlight { color: #f98c0b; } /* --------------------------- CONTAINERS --------------------------- */ .container { width: 960px; margin: 0 auto; padding: 0; padding-top: 30px; padding-bottom: 30px; } .container:after { content: "\0020"; display: block; height: 0; clear: both; visibility: hidden; } .nobottompadding { padding-bottom: 0px; } .container.contact { background-image: url('images/contact.png'); background-repeat: no-repeat; } /* --------------------------- COLUMNS --------------------------- */ .column { width: 960px; float: left; } .column:after { content: "\0020"; display: block; height: 0; clear: both; visibility: hidden; } .column.third { float: left; margin-right: 20px; width: 306px; padding-top: 30px; padding-bottom: 30px; } .column.last { margin-right: 0px; float: right; } .column.half { width: 460px; min-height: 300px; margin-top: 120px; } .column.rtl { direction: rtl; } .column.ltr { direction: ltr; } .column.image { margin: 0px; } /* --------------------------- COLORS --------------------------- */ .darkgrey { background-color: #1b1b1b; } .darkestgrey { background-color: #090909; } .lightgrey { background-color: #eeeeee; } .lightestgrey { background-color: #f5f5f5; } /* --------------------------- BUTTONS --------------------------- */ .button { position: relative; text-transform: uppercase; text-align: center; font-size: 14px; border: solid 2px #f98c0b; display: inline-block; width: 240px; left: 50%; margin: 20px auto; margin-left: -160px; padding: 10px 40px 10px 40px; transition: all 0.2s linear; } .button:hover { width:260px; margin-left:-170px; -webkit-transition:500ms linear; } .button.light { color: #fff; } .nextbutton { padding-top: -2px; float: right; text-align: right; font-size: 12px; width: 48px; height: 16px; background-image: url('images/arrow.png'); background-repeat: no-repeat; margin-top: 20px; margin-bottom: 20px } .nextbutton a { color: inherit; text-decoration: none; } .darkgrey a, darkestgrey a { color: #fff; } .scroll { color: inherit; text-decoration: none; } /* --------------------------- NAVIGATION --------------------------- */ header { position: fixed; z-index: 10; width: 100%; height: 88px; background-color: #eeeeee; margin: 0px; } .navcontainer { width: 960px; margin: 0 auto; height: 88px; } .navcontainer:after { content: "\0020"; display: block; height: 0; clear: both; visibility: hidden; } .navlinks { float: right; margin-right: 10px; padding-top: 28px; } ul li { text-transform: uppercase; font-size: 12px; display: inline; color: #1b1b1b; margin-left: 40px; } ul li a { color: inherit; text-decoration: none; } ul li a:hover { border-bottom: 2px solid #f98c0b; padding-bottom:4px; } .logo { float: left; margin: 0 auto; padding: 0px; height: 150px; width: 150px; } /* --------------------------- PRICING --------------------------- */ .price { font-size: 60px; text-align: center; margin: 30px 50px 10px 50px; border-radius: 50%; width: 200px; height: 200px; border: 2px solid #f98c0b; } /* --------------------------- FLOWCHART --------------------------- */ .flowbox { text-align: center; color: #fff; width: 260px; border: 2px solid #f98c0b; margin: auto; padding: 20px; } .flowbox.right { float: right; display: inline; } .flowbox.rounded { width: 160px; border-radius: 50%; } .flowline { font-size: 0; width: 3px; height: 20px; background-color: #3b3b3b; margin: auto; } /* --------------------------- SLIDER --------------------------- */ .rslides { position: relative; list-style: none; overflow: hidden; width: 100%; padding: 0; margin: 0; } .rslides li { -webkit-backface-visibility: hidden; position: absolute; display: none; width: 100%; left: 0; top: 0; padding: 0; margin: 0; } .rslides li:first-child { position: relative; float: left; } .rslides img { display: block; height: auto; float: left; width: 100%; border: 0; margin-bottom: 20px; } </code></pre>
[]
[ { "body": "<p><strong>CSS</strong></p>\n\n<p>Instead of having 5 different rules all saying the same thing for 5 selectors. You can group them like this.</p>\n\n<pre><code>h1.light,\nh2.light,\n.darkgrey a,\n.darkestgrey a,\n.button.light\n {\n color: #fff;\n}\n\nbody,\n.underline.light {\n background-color: #fff;\n}\n</code></pre>\n\n<p>Use one line for margins.</p>\n\n<pre><code>h1 {\n margin-top: 20px 0;\n}\n\nh2 {\n margin: 0 0 20px 0;\n}\n\n.underline {\n margin: 20px auto 30px;\n}\n\n.button {\n margin: 20px auto 20px -160px;\n}\n\n.nextbutton {\n margin: 20px 0;\n}\n</code></pre>\n\n<p>Use one line for paddings.</p>\n\n<pre><code>.container {\n padding: 30px 0;\n}\n\n.column.third {\n padding: 30px 0;\n}\n</code></pre>\n\n<hr>\n\n<p><strong>HTML</strong></p>\n\n<p>You should remove this from your head.</p>\n\n<pre><code>&lt;meta name=\"keywords\" content=\"3D, interactive, virtual, simulations, training, games, gamification\"&gt;\n</code></pre>\n\n<p>Most search engines do not use the meta keywords for their algorithm top rankings anymore. From what I've heard, having the meta keywords can only count against you for SEO (Search Engine Optimization). Because I believe that search engines will still penalize a site for having false and or repetitive keywords. Yes, your keywords are correct, but there is no point in including them on websites anymore. <a href=\"http://en.wikipedia.org/wiki/Meta_element#The_keywords_attribute\">http://en.wikipedia.org/wiki/Meta_element#The_keywords_attribute</a></p>\n\n<p>The description is still used and is very important because it will likely show up when searching for your site.\nHowever, search engines may show something other than your description based on the users search keywords.\nThe description should be more detailed and longer than just \"3D Interactive Training\". </p>\n\n<pre><code>&lt;meta name=\"description\" content=\"3D Interactive Training\"&gt;\n</code></pre>\n\n<p><a href=\"http://en.wikipedia.org/wiki/Meta_element#The_description_attribute\">http://en.wikipedia.org/wiki/Meta_element#The_description_attribute</a></p>\n\n<hr>\n\n<p>There's nothing evil about line breaks, so it's whatever you prefer to use.\nThe way you used them here is pretty unusual though.</p>\n\n<pre><code>&lt;div class=\"column\"&gt;\n &lt;p&gt;&lt;br /&gt;&lt;br /&gt;&lt;br /&gt;&lt;/p&gt;\n &lt;a class=\"anchor\" id=\"welcome\"&gt;&lt;/a&gt;&lt;h1 class=\"light\"&gt;&lt;br /&gt;&lt;br /&gt;WELCOME TO THE FUTURE OF TRAINING&lt;/h1&gt;\n</code></pre>\n\n<p>I'd probably change that to this:</p>\n\n<pre><code>&lt;div class=\"column\"&gt;\n &lt;a class=\"anchor\" id=\"welcome\"&gt;&lt;/a&gt;&lt;h1 class=\"firsth1 light\"&gt;WELCOME TO THE FUTURE OF TRAINING&lt;/h1&gt;\n\n#welcome { margin: 40px 0 0 0; } /* adjust accordingly */\n.firsth1 { margin: 20px 0 0 0; } /* adjust accordingly */\n</code></pre>\n\n<p>How you have them here looks fine.</p>\n\n<pre><code>&lt;div class=\"column half last image rtl\"&gt; \n &lt;br /&gt;&lt;br /&gt; \n &lt;img src=\"images/site_familiarisation.png\" /&gt; \n&lt;/div&gt; \n</code></pre>\n\n<p>You have quite a few lines like this too.</p>\n\n<pre><code>&lt;div class=\"nextbutton\"&gt;NEXT&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&lt;/div&gt;\n</code></pre>\n\n<p>I would change it to something like this:</p>\n\n<pre><code>&lt;div class=\"nextbutton\"&gt;NEXT&lt;/div&gt;\n\n.nextbutton {\n text-align: right; /* this might not work */\n padding: 0 0 0 20px; /* then you could do something like this instead */ /* adjust accordingly */\n}\n</code></pre>\n\n<p>Lastly, I think your use of classes is just fine. I also like how you used a limited number of <code>id</code>'s, which can too often end up making your css many more characters than needed.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-01-23T06:03:35.047", "Id": "39860", "ParentId": "39859", "Score": "11" } }, { "body": "<p>Here are some quick and non-exhaustive comments:</p>\n<h1>Wrong usage of <code>br</code></h1>\n<p>Your use of <code>br</code> is wrong, you should use margin or padding for that.</p>\n<p>For example, to have a fixed menu just put the other content on a div, and give that div margin-top.<br />\n(Or you could hack it with <code>header+* { margin-top: 40px; }</code>, or...)</p>\n<p>See the examples in <a href=\"http://developers.whatwg.org/text-level-semantics.html#the-br-element\" rel=\"noreferrer\">http://developers.whatwg.org/text-level-semantics.html#the-br-element</a><br />\n, where this is stated:</p>\n<blockquote>\n<blockquote>\n<p>While line breaks are usually represented in visual media by physically moving subsequent text to a new line, a style sheet or user agent would be equally justified in causing line breaks to be rendered in a different manner, for instance as green dots, or as extra spacing.</p>\n</blockquote>\n<p>br elements must be used only for line breaks that are actually part of the content, as in poems or addresses.</p>\n<p>(...)</p>\n<p>If a paragraph consists of nothing but a single br element, it represents a placeholder blank line (e.g. as in a template). Such blank lines must not be used for presentation purposes.</p>\n</blockquote>\n<h1>Wrong usage of <code>&amp;nbsp;</code></h1>\n<p>Similar to the suggestion about br.</p>\n<p>For example, remove the <code>&amp;nbsp;</code>s from <code>div.nextbutton</code>, and use css to put everything in place: <code>.nextbutton { padding-right: 18px; /*16+2*/ background-position: right center;}</code></p>\n<h1>Invalid HTML</h1>\n<p>Your HTML <a href=\"http://validator.w3.org/check?uri=https%3A%2F%2Fdl.dropboxusercontent.com%2Fu%2F10251831%2FTraining%2520Website%2Findex.html&amp;charset=%28detect+automatically%29&amp;doctype=Inline&amp;group=0\" rel=\"noreferrer\">is not valid</a>.</p>\n<p>Also, I cannot stress this enough: <strong>you should use UTF8 as your default encoding</strong>, and not ASCII.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-01-23T14:13:59.737", "Id": "39873", "ParentId": "39859", "Score": "7" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-01-23T05:28:07.903", "Id": "39859", "Score": "11", "Tags": [ "html", "beginner", "css" ], "Title": "One page website with JS functionality" }
39859
<p>I was doing a simple exercise to calculate the amount based on an expression.</p> <p>For example:</p> <p><code>(((2*2)+(3*5/5)+(2*5)))</code> outputs 17</p> <p><code>((2*2)(3*5/5)(2*5))</code> output 120 etc</p> <p>I have written the code, but I am not satisfied with what I've done. Could you please help me to review the code and suggest the best approach for that?</p> <pre><code>import java.util.ArrayList; public class Calculator { private static ArrayList&lt;String&gt; data; private static Element element = new Element(); int startIndex = 0; int endIndex = 0; public int length = 0; boolean startFlag = false; public double calculatedValue = 0; public Calculator() { // TODO Auto-generated constructor stub } public static void main(String[] args) { // String testExpression = "(((2*2)+(3*5/5)+(2*5)))";//17 String testExpression = "((2*2)(3*5/5)(2*5))"; // 120-- new Calculator().parsedExpression(testExpression); } public void parsedExpression(String testExpression) { System.out.println(testExpression + " Before formatting"); testExpression = testExpression.replaceAll("\\)\\(", ")*("); // To // change // (a+b)(b+c) // to // (a+b)*(b+c) System.out.println(testExpression + " After first formatting"); data = CalculatorUtil.parseExpression(testExpression); System.out.println("Total Sum====" + process()); } public double process() { System.out.println("Array:ist" + data); startIndex = 0; endIndex = 0; length = data.size(); System.out.println("===" + data.indexOf("(")); if (data.indexOf("(") &gt;= 0) { getCalIndex(); System.out.println("startIndex=" + startIndex + "==" + endIndex); } if (startIndex &lt; endIndex) { double value = calculate(startIndex, endIndex); calculatedValue = value; System.out.println("CalculatedValue=" + value); // Reset arrayList if (startIndex &gt;= 0 || endIndex &lt;= length) { // Resize the list ArrayList&lt;String&gt; tempList = new ArrayList&lt;&gt;(); int j = 0; for (int i = 0; i &lt; startIndex - 1; i++) { tempList.add(data.get(i)); } tempList.add(value + ""); for (int i = endIndex; i &lt; length; i++) { tempList.add(data.get(i)); } data = tempList; process(); } } return calculatedValue; } private void getCalIndex() { endIndex = 0; startIndex = 0; for (String element : data) { endIndex++; startIndex++; if (element.equals(")")) { for (int i = endIndex - 1; i &gt;= 0; i--) { if (data.get(i).equals("(")) { return; } startIndex--; } } } } public double calculate(int startIndex, int endIndex) { int j = 0; element = new Element(); for (int i = startIndex; i &lt; endIndex; i++) { switch (data.get(i)) { case "*" : addOrManipulateEntitySecond('*', i, j); break; case "/" : addOrManipulateEntitySecond('/', i, j); break; case "-" : addOrManipulateEntityFirst('-', i, j); break; case "+" : addOrManipulateEntityFirst('+', i, j); break; default : break; } } /** Printing the Elements **/ double operateCalculate = operate(element.getFirst(), element.getOperator(), element.getSecond()); System.out.println("OperateCacluate=" + startIndex + "=" + endIndex + "=" + operateCalculate); return operateCalculate; } private static void addOrManipulateEntityFirst(char o, int i, int j) { if (element.getOperator() == '\u0000') { element = new Element(Double.valueOf(data.get(i - 1)), Double.valueOf(data.get(i + 1)), o); } else { element.setFirst(element.operate()); element.setSecond(Double.valueOf(data.get(i + 1))); element.setOperator(o); } } private void addOrManipulateEntitySecond(char o, int i, int j) { if (element.getOperator() == '\u0000') { element = new Element(Double.valueOf(data.get(i - 1)), Double.valueOf(data.get(i + 1)), o); } else { element.setSecond(operate(element.getSecond(), o, Double.valueOf(data.get(i + 1)))); // elements[j].setFirst(Double.valueOf(data.get(i+1))); // elements[j].setOperator(o); } } private double operate(double first, char o, double second) { double result = 0; switch (o) { case '*' : result = first * second; break; case '/' : result = first / second; break; case '+' : result = first + second; break; case '-' : result = first - second; break; default : break; } if (result == 0) { result = calculatedValue; } return result; } } public class Element { private double first; private double second; private char operator; private double result; public Element() { } public Element(double first, double second, char operator) { this.first = first; this.second = second; this.operator = operator; System.out.println(this); } public double operate() { switch (operator) { case '*' : result = first * second; break; case '/' : result = first / second; break; case '+' : result = first + second; break; default : break; } return result; } @Override public String toString() { // TODO Auto-generated method stub return "[ " + first + " " + operator + " " + second + " ]"; } public double getFirst() { return first; } public void setFirst(double first) { System.out.println("First : " + first); this.first = first; } public double getSecond() { return second; } public void setSecond(double second) { this.second = second; } public char getOperator() { return operator; } public void setOperator(char operator) { this.operator = operator; } public double getResult() { return result; } public void setResult(double result) { this.result = result; } } import java.util.ArrayList; import java.util.regex.Matcher; import java.util.regex.Pattern; public class CalculatorUtil { public static final String INTEGER_FROM_STRING = "\\d+"; public static final String FLOAT_FROM_STRING = "(\\d+[.]\\d+)"; public static final String OPERATORS_FROM_STRING = "(\\/)|(\\-)|(\\+)|(\\*)|(\\%)|(\\()|(\\))|(\\^)"; public static final String NUMBERS_FROM_STRING = FLOAT_FROM_STRING+"|"+INTEGER_FROM_STRING; public static final String NUMBERS_AND_OPERATORS_FROM_STRING = NUMBERS_FROM_STRING+"|"+OPERATORS_FROM_STRING; public static final String MULTIPLICATION_COMMON = "\\)\\("; public static final String MULTIPLICATION_VALID = ")*("; private static Pattern pattern; private static Matcher matcher; public CalculatorUtil() { // TODO Auto-generated constructor stub } /** * * @param input * @return The data as ArrayList&lt;String&gt; */ public static ArrayList&lt;String&gt; parseExpression(String input) { pattern = Pattern.compile(NUMBERS_AND_OPERATORS_FROM_STRING); matcher = pattern.matcher(input); ArrayList&lt;String&gt; data = new ArrayList&lt;String&gt;(); while(matcher.find()) data.add(matcher.group()); return data; } } </code></pre>
[ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-01-23T09:14:50.890", "Id": "66885", "Score": "3", "body": "Do you have any experience with writing parsers? There are less convoluted ways to do what you're doing, such as writing a bog-standard recursive descent parser." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-01-23T09:36:00.883", "Id": "66888", "Score": "2", "body": "Have you considered converting the input to Reverse Polish Notation? Not having the user do it, just taking the input, convert it to RPN, and then evaluate the RPN. This would allow the user to skip unneeded parentheses." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-01-24T08:36:15.547", "Id": "67054", "Score": "1", "body": "do google search for \"recursive descent parser for arithmetic expressions\"." } ]
[ { "body": "<p>I agree with the point in the comments. The approach you can implement that would simplify your code heavily is a recursion. The structure would be following the idea that you have interface/class Element, lets say, as you have it here but that would be just an interface. This interface would have implementord for binary and unary and 0-nary operation. Binary op would have childs plus,minus and so on, unary would have childs parentheses and unary minus and 0-nary's child is a number. Number has zero arguments so hence it can be considered 0-nary operation. The childs of those classes would be of type Element.</p>\n\n<p>The interface would implement the method calculate and if you want to print it out also a method print(outputstream).</p>\n\n<p>That is regarding how to parse. You would definitely like to use recursion because it is easier and shorter to write and also the case you are solving is of a recursive character.</p>\n\n<p>I liked how you used matching for checking if it a valid input. That is always good to validate your inputs. With the recursive approach you may validate it on the go, not all at the beginning.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-02-09T08:44:30.747", "Id": "41278", "ParentId": "39863", "Score": "3" } } ]
{ "AcceptedAnswerId": "41278", "CommentCount": "3", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-01-23T08:02:06.833", "Id": "39863", "Score": "3", "Tags": [ "java", "math-expression-eval" ], "Title": "Refactoring calculator expression" }
39863
<p>As suggested <a href="https://stackoverflow.com/questions/21278204/stdunordered-map-how-to-track-max-min-key-at-any-time">here</a>, I'm using Boost multi-index to implement orderbook. So far my code looks like this:</p> <p><code>"CommonsNative.h"</code> contains <code>typedef int64_t myDecimal;</code> and <code>enum Side { Buy, Sell };</code></p> <pre><code>#pragma once #include "CommonsNative.h" #include &lt;boost/multi_index_container.hpp&gt; #include &lt;boost/multi_index/member.hpp&gt; #include &lt;boost/multi_index/ordered_index.hpp&gt; #include &lt;boost/multi_index/hashed_index.hpp&gt; using boost::multi_index_container; using namespace boost::multi_index; struct OrderBookItem { myDecimal price; int32_t lots; OrderBookItem(myDecimal price_) :price(price_), lots(0) { } }; typedef multi_index_container &lt;OrderBookItem, indexed_by&lt; hashed_unique&lt; BOOST_MULTI_INDEX_MEMBER(OrderBookItem,myDecimal,price) &gt;, ordered_unique&lt; BOOST_MULTI_INDEX_MEMBER(OrderBookItem,myDecimal,price), std::greater&lt;myDecimal&gt; /* sorted beginning with most frequent */ &gt; &gt;&gt; OrderBookContainer; class OrderBook { public: OrderBook(void); ~OrderBook(void); void Add(Side side_, myDecimal price_, int lots_) { if (side_ == Buy) { // inserts or returns existent OrderBookContainer::iterator it = buyContainer.insert(price_).first; // how to add lots i.e. OrderBookItem.lots += lots_? // auto curLevel = buyContainer.get&lt;name&gt;(price); // curLevel.lots += Lots; } else if (side_ == Sell) { // inserts or returns existent OrderBookContainer::iterator it = sellContainer.insert(price_).first; } } private: OrderBookContainer buyContainer; OrderBookContainer sellContainer; }; </code></pre> <p>I have the following questions:</p> <ol> <li><p>For here:</p> <blockquote> <pre><code>OrderBookContainer::iterator it = buyContainer.insert(price_).first; </code></pre> </blockquote> <p>If I already have an item with <code>price = price_</code> I receive it in \$O(1)\$ (from hashtable). If such a level doesn't exist, then is it added in \$O(log n)\$? If I'm wrong, then what should I write to get an item if it exists (in \$O(1)\$) otherwise add it (in \$O(log n)\$)?</p></li> <li><p>Once I have an item, how can I modify <code>lots</code> to something like this?</p> <pre><code>OrderBookItem.lots += lots_ </code></pre></li> </ol>
[ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-01-23T23:07:41.120", "Id": "67012", "Score": "0", "body": "javapowered ..... time to change your nick? ;-)" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-01-24T07:28:25.917", "Id": "67049", "Score": "0", "body": "not using java for 3+ years so probably can change to c#++powered :)" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-07-05T20:45:55.863", "Id": "98928", "Score": "0", "body": "The second question is off-topic, as well as the second sub-question of the first question. We cannot assist with adding new implementation, but we can review everything else. I've already given some advice of my own below." } ]
[ { "body": "<ul>\n<li><p><code>myDecimal</code> is an absolutely unhelpful name overall. I don't see any need to give <code>int64_t</code> a <code>typedef</code> here, but even if there is one, then it should still use a better name.</p></li>\n<li><p>Empty <code>void</code> parameters are not needed in C++:</p>\n\n<blockquote>\n<pre><code>OrderBook(void);\n~OrderBook(void);\n</code></pre>\n</blockquote>\n\n<p>You also don't need these defaults as the compiler will provide them for you. They would only be necessary if you need to overload them <em>and</em> will still need default versions.</p></li>\n<li><p>It's a little less-readable not having whitespace after commas:</p>\n\n<blockquote>\n<pre><code>BOOST_MULTI_INDEX_MEMBER(OrderBookItem,myDecimal,price)\n</code></pre>\n</blockquote>\n\n<p>Not only that, but you already add this whitespace in other places. Keep it consistent.</p>\n\n<pre><code>BOOST_MULTI_INDEX_MEMBER(OrderBookItem, myDecimal, price)\n</code></pre></li>\n<li><p>You use different styles of curly braces. C++ doesn't restrict you to a particular one, so choose one you prefer and stick with it.</p></li>\n<li><p>Although this line has been commented out, are you still using C++11?</p>\n\n<blockquote>\n<pre><code>// auto curLevel = buyContainer.get&lt;name&gt;(price);\n</code></pre>\n</blockquote>\n\n<p>If so, then you can replace <code>OrderBookContainer::iterator</code> with <code>auto</code>:</p>\n\n<pre><code>auto it = buyContainer.insert(price_).first;\n</code></pre>\n\n<p></p>\n\n<pre><code>auto it = sellContainer.insert(price_).first;\n</code></pre></li>\n</ul>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-07-05T19:33:57.430", "Id": "56224", "ParentId": "39870", "Score": "3" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "3", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-01-23T12:04:44.480", "Id": "39870", "Score": "7", "Tags": [ "c++", "boost", "container" ], "Title": "Boost multi-index based orderbook" }
39870
<p>I have a little js I call a "jqGrid Factory" to encapsulate common settings and functionality across my web app.</p> <p>I just want to see what improvements I can make.</p> <pre><code> var jqGridReportFactory = (function () { var config = { datatype: 'json', mtype: 'GET', height: 'auto', autowidth: true, shrinkToFit: true, gridview: true, sortable: true, rowNum: 50, rowList: [50, 100, 200], viewrecords: true, loadonce: false, sortorder: 'asc', sortname: 'Affiliate', subGridSortname: 'SubAffiliate' }, subGridOptions = { plusicon: "ui-icon-plus", minusicon: "ui-icon-minus", openicon: "ui-icon-carat-1-sw" }; function createReport(gridOptions, optionalConfig) { $.extend(config, optionalConfig); //$.extend(gridOptions, gridOptions); var jqGridObj = { url: gridOptions.url, datatype: config.datatype, mtype: config.mtype, postData: gridOptions.postData, colNames: gridOptions.colNames, colModel: gridOptions.colModel, height: config.height, autowidth: config.autowidth, shrinkToFit: config.shrinkToFit, gridview: config.gridview, sortable: config.sortable, rowNum: config.rownum, rowList: config.computeHighlightColorsrowList, viewrecords: config.viewrecords, loadonce: config.loadonce, sortorder: config.sortorder, sortname: gridOptions.sortname, pager: gridOptions.pager, loadError: function (xhr, st, err) { reportLoadError('onLoadConversionHistory', xhr, st, err); unblockUI(); }, gridComplete: function () { unblockUI(); goToScrollPosition($('#reportPlaceHolder')); }, subGrid: gridOptions.subGrid, onSelectRow: function (rowid) { $(this).jqGrid("toggleSubGridRow", rowid); } }; if (gridOptions.subGrid) { jqGridObj = addSubGrid(jqGridObj, gridOptions); } //jqGrid factory go!! $("#" + gridOptions.id).jqGrid(jqGridObj); } function addSubGrid(jqGridObj, gridOptions) { var subGridObj = { subGridOptions: subGridOptions, subGridRowExpanded: function (subgridId, rowId) { var affiliate = $("#" + id).jqGrid("getCell", rowId, 'Affiliate'); var subgridTableId = subgridId + "_t"; var $subGrid; $("#" + subgridId).html("&lt;table id='" + subgridTableId + "' class='scroll'&gt;&lt;/table&gt;"); $subGrid = $('#' + subgridTableId); //cache subgrid, more performant var subGridColNames = jQuery.extend({}, gridOptions.colNames); var subGridColModel = jQuery.extend({}, gridOptions.colModel); //change parent names from Affiliate to Subaffiliate //other than that subGrid model is exactly the same as parent Affiliate model for all reports so far subGridColNames[0] = 'SubAffiliate'; subGridColModel[0].name = 'SubAffiliate'; subGridColModel[0].index = 'SubAffiliate'; //add affiliate to subGridPostData var a = { Affiliate: affiliate }; $.extend(gridOptions.subGridPostdata, a); $subGrid.jqGrid({ url: gridOptions.url, datatype: gridOptions.datatype, mtype: gridOptions.mtype, postData: gridOptions.subGridPostdata, colNames: subGridColNames, colModel: subGridColModel, height: config.height, sortname: config.subGridSortname, sortorder: config.sortorder, loadonce: config.loadonce, //these subgrid setting should not be overridden in my opinion - Brian Ogden autowidth: true, shrinkToFit: true, gridview: false, sortable: false, viewrecords: true /////////////////////// }); if (gridOptions.subGridHeadersHidden) { //hide subgrid column headers $subGrid.closest("div.ui-jqgrid-view") .children("div.ui-jqgrid-hdiv") .hide(); } }, subGridRowColapsed: function (subgridId, rowId) { // this function is called before removing the data var subgridTableId; subgridTableId = subgridId + "_t"; // $("#" + subgridTableId).remove(); } }; $.extend(true,jqGridObj, subGridObj); return jqGridObj; } return { createReport: createReport }; })(); </code></pre> <p><strong>UPDATE</strong></p> <p>Just wanted to show the latest of my refactoring of my jqgrid factory, I didn't renamed some of the options object members to camel case because I thought it was better for the users of this factory to match the option value that jqGrid uses:</p> <pre><code>var jqGridReportFactory = (function () { var constAffiliateStr = "Affiliate"; var constSubAffiliateStr = "SubAffiliate"; //default icons should be used for all reports so they not currently an option that can changed when using this jqgrid factory - Brian Ogden 1-24-2014 var subo = { plusicon: "ui-icon-plus", minusicon: "ui-icon-minus", openicon: "ui-icon-carat-1-sw" }; function createReport(o) { o = $.extend({ //apply default properties datatype: 'json', mtype: 'GET', height: 'auto', autowidth: true, shrinkToFit: true, gridview: true, sortable: true, rowNum: -1, rowList: [50, 100, 200, -1], viewrecords: true, loadonce: true, footerrow: false, sortorder: 'asc', sortname: constAffiliateStr, subGridSortname: constSubAffiliateStr, subgrid: false, subGridHeadersHidden: true }, o); var jqGridObj = { url: o.url, datatype: o.datatype, mtype: o.mtype, postData: o.postData, colNames: o.colNames, colModel: o.colModel, height: o.height, autowidth: o.autowidth, shrinkToFit: o.shrinkToFit, gridview: o.gridview, sortable: o.sortable, rowNum: o.rowNum, rowList: o.rowList, viewrecords: o.viewrecords, loadonce: o.loadonce, sortorder: o.sortorder, sortname: o.sortname, pager: o.pager, footerrow: true, loadError: function (xhr, st, err) { reportLoadError('onLoad' + o.id, xhr, st, err); unblockUI(); }, loadComplete: function () { if (o.rowNum == -1) { $(o.pager + ' option[value=-1]').text('All'); //if loadOnce is true displays -1 if (o.loadonce) $(o.pager + ' input.ui-pg-input').next().text('1'); } if (o.loadComplete) o.loadComplete(); }, gridComplete: function () { unblockUI(); goToScrollPosition($('#reportPlaceHolder')); if (o.gridComplete) o.gridComplete(); }, subGrid: o.subGrid, onSelectRow: function (rowid) { $(this).jqGrid("toggleSubGridRow", rowid); }, onSortCol: function (index, idxcol, sortorder) { var $icons = $(this.grid.headers[idxcol].el).find("&gt;div.ui-jqgrid-sortable&gt;span.s-ico"); if (this.p.sortorder === 'asc') { //$icons.find('&gt;span.ui-icon-asc').show(); $icons.find('&gt;span.ui-icon-asc')[0].style.display = ""; $icons.find('&gt;span.ui-icon-asc')[0].style.marginTop = "0px"; $icons.find('&gt;span.ui-icon-desc').hide(); } else { //$icons.find('&gt;span.ui-icon-desc').show(); $icons.find('&gt;span.ui-icon-desc')[0].style.display = ""; $icons.find('&gt;span.ui-icon-desc')[0].style.marginTop = "0px"; $icons.find('&gt;span.ui-icon-asc').hide(); } } }; /*=================================================*/ //Build subGrid /*=================================================*/ if (o.subGrid) { /*=================================================*/ //Check to see if subGrid colModel and colNames passed in, if not use Affiliate colModel and colNames /*=================================================*/ var temp; if (!o.subGridColModel) { temp = $.extend(true, [], o.colModel); //deep copy array of objects temp[0].name = constSubAffiliateStr; temp[0].index = constSubAffiliateStr; o.subGridColModel = temp; } if (!o.subGridColNames) { //temp = o.colNames.slice(0); temp = $.extend(true, [], o.colNames); //deep copy not needed but better safe then sorry temp[0] = constSubAffiliateStr; o.subGridColNames = temp; } /*=================================================*/ var subGridObj = { subo: subo, subGridRowExpanded: function (subgridId, rowId) { var affiliate = $("#" + o.id).jqGrid("getCell", rowId, 'Affiliate'); var subgridTableId = subgridId + "_t"; var $subGrid; $("#" + subgridId).html("&lt;table id='" + subgridTableId + "' class='scroll'&gt;&lt;/table&gt;"); $subGrid = $('#' + subgridTableId); //cache subgrid, more performant //add affiliate to subGridPostData var a = { Affiliate: affiliate }; $.extend(o.subGridPostData, a); $subGrid.jqGrid({ url: o.url, datatype: o.datatype, mtype: o.mtype, postData: o.subGridPostData, colNames: o.subGridColNames, colModel: o.subGridColModel, height: o.height, sortname: o.subGridSortname, sortorder: o.sortorder, loadonce: o.loadonce, sortable: o.sortable, //these subgrid setting should not be overridden in my opinion - Brian Ogden autowidth: true, shrinkToFit: true, gridview: false, viewrecords: true /////////////////////// }); if (o.subGridGroupHeaders) { $subGrid.jqGrid('setGroupHeaders', { useColSpanStyle: true, groupHeaders: o.subGridGroupHeaders }); } if (o.subGridHeadersHidden) { //hide subgrid column headers $subGrid.closest("div.ui-jqgrid-view") .children("div.ui-jqgrid-hdiv") .hide(); } }, subGridRowColapsed: function (subgridId, rowId) { // this function is called before removing the data var subgridTableId; subgridTableId = subgridId + "_t"; // $("#" + subgridTableId).remove(); } }; $.extend(jqGridObj, subGridObj); } /*=================================================*/ //jqGrid factory go!! return $("#" + o.id).jqGrid(jqGridObj); } return { createReport: createReport }; })(); </code></pre>
[]
[ { "body": "<p>I like your code, good use of the Revealing Module pattern.</p>\n\n<p>I only have the following minor observations:</p>\n\n<ul>\n<li><code>mtype</code> could use a better name ( I know, jqGrid uses it )</li>\n<li><code>autowidth</code> -> <code>autoWidth</code> ( lowerCamelCasing )</li>\n<li><code>gridview</code> -> <code>gridView</code></li>\n<li><code>rowList: [50, 100, 200]</code> could use a comment as to what it does</li>\n<li><code>viewrecords</code> -> <code>viewRecords</code>( lowerCamelCasing ) etc. etc.</li>\n<li><code>sortorder</code> -> Could use a comment with the possible values</li>\n<li><code>subGridOptions</code> -> could use a comment with this URL : <a href=\"http://api.jqueryui.com/theming/icons/\" rel=\"nofollow\">http://api.jqueryui.com/theming/icons/</a></li>\n<li>delete uncommented code : <code>//$.extend(gridOptions, gridOptions);</code></li>\n<li>You should seriously consider building <code>jqGridObj</code> with <code>$.extend</code> out of <code>gridOptions</code> and <code>config</code>, cutting almost 20 lines.</li>\n<li>It is considered better to have 1 <code>var</code> statement with comma-separated variables instead of multiple <code>var</code> statements. ( in <code>subGridObj</code> )</li>\n<li><code>$subGrid.jqGrid</code> could also probably be built with <code>$.extend</code></li>\n</ul>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-01-23T23:40:09.220", "Id": "67015", "Score": "0", "body": "Hi @konijn,thanks for your review,I was wondering,could you elaborate with a snippet of how I might build $subGrid.jqGrid with $.extend?" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-01-23T23:48:56.883", "Id": "67016", "Score": "0", "body": "Oh nevermind! I understand what you mean by building $subgrid.jqGrid with $.extend now, instead of calling the function addSubGrid to build it I believe is what you mean" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-01-23T23:49:41.503", "Id": "67017", "Score": "1", "body": "That's indeed what I meant, I guess you would extract your subgrid defaults into a properly named variable first." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-01-25T01:17:07.717", "Id": "67209", "Score": "0", "body": "I have made some improvements if you want to check them out." } ], "meta_data": { "CommentCount": "4", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-01-23T15:53:24.867", "Id": "39880", "ParentId": "39871", "Score": "4" } } ]
{ "AcceptedAnswerId": "39880", "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-01-23T12:27:57.950", "Id": "39871", "Score": "7", "Tags": [ "javascript", "jquery", "revealing-module-pattern" ], "Title": "First \"Revealing Module\" implementation" }
39871
<p>I'm using these 2 functions to handle file input/output and would like to know if there's anything that should be changed.</p> <p>For content retrieval, enough space is allocated and the file content is copied. To make sure saving a file either saves all or nothing, I'm writing to a buffer then renaming it after all content is successfully written.</p> <p>I'm particularly interested in knowing whether these functions are safe or not since <code>tmpnam</code> is considered dangerous. I read the main risk is a file with the name returned by <code>tmpnam</code> being created before we are able to do it, so I'm using <code>wbx</code>to make sure it doesn't happen. Is this enough or there are other security concerns that I'm not aware of? </p> <p><strong>files.h</strong></p> <pre><code>#ifndef FILES_H #define FILES_H #include &lt;stdlib.h&gt; #define FILE_SUCCESS 0 #define FILE_ERROR 1 void *file_get_content(const char *file_name, size_t *file_size_fill); //Save all or nothing int file_save_content( const char *file_name, const void *content, size_t size ); #endif </code></pre> <p><strong>files.c</strong></p> <pre><code>#include &lt;stdio.h&gt; #include &lt;sys/stat.h&gt; #include "files.h" #define BYTE 1 #define READ_MODE "rb" //Use the new "x" subspecifier so fopen will fail if a file with the name //returned by tmpnam exists #define SAFE_WRITE "wbx" void *file_get_content(const char *file_name, size_t *file_size_fill) { //Get file size, SEEK_END is not portable struct stat file_stat; if(stat(file_name, &amp;file_stat) != 0) return NULL; //Check if the file actually contains anything, since malloc can return //values other than NULL for malloc(0) if(file_stat.st_size == 0) return NULL; //Space to save the contents void *content = malloc(file_stat.st_size); if(content == NULL) return NULL; //Open file FILE *file = fopen(file_name, READ_MODE); if(file == NULL){ free(content); return NULL; } //Read it all if(fread(content, BYTE, file_stat.st_size, file) != file_stat.st_size){ free(content); fclose(file); return NULL; } fclose(file); *file_size_fill = file_stat.st_size; return content; } //Save the file content safely, it either saves all or nothing int file_save_content( const char *file_name, const void *content, size_t size ) { //Get a name for the temp file char temp_file_name[L_tmpnam]; if(tmpnam(temp_file_name) == NULL) return FILE_ERROR; //Create it FILE *temp_file = fopen(temp_file_name, SAFE_WRITE); if(temp_file == NULL) return FILE_ERROR; //Write if(fwrite(content, BYTE, size, temp_file) != size){ fclose(temp_file); remove(temp_file_name); return FILE_ERROR; } //Replace old file fclose(temp_file); if(rename(temp_file_name, file_name) != 0){ remove(temp_file_name); return FILE_ERROR; } return FILE_SUCCESS; } </code></pre> <p><strong><code>file_save_content()</code> after following the suggestions given by 200_success</strong></p> <pre><code>int file_save_content(const char *file_name, const void *content, size_t size) { /* Create temp file */ char tmp[] = {'t','m','p','X','X','X','X','X','X', '\0'}; int error; int fd = mkstemp(tmp); if(fd == -1) return FILE_ERROR; if(write(fd, content, size) != (ssize_t)size){ error = errno; close(fd); errno = error; return FILE_ERROR; } /* Replace old file */ if(rename(tmp, file_name) != 0){ error = errno; unlink(tmp); close(fd); errno = error; return FILE_ERROR; } close(fd); return FILE_SUCCESS; } </code></pre>
[]
[ { "body": "<p>I think that a more idiomatic C interface would be</p>\n\n<pre><code>ssize_t file_get_content(const char *file_name, char *content[]);\n</code></pre>\n\n<p>Returning the number of bytes actually read would be analogous to <code>read(2)</code> and <code>printf(3)</code>. On error, the return value could be <code>-1</code>, and the reason would be in <code>errno</code>. For consistency, I would have <code>file_save_content()</code> return the number of bytes written, or <code>-1</code> on error.</p>\n\n<p>It would be convenient if you allocated an extra byte and appended a <code>\\0</code> terminator to the result. Then the caller has the option to treat the buffer as a null-terminated string, if it believes the file to contain text. It would still be able to treat it as binary data (possibly containing <code>NUL</code> bytes) based on the return value.</p>\n\n<p>When getting the contents of an empty file, I would expect it to produce an \"empty\" buffer, not a <code>NULL</code> pointer.</p>\n\n<p>There is a possibility of a race condition: the file could be truncated between the <code>stat()</code> and the <code>fread()</code>. You could actually handle that case a bit more gracefully.</p>\n\n<pre><code>int file_get_content(const char *file_name, char *buf[]) {\n struct stat file_stat;\n if (0 != stat(file_name, &amp;file_stat)) {\n return -1;\n }\n\n if (NULL == (*buf = 1 + malloc(file_stat.st_size))) {\n return -1;\n }\n\n FILE *file;\n if (NULL == (file = fopen(file_name, \"rb\"))) {\n free(*buf);\n return -1;\n }\n\n ssize_t bytes_read = fread(*buf, 1, file_stat.st_size, file);\n (*buf)[bytes_read] = '\\0';\n fclose(file);\n return bytes_read;\n}\n</code></pre>\n\n<hr>\n\n<p>In <code>file_save_content()</code>, avoid <code>tmpnam()</code>, which allows a race condition between the time you call <code>tmpnam()</code> and <code>fopen()</code>. Also, <code>rename()</code> would fail unless the temporary file and the destination are on the same filesystem. As an alternative, I would recommend <code>mkstemp()</code> with the destination filename plus a <code>\".XXXXXX\"</code> suffix, followed by <code>fdopen()</code>.</p>\n\n<p>As a nitpick, I'd prefer <code>unlink()</code> over <code>remove()</code>, since the former refuses to remove directories.</p>\n\n<p>In the error handlers of <code>file_save_content()</code>, save and restore <code>errno</code>, because it would be more useful for the caller to see the original reason for the failure rather than a problem with the subsequent cleanup.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-01-24T02:04:51.380", "Id": "67026", "Score": "1", "body": "+1, nice answer. Note that `(*buf)[1 + bytes_read] = '\\0';` should drop the 1" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-01-24T02:21:51.110", "Id": "67029", "Score": "0", "body": "@WilliamMorris Thanks! Fixed in [Rev 2](http://codereview.stackexchange.com/revisions/39926/2)." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-01-24T16:17:09.790", "Id": "67103", "Score": "0", "body": "Thank you for reviewing the code. Do you mind explaining how could a race condition happen when calling `fopen` with the x subspecifier since it will only be opened if the file doesn't exist?" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-01-24T22:40:17.687", "Id": "67186", "Score": "0", "body": "There is a slim chance that a colliding file could be created between [`tmpnam()` and `fopen()`](http://en.wikipedia.org/wiki/Time-of-check-to-time-of-use). Fortunately, there is no security hole, since you call `fopen()` with the `\"x\"` flag, but an attacker _might_ be able to cause grief by triggering failures. It's a farfetched scenario, but an avoidable one." } ], "meta_data": { "CommentCount": "4", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-01-24T00:14:20.883", "Id": "39926", "ParentId": "39876", "Score": "5" } } ]
{ "AcceptedAnswerId": "39926", "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-01-23T15:23:45.660", "Id": "39876", "Score": "7", "Tags": [ "c", "security", "file" ], "Title": "Are these file handling functions safe?" }
39876
<p>I needed to build a one-way web service for a mobile app I developed. Its only goal is to receive incoming JSON data and insert it into the correct tables. It works, but it looks very "kludgy" and cobbled together (happens a lot with solo development). </p> <p>I'd like another pair of eyes to see where it could be improved as far as design, robustness, readability, etc. This code is not yet in production, so I can implement suggested changes as needed.</p> <pre><code>&lt;?php $body = file_get_contents("php://input"); $json = json_decode($body, true); //print_r($json); function extractArray($arr) { foreach ($arr as $k =&gt; $v) { if (is_array($v)) { extractArray($arr[$k]); foreach ($v as $kk =&gt; $vv) { if (is_array($vv)) { unset($arr[$k][$kk]); $arr[$kk] = $vv; // if you want the key to the array to be preserved. // $arr[] = $vv; // would be safer, or check isset($arr[$kk]) first. } } } } return $arr; } function dbInsert(&amp;$data) { $tracks = array_shift($data); // //remove unneeded parent array $tracks = extractArray($tracks); /* * Note: user_id/page_id purposely unset. Why? On the client side, Backbone.js * creates a model ID if one is not created manually. So, we create one on * the client side, but then remove it on the server side. Saves a lot of hassle otherwise. * db creates autoincrement id. * */ unset($tracks['user_id']); $trackCols = array_keys($tracks); $trackVals = array_values($tracks); //connect to db $dbh = new PDO('mysql:host=localhost;dbname=kpl', 'root', 'root'); $dbh-&gt;setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION); //insert tracker data try { $sth = $dbh-&gt;prepare("INSERT INTO tracker (" . implode(", ", $trackCols) . ") VALUES ('" . implode("', '", $trackVals) . "')"); $sth-&gt;execute(); $tracksPK = $dbh-&gt;lastInsertId(); } catch (PDOException $e) { return print_r('Tracker insert failed: ' . $e-&gt;getMessage()); } $pages = array_pop($data); foreach ($pages as &amp;$page) { unset($page['page_id']); $pageCols = array_keys($page); /* * Note: Could not use same query structure as trackers because the foreign key user_id * is set dynamically. * */ try { $sth = $dbh-&gt;prepare("INSERT INTO page (" . implode(", ", $pageCols) . ") VALUES (" . $page['view_count'] . "," . $page['visit_timestamp'] . ",'" . $page['page_viewed'] . "'," . $tracksPK . ",'" . $page['model_type'] . "')"); $sth-&gt;execute(); } catch (PDOException $e) { return print_r('Page insert failed: ' . $e-&gt;getMessage()); } } return true; } if (isset($json)) { $info = dbInsert($json); print_r($info); } else { die('JSON data fail'); } </code></pre>
[ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-01-23T16:48:54.730", "Id": "66930", "Score": "0", "body": "As an addendum, I found a decent example of how to encapsulate my db class [Database class](http://pastie.org/8660848). Trying to incorporate this now like this `try {\n $database->query(\"INSERT INTO tracker (\" . implode(\", \", $trackCols) . \") VALUES ('\" . implode(\"', '\", $trackVals) . \"')\");\n $database->execute();\n } catch (PDOException $e) {\n return print_r('Tracker insert failed: ' . $e->getMessage());\n }`. Getting xhr error returned `[INFO] xhr error: status - 500, responseText - null`" } ]
[ { "body": "<p>There are some big holes in your security </p>\n\n<ol>\n<li>Authenticate the data source. (Is it a legitimate source, username/password/etc)</li>\n<li>Sanitize the user data.</li>\n</ol>\n\n<p>Check $trackCols against a list of valid column names you are expecting, to stop me doing things like I have below.</p>\n\n<pre><code>$valid_cols = array('id', 'user', 'name');\nforeach ($trackCols as $col) {\n if (!in_array($col, $valid_cols)) {\n die(\"Alert! Unexpected Column $col\");\n }\n}\n</code></pre>\n\n<p>PDO allows you to bind variables to the statement, and it will escape any dangerous data.\nThis will help stop people from creating attacks as I have below.</p>\n\n<pre><code>$sth = $dbh-&gt;prepare('SELECT name, colour, calories\n FROM fruit\n WHERE calories &lt; :calories AND colour = :colour');\n$sth-&gt;bindParam(':calories', $calories, PDO::PARAM_INT);\n$sth-&gt;bindParam(':colour', $colour, PDO::PARAM_STR, 12);\n$sth-&gt;execute();\n</code></pre>\n\n<p>I have included a test script below (DO NOT RUN AGAINST YOUR LIVE DATABASE)</p>\n\n<p>I have manufactured some bad json data so that it will execute a delete statement on the tracker table in your database. </p>\n\n<p>Obviously it won't work unless I get the table and column names correct, but as your code is now, if I try a dummy column name it will give me back an sql error message, which can help me to narrow it down.</p>\n\n<p>Log the error message instead of returning them. This is an API, all the client end needs to know is that it failed. Don't give the attacker any more information then necessary.</p>\n\n<pre><code>&lt;?php\n\n// WARNING MAKE SURE YOU ONLY RUN THIS AGAINST A TEST DATABASE\n\n$bad_sql = 'id) VALUES (1); DELETE FROM tracker; INSERT INTO tracker(id';\n$json = json_encode(array(array($bad_sql =&gt; '99999')));\n\n$ch = curl_init();\n\ncurl_setopt($ch, CURLOPT_URL, \"http://yourdomain/api.php\" );\ncurl_setopt($ch, CURLOPT_RETURNTRANSFER, 1 );\ncurl_setopt($ch, CURLOPT_POST, 1 );\ncurl_setopt($ch, CURLOPT_POSTFIELDS, $json);\ncurl_setopt($ch, CURLOPT_HTTPHEADER, array('Content-Type: application/json'));\n\n$result=curl_exec ($ch);\n\nvar_dump($result);\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-01-26T15:21:20.150", "Id": "67369", "Score": "0", "body": "I forgot to mention that this isn't a public interface. The url is encoded and static in the app. Unless the user hacks the app itself, sql injection is unlikely. Probably would have saved you the effort of writing this. I do appreciate your reply." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-01-26T20:17:55.477", "Id": "67417", "Score": "3", "body": "Yes, details like that would have been helpful if disclosed upfront, hHowever it is still a good idea to santitize user data and use bind params regardless, even if it just to get into the habit. I can't imagine why someone would want to hack your app, but if they did it would be simple enough to run it through a proxy and monitor the traffic. Also logging in an api is essential otherwise if an error occurs you will have no way of analyzing what went wrong." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-01-27T14:43:22.230", "Id": "67498", "Score": "3", "body": "All valid points. Sometimes, we are so close to the code that we forget that others don't have the same perspective. That's why I'm glad there's a site like this. It helps mitigate some of the negative aspects of solo freelance consulting." } ], "meta_data": { "CommentCount": "3", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-01-26T09:10:48.177", "Id": "40082", "ParentId": "39877", "Score": "7" } } ]
{ "AcceptedAnswerId": "40082", "CommentCount": "1", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-01-23T15:27:49.487", "Id": "39877", "Score": "7", "Tags": [ "php" ], "Title": "Home-grown web service" }
39877
<p>I have a <a href="http://en.wikipedia.org/wiki/BLAST" rel="nofollow">BLAST</a> output file and want to calculate query coverage, appending the query lengths as an additional column to the output. Let's say I have</p> <pre><code>2 7 15 </code></pre> <pre><code>f=open('file.txt', 'r') lines=f.readlines() import re for line in lines: new_list=re.split(r'\t+',line.strip()) q_start=new_list[0] q_end=new_list[1] q_len=new_list[3] q_cov=((float(q_end)-float(q_start))/float(q_len))*100 q_cov=round(q_cov,1) q_cov=str(q_cov) new_list.append(q_cov) r=open('results.txt', 'a') x='\t'.join(new_list) x=x+'\n' r.writelines(x) f.close() r.close() </code></pre>
[]
[ { "body": "<p>One serious bug is that you open <code>results.txt</code> for each line of input. It's almost always better to <a href=\"https://stackoverflow.com/a/9283052/1157100\">open files in a <code>with</code> block</a>. Then, you won't have to worry about closing your filehandles, even if the code exits abnormally. The <code>with</code> block would have made your <code>results.txt</code> mistake obvious as well.</p>\n\n<p>Since you want to treat your <code>q_start</code>, <code>q_end</code>, and <code>q_len</code> as numbers, I wouldn't even bother to assign their string representations to a variable. Just convert them to a <code>float</code> as soon as possible. Similarly, <code>q_cov</code> should be a <code>float</code>; I would just stringify it at the last moment. I would also postpone rounding just for the purposes of formatting the output, preferring to preserve precision in <code>q_cov</code> itself.</p>\n\n<p>Put your <code>import</code> statements at the beginning of the program.</p>\n\n<pre><code>import re\n\nwith open('file.txt') as input, open('results.txt', 'a') as output:\n for line in input.readlines():\n fields = re.split(r'\\t+', line.strip())\n q_start, q_end, q_len = map(float, (fields[0], fields[1], fields[3]))\n q_cov = 100 * (q_end - q_start) / q_len\n print &gt;&gt;output, '\\t'.join(fields + [str(round(q_cov, 1))])\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-01-23T19:42:32.223", "Id": "66960", "Score": "0", "body": "++ for with block" } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-01-23T18:21:17.647", "Id": "39897", "ParentId": "39879", "Score": "4" } } ]
{ "AcceptedAnswerId": "39897", "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-01-23T15:45:57.800", "Id": "39879", "Score": "6", "Tags": [ "python", "regex", "linux", "csv", "bioinformatics" ], "Title": "Calculate query coverage from BLAST output" }
39879
<p>The <a href="http://msdn.microsoft.com/en-us/library/dd460717.aspx" rel="nofollow">Task Parallel Library</a> (TPL) is a set of public types and APIs in the <a href="http://msdn.microsoft.com/en-us/library/system.threading.tasks.aspx" rel="nofollow">System.Threading.Tasks</a> namespace in the .NET Framework 4 and 4.5. The purpose of the TPL is to make developers more productive by simplifying the process of adding parallelism and concurrency to applications. The TPL scales the degree of concurrency dynamically to most efficiently use all the processors that are available. In addition, the TPL handles the partitioning of the work, the scheduling of threads on the <a href="http://msdn.microsoft.com/en-us/library/system.threading.threadpool.aspx" rel="nofollow">ThreadPool</a>, cancellation support, state management, and other low-level details. </p>
[]
[]
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-01-23T16:06:21.013", "Id": "39881", "Score": "0", "Tags": null, "Title": null }
39881
The Task Parallel Library is part of .NET 4 and .NET 4.5. It is a set of APIs to enable developers to program asynchronous applications.
[]
[]
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-01-23T16:06:21.013", "Id": "39882", "Score": "0", "Tags": null, "Title": null }
39882
<p>Several programming languages support an asynchronous programming model using co-routines, with the <code>async</code> and <code>await</code> keywords.</p> <p>Support for the model was added to C# and VB in VS2012, and Python in 3.5. A <a href="https://github.com/tc39/ecmascript-asyncawait" rel="nofollow noreferrer">proposal for the feature</a> in ECMAScript has been accepted into stage 1 for ECMAScript 7. Dart 1.9 also <a href="http://news.dartlang.org/2015/03/dart-19-release-youve-been-await-ing-for.html" rel="nofollow noreferrer">adds support for the model</a>.</p> <h2 id="c-and-visual-studio-s9d9">C# and Visual Studio</h2> <p>Asynchronous programming with <code>async</code> and <code>await</code> was introduced with C# 5.0 in Visual Studio 2012. The run-time support for this language concept is a part of .NET 4.5 / Windows Phone 8 / Windows 8.x Store Runtime.</p> <p>It's also possible to use <code>async/await</code> and target .NET 4.0 / Windows Phone 7.1 / Silverlight 4 / MonoTouch / MonoDroid / Portable Class Libraries, with Visual Studio 2012+ and <a href="http://www.nuget.org/packages/microsoft.bcl.async" rel="nofollow noreferrer"><code>Microsoft.Bcl.Async</code></a> NuGet package, which is licensed for production code.</p> <p>Async CTP add-on for VS2010 SP1 is also <a href="http://www.microsoft.com/en-us/download/details.aspx?id=9983" rel="nofollow noreferrer">available</a>, but it is not suitable for production development.</p> <h2 id="python-i3pb">Python</h2> <p>Similar syntax was introduced to Python 3.5 (see <a href="https://www.python.org/dev/peps/pep-0492/" rel="nofollow noreferrer">PEP 492 - <em>Coroutines with async and await syntax</em></a>.</p> <p>Previously, it was possible to write co-routines using generators; with the introduction of <code>await</code> and <code>async</code> co-routines were lifted to a native language feature.</p> <h2 id="ecmascript-8eum">Ecmascript</h2> <p>The introduction of Promises and Generators in ECMAScript presents an opportunity to dramatically improve the language-level model for writing asynchronous code in ECMAScript.</p> <p>A similar proposal was made with Deferred Functions during ES6 discussions. The proposal here supports the same use cases, using similar or the same syntax, but directly building upon generators and promises instead of defining custom mechanisms.</p> <p>Development of this proposal is happening at <a href="https://github.com/tc39/ecmascript-asyncawait" rel="nofollow noreferrer">https://github.com/tc39/ecmascript-asyncawait</a>. Please file issues there. Non-trivial contributions are limited to TC39 members but pull requests for minor issues are welcome and encouraged!</p> <h3 id="status-of-this-proposal-2ppn">Status of this proposal</h3> <p>This proposal was accepted into stage 1 (&quot;Proposal&quot;) of the ECMAScript 7 spec process in January 2014 (discussion).</p> <h3 id="examples-xhp4">Examples</h3> <p>Take the following example, first written using Promises. This code chains a set of animations on an element, stopping when there is an exception in an animation, and returning the value produced by the final successfully executed animation.</p> <pre><code>function chainAnimationsPromise(elem, animations) { var ret = null; var p = currentPromise; for(var anim in animations) { p = p.then(function(val) { ret = val; return anim(elem); }) } return p.catch(function(e) { /* ignore and keep going */ }).then(function() { return ret; }); } </code></pre> <p>Already with promises, the code is much improved from a straight callback style, where this sort of looping and exception handling is challenging.</p> <p>Task.js and similar libraries offer a way to use generators to further simplify the code maintaining the same meaning:</p> <pre><code>function chainAnimationsGenerator(elem, animations) { return spawn(function*() { var ret = null; try { for(var anim of animations) { ret = yield anim(elem); } } catch(e) { /* ignore and keep going */ } return ret; }); } </code></pre> <p>This is a marked improvement. All of the promise boilerplate above and beyond the semantic content of the code is removed, and the body of the inner function represents user intent. However, there is an outer layer of boilerplate to wrap the code in an additional generator function and pass it to a library to convert to a promise. This layer needs to be repeated in every function that uses this mechanism to produce a promise. This is so common in typical async JavaScript code, that there is value in removing the need for the remaining boilerplate.</p> <p>With async functions, all the remaining boiler plate is removed, leaving only the semantically meaningful code in the program text:</p> <pre><code>async function chainAnimationsAsync(elem, animations) { var ret = null; try { for(var anim of animations) { ret = await anim(elem); } } catch(e) { /* ignore and keep going */ } return ret; } </code></pre> <p>This is morally similar to generators, which are a function form that produces a Generator object. This new async function form produces a Promise object.</p> <h2 id="trivia-yz2x">Trivia</h2> <p>Asynchronicity doesn't assume multithreading, <code>async</code> or <code>await</code> keywords do not magically create any threads.</p> <h2 id="resources-atic">Resources:</h2> <h3 id="c-izud">C#</h3> <ul> <li><a href="http://channel9.msdn.com/Shows/Going+Deep/Stephen-Toub-Task-Based-Asynchrony-with-Async" rel="nofollow noreferrer">Stephen Toub, video: Task-Based Asynchrony with Async</a></li> <li><a href="http://channel9.msdn.com/Events/Build/BUILD2011/TOOL-829T" rel="nofollow noreferrer">Stephen Toub, video: The zen of async: Best practices for best performance</a></li> <li><a href="https://web.archive.org/web/20160716094921/http://blogs.msdn.com:80/b/pfxteam/archive/2012/04/12/async-await-faq.aspx" rel="nofollow noreferrer">Stephen Toub and Parallel Team's blog - Async/Await FAQ</a></li> <li><a href="http://blog.stephencleary.com/2012/02/async-and-await.html" rel="nofollow noreferrer">Stephen Cleary's blog - Async and Await</a></li> <li><a href="http://blog.stephencleary.com/2013/11/there-is-no-thread.html" rel="nofollow noreferrer">Stephan Cleary's post - There Is No Thread</a></li> <li><a href="https://web.archive.org/web/20151102210456/http://blogs.msdn.com/b/ericlippert/archive/tags/async/" rel="nofollow noreferrer">Eric Lippert's blog - <code>async</code>-tagged posts</a></li> <li><a href="http://msdn.microsoft.com/en-us/magazine/jj991977.aspx" rel="nofollow noreferrer">MSDN Magazine - Best Practices in Asynchronous Programming</a></li> <li><a href="http://msdn.microsoft.com/en-us/magazine/gg598924.aspx" rel="nofollow noreferrer">MSDN Magazine - It's All About the SynchronizationContext</a></li> <li><a href="http://msdn.microsoft.com/en-us/magazine/hh456402.aspx" rel="nofollow noreferrer">MSDN Magazine - Pause and Play with Await</a></li> <li><a href="http://msdn.microsoft.com/en-us/magazine/hh456402.aspx" rel="nofollow noreferrer">MSDN Magazine - Async Performance: Understanding the Costs of Async and Await</a></li> <li><a href="http://www.microsoft.com/en-us/download/details.aspx?id=23753" rel="nofollow noreferrer">MSDN - C# Language Specification for Asynchronous Functions</a></li> <li><a href="http://msdn.microsoft.com/en-us/library/hh873175.aspx" rel="nofollow noreferrer">MSDN - Task-based Asynchronous Pattern</a></li> <li><a href="http://www.microsoft.com/en-us/download/details.aspx?id=14058" rel="nofollow noreferrer">MSDN - Whitepaper: Asynchrony in .NET</a></li> <li><a href="http://msdn.microsoft.com/en-us/library/hh191443.aspx" rel="nofollow noreferrer">MSDN - Asynchronous Programming with Async and Await</a></li> </ul> <h3 id="ecmascript-1-ejw0">Ecmascript</h3> <ul> <li><a href="http://tc39.github.io/ecmascript-asyncawait/" rel="nofollow noreferrer">TC39 documentation and discussion for Async Functions in EcmaScript</a></li> </ul> <h2 id="related-8htg">Related:</h2> <p><a href="/questions/tagged/task-parallel-library" class="post-tag" title="show questions tagged &#39;task-parallel-library&#39;" rel="tag">task-parallel-library</a> - <a href="http://stackoverflow.com/tags/task-parallel-library/info">Task Parallel Library</a></p>
[]
[]
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2014-01-23T16:07:32.567", "Id": "39883", "Score": "0", "Tags": null, "Title": null }
39883
This covers the asynchronous programming model supported by various programming languages, using the async and await keywords.
[]
[]
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-01-23T16:07:32.567", "Id": "39884", "Score": "0", "Tags": null, "Title": null }
39884
<p>I've written a function that can be used at runtime to suggest how the provided incomplete Lua expression can be completed so that it would make sense (that is, it would evaluate to a non-nil value). For example, this can be used with an application console that can evaluate Lua expressions at runtime, so that it would allow you to autocomplete expressions such as "network.database[index].ro" with a Tab press to "network.database[index].rowCount" or "network.database[index].rows" (provided that <code>network.database[index]</code> is a table that contains values at the <code>rowCount</code> and <code>rows</code> indices).</p> <p>I am interested in all kinds of suggestions of how can this be improved. Did I handle all the special cases? Any C++ style suggestions?</p> <pre><code>extern "C" { #include "lua.h" #include "lualib.h" #include "lauxlib.h" } #include &lt;set&gt; #include &lt;string&gt; #include &lt;vector&gt; #include &lt;boost/algorithm/string/predicate.hpp&gt; // ================================================================================= // The 'buildAutoCompleteCandidates' returns a collection of options that suggest how // the provided string could be completed so that it would evaluate to a valid value. // // For example, when there's a console that can be used to evaluate Lua expressions // at the application's runtime, this can be used to provide the console with the autocomplete // feature, similar to a &lt;Tab&gt; press in bash etc. // // For instance, the expression 'world.entities[1].p' can perhaps be autocompleted // as 'world.entities[1].posX', 'world.entities[1].posY', or 'world.entities[1].pivot', // and so on. // // NOTES: // 1/ The expression to autocomplete is evaluated at runtime. // 2/ The autocomplete search traverses metatables' __index tables as needed. // 3/ The metatables' non-table __index values (such as __index functions) stop the search. // 4/ Endless metatable loops are detected and stop the search. // 5/ The Lua stack remains in its original state when the call is over. // 6/ Global variable names can be autocompleted as well. // ================================================================================= std::vector&lt;std::string&gt; buildAutoCompleteCandidates (lua_State* L, const std::string&amp; str) { std::string strBase; std::string strSep; std::string strKeyStart; // str: "world.entities[1].p" // --&gt; strBase: "world.entities[1]" // --&gt; strSep: "." // --&gt; strKeyStart: "p" auto lastSepPos = str.find_last_of(".:"); if (lastSepPos == std::string::npos) { strKeyStart = str; } else { strBase = str.substr(0, lastSepPos); strKeyStart = str.substr(lastSepPos+1); strSep = str[lastSepPos]; } std::vector&lt;std::string&gt; result; if (strBase.empty()) { // For Lua 5.1 replace the line with: // lua_pushvalue(L, LUA_GLOBALSINDEX) lua_pushglobaltable(L); } else { // Evaluate the expresssion contained in strBase // and leave the result at the topmost stack position. luaL_loadstring(L, ("return " + strBase).c_str()); lua_pcall(L, 0, 1, 0); if (!lua_istable(L, -1)) { lua_pop(L, 1); return result; } } // We now have the base table whose indices we need // to iterate over at the topmost (-1) stack position. std::set&lt;const void*&gt; visited; while (true) { // Iterate over the table: for (lua_pushnil(L); lua_next(L, -2); lua_pop(L, 1)) { // For the ':' separator, it only makes sense // to propose autocompletion with 'function' values: if (strSep == ":" &amp;&amp; !lua_isfunction(L, -1)) { continue; } // Consider only the string indices: if (lua_type(L, -2) == LUA_TSTRING) { std::string key = lua_tostring(L, -2); if (boost::starts_with(key, strKeyStart)) { result.push_back(strBase + strSep + key); } } } // Follow one step up in the metatable chain: visited.insert(lua_topointer(L, -1)); if (lua_getmetatable(L, -1) != 0) { lua_remove(L, -2); lua_getfield(L, -1, "__index"); lua_remove(L, -2); if (!lua_istable(L, -1)) { // Non-table '__index' values cannot // provide us with a list of all indices. lua_pop(L, 1); break; } // Detect and break metatable cycles. const void* index = lua_topointer(L, -1); if (visited.find(index) != visited.end()) { lua_pop(L, 1); break; } } else { lua_pop(L, 1); break; } } return result; } </code></pre>
[ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-04-02T09:36:30.970", "Id": "80278", "Score": "0", "body": "I don't know Lua, but aren't you scared of side effects when you evaluate your base string? Like deleteMyHardDrive().f<complete here>" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-04-14T16:28:51.780", "Id": "82618", "Score": "0", "body": "@kutschkem That is a valid concern. At the moment, I am using this for an internal project only, so I don't really need it, but otherwise this would certainly had to be addressed." } ]
[ { "body": "<h2>Single Responsibility Principle</h2>\n\n<p>Your function does a lot! It has over 100 LoC and there clearly are seams where separation should take place. You should have an own function for each completion case:</p>\n\n<ul>\n<li>\"global completion\" (where no separator occurs in the string)</li>\n<li>completion after <code>.</code></li>\n<li>completion after <code>:</code> (doing the check for <code>:</code> in the extraction loop is unnecessary work, it should be outside!)</li>\n</ul>\n\n<p>At first this might look like much code duplication but there are more extractions that reduce it:</p>\n\n<p>Traversing the <code>__index</code> metatables (and detecting loops therein) is orthogonal to the actual extraction of indices. You could write a <code>for_each_indices_metatable</code> helper function that calls the extraction method on each metatable.</p>\n\n<p>Likewise the \"local\" traversal of the indices of a table is orthogonal to the extraction of (function) string completions. This would make for another <code>for_each_index</code> method that gets passed the functor to find the indices whose prefix was entered.</p>\n\n<p>Speaking of this extraction function: It should only extract the local indices and not the whole completed string (so \"bar\" instead of \"foo.bar\" for \"foo.b\"). This allows for more finegrained handling and you still can prepend \"foo.\" later on.</p>\n\n<h2>Spaghetti code</h2>\n\n<p>Because everything is in one function there are many variables visible in those parts of the code that don't need them. The aforementioned function extractions would also lessen this effect.</p>\n\n<h2>Side-effects</h2>\n\n<p>As noted by kutschkem you could invoke side-effects during your function. I feel that you underestimate this problem.</p>\n\n<p>Not only can these effects be very subtle (meaning you will observe them long after you introduced them), they are also not always that obvious (<code>__index</code> could do some nasty things for you) and the programmers awareness is not always best.</p>\n\n<p>Unfortunately, this problem is not easily solvable. For simple expressions you could try to parse them yourself instead of evaluating them. The modularization that I proposed should help you with this but the limits are reached very fast: \nYou cannot do functions calls because each could have side-effects. You might try to white-list some functions but that would be very tedious and still no guarantee that there are no side-effects (you might overlook code-paths, the functions might be blackboxes, changed parameter values could introduce indirect side-effects).</p>\n\n<p>So the completion will always be relatively limited. However, you could get some inspiration on code completion tools for other script languages that might give you an idea on how to approach this problem.</p>\n\n<h2>Use the right methods</h2>\n\n<p>Instead of <code>std::set::find</code> you should use <code>std::set::count</code> to determine if an element is already inside the set if you don't need its iterator. This makes the code shorter and expresses your intent more clearly.</p>\n\n<h2>Use standard documentation formats</h2>\n\n<p>You have written a whole lot of documentation comments for your function but they are in a non standard format. You should use a format like doxygen instead to make the comments parseable for automatic documentation generators.</p>\n\n<h2>Naming</h2>\n\n<p>Some of the names could be improved. For example:</p>\n\n<ul>\n<li><code>L</code>, this name might be standard in the lua code but it looks like a macro name (and might (hopefully not) collide with an existing macro), <code>luaState</code> would be a very straightforward and not too long name</li>\n<li><code>str</code> -> <code>completionExpression</code></li>\n<li><code>strBase</code> -> <code>baseExpression</code></li>\n<li><code>strSep</code> -> <code>lastSeparator</code> (in accordance with <code>lastSepPos</code>)</li>\n<li><code>strKeyStart</code> -> <code>completionKeyPrefix</code></li>\n<li><code>visited</code> -> <code>visitedMetaTables</code></li>\n</ul>\n\n<h2>Usability</h2>\n\n<p>You might also want to support completion for <code>table[</code> contexts.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-08-30T12:28:09.763", "Id": "61550", "ParentId": "39887", "Score": "5" } } ]
{ "AcceptedAnswerId": "61550", "CommentCount": "2", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-01-23T16:49:50.880", "Id": "39887", "Score": "14", "Tags": [ "c++", "lua" ], "Title": "Runtime expression autocompletion" }
39887
<p>For a website with four pages (blog, portfolio, profil and impressum) I have four different color schemes (for links, headings, code, etc.). This results in bloated CSS which I want to reduce.</p> <p>Here is a <a href="http://jsfiddle.net/A8xHf/" rel="nofollow"><strong>demo</strong></a>. You see the navigation items use the color scheme of the page it links to. In the demo we're on the blog page with a green theme. Styling the different pages works by adding a class to the root element (i.e. <code>&lt;html class=page--blog&gt;</code>).</p> <p><strong>How can I improve this approach of styling things page-dependant?</strong></p> <p>Also what kind of <em>naming</em> would be appropriate? I could use the titles of the pages (<code>page--blog</code>, <code>link--blog</code>, &hellip;) or the colors (<code>page--green</code>, <code>link--green</code>, &hellip;). Other ideas/suggestions?</p> <p><strong>HTML:</strong></p> <pre><code>&lt;html class="page page--blog"&gt; &lt;nav class=site-nav&gt; &lt;a href=# class=link--green&gt;Blog&lt;/a&gt;&lt;!-- --&gt;&lt;a href=# class=link--orange&gt;Portfolio&lt;/a&gt;&lt;!-- --&gt;&lt;a href=# class=link--blue&gt;Profil&lt;/a&gt;&lt;!-- --&gt;&lt;a href=# class=link--red&gt;Impressum&lt;/a&gt; &lt;/nav&gt; &lt;main class=page-content&gt; &lt;p&gt;Regular paragraph, containing &lt;a href=#&gt;a link&lt;/a&gt;. Crazy, huh?&lt;/p&gt; &lt;/main&gt; &lt;/html&gt; </code></pre> <p><strong>CSS:</strong></p> <pre><code>.site-nav { background-color: #444; a { color: white; display: inline-block; padding: 20px; } } .link--green { background-color: forestgreen; .page:not(.page--blog) &amp;:hover { background-color: yellowgreen; } } .link--blue { /* ... */ } .link--orange { /* ... */ } .link--red { /* ... */ } .page-content { a, h1, h2, h3, h4, h5, h6 { .page--blog &amp; { color: forestgreen; } .page--profil &amp; { /* ... */ } .page--portfolio &amp; { /* ... */ } .page--impressum &amp; { /* ... */ } } } </code></pre> <p><strong>possible solutions/ideas:</strong></p> <ul> <li>additional CSS file only used on these sites (extra HTTP request)</li> <li>page-specific CSS in <code>style</code> tags inside the actual html document (hard to manage)</li> <li>Using SASS mixins to generate the CSS for the four pages (won't reduce bloat)</li> </ul>
[ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-01-23T17:34:42.150", "Id": "66938", "Score": "1", "body": "Sass is the name of the CSS preprocessor, which has 2 syntaxes: scss and sass. There's no reason to have an scss tag." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-01-23T17:42:45.663", "Id": "66941", "Score": "1", "body": "No. Look at the tag description for [sass]. It has nothing to do with the sass syntax. If you look over on SO, there is no scss tag, only an alias to sass (see: http://stackoverflow.com/tags/sass/info)." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-01-23T17:53:13.640", "Id": "66947", "Score": "3", "body": "Meta Discussion, http://meta.codereview.stackexchange.com/q/1455/18427" } ]
[ { "body": "<p>Some days passed and I feel like I should share the changes I have made so far.</p>\n\n<h2>Naming</h2>\n\n<p>I started using page names instead of color names on classes and variables. This leaves me with the benefit of being able to change the color scheme of an entire page only by changing the value of the color variable.</p>\n\n<pre><code>.page--home -&gt; .page--blog\n.nav__item--green -&gt; .nav__item--blog\n$green-color -&gt; $blog-color\n</code></pre>\n\n<h2>Generating page-specific CSS with a mixin</h2>\n\n<ul>\n<li>I need to style certain elements depending on the class I assign to the root element (e.g. <code>&lt;html class=page--blog&gt;</code>)</li>\n<li>The needed arguments I pass to the mixin are <code>$element</code> (a selector like <code>.site-nav</code> or <code>h1</code>) and <code>$property</code> (a CSS property like <code>color</code>)</li>\n<li>There also is an optional argument which allows me to switch to light color variations</li>\n</ul>\n\n<p><strong>Mixin:</strong></p>\n\n<pre><code>@mixin themify($element, $property, $light-colors: false) {\n $pages: null;\n @if $light-colors == true {\n $pages: blog $green-color-light,\n portfolio $orange-color-light,\n profil $blue-color-light,\n impressum $red-color-light;\n } @else {\n $pages: blog $green-color,\n portfolio $orange-color,\n profil $blue-color,\n impressum $red-color;\n }\n\n @each $page in $pages {\n .page--#{nth($page, 1)} #{$element} {\n #{$property}: nth($page, 2);\n }\n }\n}\n\n/* Call the mixin without optional argument */\n@include themify(site-nav, background-color);\n\n/* ...use the light colors instead of the normal ones */\n@include themify(site-nav, background-color, $light-color: true);\n</code></pre>\n\n<p><strong>Problems with the mixin:</strong></p>\n\n<ul>\n<li>I can't pass a list of selectors like <code>a, h1, h2, h3, h4, h5, h6</code> &ndash; Didn't find a solution so far (probably going to involve multi-dimensional lists)</li>\n<li>Still creates the bloated CSS, but eases my work</li>\n</ul>\n\n<p><strong>I still would love to hear some suggestions/improvements.</strong></p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-01-26T11:09:30.667", "Id": "40088", "ParentId": "39890", "Score": "5" } }, { "body": "<p>I hope someone proves me wrong, but I don't think you will be able to decrease your css.\nUnless you code it in php and only include the css on those specific pages</p>\n\n<p>Such as</p>\n\n<pre><code>if ( is_home() )\n{\n#include 'home.css';\n}\nelse (is_blog())\n{\n#include 'blog.css';\n}\n</code></pre>\n\n<p>and so fourth.</p>\n\n<p>But what i have done when using css is create a file named main.css and put all my @include 'xxxxx.css' in there. then i just have a single line in my header that includes the 'main.css'</p>\n\n<p>It works.</p>\n\n<p>You might want to also look up LESS. it is a way to partially program css with php if i understand correctly.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-02-24T18:25:50.577", "Id": "73560", "Score": "0", "body": "1. I'm using SASS and have my several SCSS-files for things like site-nav, pagination, etc. 2. I could add the CSS to the HTML documents, but this is a maintainance nightmare. 3. I'm hosting with GitHub Pages. PHP is not possible." } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-02-24T18:10:17.590", "Id": "42687", "ParentId": "39890", "Score": "1" } } ]
{ "AcceptedAnswerId": "40088", "CommentCount": "3", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-01-23T17:25:57.070", "Id": "39890", "Score": "8", "Tags": [ "html", "css", "sass", "scss" ], "Title": "Improve page-specific CSS for different color schemes" }
39890
<blockquote> <p>Write a recursive version of the function reverse(s), which reverses the string <code>s</code> in place.</p> </blockquote> <p>Here is my solution:</p> <pre><code>void reverse(char a[], int i, int j) { char tmp; if(i &gt;= j) { return; } reverse(a, i + 1, j - 1); tmp = a[i]; a[i] = a[j]; a[j] = tmp; } </code></pre> <p>This exercise is right after the presentation of the quicksort algorithm.</p> <p>This is the signature of the quicksort function presented in the book:</p> <pre><code>void qsort(int v[], int left, int right) </code></pre> <p>This is why I added 2 new parameters to the functions - to narrow the size of the array.</p> <p>There are 2 base cases:</p> <ol> <li>When <code>i == j</code>, so <code>n</code> is even</li> <li>When <code>i &gt; j</code>, so <code>n</code> is odd</li> </ol> <p><code>n</code> represents the number of characters in string <code>s</code>.</p>
[]
[ { "body": "<p>It looks ok to me.</p>\n\n<p>As a few comments in a random order:</p>\n\n<ul>\n<li>I guess I don't have to tell you that writing a non-recursive function for this is quite straightforward.</li>\n<li>You could give <code>tmp</code> its final value as you define it : <code>char tmp = a[i];</code>.</li>\n<li>You could make it a <a href=\"http://en.wikipedia.org/wiki/Tail_call\" rel=\"nofollow\">tail call recursion</a> by doing <code>reverse(a, i+1, j-1)</code> at the end.</li>\n<li>It might be a good option to define a function <code>reverse</code> taking only the array and the length as an argument and calling the one you've just posted here. If you were to use this function in a C++ program, you could do this with a single function definition if you use default parameter (i is 0 by default). The main drawback is that you have to give the parameter a somewhat awkward order.</li>\n</ul>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-01-24T07:47:26.253", "Id": "67051", "Score": "2", "body": "C functions can't have default parameters as in C++. You _could_ have variadic functions, but that would be nasty." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-01-24T09:24:24.840", "Id": "67058", "Score": "0", "body": "Indeed, updated my answer." } ], "meta_data": { "CommentCount": "2", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-01-23T17:37:37.910", "Id": "39892", "ParentId": "39891", "Score": "3" } }, { "body": "<p>Just to add my 2 cents on top of the comments of @Josay: in C you can make your function an helper function to a wrapper with a more convenient interface.</p>\n\n<p>For instance you can think of passing only the <code>\\0</code> terminated string to the interface:</p>\n\n<pre><code>static void reverse_helper(char * str, size_t ii, size_t jj) {\n // Exchange characters\n char tmp = str[ii];\n str[ii] = str[jj];\n str[jj] = tmp;\n // Check next move\n ii++;\n jj--;\n if( ii &gt;= jj) {\n return;\n }\n reverse_helper(str,ii,jj);\n}\n\n// Requires a '\\0' terminated string\nvoid reverse(char * str) {\n size_t str_length = 0;\n while( str[str_length] != '\\0') {\n str_length++;\n }\n if (str_length == 0) return;\n reverse_helper(str,0,str_length-1);\n}\n</code></pre>\n\n<p>Apart from this minor detail, your function looks completely fine to me.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-01-24T10:00:55.120", "Id": "39948", "ParentId": "39891", "Score": "2" } } ]
{ "AcceptedAnswerId": "39892", "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-01-23T17:28:08.500", "Id": "39891", "Score": "5", "Tags": [ "c", "strings", "recursion" ], "Title": "Recursive reverse function" }
39891
<p>Sass is an extension of CSS3, adding nested rules, variables, mixins, selector inheritance, and more. It’s translated to well-formatted, standard CSS using the command line tool or a web-framework plugin.</p> <p>Sass has two syntaxes. The new main syntax (as of Sass 3) is known as “SCSS” (for “Sassy CSS”), and is a superset of CSS3’s syntax. This means that every valid CSS3 stylesheet is valid SCSS as well. SCSS files use the extension .scss.</p> <p>The second, older syntax is known as the indented syntax (or just “Sass”). Inspired by Haml’s terseness, it’s intended for people who prefer conciseness over similarity to CSS. Instead of brackets and semicolons, it uses the indentation of lines to specify blocks. Although no longer the primary syntax, the indented syntax will continue to be supported. Files in the indented syntax use the extension .sass.</p> <p><a href="http://sass-lang.com/documentation/file.SASS_REFERENCE.html" rel="nofollow">SASS Documentation</a></p> <p><a href="http://stackoverflow.com/q/5654447/1214743">What's the difference between SCSS and Sass?</a></p>
[]
[]
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-01-23T17:41:49.147", "Id": "39893", "Score": "0", "Tags": null, "Title": null }
39893
The new main syntax for SASS 3, known as Sassy CSS (SCSS), is a superset of CSS3's syntax.
[]
[]
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-01-23T17:41:49.147", "Id": "39894", "Score": "0", "Tags": null, "Title": null }
39894
<p>I'm trying to find maximum the <a href="http://en.wikipedia.org/wiki/Collatz_conjecture#Statement_of_the_problem" rel="nofollow">Collatz sequence</a> between 1 and 1000000. I wrote the following code below. I guess it is correct but it is extremely slow. Can you give me a few hints to make it faster?</p> <pre><code>#include &lt;iostream&gt; #include &lt;vector&gt; #include &lt;algorithm&gt; using namespace std; bool myfn(int i, int j) { return i&lt;j; } int collatz(int x); int main() { vector &lt;int&gt; myvector; for(int i = 1; i &lt; 1000000; i++) { myvector.push_back(collatz(i)); } cout&lt;&lt;*max_element(myvector.begin(),myvector.end(),myfn); return 0; } int collatz(int x) { int counter = 1; while(1) { if(x == 1) break; if(x % 2 == 0) { x = x / 2; counter++; } else { x = 3 * x + 1; counter++; } } return counter; } </code></pre>
[ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-01-24T02:47:35.757", "Id": "67031", "Score": "1", "body": "Just a minor point: `x = x / 2` can be shortened to `x /= 2`." } ]
[ { "body": "<p>Your program is non-portable, since an <a href=\"https://stackoverflow.com/a/589684/1157100\"><code>int</code> is only guaranteed to hold numbers up to 32767</a>. I would change your data type to <code>unsigned long long</code>; otherwise, <a href=\"http://oeis.org/A222292/internal\" rel=\"nofollow noreferrer\"><code>collatz(159487)</code></a> will overflow.</p>\n\n<hr>\n\n<p>Your <code>while</code> condition is clumsy.</p>\n\n<pre><code>while(1)\n{\n if(x == 1)\n break;\n …\n}\n</code></pre>\n\n<p>should just be</p>\n\n<pre><code>while (x != 1)\n{\n …\n}\n</code></pre>\n\n<hr>\n\n<p>The key insight is that if you already know, for example, the value of <code>collatz(37)</code>, then <code>collatz(74)</code> is just <code>1 + collatz(74 / 2)</code>, and you can reuse the previously computed result. Therefore, your <code>collatz()</code> function should have access to the results vector — either</p>\n\n<ol>\n<li>pass it in by reference, or</li>\n<li>make the vector an instance variable, and the function a method of the class.</li>\n</ol>\n\n<p>It turns out that recursion works quite well for this problem: every chain will terminate in a few hundred steps, so your function call chains will be at most a few hundred frames deep. Using recursion allows you to cache the result for every number along the chain, which you can't do using iteration.</p>\n\n<pre><code>#include &lt;iostream&gt;\n#include &lt;limits&gt;\n#include &lt;stdexcept&gt;\n#include &lt;vector&gt;\n\nint collatz(unsigned long long n, std::vector&lt;int&gt; &amp;results) {\n int c;\n if (n == 1) {\n return 1;\n } else if (n &lt; results.size() &amp;&amp; results[n]) {\n return results[n];\n } else if (n % 2 == 0) {\n c = 1 + collatz(n / 2, results);\n } else if (n &gt;= (std::numeric_limits&lt;unsigned long long&gt;::max() - 1) / 3) {\n throw std::overflow_error(\"Overflow\");\n } else {\n c = 1 + collatz(3 * n + 1, results);\n }\n if (n &lt; results.size()) {\n results[n] = c;\n }\n return c;\n}\n\nint main() {\n const unsigned long long N = 1000000ULL;\n std::vector&lt;int&gt; results(N);\n int max = 0, max_i;\n for (unsigned long long i = 1; i &lt; N; ++i) {\n results[i] = collatz(i, results);\n // std::cout &lt;&lt; \"collatz(\" &lt;&lt; i &lt;&lt; \") = \" &lt;&lt; results[i] &lt;&lt; std::endl;\n if (max &lt; results[i]) {\n max = results[i];\n max_i = i;\n }\n }\n std::cout &lt;&lt; \"Max: \" &lt;&lt; max_i &lt;&lt; \" with \" &lt;&lt; max &lt;&lt; \" steps\" &lt;&lt; std::endl;\n return 0;\n}\n</code></pre>\n\n<p>By packaging your code into a class, you can let <code>main()</code> not worry about some of the details:</p>\n\n<pre><code>template &lt;typename T&gt;\nclass Collatz {\n public:\n Collatz(T limit) : limit(limit), results(limit) {}\n\n int operator[](T n) {\n int c;\n if (n == 1) {\n return 1;\n } else if (n &lt; results.size() &amp;&amp; results[n]) {\n return results[n];\n } else if (n % 2 == 0) {\n c = 1 + (*this)[n / 2];\n } else if (n &gt;= (std::numeric_limits&lt;T&gt;::max() - 1) / 3) {\n throw std::overflow_error(\"Overflow\");\n } else {\n c = 1 + (*this)[3 * n + 1];\n }\n if (n &lt; results.size()) {\n results[n] = c;\n }\n return c;\n }\n\n const T limit;\n\n private:\n std::vector&lt;int&gt; results;\n}; \n\nint main() {\n Collatz&lt;unsigned long long&gt; collatz(1000000ULL);\n int max = 0, max_i;\n for (unsigned long long i = 1; i &lt; collatz.limit; ++i) {\n // std::cout &lt;&lt; \"collatz(\" &lt;&lt; i &lt;&lt; \") = \" &lt;&lt; collatz[i] &lt;&lt; std::endl;\n if (max &lt; collatz[i]) {\n max = collatz[i];\n max_i = i;\n }\n }\n std::cout &lt;&lt; \"Max: \" &lt;&lt; max_i &lt;&lt; \" with \" &lt;&lt; max &lt;&lt; \" steps\" &lt;&lt; std::endl;\n return 0;\n}\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-01-23T19:36:48.300", "Id": "66958", "Score": "0", "body": "**make the vector an instance variable, and the function a method of the class.** Can you make this a little bit more clear? I couldn't understand. Thanks for such a helpful answer by the way." } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-01-23T19:11:38.773", "Id": "39904", "ParentId": "39898", "Score": "7" } } ]
{ "AcceptedAnswerId": "39904", "CommentCount": "1", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-01-23T18:30:50.490", "Id": "39898", "Score": "5", "Tags": [ "c++", "performance", "collatz-sequence" ], "Title": "Finding maximum Collatz sequence between 1-1000000" }
39898
<p>This pattern is like the module pattern; it focuses on public &amp; private methods. The difference is that the revealing module pattern was engineered as a way to ensure that all methods and variables are kept private until they are explicitly exposed; usually through an object literal returned by the closure in which it’s defined. It also allows the developer to avoid a lot of <code>this.</code> in the code.</p>
[]
[]
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-01-23T18:41:55.770", "Id": "39899", "Score": "0", "Tags": null, "Title": null }
39899
This pattern is like the module pattern; it focuses on public & private methods. The difference is that the revealing module pattern was engineered as a way to ensure that all methods and variables are kept private until they are explicitly exposed; usually through an object literal returned by the closure in which it’s defined. It also allows the developer to avoid a lot of `this.` in the code.
[]
[]
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-01-23T18:41:55.770", "Id": "39900", "Score": "0", "Tags": null, "Title": null }
39900
<p>I want to implement the cleanest amount of CSS through proper use of inheritance. All links need to be a shade of white, so lets say <code>#fff</code> </p> <p><strong>HTML</strong></p> <pre><code>&lt;div class="header"&gt; &lt;div class="headerLogo"&gt; &lt;a href="/"&gt;BruxZir&lt;/a&gt; &lt;/div&gt; &lt;div class="headerMenu"&gt; &lt;a href="#"&gt;&amp;equiv;&lt;/a&gt; &lt;!-- other HTML and JS left out --&gt; &lt;/div&gt; &lt;/div&gt; </code></pre> <p><strong>CSS</strong></p> <pre><code>.header { background-color: #333; color: #fff; height: 36px; width: 100%; line-height: 36px; } /* should be replaced with image */ .headerLogo { display:inline; font-size: 24px; line-height: 36px; padding-left: 6px; } .headerLogo a{ color:#fff; text-decoration:none; } .headerMenu{ float:right; font-size: 36px; margin-right: 6px; } .headerMenu a { /* needs the same rules for color, font-size, no text-decoration */ } </code></pre> <p>Here is my <a href="http://codepen.io/JGallardo/pen/zJqKd" rel="nofollow">Codepen</a></p> <p>I am thinking that since many of these rules will apply to the rest of the links in the header, I can set this up somehow for better inheritance. Also wondering if I would be better served using <code>&lt;span&gt;</code>s instead of <code>&lt;div&gt;</code>s for the logo and the menu?</p>
[ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-01-23T19:47:24.227", "Id": "66963", "Score": "2", "body": "Using `div`'s there is just fine. Why not `.header a { color: #fff; }`?" } ]
[ { "body": "<p>KleinFreund is right.</p>\n\n<p>if you want all the links the same throughout the header</p>\n\n<pre><code>.header a {\n color: #fff;\n text-decoration: none;\n}\n</code></pre>\n\n<p>and if you want the links throughout the entire page to be the same color than you want something like this</p>\n\n<pre><code>a {\n color: #fff;\n text-decoration: none;\n}\n</code></pre>\n\n<hr>\n\n<p>I assume that your Header Logo is going to be an Image or a Picture. If you want your Logo to link somewhere then you should use an image tag and then wrap it in an anchor tag</p>\n\n\n\n<pre><code>&lt;a href=\"http://www.somelink.com\"&gt;\n &lt;img src=\"/somefolder/somecoolLogo.jpg\" alt=\"Describing text\"/&gt;\n&lt;/a&gt;\n</code></pre>\n\n<p>The <code>alt</code> attribute is what most search engines use to find images. it's also pretty much mandatory, because it's used a lot for screen readers and stuff for people that can't see or can't see well. there are other attributes for image tags too.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-01-23T20:30:03.280", "Id": "39910", "ParentId": "39905", "Score": "4" } }, { "body": "<p>The worst aspect of your code is the markup, not the CSS. Unless you need the div as an actual styling hook, you can safely discard it. After all, you're not styling it in any meaningful way (what you do have can just as easily be applied to the descendant tags).</p>\n\n<pre><code>&lt;div class=\"header\"&gt;\n &lt;a href=\"/\" class=\"headerLogo\"&gt;BruxZir&lt;/a&gt;\n &lt;a href=\"#\" class=\"headerMenu\"&gt;&amp;equiv;&lt;/a&gt; &lt;!-- other HTML and JS left out --&gt;\n&lt;/div&gt;\n</code></pre>\n\n<p>However, the inclusion of semantic tags might be a better way to go:</p>\n\n<pre><code>&lt;header&gt;\n &lt;h1&gt;&lt;a href=\"/\" class=\"logo\"&gt;BruxZir&lt;/a&gt;&lt;/h1&gt;\n &lt;nav&gt;\n &lt;a href=\"#\" class=\"menu\"&gt;&amp;equiv;&lt;/a&gt; &lt;!-- other HTML and JS left out --&gt;\n &lt;/nav&gt;\n&lt;/header&gt;\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-01-23T21:11:05.640", "Id": "66984", "Score": "2", "body": "I often see the `<h1>` added to wrap the logo. But I don't agree that it is the \"best\" way to go, mostly because of SEO reasons (in my case this text will be replaced with an image) and that fact that it is a block element." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-01-23T21:47:56.213", "Id": "66991", "Score": "1", "body": "If the title of the site is \"BruxZir\", then any tag other than h1 is superfluous. Markup should not be chosen based on SEO or what it looks like, it should be chosen based on the type of content in question." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-01-23T22:16:04.937", "Id": "66995", "Score": "0", "body": "@JGallardo, if your Logo is an Image, than you should use an Image Tag for it. `<img>` with all the nice Bells and Whistles (Attributes) that it comes with, that is how you work the Optimization on a Logo." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-01-27T14:18:30.370", "Id": "67493", "Score": "0", "body": "@JGallardo Cimmanon makes a good point here. if you build a good site with good structure, following all the standards, then your site will also be good for SEO. on the other hand if you try to build a Site strictly to maximize SEO it will look crappy to a human and will most likely be scored badly by Google. you need a happy medium. I would try to make the content of your page worth reading, then you will get more people reading it and sharing it, that is what google looks for, content that is relevant." } ], "meta_data": { "CommentCount": "4", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-01-23T20:36:37.313", "Id": "39911", "ParentId": "39905", "Score": "7" } } ]
{ "AcceptedAnswerId": "39911", "CommentCount": "1", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-01-23T19:24:26.053", "Id": "39905", "Score": "4", "Tags": [ "html", "css" ], "Title": "Making CSS rules for links in header more DRY" }
39905
<p>I have the following grid shape:</p> <pre><code> __ __ __ |__|__|__| |__|__|__| </code></pre> <p>I have the following 3 types of shapes to fill it (they cannot rotate):</p> <pre><code> __ |__| __ |__| |__| (6x6 one above, or full size) </code></pre> <p>I have also 3 "shape lists" that need to fill it in priority, as in:</p> <pre><code>ShapeList1 = all types ShapeList2 = all types ShapeList3 = only single type </code></pre> <p>The lists are actually stacks, and I cannot have any empty spaces. I also need to pop the the first shape off each stack, if it does not fill it, go to the next type. ShapeList3 will always be able to complete the grid as it only has the 1x1 type. If it gets to the end of ShapeList3 I try the shapes in order again, trying to fill the grid, until the shape is filled.</p> <p>I have this working but I have a lot of while loops, including a nested loop. This is a code smell and I feel as if I could do this better. Here's my current building code in pseudo-C#:</p> <pre><code> var largeContentBlock = new LargeContentBlock(); while (!largeContentBlock.Complete &amp;&amp; aggregatePageFeed.ShapeList3.Any()) { while (aggregatePageFeed.ShapeList1.Any() &amp;&amp; largeContentBlock.CanAddBlock(aggregatePageFeed.ShapeList1.Peek().Size) &amp;&amp; !largeContentBlock.Complete) { largeContentBlock.Add(aggregatePageFeed.ShapeList1.Pop()); } while (aggregatePageFeed.ShapeList2.Any() &amp;&amp; largeContentBlock.CanAddBlock(aggregatePageFeed.ShapeList2.Peek().Size) &amp;&amp; !largeContentBlock.Complete) { largeContentBlock.Add(aggregatePageFeed.ShapeList2.Pop()); } if (!largeContentBlock.Complete &amp;&amp; largeContentBlock.CanAddBlock(aggregatePageFeed.ShapeList3.Peek().Size)) largeContentBlock.Add(aggregatePageFeed.ShapeList3.Pop()); } return largeContentBlock; </code></pre> <p>That's pretty ugly, I have it a little nicer by wrapping the while statements in functions. What pattern can I be using to make this nicer? I feel as if this is a solved problem.</p>
[ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-01-24T05:30:14.087", "Id": "67037", "Score": "0", "body": "By pattern, are you looking for suggestions or direction on an approach/algorithm to solve the problem? The general class of 'packing problems' is very well covered, but it sounds like there are a few specific requirements behind this..." } ]
[ { "body": "<p>There is a fair amount of common code that can be extracted into a function.</p>\n\n<p>There is a common check in the while clause and the if clause.</p>\n\n<pre><code>boolean CanAdd(LargeContentBlock largeContentBlock, ShapeList shapes)\n{\n return largeContentBlock.CanAddBlock(shapes.Peek().Size)\n &amp;&amp; !largeContentBlock.Complete;\n}\n</code></pre>\n\n<p>The two inner <code>while</code> loops are doing the same thing, just with two different lists. This is a perfect instance to abstracting the common code into a function.</p>\n\n<pre><code>void AddContent(LargeContentBlock largeContentBlock, ShapeList shapes)\n{\n while (shapes.Any() &amp;&amp; CanAdd(largeContentBlock, shapes))\n {\n largeContentBlock.Add(shapes.Pop());\n }\n}\n</code></pre>\n\n<p>Now your code looks like:</p>\n\n<pre><code>var largeContentBlock = new LargeContentBlock();\n\nwhile (!largeContentBlock.Complete &amp;&amp; aggregatePageFeed.ShapeList3.Any())\n{\n AddContent(largeContentBlock, aggregatePageFeed.ShapeList1);\n AddContent(largeContentBlock, aggregatePageFeed.ShapeList2);\n\n if (CanAdd(largeContentBlock, aggregatePageFeed.ShapeList3))\n largeContentBlock.Add(aggregatePageFeed.ShapeList3.Pop());\n}\n\nreturn largeContentBlock;\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-01-23T20:07:01.383", "Id": "66967", "Score": "0", "body": "Why was this downvoted?" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-01-23T20:36:30.227", "Id": "66979", "Score": "1", "body": "@chumofchance It hasn't been downvoted. This answer has two upvotes, no downvotes. Your question has one up-vote, no down-votes." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-01-24T19:11:03.773", "Id": "67130", "Score": "0", "body": "My fault, I thought I had upvoted it and saw it as 0 still, must have been a caching issue." } ], "meta_data": { "CommentCount": "3", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-01-23T19:40:05.643", "Id": "39909", "ParentId": "39908", "Score": "7" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "1", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-01-23T19:25:23.887", "Id": "39908", "Score": "5", "Tags": [ "c#", "design-patterns" ], "Title": "Reducing nested while statements for building a grid?" }
39908
<p>This class provides animation messages to the user. Looking for general feedback.</p> <p>I've posted the library I use as well if you have time to look that over.</p> <pre><code>/*************************************************************************************************** SMessenger - messaging system to provide feedback to the user */ var SMessenger = $A.Class.create({ Name: 'SMessenger', // static constants A: { DELAYTRANS: 1000, DELAY: 2000, GRANULARITY: 15, GRANULARITY_POSITION: 1, OFFSET: 40, RADIX: 10, UNITS: 'px' }, // holds dome elements E: { // the dom holds the messages dynamic: '#dynamic' }, init: function () { // pull the elements dynamically at init time $A.eachChild(this.E.dynamic, function (val) { this.E[val.id] = $A.el('#' + val.id); }, this); }, // s_ denotes server response populateMessage: function (element, type) { var period = ''; // messages from the server will have a period // they are denoted by a preceding s_ if (type.match("s_")) { type = type.replace('s_', ''); period = '.'; } element.innerHTML = this.E['dyn_' + type].innerHTML + period; }, // creates a fading message for the user fadingMessage: function (obj) { this.populateMessage(obj.response_element[0], obj.state); obj.response_element.fade('down', this.A.DELAY); }, // creates a message that fades up and then fades down. popMessage : function (obj) { var self = this; this.populateMessage(obj.response_element, obj.state); $A(obj.pane_element).fade('up', this.A.DELAYTRANS, function () { $A.setTimeout(function () { $A(obj.pane_element).fade('down', self.A.DELAYTRANS, function () { self.hideInput(false, obj); }); }, self.A.DELAY); }); }, // creates a sliding message slidingMessage : function (obj) { var self = this, el = obj.pane_element; this.populateMessage(obj.response_element, obj.state); el.style.display = 'inline'; this.hideInput(true, obj); $A.peakOut(el, 40, 2000, function () { el.style.display = 'none'; self.hideInput(false, obj); }); }, // hides or exposes input - enter, button - while the message is being displayed hideInput: function (hide, obj) { if (hide) { if (obj.input_element) { obj.input_element.removeEventListener("keypress", obj.enter); } obj.cover_element.style.display = 'inline'; } else { if (obj.input_element) { obj.input_element.addEventListener("keypress", obj.enter); } obj.cover_element.style.display = 'none'; } }, // resets inputs // set the inputs to empty // a focus and a blur will trigger event handlers resetInput: function (array, checkbox) { $A.someIndex(array, function (val) { val.value = ''; val.focus(); val.blur(); }); if (checkbox) { checkbox.checked = true; } } }, true); </code></pre>
[]
[ { "body": "<p>It looks really good! The only bit I don't like is the nested <code>ifs</code>, but I'm really nit-picking.</p>\n\n<pre><code> if (hide) {\n if (obj.input_element) {\n obj.input_element.removeEventListener(\"keypress\", obj.enter);\n }\n obj.cover_element.style.display = 'inline';\n } else {\n if (obj.input_element) {\n obj.input_element.addEventListener(\"keypress\", obj.enter);\n }\n obj.cover_element.style.display = 'none';\n }\n</code></pre>\n\n<p>Maybe....</p>\n\n<pre><code>obj.cover_element.style.display = hide ? 'inline' : 'none';\nif (!obj.input_element) return;\n\nif (hide) {\n obj.input_element.removeEventListener(\"keypress\", obj.enter);\n}\nelse {\n obj.input_element.addEventListener(\"keypress\", obj.enter);\n}\n</code></pre>\n\n<p>Putting the return value at the start, instead of protecting both blocks from it being null, makes it slightly more understandable. But I still don't like that section much.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-02-07T08:26:37.560", "Id": "41139", "ParentId": "39912", "Score": "3" } }, { "body": "<p>From a once over:</p>\n\n<ul>\n<li>if <code>'s_'</code> denotes a server response, then you ought to have a variable for it;<br> <code>var serverResponsePrefix = 's_';</code></li>\n<li>You should choose a consistent string quote, either always ' or \", my suggestion is '</li>\n<li>You could replace <code>2000</code> in <code>$A.peakOut(el, 40, 2000, function ()</code> with <code>DELAYTRANS</code></li>\n<li><p><code>hideInput</code> looks unfortunate.., I would go for<br></p>\n\n<pre><code>var actions = {\n hide : { eventFunction : 'removeEventListener', display = 'none' },\n show : { eventFunction : 'addEventListener' , display = 'inline'}};\nvar action = hide ? actions.hide : actions.show;\nif (obj.input_element) {\n obj.input_element[action.eventFunction](\"keypress\", obj.enter);\n}\nobj.cover_element.style.display = action.display;\n</code></pre>\n\n<p>Also, when you think about it, <code>hideInput</code> is lying about what it does, it either shows or hides, so it should get a better name, or you should split this out into 2 dedicated functions.</p></li>\n<li><p>As always, lowerCamelCase is good for you..</p></li>\n</ul>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-02-07T15:38:02.340", "Id": "70619", "Score": "0", "body": "Your `hideInput` is even more obfuscated!" } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-02-07T15:14:32.530", "Id": "41157", "ParentId": "39912", "Score": "2" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-01-23T20:38:52.100", "Id": "39912", "Score": "4", "Tags": [ "javascript" ], "Title": "A class for animating messages as feedback to the user" }
39912
<p>Concerned with the length of this and the organization. Looking to organize it better if possible. If anyone knows the jQuery equivalent of these methods I would like to put them in the comments.</p> <p>I'm not interested in changing the style, i.e. - identifier names, whitespace, etc.</p> <pre><code>/*************************************************************************************************** **DOM - additional coverage for the dom - consistent coding style ... - fewer function branches ***************************************************************************************************/ (function (win, doc) { "use strict"; // p(R)ivate propeties go here var Priv = {}, // (P)ublic properties go here Pub = function (selector) { return new Priv.Constructor(selector); }, // (D)ependencies go here $A; $A = (function manageGlobal() { // manually match to utility global Priv.g = '$A'; if (win[Priv.g] &amp;&amp; win[Priv.g].pack &amp;&amp; win[Priv.g].pack.utility) { // utility was found, add dom win[Priv.g].pack.dom = true; } else { throw new Error("dom requires utility module"); } return win[Priv.g]; }()); Pub.Debug = (function () { var publik = {}, hold = {}; // addTags and removeTags can add and remove groups of html tags for // visual feedback on how a site works publik.addTags = function (tag) { if (hold[tag]) { $A.someIndex(hold[tag], function (val) { if (tag === 'script' || tag === 'style') { document.head.appendChild(val); } else { document.body.appendChild(val); } }); } }; publik.removeTags = function (tag) { var styles = document.getElementsByTagName(tag), i; hold[tag] = []; for (i = styles.length; i; i--) { hold[tag][i] = styles[i]; $A.removeElement((styles[i])); } }; publik.removeStorage = function () { localStorage.clear(); sessionStorage.clear(); }; // extracts z-indices not set to auto publik.zIndex = function () { var obj_2d = {}, elements = document.body.getElementsByTagName("*"), z_index; // loop through elements and pull information from them $A.someIndex(elements, function (val, index) { z_index = win.getComputedStyle(val).getPropertyValue("z-index"); // ignore elements with the auto value if (z_index !== "auto") { obj_2d[index] = [val.id, val.tagName, val.className, z_index]; } }); return obj_2d; }; return publik; }()); Pub.el = function (selector_native) { if (selector_native) { var tokens = selector_native.match(/^(@|#|\.)([\x20-\x7E]+)$/), type, identifier; if (!tokens || !tokens[1] || !tokens[2]) { return new Error("mal-formed selector"); } type = tokens[1]; identifier = tokens[2]; if (type === '#') { return doc.getElementById(identifier); } if (type === '.' &amp;&amp; doc.getElementsByClassName) { return doc.getElementsByClassName(identifier); } if (type === '@') { return doc.getElementsByName(identifier); } return new Error("mal-formed selector"); } }; Pub.removeElement = function (el) { if (el &amp;&amp; el.parentNode) { return el.parentNode.removeChild(el); } return null; }; Pub.insertAfter = function (el, ref) { if (el &amp;&amp; ref &amp;&amp; ref.parentNode) { return ref.parentNode.insertBefore(el, ref.nextSibling); } return null; }; Pub.isElement = function (obj) { return !!(obj &amp;&amp; obj.nodeType === 1); }; Pub.eachChild = function (ref_el, func, con) { if (ref_el) { var iter_el = ref_el.firstChild, result; do { result = func.call(con, iter_el, ref_el); if (result !== undefined) { return result; } iter_el = iter_el.nextSibling; } while (iter_el !== null); } return null; }; Pub.HTMLToElement = function (html) { var div = document.createElement('div'); div.innerHTML = html; return div.firstChild; }; Pub.getData = function (id) { var data, obj = {}, el = document.getElementById(id); if (el.dataset) { $A.someKey(el.dataset, function (val, key) { obj[key] = val; }); } else { data = $A.filter(el.attributes, function (at) { return (/^data-/).test(at.name); }); $A.someIndex(data, function (val, i) { obj[data[i].name.slice(5)] = val.value; }); } return obj; }; Priv.hasClass = function (el, name) { return new RegExp('(\\s|^)' + name, 'g').test(el.className); }; Priv.toggleNS = function (el, ns, prop) { Pub.someString(el.className, function (val) { if (val.match(/toggle_/)) { var names = val.split(/_/); if (names[1] === ns &amp;&amp; names[2] !== prop) { Pub.removeClass(el, val); } } }); }; Pub.addClass = function (el, name) { if (!Priv.hasClass(el, name)) { el.className += (el.className ? ' ' : '') + name; } var temp = name.match(/toggle_(\w+)_(\w+)/); if (temp) { Priv.toggleNS(el, temp[1], temp[2]); return; } }; Pub.removeClass = function (el, name) { el.className = name ? el.className.replace(new RegExp('(\\s|^)' + name, 'g'), '') : ''; }; Priv.Constructor = function (selector) { var type, type1, type2, temp, obj_type; // $A object detected if (selector instanceof Priv.Constructor) { return selector; } // window object detected if (selector === win) { this[0] = selector; return this; } // document object detected if (selector === doc) { this[0] = selector; return this; } // element object detected if (Pub.isElement(selector)) { this[0] = selector; return this; } // only strings should be left if (selector) { obj_type = $A.getType(selector); } if (obj_type !== 'String') { return this; } // selector is a symbol follwed by asci type = selector.match(/^(@|#|\.)([\x20-\x7E]+)$/); if (!type) { return this; } type1 = type[1]; type2 = type[2]; // id if (type1 === '#') { temp = doc.getElementById(type2); if (!temp) { return this; } this[0] = temp; return this; } // class if (type1 === '.' &amp;&amp; doc.getElementsByClassName) { temp = doc.getElementsByClassName(type2); if (!temp) { return this; } $A.someIndex(temp, function (val, index) { this[index] = val; }, this); return this; } // name if (type1 === '@') { temp = doc.getElementsByName(type2); if (!temp) { return this; } $A.someIndex(temp, function (val, index) { this[index] = val; }, this); return this; } }; // jQuery like prototype assignment Priv.proto = Priv.Constructor.prototype; Priv.proto.fade = function (direction, max_time, callback) { var privates = {}, self = this; // initialize privates.elapsed = 0; privates.GRANULARITY = 10; if (privates.timer_id) { win.clearInterval(privates.timer_id); } (function next() { privates.elapsed += privates.GRANULARITY; if (!privates.timer_id) { privates.timer_id = win.setInterval(next, privates.GRANULARITY); } if (direction === 'up') { $A.someKey(self, function (val) { val.style.opacity = privates.elapsed / max_time; }); } else if (direction === 'down') { $A.someKey(self, function (val) { val.style.opacity = (max_time - privates.elapsed) / max_time; }); } if (privates.elapsed &gt;= max_time) { if (callback) { callback(); } win.clearInterval(privates.timer_id); } }()); }; Pub.peakOut = function (elem, offset, delay, callback) { var privates = {}; // constants initialization privates.RADIX = 10; privates.GRAN_TIME = 15; privates.GRAN_DIST = 1; privates.UNITS = 'px'; // privates initialization privates.el = elem; privates.start = parseInt(Pub.getComputedStyle(privates.el).getPropertyValue("top"), privates.RADIX); privates.status = 'down'; privates.end = privates.start + offset; privates.current = privates.start; privates.id = null; (function next() { if ((privates.status === 'down') &amp;&amp; (privates.current &lt; privates.end)) { privates.current += privates.GRAN_DIST; privates.el.style.top = privates.current + privates.UNITS; if (!privates.id) { privates.id = Pub.setInterval(next, privates.GRAN_TIME); } } else if ((privates.status === 'down') &amp;&amp; (privates.current === privates.end)) { privates.status = 'up'; Priv.resetInterval(privates); Pub.setTimeout(next, delay); } else if ((privates.status === 'up') &amp;&amp; (privates.current &gt; privates.start)) { privates.current -= privates.GRAN_DIST; privates.el.style.top = privates.current + privates.UNITS; if (!privates.id) { privates.id = Pub.setInterval(next, privates.GRAN_TIME); } } else if ((privates.status === 'up') &amp;&amp; (privates.current === privates.start)) { Priv.resetInterval(privates); callback(); } }()); }; Priv.resetInterval = function (privates) { Pub.clearInterval(privates.id); privates.id = 0; }; Priv.expandFont = function (direction, max_time) { var self = this, el_prim = self[0], privates = {}; if (el_prim.timer_id) { return; } el_prim.style.fontSize = Pub.getComputedStyle(el_prim, null).getPropertyValue("font-size"); privates.final_size = parseInt(el_prim.style.fontSize, privates.RADIX); privates.GRANULARITY = 10; privates.time_elapsed = 0; (function next() { $A.someKey(self, function (val) { if (direction === 'up') { val.style.fontSize = ((privates.time_elapsed / max_time) * privates.final_size) + 'px'; } else if (direction === 'down') { val.style.fontSize = ((max_time - privates.time_elapsed) / max_time) + 'px'; } }); privates.time_elapsed += privates.GRANULARITY; // completed, do not call next if (el_prim.timer_id_done) { Pub.clearTimeout(el_prim.timer_id); el_prim.timer_id = undefined; el_prim.timer_id_done = undefined; // intermediate call to next } else if (privates.time_elapsed &lt; max_time) { el_prim.timer_id = Pub.setTimeout(next, privates.GRANULARITY); // normalizing call to guarante (elapsed === max) } else if (privates.time_elapsed &gt;= max_time) { el_prim.timer_id = Pub.setTimeout(next, privates.GRANULARITY); el_prim.timer_id_done = true; privates.time_elapsed = max_time; } }()); }; Priv.proto.expandFont = function (direction, max_time, big_size) { return Priv.expandFont.call(this, direction, max_time, big_size); }; Pub.expandFont = (function () { return function (element, direction, max_time, big_size) { var temp = []; temp[0] = element; Priv.expandFont.call(temp, direction, max_time, big_size); }; }()); /**************************************************************************************************/ Priv.functionNull = function () { return undefined; }; // createEvent Priv.createEvent = function () { if (doc.createEvent) { return function (type) { var event = doc.createEvent("HTMLEvents"); event.initEvent(type, true, false); $A.someKey(this, function (val) { val.dispatchEvent(event); }); }; } if (doc.createEventObject) { return function (type) { var event = doc.createEventObject(); event.eventType = type; $A.someKey(this, function (val) { val.fireEvent('on' + type, event); }); }; } return Priv.functionNull; }; Priv.proto.createEvent = function (type) { return Priv.createEvent.call(this, type); }; Pub.createEvent = (function () { return function (element, type) { var temp = []; temp[0] = element; Priv.createEvent.call(temp, type); }; }()); // addEvent Priv.addEvent = (function () { if (win.addEventListener) { return function (type, callback) { $A.someKey(this, function (val) { val.addEventListener(type, callback); }); }; } if (win.attachEvent) { return function (type, callback) { $A.someKey(this, function (val) { val.attachEvent('on' + type, callback); }); }; } return Priv.functionNull; }()); Priv.proto.addEvent = function (type, callback) { return Priv.addEvent.call(this, type, callback); }; Pub.addEvent = (function () { return function (element, type, callback) { var temp = []; temp[0] = element; Priv.addEvent.call(temp, type, callback); }; }()); Priv.proto.removeEvent = (function () { if (win.removeEventListener) { return function (type, callback) { $A.someKey(this, function (val) { val.removeEventListener(type, callback); }); }; } if (win.detachEvent) { return function (type, callback) { $A.someKey(this, function (val) { val.detachEvent('on' + type, callback); }); }; } return Priv.functionNull; }()); Priv.proto.removeEvent = function (type, callback) { return Priv.removeEvent.call(this, type, callback); }; Pub.removeEvent = (function () { return function (element, type, callback) { var temp = []; temp[0] = element; Priv.removeEvent.call(temp, type, callback); }; }()); Pub.ajax = function (config_ajax) { var xhr; // get if (config_ajax.type === 'get') { xhr = new win.XMLHttpRequest(); xhr.open('GET', config_ajax.url, true); xhr.onload = function () { if (this.status === 200) { config_ajax.callback(xhr.responseText); } }; xhr.send(null); } // post if (config_ajax.type === 'post') { xhr = new win.XMLHttpRequest(); xhr.open("POST", config_ajax.url, true); xhr.setRequestHeader("Content-type", "application/x-www-form-urlencoded"); xhr.onload = function () { if (this.status === 200) { config_ajax.callback(xhr.responseText); } }; xhr.send(config_ajax.data); } // post for form_data if (config_ajax.type === 'multi') { xhr = new win.XMLHttpRequest(); xhr.open("POST", config_ajax.url, true); xhr.onload = function () { if (this.status === 200) { config_ajax.callback(xhr.responseText); } }; xhr.send(config_ajax.data); } }; Priv.Queue = (function () { var queue = [], publik = {}; function getIndexFromToken(callback) { var hold; $A.someIndex(queue, function (val, index) { if (val.callback === callback) { hold = index; return index; } }); return hold; } function getBlockedProperty(item) { var blocked; if (item) { blocked = item.blocked; } else { blocked = false; } return blocked; } publik.addItem = function (callback) { var temp = {}; temp.blocked = false; temp.callback = callback; temp.response_text = null; queue.push(temp); }; publik.itemCompleted = function (response_text, callback) { var index, item, blocked; index = getIndexFromToken(callback); if (index !== 0) { queue[index].blocked = true; queue[index].response_text = response_text; } else { item = queue.shift(); item.callback(response_text); blocked = getBlockedProperty(queue[0]); while (blocked) { item = queue.shift(); item.callback(item.response_text); blocked = getBlockedProperty(queue[0]); } } }; return publik; }()); Pub.serialAjax = function (source, callback) { Priv.Queue.addItem(callback); Pub.ajax({ type: 'get', url: source, callback: function (response_text) { Priv.Queue.itemCompleted(response_text, callback); } }); }; Pub.setTimeout = function () { return win.setTimeout.apply(win, arguments); }; Pub.clearTimeout = function () { return win.clearTimeout.apply(win, arguments); }; Pub.setInterval = function () { return win.setInterval.apply(win, arguments); }; Pub.clearInterval = function () { return win.clearInterval.apply(win, arguments); }; Pub.getComputedStyle = function () { return win.getComputedStyle.apply(win, arguments); }; Pub.createDocumentFragment = function () { return doc.createDocumentFragment.apply(doc, arguments); }; Pub.createElement = function () { return doc.createElement.apply(doc, arguments); }; Pub.FormData = win.FormData; Pub.FileReader = win.FileReader; Pub.localStorage = win.localStorage; Pub.sessionStorage = win.sessionStorage; Pub.log = function (obj) { var logger, type, temp, completed; // wrap win.console to protect from IE // bind to satisfy Safari if (win.console) { logger = win.console.log.bind(win.console); } else { return; } // validation type = $A.getType(obj); if (!type) { logger("Object did not stringify"); return; } // host objects if (type === 'Event') { logger('LOG|host|event&gt;'); logger(obj); return; } // library objects if (win.jQuery &amp;&amp; (obj instanceof win.jQuery)) { logger('LOG|library|jquery&gt;'); logger(obj); return; } // language objects $A.someIndex(['Arguments', 'Array', 'Object'], function (val) { if (type === val) { try { temp = JSON.stringify(obj, null, 1); } catch (e) { temp = false; } if (temp) { logger('LOG|language|' + type + '&gt;'); logger(temp); } else { logger('LOG|language|' + type + '&gt;'); logger(obj); } completed = true; } }); if (completed) { return; } $A.someIndex(['Boolean', 'Date', 'Error', 'Function', 'JSON', 'Math', 'Number', 'Null', 'RegExp', 'String', 'Undefined'], function (val) { if (type === val) { logger('LOG|language|' + type + '&gt;'); logger(obj); completed = true; } }); if (completed) { return; } // remaining logger('LOG|not_implemented|&gt;'); logger(obj); return; }; win[Priv.g] = $A.extendSafe(Pub, $A); }(window, window.document)); </code></pre>
[ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-01-23T21:10:54.893", "Id": "66983", "Score": "3", "body": "\"Concerned with the length of this and the organization\", Ironically the StackExchange system automatically flagged this question as \"excessively long\" :) There's nothing wrong with your question though." } ]
[ { "body": "<p>From a once over</p>\n\n<ul>\n<li>ASCII header, using \"use strict\" in a surrounding function, good stuff</li>\n<li><code>addTags</code>, would have been nice if the caller could set the parent to which the tags should be added ( a la jQuery )</li>\n<li><code>addTags</code>, it is unclear from naming what <code>hold</code> is, what is supposed to do, there are no explaining comments either</li>\n<li><code>addTags</code>, it is clear after reading <code>removeTags</code>, maybe you should put that function there</li>\n<li><code>addTags</code>, <code>removeTags</code>, the code does not put the tags back from where they were removed, that is a very limited feature</li>\n<li><code>removeTags</code> -> <code>styles</code> seems an unfortunate name, the parameter could have been called <code>tagName</code></li>\n<li><code>removeStorage</code> -> Seems to be the wrong library, you have different a library for storage already</li>\n<li><code>zIndex</code> -> why not just return the elements in the array ? It would take less memory, while returning more info</li>\n<li><code>Pub.el</code> needs a comment with sample <code>selector_native</code> values</li>\n<li><code>Pub.removeElement</code> etc., silent failures, could be frustrating</li>\n<li><code>isElement</code> -> <code>!!</code> on a Boolean expression seems pointless, update : it is not pointless, it will convert a falsey value to the boolean false.</li>\n<li><code>eachChild</code> -> some cryptic names, not following lowerCamelCase, the name is lying since it is not guaranteed to iterate over <code>each</code> child</li>\n<li><code>HTMLToElement</code> is smart, but could use a comment as to how it works</li>\n<li><code>someKey</code> -> sigh.. , really you should use js 1.6, or use the shims</li>\n<li><code>Priv.Constructor</code> -> too much white space by far</li>\n<li><code>win</code> -> you are making it too hard, just use <code>window</code></li>\n<li><code>doc</code> -> seriously..</li>\n<li><code>(/^(@|#|\\.)([\\x20-\\x7E]+)$/</code> is used twice, you should give it a good name in a constant</li>\n<li>You are having code in <code>Priv.Constructor</code> that is very similar to what is in <code>Pub.el</code>, consider merging some of this code</li>\n</ul>\n\n<p>From here I still only reviewed half of the code. \nYour helper functions like <code>expandFont</code> really need each a few lines of comment so that the reader can easily determine what it does ( yes, it increase the font but what does <code>max_time</code>, <code>big_size</code> and <code>direction</code> do ?? )</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-01-27T15:55:45.627", "Id": "67512", "Score": "0", "body": "Done. However, since your code never checks for boolean equality with `===` it still is kind of pointless ;)" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-01-27T16:00:55.547", "Id": "67514", "Score": "0", "body": "I'm not interested in advice on style - identifier names, whitespace, etc. I've updated the question to reflect this, so you can remove those bullets as well." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-01-27T16:25:08.003", "Id": "67518", "Score": "3", "body": "@www.arcmarks.com reviewers are free to comment on **any** aspect of the code you post, not just what you deem useful." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-01-27T16:26:28.807", "Id": "67520", "Score": "0", "body": "right its your content, take it." } ], "meta_data": { "CommentCount": "4", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-01-24T20:13:22.620", "Id": "39994", "ParentId": "39913", "Score": "4" } } ]
{ "AcceptedAnswerId": "39994", "CommentCount": "1", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-01-23T20:43:52.240", "Id": "39913", "Score": "3", "Tags": [ "javascript", "jquery" ], "Title": "A package for the DOM" }
39913
<p>Addressed both issues in this <a href="https://codereview.stackexchange.com/questions/39619/a-package-for-sort-algorithms-v2">codereview post</a>.</p> <p>Fixed the indexing issue and the call mechanism of the function expression.</p> <p>Looking for perfect code. Hope this is the last rev.</p> <pre><code> /*************************************************************************************************** **ALGORITHMS ***************************************************************************************************/ // self used to hold client or server side global (function () { "use strict"; // holds (Pub)lic properties var Pub = {}, // holds (Priv)ate properties Priv = {}, // holds "imported" library properties $A; (function manageGlobal() { // Priv.g holds the single global variable, used to hold all packages Priv.g = '$A'; if (this[Priv.g] &amp;&amp; this[Priv.g].pack &amp;&amp; this[Priv.g].pack.utility) { this[Priv.g].pack.algo = true; $A = this[Priv.g]; } else { throw new Error("algo requires utility module"); } }()); Pub.swap = function (arr, i, j) { var temp = arr[i]; arr[i] = arr[j]; arr[j] = temp; }; // checks to see if sorted Pub.isSorted = function (arr) { var i, length = arr.length; for (i = 1; i &lt; length; i++) { if (arr[i] &lt; arr[i - 1]) { return false; } } return true; }; // repeatedly orders two items ( a bubble ) at a time Pub.bubbleSort = function (arr) { var index_outer, index_inner, swapped = false, length = arr.length; for (index_outer = 0; index_outer &lt; length; index_outer++) { swapped = false; for (index_inner = 0; index_inner &lt; length - index_outer; index_inner++) { if (arr[index_inner] &gt; arr[index_inner + 1]) { Pub.swap(arr, index_inner, index_inner + 1); swapped = true; } } if (!swapped) { break; } } return arr; }; // repeatedly finds minimum and places it the next index Pub.selectionSort = function (arr) { var index_outer, index_inner, index_min, length = arr.length; for (index_outer = 0; index_outer &lt; length; index_outer++) { index_min = index_outer; for (index_inner = index_outer + 1; index_inner &lt; length; index_inner++) { if (arr[index_inner] &lt; arr[index_min]) { index_min = index_inner; } } if (index_outer !== index_min) { Pub.swap(arr, index_outer, index_min); } } return arr; }; // repeatedly places next item in correct spot using a "shift" Pub.insertionSort = function (arr) { var index_outer, index_inner, value, length = arr.length; for (index_outer = 1; index_outer &lt; length; index_outer++) { value = arr[index_outer]; // JavaScript optimization - index_inner &gt;=0 is removed // as the array index will return undefined for a negative index for (index_inner = index_outer - 1; (arr[index_inner] &gt; value); index_inner--) { arr[index_inner + 1] = arr[index_inner]; } arr[index_inner + 1] = value; } return arr; }; // module complete, release to outer scope this[Priv.g] = $A.extendSafe(this[Priv.g], Pub); }).call(this); </code></pre>
[]
[ { "body": "<p>I would remove <code>Pub.swap</code> and copy its code where you need it.</p>\n\n<p>That's because function calls are expensive, so better avoid calling a function at each iteration if possible.</p>\n\n<p>And try to cache the expressions in loop's condition. For example, </p>\n\n<pre><code>var lengthMinusIndexOuter = length - index_outer;\nfor (index_inner = 0; index_inner &lt; lengthMinusIndexOuter; index_inner++) {\n</code></pre>\n\n<p>instead of </p>\n\n<pre><code>for (index_inner = 0; index_inner &lt; length - index_outer; index_inner++)\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-01-26T02:15:52.330", "Id": "67316", "Score": "0", "body": "The caching sound like a good idea, but I don't think a function call is so costly that it is worth making the code less DRY." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-01-26T03:16:44.327", "Id": "67323", "Score": "0", "body": "@www.arcmarks.com You would be surprised of how costly are function calls: see slides 10~19 of [Extreme JavaScript Performance](http://www.slideshare.net/madrobby/extreme-javascript-performance) slideshow" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-01-26T18:29:19.443", "Id": "67390", "Score": "0", "body": "over 3 years old..." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-01-26T20:50:51.543", "Id": "67423", "Score": "0", "body": "@www.arcmarks.com Well, newer javascript engines are more optimized and can do more operations per second. But inline code is still faster than function calls, because inline code runs faster too." } ], "meta_data": { "CommentCount": "4", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-01-25T03:37:33.543", "Id": "40020", "ParentId": "39915", "Score": "3" } } ]
{ "AcceptedAnswerId": "40020", "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-01-23T22:06:57.873", "Id": "39915", "Score": "2", "Tags": [ "javascript", "algorithm", "sorting" ], "Title": "A package for sort algorithms - v3" }
39915
<p>After finishing Project Euler 24, I decided to make a scrabble type of application using /usr/lib/dict as my dictionary what I cat that into a word file. It does take a few seconds, and the dictionary selection isn't that great.</p> <p>Is there any way I could make it faster, more effective, and with a better dictionary source?</p> <pre><code>public class Scrabble { public static ArrayList&lt;String&gt; numbers = new ArrayList&lt;String&gt;(); public static ArrayList&lt;String&gt; numbers2 = new ArrayList&lt;String&gt;() { }; public static void main(String[] args) { Scanner dict = null; try { dict = new Scanner(new File("words.txt")); } catch (FileNotFoundException ex) { } while (dict.hasNextLine()) { numbers.add(dict.nextLine()); } String n = "gojy";//random text here rearrange("", n); LinkedHashSet&lt;String&gt; listToSet = new LinkedHashSet&lt;String&gt;(numbers2); ArrayList&lt;String&gt; listWithoutDuplicates = new ArrayList&lt;String&gt;(listToSet); for (int i = 0; i &lt; listWithoutDuplicates.size(); i++) { if (numbers.contains(listWithoutDuplicates.get(i))) { System.out.println(listWithoutDuplicates.get(i)); } } } public static void rearrange( String q, String w) { if (w.length() &lt;= 1) { String k = q + w; numbers2.add(k);//full word numbers2.add(q);//smaller combination to get words with less letters. doesn't work too well } else { for (int i = 0; i &lt; w.length(); i++) { String c = w.substring(0, i) + w.substring(i + 1); rearrange(q + w.charAt(i), c); } } } } </code></pre>
[]
[ { "body": "<p>If what you are trying to do is store a huge list of valid words in such a way that you can test whether a given string is a valid word, a Trie works well. See <a href=\"https://stackoverflow.com/questions/2225540/trie-implementation\">this</a> Stack Overflow question.</p>\n\n<p>Load the wordlist into the Trie when your server starts, and use the same Trie for all games (assuming this is a client server game). It's trickier than the linked thread if you need to include more than the standard 26 letters of the alphabet, but I've done a Unicode Trie for a chat filter before and I could help if you need that.</p>\n\n<p>I don't understand what you are trying to do with the rearrange method. Can you explain?</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-01-24T00:04:16.140", "Id": "67020", "Score": "0", "body": "The rearrange method is basically like if I have \"abc\", it'll do \"a\",\"b\",\"c\",\"ab\",\"bc\",\"ac\",\"cb\",\"ca\",\"ba\", etc.. Also, thanks. I will look into Tries" } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-01-23T23:46:52.657", "Id": "39923", "ParentId": "39922", "Score": "7" } }, { "body": "<p>@Teresa has already provided some good hints on how to improve the performance by using a better data structure so I'll concentrate on general things:</p>\n\n<ol>\n<li><p>Your code has a bug such as that it will crash with a <code>NullPointerException</code> if the file cannot be found.</p>\n\n<ul>\n<li>You initialize <code>dict</code> to <code>null</code></li>\n<li>You catch the <code>FileNotFoundException</code> when trying to create <code>dict</code></li>\n<li>If the exception got caught the <code>dict</code> will still be <code>null</code> and it will throw when you try to access it.</li>\n</ul>\n\n<p>So the whole <code>try-catch</code> around the <code>Scanner</code> instantiation is pretty much useless as it will crash anyway. Even worse: Instead of getting a <code>FileNotFoundException</code> which pretty much tells you what is wrong you get a fairly meaningless <code>NullPointerException</code>.</p></li>\n<li><p>You have two static arrays <code>numbers</code> and <code>numbers2</code>. These names are useless as they do in no way give you any idea whatsoever what they are being used for. The name of a variable, method, class, parameter, etc. is effectively the advertising sign for its purpose. A good concise name goes a long way of </p>\n\n<ul>\n<li>Making your code more readable and understandable</li>\n<li>Reducing bugs by misunderstanding the purpose of your own variables</li>\n</ul>\n\n<p>In this case there is not much code and it's not terribly complicated but you should get into the habit of choosing good names.</p></li>\n<li><p><code>dict</code> is not a good name for the <code>Scanner</code> as it doesn't represent a dictionary in itself - it's a reader which reads lines from a file.</p></li>\n<li><p>All your code is in the <code>main</code> method. You should get into the habit of building reusable pieces of code - in the case of Java this means creating reusable classes. So I'd suggest your create a dedicated class which holds your lookup structure and provide as well defined interface for adding valid words and looking up a word. Something like this:</p>\n\n<pre><code>public class WordLookup\n{\n public WordLookup()\n {\n ...\n }\n\n public void addValidWord(string word)\n {\n ...\n }\n\n public bool isValidWord(string word)\n {\n ...\n }\n}\n</code></pre>\n\n<p>Now <code>main</code> can be rewritten as:</p>\n\n<pre><code>public static void main(String[] args) {\n Scanner reader = new Scanner(new File(\"words.txt\"));\n\n WordLookup lookup = new WordLookup();\n\n while (reader.hasNextLine()) {\n lookup.addValidWord(reader.nextLine());\n }\n\n String n = \"gojy\";//random text here\n\n rearrange(\"\", n);\n LinkedHashSet&lt;String&gt; listToSet = new LinkedHashSet&lt;String&gt;(numbers2);\n ArrayList&lt;String&gt; listWithoutDuplicates = new ArrayList&lt;String&gt;(listToSet);\n for (int i = 0; i &lt; listWithoutDuplicates.size(); i++) {\n string currentWord = listWithoutDuplicates.get(i);\n if (lookup.isValidWord(currentWord)) {\n System.out.println(currentWord);\n }\n }\n}\n</code></pre>\n\n<p>What do you gain from it: You can now fiddle with the implementation of <code>WordLookup</code> without having to touch the <code>main</code> method.</p></li>\n</ol>\n\n<p>I came across a saying a while ago, don't remember where, which I quite like:</p>\n\n<blockquote>\n <p>Train like you fight because you will fight like you train</p>\n</blockquote>\n\n<p>So train yourself to write well structured encapsulated code even for seemingly simple things because it will form a habit. Even if you don't want to develop software professionally in the long run you will find it more rewarding when you do it right.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-01-24T09:47:15.453", "Id": "67062", "Score": "0", "body": "I would move even more code out of `main()`. How about `WordLookup lookup = WordLookup.load(new File(\"words.txt\"))`?" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-01-24T09:53:39.557", "Id": "67063", "Score": "0", "body": "Hm, don't know about putting the responsibility about loading the list from a file into the class. Ideally you make the ctor take an `Iterable<string>`. Then you can use something like this: http://stackoverflow.com/a/4677481/220986 to pipe in the words without having to read the entire file into memory first and `WordLookup` doesn't need to know where it's coming from." } ], "meta_data": { "CommentCount": "2", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-01-24T08:31:03.120", "Id": "39944", "ParentId": "39922", "Score": "6" } }, { "body": "<p>I found the code rather hard to follow due to some unconventional naming:</p>\n\n<ul>\n<li><code>numbers</code> and <code>numbers2</code> are actually lists of <code>String</code>s, not numbers.</li>\n<li><code>dict</code> is a <code>Scanner</code>, not a dictionary.</li>\n<li><code>n</code> is a <code>String</code>, not an integer.</li>\n</ul>\n\n<hr>\n\n<p>The <code>numbers2</code> assignment has inexplicable trailing braces. That creates an anonymous inner class that extends <code>ArrayList</code>, but not overriding or defining any additional members!</p>\n\n<hr>\n\n<p>You swallowed <code>FileNotFoundException</code>, which just makes debugging more difficult. In general, if you don't know what to do about an exception, just let it propagate. In this case,</p>\n\n<pre><code>public static void main(String[] args) throws FileNotFoundException\n</code></pre>\n\n<p>will take care of it.</p>\n\n<hr>\n\n<p>To iterate through all elements of a list…</p>\n\n<pre><code>for (String s : listWithoutDuplicates) {\n …\n}\n</code></pre>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-01-24T10:04:25.730", "Id": "39949", "ParentId": "39922", "Score": "3" } } ]
{ "AcceptedAnswerId": "39923", "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-01-23T23:20:50.597", "Id": "39922", "Score": "8", "Tags": [ "java", "algorithm", "performance", "search", "hash-map" ], "Title": "Scrabble algorithm review and performance suggestions" }
39922
<p>I've been iterating on my repository pattern implementation over the course of the past 4-5 months. In my new projects I choose to use this pattern and I try to improve upon what I learned in previous projects. I'm pretty pleased with the state of my current implementation. I feel like I could improve upon my validation logic somehow, though.</p> <p>First and foremost, my code is on GitHub in its entirety: <a href="https://github.com/ryancole/Warcraft">https://github.com/ryancole/Warcraft</a></p> <h3>Description of my implementation</h3> <p>I've gone with a layered approach consisting of my POCO entity classes, the repositories and finally services on top of the repositories. I have a service layer because I've chosen to use a generic repository class. My repository class is basic and provides the core CRUD operations. It's also purposefully leaky, because it's intended to sit behind my service layer - so, my repository class returns <code>IQueryable</code>. My service layer returns <code>ICollection</code>, on the other hand.</p> <pre><code>public interface IRepository&lt;T&gt; where T : class { #region Properties /// &lt;summary&gt; /// Retrieve all entities /// &lt;/summary&gt; IQueryable&lt;T&gt; All { get; } #endregion #region Methods /// &lt;summary&gt; /// Count entities matching a predicate /// &lt;/summary&gt; int Count(Expression&lt;Func&lt;T, bool&gt;&gt; predicate); /// &lt;summary&gt; /// Insert an entity /// &lt;/summary&gt; T Insert(T entity); /// &lt;summary&gt; /// Retrieve entities matching a predicate /// &lt;/summary&gt; IQueryable&lt;T&gt; Where(Expression&lt;Func&lt;T, bool&gt;&gt; predicate); #endregion } </code></pre> <p>I have a unit of work class, which contains my <code>DbContext</code> instance and provides access to my various services. The unit of work class also exposes a <code>SaveChanges</code> method. The intention is that users of my libraries will just pass this unit of work class through to their MVC controllers, and therefor do not have to deal with any of the underlying contexts, repositories, etc - only the services with their explicitly crafted methods for specific tasks.</p> <pre><code>public interface ISession : IDisposable { #region Properties IAccountService Accounts { get; } ICharacterService Characters { get; } #endregion #region Methods bool SaveChanges(); #endregion } public interface ICharacterService { #region Methods /// &lt;summary&gt; /// Insert a new Character /// &lt;/summary&gt; Character Insert(Character character); /// &lt;summary&gt; /// Retrieve a Character with the specified Name /// &lt;/summary&gt; Character GetByName(string name); /// &lt;summary&gt; /// Retrieve all Characters /// &lt;/summary&gt; ICollection&lt;Character&gt; GetAll(); /// &lt;summary&gt; /// Retrieve all Characters for the given Account /// &lt;/summary&gt; ICollection&lt;Character&gt; GetByAccount(Account account); #endregion } </code></pre> <p>The only thing that I think if slightly leaky is updating an existing entity. Updating an entity is just done by relying on the <code>DbContext</code> to track the changes, and then calling the unit of work's <code>SaveChanges</code> method. So, updating entities is not funneled through any service method. And this creates my current situation and question about my implementation.</p> <h3>My question</h3> <p>Where can I perform validation that works for both inserts and updates, with minimal repeating of myself?</p> <p>My original intention and plan was to perform all validation inside of my service layer. So, when adding a new entity you'd call the <code>Insert</code> method and I'd just validate in there. But, with how I do updating of existing entities, there is no <code>Update</code> method, and therefor no place to put that validation in my service layer.</p> <p>So, what I'm doing now instead is just putting basic validation inside of the POCO entity classes themselves, using <code>DataAnnotations</code>. Any validation that requires data from the database is done in the <code>DbContext</code> override method <code>ValidateEntity</code>. This method works nice, because of how well it integrates with EF for inserts and updates. But, this method kind of sucks because validation is split up into 2 different places and neither are my desired location which would be the service layer!</p> <p>What do you think of my implementation of the repository pattern? Any improvements I could make?</p> <p>Do you know of any better way to perform validation that works for both inserts and updates? Any way using dep injection or anything?</p>
[ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-01-24T01:45:33.257", "Id": "67025", "Score": "0", "body": "Welcome to CR! Awesome first post, keep 'em coming! :)" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-01-24T02:18:47.040", "Id": "67027", "Score": "0", "body": "Is `Character` one of your POCO classes?" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-01-24T02:21:03.290", "Id": "67028", "Score": "0", "body": "Yea, it is. Just a plain class with some data annotations and `IValidatableObject` logic." } ]
[ { "body": "<blockquote>\n <p><em>The only thing that I think if slightly leaky is updating an existing entity.</em></p>\n</blockquote>\n\n<p>It isn't the only leak you have:</p>\n\n<pre><code>public interface ISession : IDisposable\n</code></pre>\n\n<p>This is a <em>leaky abstraction</em>. You have a specific implementation in mind - one that implements <code>IDisposable</code>, and you're leaking this specific implementation into the <code>ISession</code> interface.</p>\n\n<p>That said, I don't really see what the abstract repository earns you. I've seen people wrap EF with a repository/unit-of-work so that they could \"swap the ORM\" as needed (if that's ever needed), and I can understand why someone really willing to decouple their service layer from the underlying data access technology would want to do that.</p>\n\n<p>But you're purposely leaking <code>IQueryable&lt;T&gt;</code> into your service layer, which defeats the purpose of the repository abstraction.</p>\n\n<p>Why bother? The added complexity doesn't seem to simplify extending the application. I think your service layer can afford to play with EF directly - <code>DbContext</code> <strong>is</strong> a repository <em>and</em> a unit-of-work. No need to look further.</p>\n\n<hr>\n\n<p>What you've identified as a <em>leak</em> with the updating of entities, stems from the fact that your service layer is passing <em>entities</em> to your Web/UI layer - you need a <em>seam</em> here: <em>entities</em> belong with EF and the data-related stuff, not in your UI.</p>\n\n<p>I have to admit I don't do much Web development, but in WPF I'd make that service layer work with <em>ViewModel</em> objects, and be able to \"translate\" a <em>ViewModel</em> into one or more <em>entities</em>. This \"seam\" completely decouples your front-end from your back-end. Yes, often the <em>ViewModel</em> class will look very similar to the <em>entity</em> class it's wrapping (see <a href=\"https://codereview.stackexchange.com/questions/30769/converting-between-data-and-presentation-types\">this question</a> for a WPF example), but it will only expose what the UI is interested in, so you can keep fields like <code>Id</code>, <code>DateInserted</code> and <code>DateUpdated</code> in the service and data layers and not be bothered with them in the UI layer. I don't think that concern is WPF-specific.</p>\n\n<p>With the service layer performing the \"translation\" between <em>ViewModel</em> and <em>entity</em> types, you have a perfectly logical spot to perform your validations in, exactly where you wanted to do them in the first place.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-01-24T03:09:21.943", "Id": "67032", "Score": "0", "body": "Hmm. I really like the sound of your answer. I'm currently trying to absorb what you said and think about how it'd look. So, if I scrap the generic repository class, which is indeed pointless as far as I'm concerned, and make my services translate between `ViewModel` and `Entity` ... I'm just trying to picture what these `ViewModel` classes would look like. It sounds like I would need a lot of them, one for every possible `View`. Also, my service methods would need to be very specific as well, one for each `View` also, basically." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-01-24T03:17:42.333", "Id": "67033", "Score": "0", "body": "Thanks! I might be completely wrong though. I hope to see another review from a C# programmer that's more into ASP.NET/MVC; my WPF/Windows background might be making me say weird things. But I like that you like the sound of it! :)" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-01-24T03:21:59.503", "Id": "67034", "Score": "0", "body": "Well, I feel like the general concept is the same. If you look at my code on Github, you'll see that I do use seperate view model classes in the web project, except that they directly use the actual entity classes. I'm still trying to properly understand how to break up dependency though. I'm looking at the other question you linked, and I'm trying to let it sink in." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-01-24T03:24:10.433", "Id": "67035", "Score": "0", "body": "Does it make sense though that my service layer will basically have a method specifically for handling every view? It seems very specific, and not useful for other applications other than my ASP.NET application. Unless I'm thinking too specific." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-01-24T03:45:50.200", "Id": "67036", "Score": "0", "body": "At one point I had my entities each implementing an interface; the ViewModel that wrapped that entity would take the *interface* as a constructor parameter, and that allowed me to completely decouple ViewModel & Entity types. But I threw it all out the window, it *worked*, but it was overkill. Keep It Simple, Stupid. And pragmatic. Your service methods would return things like `IEnumerable<SomeViewModel>` and take in parameters like `SomeViewModel viewModel`; that should be useful to anyone that needs to play with `SomeViewModel` :)" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-01-24T18:59:54.570", "Id": "67128", "Score": "1", "body": "I'm not sure if the service layer should be doing the mapping. That sounds like you are mixing it's responsibilities to me. I would consider having a mapping layer and the service separate." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-01-24T19:31:23.543", "Id": "67137", "Score": "0", "body": "@dreza you're probably right. If you have some spare time, I'd really like to see (read: upvote) your answer on this one!" } ], "meta_data": { "CommentCount": "7", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-01-24T02:50:51.987", "Id": "39928", "ParentId": "39927", "Score": "5" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "3", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-01-24T01:07:31.520", "Id": "39927", "Score": "5", "Tags": [ "c#", "asp.net", "entity-framework", "asp.net-mvc" ], "Title": "Entity Framework, code-first repository pattern review. Where to validate?" }
39927
<pre><code>class MyObject { public static enum Type {A, B, C, D;} public static final int ID_MAIN = 1; public static final int ID_MAIN_UK = 2; public static final int ID_MAIN_US = 3; public static final int ID_SUB = 4; // lots more constants here public static final String DESCRIPTION_1 = "Desc Full Name"; public static final String DESCRIPTION_2 = "Desc2 Full Name"; // lots more constants here private int id; public MyObject(final int id) { this.id = id; } //simple getter public int getID() { return this.id;} // real responsibility of the class is in the following two methods public static String getDescription() { switch(id) { case MyObject.ID_MAIN: case MyObject.ID_MAIN_UK: return MyObject.DESCRIPTION_1; case MyObject.ID_SUB: return MyObject_Description_2; default: // throw IllegalArgException } } public static Type getType(int id) { switch(id) { case MyObject.ID_MAIN: case MyObject.ID_SUB: return Type.A; case MyObject.ID_MAIN_UK: case MyObject.ID_MAIN_US: return Type.B; default: return Type.Undefined; } } } </code></pre> <p>Basically, there is an ID that maps to both a description and a type. This ID is passed in during construction of the class and it should map to a set of constants already contained in the class. If the id is not part of the list of constants, an error is thrown when trying to get the description that maps to the id and an 'Unknown' type is return if the type is queried. The ID maps a description to a set of constants. The same ID maps to a certain Type (defined as an enum).</p> <p>This code is pretty ugly because there are tons of constants defined at the top, which makes the switch statements pretty bloated. Is there a simple way to refactor this without changing the public interface? It seems trivially simple, but it seems pretty ugly no matter how you slice it. How can I simplify these mappings to make the code more concise?</p> <p>I was thinking about representing the mappings in a text file and having a manager class that held simple containers in a hashmap. When the manager class is constructed, it would create the objects by reading the text file and map them to an ID. When the manager is queried with the ID, it would just call the corresponding get method, for instance:</p> <pre><code>class Manager { private HashMap&lt;int, MyObject&gt; objectMap; public Manager() {} //construct the object map public String getDescription(int id) { return objectMap.get(id).getDescription();} public Type getType(int id) { return objectMap.get(id).getType();} } class DataContainer { private String description; private Type type; public DataContainer(String desc, Type type) {//set mem vars} public String getDescription() //simple getter public Type getType() //simple getter } </code></pre> <p>But this solution seems too complicated. Is there a better solution, preferably one that would keep everything in one class?</p>
[ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-01-24T06:04:51.140", "Id": "67038", "Score": "0", "body": "Static methods cannot possibly switch on instance variable `id`." } ]
[ { "body": "<p>This is a classic case for <a href=\"http://docs.oracle.com/javase/tutorial/java/javaOO/enum.html\" rel=\"nofollow\">using an Enum</a>....</p>\n\n<pre><code>public enum MyEnum {\n ID_MAIN(\"Desc Full Name\", Type.A),\n ID_MAIN_UK(\"Desc Full Name\", Type.B),\n ID_SUB(\"Desc1 Full Name\", Type.A),\n .....\n\n\n\n private final String description;\n private final Type type;\n\n private MyEnum(String desc, Type type) {\n this.type = type;\n this.description = desc;\n }\n\n public int getID() {\n return ordinal() + 1;\n }\n\n public String getDescription() {\n return description;\n }\n\n public Type getType() {\n return type;\n }\n}\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-01-24T06:32:33.503", "Id": "67042", "Score": "2", "body": "The sample code a) already uses an enum and b) didn't look so simple. Each enum didn't map directly to an ID one greater. A map or two are required here, encapsulated within an ID-to-enum-and-description helper." } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-01-24T03:47:15.073", "Id": "39930", "ParentId": "39929", "Score": "2" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "1", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-01-24T03:31:54.207", "Id": "39929", "Score": "5", "Tags": [ "java", "constants" ], "Title": "Refactoring Java class with lots of constants" }
39929