body
stringlengths
25
86.7k
comments
list
answers
list
meta_data
dict
question_id
stringlengths
1
6
<p>I have a rather clunky function that returns a number based on certain values:</p> <pre><code>local = {'abs154': '4'} w12,sv2,sv4,sv6,sv8,sv10,sv12=75,95,110,104,101,110,116 supers = [["5", w12], ["6", w12], ["7", w12], ["8", w12], ["16", w12], ["17", w12], ["18", w12], ["9", sv2], ["11", sv2], ["12", sv2], ["13", sv2], ["14", sv2], ["15", sv2], ["19", sv4], ["23", sv4], ["24", sv4], ["25", sv4], ["26", sv4], ["28", sv6], ["29", sv6], ["30", sv6], ["31", sv6], ["32", sv6], ["33", sv6], ["35", sv8], ["36", sv8], ["37", sv8], ["38", sv8], ["39", sv8], ["40", sv8], ["41", sv8], ["42", sv8], ["43", sv8], ["44", sv8], ["45", sv8], ["46", sv8], ["47", sv8], ["48", sv8], ["49", sv8], ["50", sv8], ["52", sv10], ["53", sv10], ["55", sv10], ["57", sv10], ["58", sv10], ["59", sv10], ["60", sv10], ["61", sv10], ["62", sv10], ["63", sv10], ["64", sv10], ["65", sv10], ["66", sv10], ["68", sv2], ["71", sv12], ["72", sv12], ["73", sv12], ["74", sv12], ["75", sv12], ["76", sv12], ["77", sv12], ["78", sv12], ["79", sv12], ["80", sv12], ["81", sv12], ["82", sv12], ["83", sv12], ["84", sv12]] def Server(group): try: sn = local[group] except KeyError: group = group.replace("-", "q") fnv = float(int(group[0:min(5, len(group))], 36)) lnv = group[6: (6 + min(3, len(group) - 5))] if(lnv): lnv = float(int(lnv, 36)) lnv = max(lnv,1000) else: lnv = 1000 num = (fnv % lnv) / lnv maxnum = sum(map(lambda x: x[1], supers)) cumfreq = 0 sn = 0 for wgt in supers: cumfreq += float(wgt[1]) / maxnum if(num &lt;= cumfreq): sn = int(wgt[0]) break return "s" + str(sn) + ".website.com" </code></pre> <p>This all looks rather unnecessary. I would like to make it shorter and cleaner if possible.</p>
[ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-09-03T00:52:22.807", "Id": "48801", "Score": "0", "body": "sorry about the lack of code blocks. seems a bit different than stack" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-09-03T01:00:41.310", "Id": "48802", "Score": "0", "body": "Just click the code brackets in the editor toolbar while having the code selected" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-09-03T01:02:43.800", "Id": "48803", "Score": "0", "body": "edited. was referred here by stack, yet no luck thus far" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-09-03T01:20:24.347", "Id": "48804", "Score": "1", "body": "@user2602977 Have you considered breaking this down into subfunctions with suggestive names?" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-09-03T05:15:41.260", "Id": "48815", "Score": "1", "body": "What is the motivation for this code? I suspect that it's excessively complicated because of an [XY problem](http://meta.stackexchange.com/questions/66377)." } ]
[ { "body": "<ul>\n<li>Extract two functions from the except clause: one that extracts <code>num</code> from <code>group</code>, and one that looks up <code>sn</code> from <code>super</code></li>\n<li>Precomputing <code>cumfreq</code> into <code>super</code> would allow easy lookup with help from the <code>bisect</code> module.</li>\n<li><code>group[0:min(5, len(group))]</code> is same as <code>group[:5]</code> and <code>group[6: (6 + min(3, len(group) - 5))]</code> same as <code>group[6:9]</code></li>\n<li>There are redundant type conversions: <code>lnv</code> is made <code>float</code> but possibly replaced by the integer <code>1000</code>, and <code>sn</code> goes from <code>str</code> to <code>int</code> to <code>str</code>.</li>\n</ul>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-09-03T07:40:38.953", "Id": "30720", "ParentId": "30710", "Score": "0" } }, { "body": "<p>some style issues to consider:</p>\n\n<p>1) it's conventional to use ALL_CAPS for constants such as 'supers' and w1, etc.</p>\n\n<p>2) for long term maintenance, it's also a good idea to use longer more descriptive names - not only is this hard to parse for the uninitiated, it's also prone to hard-to-catch typos which will be hard to spot. It's especially bad when you do multiple assignments on a single line.</p>\n\n<p>3) supers could be a dictionary</p>\n\n<p>4) you can simplify the range logic by excepting for incomplete groups:</p>\n\n<pre><code>&lt;snip&gt;\nenter code here\ngroup = group.replace(\"-\", \"q\") \nfnv, lnv = None\ntry: \n fnv = group[:5] \n lnv = group[6:9]\nexcept IndexError:\n raise ValueError \"group string %s is malformed\"\nfn_value = int(fnv, 36)\nln_value = max(int(lnv, 36), 1000) or 1000\n</code></pre>\n\n<p>5) maxNum is always the same, it should be a constant or a cached module-level field:</p>\n\n<pre><code>informative_name = sum(map(lambda x: x[1], supers)) \n</code></pre>\n\n<p>at the top will execute at module load and wont need to be recalced for every call.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-09-05T04:42:56.533", "Id": "30805", "ParentId": "30710", "Score": "2" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "5", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-09-03T00:49:50.157", "Id": "30710", "Score": "1", "Tags": [ "python", "mathematics" ], "Title": "Cleaning and simplifying function that returns a number based on certain values" }
30710
<p>I am using <code>ExcelDataReader</code> to import an Excel file to a dataset.</p> <p>Example Excel table:</p> <blockquote> <pre><code>//ID Name Display Order Active //1 John 1 1 </code></pre> </blockquote> <p><code>ID</code>, <code>DisplayOrder</code> and <code>Active</code> columns are read as <code>double</code>, so I have to convert them to <code>long</code>, <code>int</code> and <code>bool</code> types respectively. I need to create a list of type <code>Category</code> from the DataTable of the DataSet.</p> <p>Will this code perform well? Any suggestions for a faster conversion of DataTable to List of class?</p> <pre><code>var list = result.Tables["Categories"].AsEnumerable() .Skip(1) .Select(dr =&gt; new Category { Id = Convert.ToInt64(dr.Field&lt;double&gt;("ID")), Name = dr.Field&lt;string&gt;("Name"), DisplayOrder = Convert.ToInt32(dr.Field&lt;double&gt;("Display Order")), IsActive= dr.Field&lt;double&gt;("Active") == 1 ? true : false } ).ToList(); </code></pre>
[ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-09-03T04:52:12.010", "Id": "48812", "Score": "2", "body": "I'd probably rewrite that last line as `IsActive= dr.Field<double>(\"Active\") > 0` (your ternary is unnecessary as the comparison already evaluates to `true` or `false`) because of `double` rounding issues and equality comparisons." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-09-03T04:55:04.963", "Id": "48813", "Score": "0", "body": "Thanks Jesse. Anything else to improve?" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-09-03T05:05:51.523", "Id": "48814", "Score": "3", "body": "I gotta say, this looks pretty tip-top and concise." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-09-03T18:38:58.630", "Id": "48859", "Score": "0", "body": "You can access DataRow fields by name directly: `dr[\"ID\"]`, `dr[\"Name\"]` etc. They're of type `object`, but the `Convert.To____()` functions handle that." } ]
[ { "body": "<p>I created an extension method for <code>DataTable</code> to convert them into a <code>List&lt;T&gt;</code></p>\n\n<pre><code>public static class Helper\n{\n /// &lt;summary&gt;\n /// Converts a DataTable to a list with generic objects\n /// &lt;/summary&gt;\n /// &lt;typeparam name=\"T\"&gt;Generic object&lt;/typeparam&gt;\n /// &lt;param name=\"table\"&gt;DataTable&lt;/param&gt;\n /// &lt;returns&gt;List with generic objects&lt;/returns&gt;\n public static List&lt;T&gt; DataTableToList&lt;T&gt;(this DataTable table) where T : class, new()\n {\n try\n {\n List&lt;T&gt; list = new List&lt;T&gt;();\n\n foreach (var row in table.AsEnumerable())\n {\n T obj = new T();\n\n foreach (var prop in obj.GetType().GetProperties())\n {\n try\n {\n PropertyInfo propertyInfo = obj.GetType().GetProperty(prop.Name);\n propertyInfo.SetValue(obj, Convert.ChangeType(row[prop.Name], propertyInfo.PropertyType), null);\n }\n catch\n {\n continue;\n }\n }\n\n list.Add(obj);\n }\n\n return list;\n }\n catch\n {\n return null;\n }\n }\n}\n</code></pre>\n\n<p><strong>Example:</strong></p>\n\n<pre><code>DataTable dtTable = GetEmployeeDataTable();\nList&lt;Employee&gt; employeeList = dtTable.DataTableToList&lt;Employee&gt;();\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2015-01-05T10:50:38.023", "Id": "137733", "Score": "2", "body": "You are a lifesaver! I had no idea Convert.ChangeType even existed until today. This is much simpler than what I had been doing, trying to invoke TryParse on the destination type. And this also takes care of DBNull values in the DataTable. 10/10!" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2015-01-08T07:55:23.013", "Id": "139211", "Score": "0", "body": "Interesting code, I am just wondering of the performance of this in contrast to doing non generic code?" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2015-04-28T21:54:24.707", "Id": "159772", "Score": "3", "body": "One update you may want to consider for your great answer is only update editable properties to reduce all the exceptions that get thrown. The following would update your code appropriately: `foreach (var prop in obj.GetType().GetProperties()**.Where(p=>p.CanWrite)**)`" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2015-05-09T10:13:59.890", "Id": "163616", "Score": "7", "body": "@Nap The performance of this code would be horrifically slow due to reflection. Elegant solution with terrible performance." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2015-11-26T16:39:53.433", "Id": "206526", "Score": "1", "body": "Just a side note: I advise to rename the method to `ToList` instead of `DataTableToList` because it's already an extension method of DataTable. And it'll also match the standard convention of ToString, ToChar etc." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2016-11-11T07:54:32.063", "Id": "275754", "Score": "0", "body": "I will report that what Zer0 said is really true. It is happened on my server. :(" } ], "meta_data": { "CommentCount": "6", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-07-12T16:09:27.910", "Id": "56857", "ParentId": "30714", "Score": "41" } }, { "body": "<p>You can lose some of the reflection badness in <a href=\"https://codereview.stackexchange.com/users/49116/gaui\">Gaui's</a> <a href=\"https://codereview.stackexchange.com/a/56857/6172\">answer</a> with a little bit of refactoring and a little bit of caching as such:</p>\n\n<pre><code>public static class Helper\n{\n private static readonly IDictionary&lt;Type, ICollection&lt;PropertyInfo&gt;&gt; _Properties =\n new Dictionary&lt;Type, ICollection&lt;PropertyInfo&gt;&gt;();\n\n /// &lt;summary&gt;\n /// Converts a DataTable to a list with generic objects\n /// &lt;/summary&gt;\n /// &lt;typeparam name=\"T\"&gt;Generic object&lt;/typeparam&gt;\n /// &lt;param name=\"table\"&gt;DataTable&lt;/param&gt;\n /// &lt;returns&gt;List with generic objects&lt;/returns&gt;\n public static IEnumerable&lt;T&gt; DataTableToList&lt;T&gt;(this DataTable table) where T : class, new()\n {\n try\n {\n var objType = typeof(T);\n ICollection&lt;PropertyInfo&gt; properties;\n\n lock (_Properties)\n {\n if (!_Properties.TryGetValue(objType, out properties))\n {\n properties = objType.GetProperties().Where(property =&gt; property.CanWrite).ToList();\n _Properties.Add(objType, properties);\n }\n }\n\n var list = new List&lt;T&gt;(table.Rows.Count);\n\n foreach (var row in table.AsEnumerable().Skip(1))\n {\n var obj = new T();\n\n foreach (var prop in properties)\n {\n try\n {\n var propType = Nullable.GetUnderlyingType(prop.PropertyType) ?? prop.PropertyType;\n var safeValue = row[prop.Name] == null ? null : Convert.ChangeType(row[prop.Name], propType);\n\n prop.SetValue(obj, safeValue, null);\n }\n catch\n {\n // ignored\n }\n }\n\n list.Add(obj);\n }\n\n return list;\n }\n catch\n {\n return Enumerable.Empty&lt;T&gt;();\n }\n }\n}\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2015-08-24T20:45:21.383", "Id": "186300", "Score": "0", "body": "May want to check for a set method on the property or change to iterate over the columns in row.Table.Columns so that read-only properties are supported" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2015-08-24T20:57:53.920", "Id": "186305", "Score": "0", "body": "@moarboilerplate easily added." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2016-08-26T11:41:12.660", "Id": "261448", "Score": "0", "body": "I really like Your solution, it works fine, but I get error because I have `DateTime?` and `int?` properties in my class, I get error saying I cant cast from System.DateTIme to System.Nullable. Can this be fixed?" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2016-08-26T11:46:10.493", "Id": "261450", "Score": "0", "body": "I've found simple solution here: http://stackoverflow.com/a/3531824/965722 so maybe You could add this to Your code. This would help other finders like me." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2016-09-02T08:24:21.620", "Id": "262656", "Score": "0", "body": "@JesseC.Slicer I'm using this with large datatables that comes from other library (I can't change it). Your solution is using reflection. I found many articles about expression trees and lambdas, so I'm wondering it it would be possible to change Your code to use those instead of reflection." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2016-09-02T08:27:39.343", "Id": "262657", "Score": "0", "body": "One more question: why You have `Skip(1)` in Your code? I had to remove this, because if my datatable has single row I got no results, with this first data row is skipped. I don't see this in Gaui's answer. Is this really needed?" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2016-09-02T16:00:18.150", "Id": "262781", "Score": "0", "body": "@Misiu the original poster showed his data (and how his code worked, with the Skip) had a first row that was the column headers. Read the comments on IharS's answer." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2016-09-02T16:03:50.417", "Id": "262782", "Score": "0", "body": "Sorry I didn't noticed that comment." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2016-09-02T16:10:37.667", "Id": "262783", "Score": "0", "body": "@Misiu with regards to your reflection comment - I would challenge you to measure the performance and find where the bottleneck is. I will bet the bit that actually populates the data table is an order of magnitude slower (due to network or I/O) than any of the reflection bits." } ], "meta_data": { "CommentCount": "9", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2015-08-24T20:15:02.247", "Id": "101827", "ParentId": "30714", "Score": "4" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "4", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-09-03T03:49:58.153", "Id": "30714", "Score": "47", "Tags": [ "c#", "performance", "linq", "converting", ".net-datatable" ], "Title": "Converting DataTable to List of class" }
30714
<p>My code looks ugly. What can you recommend? I already know about <code>Enum</code>; maybe it's a good variant for this situation. Anything else?</p> <pre><code> private void writerContent(Integer firstRow, List&lt;Record&gt; records){ int firstColumn=0; int lastColumn=7; XSSFSheet sheet = workBook.getSheetAt(0); for (int lineId=firstRow;lineId&lt;records.size();lineId++) { Row row = sheet.getRow(lineId); for (int columnId=firstColumn;columnId&lt;lastColumn;columnId++){ switch (columnId){ case 0: row.createCell(columnId).setCellValue(records.get(lineId).getNumber()); break; case 1: row.createCell(columnId).setCellValue(records.get(lineId).getName()); break; case 2: row.createCell(columnId).setCellValue(records.get(lineId).getCode()); break; case 3: row.createCell(columnId).setCellValue(records.get(lineId).getCount()); break; case 4: row.createCell(columnId).setCellValue(records.get(lineId).getSimultaneouslyProcessedProducts()); break; case 5: row.createCell(columnId).setCellValue(records.get(lineId).isSimultaneousProcessing()); break; case 6: row.createCell(columnId).setCellValue(records.get(lineId).getInterchangeability()); break; } } } } </code></pre>
[]
[ { "body": "<p>Why don't you unroll the inner loop? So the final method will be like</p>\n\n<pre><code>private void writerContent(Integer firstRow, List&lt;Record&gt; records) {\n XSSFSheet sheet = workBook.getSheetAt(0);\n for (int lineId=firstRow; lineId&lt;records.size(); lineId++) {\n Record rec = records.get(lineId);\n Row row = sheet.getRow(lineId);\n row.createCell(0).setCellValue(rec.getNumber());\n row.createCell(1).setCellValue(rec.getName()); \n row.createCell(2).setCellValue(rec.getCode()); \n row.createCell(3).setCellValue(rec.getCount());\n row.createCell(4).setCellValue(rec.getSimultaneouslyProcessedProducts()); \n row.createCell(5).setCellValue(rec.isSimultaneousProcessing());\n row.createCell(6).setCellValue(rec.getInterchangeability());\n }\n}\n</code></pre>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-09-03T06:46:10.123", "Id": "30718", "ParentId": "30717", "Score": "8" } }, { "body": "<p>@gnanz's answer has a great tip for your method, but I just wanted to go over some more general style points for Java.</p>\n\n<pre><code>private void writerContent(Integer firstRow, List&lt;Record&gt; records) {\n</code></pre>\n\n<p>In general, method names should be actions and verb phrases. The name <code>writerContent</code> is a noun phrase. Perhaps this is simply a typo, where <code>writerContent</code> was supposed to be <code>writeContent</code>, though.</p>\n\n<p>More importantly: why are you passing in an <code>Integer</code> object instead of the <code>int</code> primitive type as your first parameter? Usually you should only do this if there is a very good reason to do so. As it stands, your method is vulnerable to a <code>NullPointerException</code> if it is called incorrectly. If you simply use an <code>int</code>, you remove this danger without sacrificing any functionality.</p>\n\n<p>If you really want to keep the object wrapper, at least do some sanity checking (either at the beginning of your method or when you use it). You can check for <code>null</code> and throw an <code>IllegalArgumentException</code> or simply default to <code>0</code>, depending on how you want to design it.</p>\n\n<pre><code>if(firstRow == null) {\n throw new IllegalArgumentException(\"Must supply a first row.\");\n}\n</code></pre>\n\n<p>... or ...</p>\n\n<pre><code>if(firstRow == null) {\n firstRow = 0;\n}\n</code></pre>\n\n<p>... or, if you want to get fancy with the <a href=\"http://en.wikipedia.org/wiki/%3F%3a#Java\" rel=\"nofollow\">ternary operator</a> ...</p>\n\n<pre><code>for(int lineId = firstRow == null ? 0 : firstRow; lineId &lt; records.size(); lineId++) {\n</code></pre>\n\n<p>Moving on to the rest of your code...</p>\n\n<pre><code>int firstColumn=0;\nint lastColumn=7;\nXSSFSheet sheet = workBook.getSheetAt(0);\n</code></pre>\n\n<p>You should try to use consistent style throughout your code. Above, you switch between having spaces between your assignment operator (<code>=</code>) and not having spaces. What I tell my coders is that it doesn't really matter which one you use, as long as you're consistent. The vast majority of work that will be done on the code you write will be done by people who have never looked at it before in their lives trying to do maintenance, so consistency really helps.</p>\n\n<pre><code>for (int lineId=firstRow;lineId&lt;records.size();lineId++) {\n</code></pre>\n\n<p>This <code>for()</code> loop is a bit hard to scan because it's all pressed together. Consider spacing it out: <code>for(int lineId = firstRow; lineId &lt; records.size(); lineId++) {</code></p>\n\n<p>The rest of your code in the <code>switch()</code> block is adequately addressed by the other answer.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-09-03T13:41:48.200", "Id": "30735", "ParentId": "30717", "Score": "3" } } ]
{ "AcceptedAnswerId": "30735", "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-09-03T06:34:50.870", "Id": "30717", "Score": "7", "Tags": [ "java" ], "Title": "Refactor code to populate a spreadsheet" }
30717
<p>I am developing a webapp using Spring MVC + Hibernate. I created a GenericDao class that implements basic data access methods, to be extended by all my concrete daos in the app. What I want advice or review about is the exception handling of the data access layer exceptions. Let me post a shortened version of my generic <code>Dao</code> class:</p> <pre><code>public class GenericDaoHibernateImpl&lt;E, PK extends Serializable&gt; extends AbstractDaoHibernateImpl implements GenericDao&lt;E, PK&gt; { private Class&lt;E&gt; entityClass; @SuppressWarnings("unchecked") public GenericDaoHibernateImpl() { this.entityClass = (Class&lt;E&gt;) ((ParameterizedType) getClass().getGenericSuperclass()).getActualTypeArguments()[0]; } public Class&lt;E&gt; getEntityClass() { return entityClass; } public void saveOrUpdate(E entity) throws GenericDataBaseException { try { getSession().saveOrUpdate(entity); } catch (Throwable t) { Collection&lt;Object&gt; args = new ArrayList&lt;Object&gt;(); args.add(entity); throw exceptionHandler.handle(this, t, "saveOrUpdate", args); } } public void delete(PK id) throws GenericDataBaseException, InstanceNotFoundException { try { getSession().delete(findById(id)); } catch (InstanceNotFoundException t) { throw t; } catch (Throwable t) { Collection&lt;Object&gt; args = new ArrayList&lt;Object&gt;(); args.add(id); throw exceptionHandler.handle(this, t, "delete", args); } } @SuppressWarnings("unchecked") public E findById(PK id) throws GenericDataBaseException, InstanceNotFoundException { try { E entity = (E) getSession().get(entityClass, id); if (entity == null) throw new InstanceNotFoundException(id, entityClass.getName()); return entity; } catch (InstanceNotFoundException t) { throw t; } catch (Throwable t) { Collection&lt;Object&gt; args = new ArrayList&lt;Object&gt;(); args.add(id); throw exceptionHandler.handle(this, t, "findById", args); } } @SuppressWarnings("unchecked") public List&lt;E&gt; findByProperty(String propertyName, Object propertyValue, String orderBy, boolean isOrderAsc, int firstResult, int maxResults) throws GenericDataBaseException, NoSearchResultException { try { Criteria criteria = getSession().createCriteria(getEntityClass()); criteria.add(Expression.eq(propertyName, propertyValue)); criteria.addOrder(getOrder(orderBy, isOrderAsc)); criteria.setFirstResult(firstResult); criteria.setMaxResults(maxResults); List&lt;E&gt; result = criteria.list(); if (result == null || result.size() == 0) throw new NoSearchResultException("", getEntityClass()); return result; } catch(NoSearchResultException t) { throw t; } catch (Throwable t) { Collection&lt;Object&gt; args = new ArrayList&lt;Object&gt;(); args.add(propertyName); args.add(propertyValue); args.add(orderBy); args.add(isOrderAsc); args.add(firstResult); args.add(maxResults); throw exceptionHandler.handle(this, t, "findByProperty", args); } } } </code></pre> <p>What I do is throw my own created exceptions (<code>InstanceNotFound</code>, <code>NoSearchResults</code>, <code>GenericDatabaseException</code>) and propagate them to the controller, where I catch them using @ExceptionHandler annotation:</p> <pre><code>@Controller public class MyControllerextends BaseController { public String myMethod(Model model) throws NoSearchResultException { (...) } @ExceptionHandler(InstanceNotFoundException.class) public ModelAndView instanceNotFoundException(InstanceNotFoundException e) { String message ="Error inesperado"; message = "Element with provided ID was not found"; return devuelvePaginaError(message); } @ExceptionHandler(NoSearchResultException.class) public ModelAndView handleNoSearchResultException(NoSearchResultException e) { String message ="Error inesperado"; message = "Search of " + e.getObjectClass().getSimpleName() + " with no results"; return devuelvePaginaError(message); } } </code></pre> <p>My question is, am I doing this correctly? Should I catch my exceptions earlier, in another layer? Should I even model events like "instance not found" or "No search results" as Exceptions?</p>
[]
[ { "body": "<p>I would say don't set rules like \"I will catch exceptions in this layer.\" \nWith exceptions you have two options catch them or throw them. If you know what to do with exception then catch it and proccess it in the catch section. If you dont know what to do at the current level(layer) throw it. Of course the last line of defence is before the view layer where you should catch the ones that you didn't managed to catch in the other layers and show somethin meaningful to the user.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-01-06T18:32:37.123", "Id": "38710", "ParentId": "30719", "Score": "2" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-09-03T07:20:05.473", "Id": "30719", "Score": "3", "Tags": [ "java", "error-handling", "spring", "hibernate" ], "Title": "Managing data access layer exceptions" }
30719
<p>A few days ago, I posted my version of a wildcard search algorithm, which you can see here: <a href="https://codereview.stackexchange.com/questions/30456/wildcard-search-in-c">Wildcard search in C</a></p> <p>Today I'm showing version 2. I didn't want to make it in the same post because the code is quite different.</p> <pre><code>#include &lt;stdio.h&gt; #include &lt;stdlib.h&gt; #include &lt;string.h&gt; #include &lt;stdbool.h&gt; #define MULTICHAR '*' #define ONECHAR '?' #define null NULL bool wildcard(const char *value, char *wcard) { int vsize = (int)strlen(value); int wsize = (int)strlen(wcard); bool match = false; if (vsize == 0 &amp;&amp; wsize == 0) { match = true; } else { int v = 0; int w = 0; int lookAhead = 0; bool searchMode = false; char search = '\0'; while (true) { if (wcard[w] == MULTICHAR) { //starts with * and the value matches the wcard if (w == 0 &amp;&amp; strcmp(wcard+1,value) == 0) { match = true; break; } //the * is the last character in the pattern if (!wcard[w+1]) { match = true; break; } else { //search for the next char in the pattern that is not a ? while (wcard[++w] == ONECHAR) { lookAhead++; } //if the next char in the pattern is another * we go to the start (in case we have a pattern like **a, stupid I know, but it might happen) if (wcard[w] == MULTICHAR) { continue; } search = wcard[w]; searchMode = true; } } else { if (!value[v] &amp;&amp; !wcard[w]) { if (searchMode) { match = false; } break; } if (searchMode) { char currentValue = value[v+lookAhead]; if (currentValue == search) { match = true; searchMode = false; search = '\0'; lookAhead = 0; w++; } else if (currentValue == '\0') { match = false; break; } v++; continue; } else if ((wcard[w] == ONECHAR &amp;&amp; value[v] == '\0') || (wcard[w] != value[v] &amp;&amp; wcard[w] != ONECHAR)) { match = false; break; } else { match = true; } w++; v++; } } } return match; } </code></pre> <p>I think there is still room for improvements, so any advice, tips or critiques are all welcome.</p> <p><a href="https://github.com/AntonioCS/tests/blob/master/wildcards_main.c" rel="nofollow noreferrer">You can find the tests I ran here</a>. </p> <p><a href="https://github.com/AntonioCS/tests/" rel="nofollow noreferrer">The project can be viewed here</a>.</p> <p>To compile, just do <code>make wildcard</code>.</p>
[ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-09-03T12:24:48.873", "Id": "48829", "Score": "0", "body": "I'm assuming you'd also like this to be shortened? It's considerably longer than the first version." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-09-03T19:29:30.203", "Id": "48865", "Score": "0", "body": "Yes. This is still in the early stages. It passes the tests but as microtherion mentioned in his response I already have a bug." } ]
[ { "body": "<p>I’m afraid your approach to matching multiple characters looks fundamentally misguided to me. Consider cases like:</p>\n\n<pre><code>abcbcd ab*cd\n</code></pre>\n\n<p>One approach that works is a recursive matcher, i.e. when encountering <code>*</code>, try <code>wildcard(value+1, wcard)</code> and if that fails, <code>wildcard(value, wcard+1)</code>. This will give you the standard semantics of an <code>*</code> matching as much as possible. For a minimal match, reverse the order of the two recursive calls. This is very easy to implement (much easier than your approach, in fact), but tends to need a lot of stack space for large strings.</p>\n\n<p>The alternative is to build an explicit backtracking stack, which is considerably harder to get right, but uses less memory, and usually uses it on the heap rather than the stack.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-09-03T19:38:04.610", "Id": "48866", "Score": "0", "body": "In the recursion example you give, to which do I add the +1? To the value or the wcard?" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-09-03T22:26:11.263", "Id": "48871", "Score": "1", "body": "You need both. For the greedy matcher, you first recurse with `(value+1, wcard)`, i.e. you try eating the next character. If that fails, you recurse (or, since this is a tail recursion, iterate) with `(value, wcard+1)`, i.e., match the rest of value without having the wildcard match any more characters." } ], "meta_data": { "CommentCount": "2", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-09-03T09:28:06.073", "Id": "30727", "ParentId": "30724", "Score": "1" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "2", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-09-03T08:53:14.077", "Id": "30724", "Score": "1", "Tags": [ "c", "strings", "search" ], "Title": "Wildcard search in C version 2" }
30724
<p>I am using <code>db_dataobject</code> and have provided two examples of an insert and a select query below.</p> <p>Can you please help me rewrite them in a more secure way using PDO? Is there any other way to improve them?</p> <p><strong>INSERT</strong> </p> <pre><code> $user= new DataObjects_user; $user-&gt;username = mysql_real_escape_string (strip_tags($_REQUEST['username'])); $user-&gt;password =encryptpass(mysql_real_escape_string(strip_tags($_REQUEST['password']))); $user-&gt;email =mysql_real_escape_string(strip_tags ($_REQUEST['email'])); $user-&gt;dob = mysql_real_escape_string(strip_tags($_REQUEST['dob'])); $user-&gt;member_since = date("Y-m-d H:i:s"); $id = $user-&gt;insert(); </code></pre> <p><strong>SELECT</strong></p> <pre><code>$username= mysql_real_escape_string (strip_tags($_REQUEST['username'])); $password=encryptpass($_REQUEST['password']); $user= new DataObjects_user; $password=mysql_escape_string(($password)); $user-&gt;query("select activated,userid,email,username from {$user-&gt;__table} where (username = '$username' or email='$username') AND password = '$password' "); if($user-&gt;fetch()) { </code></pre>
[]
[ { "body": "<p>I come back to this at the end, but if this answer is <em>tltr</em>, basically, I end up suggesting not to write your own DB abstraction layer, <a href=\"https://codereview.stackexchange.com/questions/29362/very-simple-php-pdo-class/29394#29394\">It's been done before</a>, way better than you're doing it now.<br/>\nThat doesn't mean the rest of this answer doesn't contain valuable tips on how to improve your code quality in general, so please do read through it:</p>\n\n<p>For a start, when you're using an object to contain data, that object is responsible for that data's integrety, not the user of the object. By that I mean: if I am to use your object, you must be able to ensure that, regardless of how I use your object (I may forget the <code>strip_tags</code> call, for example) the input won't contain any markup.<Br/>\nThe only way to do that is to define setter methods that take care of this:</p>\n\n<pre><code>class DataObjects_User\n{\n private $name = null;\n public function getName()\n {\n return $this-&gt;name;\n }\n public function setName($name = null)\n {//setting null ~= unsetting\n if ($name !== null &amp;&amp; !is_string($name))\n {\n throw new InvalidArgumentException('Name must be string');//don't hush-up errors\n }\n $this-&gt;name = is_null($name) ? $name : strip_tags($name);\n return $this;\n }\n}\n</code></pre>\n\n<p>Your code appears to require me to set a creation date manualy. Why? Why not create a field in the table that has <code>NOW()</code> as a default value? or an <code>ON UPDATE CURDATE</code> clause? wouldn't that be easier?<br/>\neven so, you could omit this, by simply adding a constructor to the object above, too:</p>\n\n<pre><code>class DataObjects_User\n{\n private $name = null;\n private $created = null;\n public function __construct()\n {\n $this-&gt;created = new \\DateTime;//I prefer to keep everything OO\n }\n public function getCreated($format = 'Y-m-j H:i:s')\n {//use class constants for the format\n if ($format === false)\n {//allow user to get the object itself?\n return $this-&gt;created;\n }\n return $this-&gt;created-&gt;format($format);\n }\n public function setCreated(DateTime $obj = null)\n {//again, null to unset\n $this-&gt;created = $obj;\n return $this;\n }\n public function getName()\n {\n return $this-&gt;name;\n }\n public function setName($name = null)\n {//setting null ~= unsetting\n if ($name !== null &amp;&amp; !is_string($name))\n {\n throw new InvalidArgumentException('Name must be string');//don't hush-up errors\n }\n $this-&gt;name = is_null($name) ? $name : strip_tags($name);\n return $this;\n }\n}\n</code></pre>\n\n<p>You may be wondering why I keep adding the option of setting the properties to <code>null</code>... well, that's perfectly simple: If these objects represent data in the DB, it's not unlikely you'll find yourself using these objects to build queries. If some of these properties have default values, or values that are irrelevant to a query, you can uset them, by passing null (or nothing, since it's the default value) to their setters. </p>\n\n<pre><code>$user = new DataObjects_User();//constructor sets created date!\n$user-&gt;setName('Bobby');\n -&gt;setCreated();//unset created\n</code></pre>\n\n<p>Now you can pass <code>$user</code> to a generic <code>createBind()</code> method. Besides, if you have a couple of these objects, just create an interface/abstract class if only for typehinting, and extend all dataobjects from that:</p>\n\n<pre><code>class DataObjects_User extends DataObjects_Abstract{}\n//the createBind method then could look like this:\npublic function createBind(DataObjects_Abstract $model)\n{\n $getters = get_class_methods($model);\n $bind = array();\n foreach($getters as $getter)\n {\n if (substr($getter,0,3) === 'get' &amp;&amp; method_exists('s'.substr($getter,1), $model))\n {//getter and setter exist, this is a property\n if ($model-&gt;{$getter}() !== null)\n {//avoid null properties\n $bind[':'.substr($getter,3)] = $model-&gt;{$getter}();\n }\n }\n }\n return $bind;\n}\n//when applied to $user\nvar_dump(\n $queryObject-&gt;createBind(\n $user-&gt;setName('Bobby')\n -&gt;setCreated()\n )\n);\n</code></pre>\n\n<p>That should yield:</p>\n\n<pre><code>array(':name' =&gt; 'Bobby');\n</code></pre>\n\n<p>Which makes life a lot easier when using prepared statements, doesn't it?</p>\n\n<p>since I'm on the subject: When using <code>PDO</code>, you don't have to bother with all those <em>deprecated</em> <code>mysql_real_escape_string</code> calls anymore... just use prepared statements. If you can't, then learn to use them. It's not that hard, and an awful lot safer at any rate than what you have now.</p>\n\n<p>Basically, with the <code>$user</code> object, being passed through the <code>createBind</code> method, all you need to do is:</p>\n\n<pre><code>$bind = $queryObject-&gt;createBind(\n $user-&gt;setName('Bobby')\n -&gt;setCreated()\n);\n$fields = array_keys($bind);\n$query = 'SELECT * FROM tbl WHERE ';\nforeach($fields as $field)\n{\n $query .= substr($field,1) .' = '.$field;\n}\n$statement = $pdoInstance-&gt;prepare($query);\n$statement-&gt;execute($bind);\n</code></pre>\n\n<p>This is just as secure as your code, if not more secure. The downsides: </p>\n\n<ul>\n<li>the properties of your objects have to be the same as the field-names in your db</li>\n<li>data and logic are too tightly coupled here...</li>\n</ul>\n\n<p>Lastly, I'd like to point that, even though it's not something that'll leave a gaping hole in your app's security, storing passwords the way you are doing is <em>not done</em>. Common practice is to store password-hashes, not encrypted passwords. Encryption, as the word implies, is a two way deal: anything that is encrypted can be decrypted. A hash-function, by its very nature is a one-way algorythm: A hash can't be <em>de-hashed</em> (well, it can be brute-forced, but even then, collisions, salt and time-complexity make that less viable to would-be hackers). Instead of encrypting the pass, try this, inside the user model:</p>\n\n<pre><code>private $passHash = null;\nconst PASS_SALT = '$0m3_r@Nd0M_5tr1n9';\npublic function setPassHash($password)\n{\n $this-&gt;passHash = hash('sha256', self::PASS_SALT.$password);\n return $this;\n}\n</code></pre>\n\n<p>But that's just on the data model. Any abstraction layer you're writing to query the DB isn't going to cut it as your app grows. As I've stated previously, in other answers:<br/></p>\n\n<p>On the whole, I'd suggest you use Doctrine entities, though. ORM's aren't very inviting at first, but once you get the hang of how easy it is to distil tables from objects and objects from tables (yes, it works both ways), you haven't got anything to worry about. </p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-09-04T15:31:12.790", "Id": "48942", "Score": "0", "body": "Or, you could simply use PDO. I don't think he neads an entire ORM solution. +1 for the nice answer." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-09-05T00:35:39.660", "Id": "48994", "Score": "0", "body": "thanks so much for the detailed answer , I will go through it in detail. quick question will the PDO bit apply to my code ? I am using PEAR DB_DataObject.. not sure if / how they work together." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-09-05T06:53:24.893", "Id": "49007", "Score": "0", "body": "@ivan: I don't think you can combine the two, to get the best of both worlds. Personally, I'd not use the PEAR package, simply because there's no guarantee it's installed on your host, and because it essentially does what other abstraction layers do, too: Doctrine allows you to use entities, like a DataObject, to perform queries, but it doesn't require you to actually install new extensions. Yes, it'll be a tad slower than the PEAR package, but it's better known => more documentation and more portable. That and development of PEAR packages have a nasty habit of being discontinued" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-09-05T06:53:59.270", "Id": "49008", "Score": "0", "body": "The package you're using is still under development ATM, but who's to say that, a year from now, it'll still be actively maintained?" } ], "meta_data": { "CommentCount": "4", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-09-03T11:47:42.887", "Id": "30731", "ParentId": "30725", "Score": "2" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-09-03T08:59:41.910", "Id": "30725", "Score": "0", "Tags": [ "php", "mysql", "security", "pdo" ], "Title": "How can I make this piece of code more secure?" }
30725
<p>Any suggestions how to make this code better? I'm novice in coding...)) In this code I'm want to show some hint depending of browser type on semi-transparent overlay. I'm detecting browser type (I'm need - Firefox, Chrome, IE 9 and higher), create all nessesary elements, append this elements to a document.body, and attach events. To detect "document.ready" I'm use domready.js</p> <pre><code>// Perform browsers detection; var browser = {}; (function() { browser.firefox = false; browser.chrome = false; browser.msie = false; var nAgt = navigator.userAgent; var verOffset; if ( (verOffset=nAgt.indexOf("MSIE"))!=-1 ) { // For IE we also need to check browser version, because hint will be shown only if version is 9 or higher; browser.version = parseInt( nAgt.substring(verOffset+5), 10 ); if (browser.version &gt;= 9 ) { browser.msie = true; browser.name = "msie"; browser.hint = { position: "fixed", display: "none", zIndex: "101", bottom: "50px", left: "35%" }; } } else if ( (verOffset=nAgt.indexOf("Chrome"))!=-1 ) { browser.chrome = true; browser.name = "chrome"; browser.hint = { position: "fixed", display: "none", zIndex: "101", bottom: "0", left: "0" }; } else if ( (verOffset=nAgt.indexOf("Firefox"))!=-1 ) { browser.firefox = true; browser.name = "firefox"; browser.hint = { position: "fixed", display: "none", zIndex: "101", top: "0", right: "10px" }; } })(); domready(function() { if (browser.firefox || browser.chrome || browser.msie) { // Create "overlay" element var overlay = document.createElement("div"); overlay.setAttribute("id", "hintOverlay"); var overlayStyles = { width: "100%", height: "100%", background: "gray", opacity: "0.75", zIndex: "100", position: "fixed", top: "0", left: "0", display: "none" }; for(var s in overlayStyles){ if (overlayStyles.hasOwnProperty(s)) { overlay.style[s] = overlayStyles[s]; } } overlay.addEventListener("click", function() { this.style.display = "none"; document.getElementById("hintElem").style.display = "none"; }); document.body.appendChild(overlay); // Create "hint" element var hintElem = document.createElement("img"); hintElem.setAttribute("src", "images/" + browser.name + ".png"); hintElem.setAttribute("id", "hintElem"); for(var s in browser.hint) { if (browser.hint.hasOwnProperty(s)) { hintElem.style[s] = browser.hint[s]; } } document.body.appendChild(hintElem); // Attach click event to all links that have "download" in name var links = document.getElementsByTagName("a"); for(var i = 0; i &lt; links.length; i++) { if(links[i].getAttribute("id").indexOf('download') == 0) { links[i].addEventListener("click", function() { document.getElementById("hintOverlay").style.display = "block"; document.getElementById("hintElem").style.display = "block"; }); } } } }); </code></pre>
[ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-09-03T11:59:58.063", "Id": "48827", "Score": "4", "body": "Why re-invent hot water? http://www.browser-update.org/ ... And then ofcourse, browser sniffing is bad. http://css-tricks.com/browser-detection-is-bad/ And what about Opera? and all those other browsers out there?" } ]
[ { "body": "<p>\"Browser-sniffing\" is bad, usually because the methods used to detect them are usually \"spoofable\" and unreliable</p>\n\n<p>User Agent string can be spoofed (changed) and can't be relied on. In fact, vendors change UAs to tell websites they are another browser, some for valid purposes. I think it was IE10 who added a \"Mozilla\" to their UA to tell websites to load non-IE versions of pages, with confidence that the newer IE will render \"unhacked\"/not modified for IE pages without breaking.</p>\n\n<p>Even if you UA strings are fixed, you can't keep track of the 70+ (I think it was 70+, or something with a 7) different browsers in the wild today. Yes, there are browsers other than the major 5, like mobile browsers, command-line browsers, headless browsers. And don't forget to count the older versions, do still use them.</p>\n\n<p>Recently, developers use feature testing instead, to check if certain features are available in the browser. <a href=\"http://modernizr.com/\" rel=\"nofollow\">Modernizr</a> is an example of such frameworks.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-09-04T19:27:43.627", "Id": "30790", "ParentId": "30729", "Score": "1" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "1", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-09-03T09:59:35.543", "Id": "30729", "Score": "0", "Tags": [ "javascript" ], "Title": "Improve my browser-detecting JavaScript" }
30729
<p>Moved from Programmers.SE.</p> <p>I have written a new version of the PBKDF2 algorithm in Haskell. It passes all of the HMAC-SHA-1 test vectors listed in <a href="http://www.ietf.org/rfc/rfc6070.txt" rel="nofollow">RFC 6070</a>, but it is not very efficient. How can I improve the code? I plan to upload it to Github (and maybe Hackage) once it is improved.</p> <pre class="lang-hs prettyprint-override"><code>{-# LANGUAGE BangPatterns #-} {- Copyright 2013, G. Ralph Kuntz, MD. All rights reserved. LGPL License. -} module Crypto where import Codec.Utils (Octet) import qualified Data.Binary as B (encode) import Data.Bits (xor) import qualified Data.ByteString.Lazy.Char8 as C (pack) import qualified Data.ByteString.Lazy as L (unpack) import Data.List (foldl') import Data.HMAC (hmac_sha1) import Text.Bytedump (dumpRaw) -- Calculate the PBKDF2 as a hexadecimal string pbkdf2 :: ([Octet] -&gt; [Octet] -&gt; [Octet]) -- pseudo random function (HMAC) -&gt; Int -- hash length in bytes -&gt; String -- password -&gt; String -- salt -&gt; Int -- iterations -&gt; Int -- derived key length in bytes -&gt; String pbkdf2 prf hashLength password salt iterations keyLength = let passwordOctets = stringToOctets password saltOctets = stringToOctets salt totalBlocks = ceiling $ (fromIntegral keyLength :: Double) / fromIntegral hashLength blockIterator message acc = foldl' (\(a, m) _ -&gt; let !m' = prf passwordOctets m in (zipWith xor a m', m')) (acc, message) [1..iterations] in dumpRaw $ take keyLength $ foldl' (\acc block -&gt; acc ++ fst (blockIterator (saltOctets ++ intToOctets block) (replicate hashLength 0))) [] [1..totalBlocks] where intToOctets :: Int -&gt; [Octet] intToOctets i = let a = L.unpack . B.encode $ i in drop (length a - 4) a stringToOctets :: String -&gt; [Octet] stringToOctets = L.unpack . C.pack -- Calculate the PBKDF2 as a hexadecimal string using HMAC and SHA-1 pbkdf2HmacSha1 :: String -- password -&gt; String -- salt -&gt; Int -- iterations -&gt; Int -- derived key length in bytes -&gt; String pbkdf2HmacSha1 = pbkdf2 hmac_sha1 20 </code></pre>
[ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-09-11T09:54:21.833", "Id": "49503", "Score": "0", "body": "Do you have a test suite that measures the algorithm's performance? It'd be much easier to test ideas for improvements." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-09-11T12:34:50.663", "Id": "49512", "Score": "0", "body": "I have a test suite that confirms that it passes the test vectors. My suite does not currently check performance. Still learning testing in Haskell." } ]
[ { "body": "<p>The <a href=\"https://stackoverflow.com/q/18718103/1333025\">comments on SO</a> give some good hints. The most critical part is obviously <code>blockIterator</code>, so let's make it a separate function:</p>\n\n<pre><code>blockIterator\n :: ([Octet] -&gt; [Octet] -&gt; [Octet]) -- ^ pseudo random function (HMAC)\n -&gt; [Octet] -- ^ password octets\n -&gt; Int -- ^ iterations\n -&gt; [Octet] -- ^ m\n -&gt; [Octet] -- ^ a\n -&gt; [Octet]\n</code></pre>\n\n<p>The implementation using folds on a list is nice and concise, but processing the list adds some unnecessary overhead, and prevents possible optimizations. If we instead rewrite it as a recursive function</p>\n\n<pre><code>blockIterator prf passwordOctets = loop\n where\n loop i m a | i == 0 = a\n | otherwise = let m' = prf passwordOctets m\n a' = zipWith xor a m'\n in a' `deepseq` \n m' `deepseq`\n loop (i - 1) m' a'\n</code></pre>\n\n<p>it gets somewhat faster. I also added <code>deepseq</code> on the octet lists so that they're fully evaluated at each round. Introducing the recursion inside <code>loop</code>, instead of making the whole <code>blockIterator</code> recursive allows GHC to inline it.</p>\n\n<p>Measuring performance can be done using the <em>criterion</em> package:</p>\n\n<pre><code>import Criterion.Main\n\n-- ...\n\nmain = do\n let stdtest n = pbkdf2HmacSha1 \"password\" \"salt\" n 20\n defaultMain [ bgroup \"stdtest\" $\n map (\\n -&gt; bench (show n) (nf stdtest n))\n [1, 2, 4096, 65536 ]\n ]\n</code></pre>\n\n<p>However, the far most time-consuming part is still processing lists inside <code>blockIterator</code>. Using <a href=\"http://hackage.haskell.org/packages/archive/array/latest/doc/html/Data-Array-ST.html#t:STUArray\" rel=\"nofollow noreferrer\">unboxed ST arrays</a> would make the code way faster. There would be no memory allocation in the loop, no need to force evaluation. The problem is, <code>hmac_sha1</code> is implemented using list, so we'd need another optimized, <code>ST</code>-based implementation.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-09-11T16:03:19.713", "Id": "31111", "ParentId": "30733", "Score": "3" } } ]
{ "AcceptedAnswerId": "31111", "CommentCount": "2", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-09-03T13:13:21.650", "Id": "30733", "Score": "3", "Tags": [ "haskell", "cryptography" ], "Title": "Code Review of Haskell PBKDF2" }
30733
<p>I have working code to show in <code>index.php</code> and <code>content-gallery.php</code> of WordPress with Bootstrap 3.0 Carousel.</p> <p>But, I know it's not clean code. Could anyone help me clean/improve it?</p> <p>This is the code we need to generate Bootstrap Carousel: </p> <pre><code>&lt;div id="carousel-example-generic" class="carousel slide"&gt; &lt;!-- Indicators --&gt; &lt;ol class="carousel-indicators"&gt; &lt;li data-target="#carousel-example-generic" data-slide-to="0" class="active"&gt;&lt;/li&gt; &lt;li data-target="#carousel-example-generic" data-slide-to="1"&gt;&lt;/li&gt; &lt;li data-target="#carousel-example-generic" data-slide-to="2"&gt;&lt;/li&gt; &lt;/ol&gt; &lt;!-- Wrapper for slides --&gt; &lt;div class="carousel-inner"&gt; &lt;div class="item active"&gt; &lt;img src="..." alt="..."&gt; &lt;div class="carousel-caption"&gt; ... &lt;/div&gt; &lt;/div&gt; ... &lt;/div&gt; &lt;!-- Controls --&gt; &lt;a class="left carousel-control" href="#carousel-example-generic" data-slide="prev"&gt; &lt;span class="icon-prev"&gt;&lt;/span&gt; &lt;/a&gt; &lt;a class="right carousel-control" href="#carousel-example-generic" data-slide="next"&gt; &lt;span class="icon-next"&gt;&lt;/span&gt; &lt;/a&gt; &lt;/div&gt; </code></pre> <p>This is the content of my content-gallery-php:</p> <pre><code>&lt;!-- Carousel ================================================== --&gt; &lt;div id="carousel-example-generic" class="carousel slide"&gt; &lt;?php function_indicators($post) ?&gt; &lt;div class="carousel-inner"&gt; &lt;?php function_slides($post) ?&gt; &lt;/div&gt; &lt;!-- Controls --&gt; &lt;a class="left carousel-control" href="#carousel-example-generic" data-slide="prev"&gt; &lt;span class="icon-prev"&gt;&lt;/span&gt; &lt;/a&gt; &lt;a class="right carousel-control" href="#carousel-example-generic" data-slide="next"&gt; &lt;span class="icon-next"&gt;&lt;/span&gt; &lt;/a&gt; &lt;/div&gt; &lt;!-- /.carousel --&gt; </code></pre> <p>And here are 3 functions to my functions.php:</p> <pre><code>function wp_get_attachment( $attachment_id ) { $attachment = get_post( $attachment_id ); return array( 'alt' =&gt; get_post_meta( $attachment-&gt;ID, '_wp_attachment_image_alt', true ), 'caption' =&gt; $attachment-&gt;post_excerpt, 'description' =&gt; $attachment-&gt;post_content, 'href' =&gt; get_permalink( $attachment-&gt;ID ), 'src' =&gt; $attachment-&gt;guid, 'title' =&gt; $attachment-&gt;post_title ); } function functions_indicators() { $special_gallery = get_post_gallery( $post, false ); $ids = explode( ",", $special_gallery['ids'] ); $html = '&lt;ol class="carousel-indicators"&gt;'; foreach( $ids as $id ) { $link = wp_get_attachment_url( $id ); $class = ( $i == 0 ) ? 'active ' : ''; $i++; $b=1; $html .= '&lt;li data-target="#carousel-example-generic" data-slide-to="'.($i - $b).'" '. 'class="'.$class.'"&gt;&lt;/li&gt;'; } $html .= '&lt;/ol&gt;'; echo $html; } function function_slides() { $special_gallery = get_post_gallery( $post, false ); $ids = explode( ",", $special_gallery['ids'] ); $html = '&lt;div class="carousel-inner"&gt;'; foreach( $ids as $id ) { $link = wp_get_attachment_url( $id ); $attachment_meta = wp_get_attachment($id); $class = ( $i == 0 ) ? 'active ' : ''; $i++; $html .= '&lt;div class="item '.$class. '"&gt;&lt;img src="' . $link . '"&gt;' . '&lt;div class="carousel-caption"&gt;&lt;h4&gt;'.$attachment_meta['title'].'&lt;/h4&gt;&lt;p&gt;'.$attachment_meta['description']. '&lt;/p&gt;&lt;/div&gt;&lt;/div&gt;'; } $html .= '&lt;/div&gt;'; echo $html;} </code></pre>
[]
[ { "body": "<p>IMO, clean wp code is hard, if not impossible to acchieve. I can tell you, however, that the first thing I'd remove from your functions is the <code>echo $html;</code> statements.</p>\n\n<p>A function is a block of code that does something, and <em>returns that data</em>, to be used anywhere. Your functions don't return anything (apart from the implicit <code>null</code>), but echo a heck of a lot. That could be considered a side-effect. Functions that have side-effects are bad news. Why not replace the <code>echo $html;</code> with a simple <code>return $html;</code> for a start, then call the functions like so:</p>\n\n<pre><code>&lt;?=function_slides();?&gt;\n</code></pre>\n\n<p><code>&lt;?=</code> is short for <code>&lt;?php echo</code>, and doesn't require the short_tags to be enabled anyway.<br/>\nThis is only the tip of the ice-berg, though. Your functions contain an awful lot of duplicate statements (<code>$special_gallery = get_post_gallery( $post, false )</code>, for one). Why not pass that as an argument, so you can keep it in scope for all calls, and avoid the overhead of repeating the same function calls?<Br/>\nWhat's more: the entire function <em>bodies</em> of both <code>function_slides</code> and <code>function_indicators</code> are remarkably similar, and could easily be combined into a single function:</p>\n\n<pre><code>function functions_slide_indicator($post) //specify argument, you forgot this\n{\n $special_gallery = get_post_gallery( $post, false );\n $ids = explode( \",\", $special_gallery['ids'] );\n $formats = array(\n 'indicator' =&gt; '&lt;li data-target=\"#carousel-example-generic\" data-slide-to=\"%d\"&gt;&lt;/li&gt;',\n 'slide' =&gt; '&lt;div class=\"item\"&gt;&lt;img src=\"%s\"&gt;&lt;div class=\"carousel-caption\"&gt;&lt;h4&gt;%s&lt;/h4&gt;&lt;p&gt;%s&lt;/p&gt;&lt;/div&gt;&lt;/div&gt;'\n );\n $html = array(\n 'indicator' =&gt; '&lt;ol class=\"carousel-indicators\"&gt;&lt;li data-target=\"#carousel-example-generic\" data-slide-to=\"0\" class=\"active\"&gt;&lt;/li&gt;',\n 'slide' =&gt; '&lt;div class=\"carousel-inner\"&gt;'\n );\n $link= wp_get_attachment_url($ids[0]);//get data for first id, not in loop\n $attachment_meta = wp_get_attachment($ids[0]);\n $html['slide'] .= sprintf(str_replace('&lt;div class=\"item\"', '&lt;div class=\"active item\"', $formats['slide']), $link, $attachment_meta['title'], $attachment_meta['description']);\n for($i = 1, $j = count($ids);$i&lt;$j;$i++)\n {//start at 1, not 0, so no active class in here\n $link = wp_get_attachment_url( $ids[$i] );\n $attachment_meta = wp_get_attachment($ids[$i]);\n $html['indicator'] .= sprintf($formats['indicator'], $i);// no need to increment/decrement it here, it'll be the value you need\n $html['slide'] .= sprintf($formats['slide'],$link, $attachment_meta['title'], $attachment_meta['description']);\n }\n $html['indicator'] .= '&lt;/ol&gt;';\n $html['slide'] .= '&lt;/div&gt;';//close markup\n return $html;//return array\n}\n</code></pre>\n\n<p>Call this like so:</p>\n\n<pre><code>&lt;?php\n $content = functions_slide_indicator($post);\n echo $content['indicator'];//indicators\n echo $content['slide'];//carousel\n</code></pre>\n\n<p>Of course, this is only the start, instead of calling that function in the loop, I'd personally go for:</p>\n\n<pre><code>$links = array_map($ids, 'wp_get_attachment_url');\n</code></pre>\n\n<p>For example. Though this isn't the most performant way to go, at least it <em>looks</em> cleaner, though it could look cleaner still, if you used <em>Objects</em>. </p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-09-04T11:38:46.913", "Id": "48902", "Score": "0", "body": "Thank you very much for your support! I'm gonna modify and probe it ;)" } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-09-04T09:21:34.013", "Id": "30758", "ParentId": "30736", "Score": "2" } } ]
{ "AcceptedAnswerId": "30758", "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-09-03T14:02:54.960", "Id": "30736", "Score": "1", "Tags": [ "php", "optimization" ], "Title": "Bootstrap 3.0 Carousel gallery post WordPress" }
30736
<p>I wrote this program which takes all the bits in a number and shifts them to the left end (for example: 01010110 --> 11110000). It's and exercise from a book. It works, but it seems to be very wasteful to use integers (I only need 8 bits). </p> <p>Can you tell me if the code is proper or not? Is the algorithm good?</p> <pre><code>#include &lt;iostream&gt; void print_bit(const int bit) { for(int i = 0x80; i != 0; i &gt;&gt;= 1) { if((bit &amp; i) != 0) std::cout &lt;&lt; "1"; else std::cout &lt;&lt; "0"; } std::cout &lt;&lt; std::endl; } int set_bits(const int bit) { int lefted = 0xFF; for(int i = 0x80; i != 0; i &gt;&gt;= 1) { if((bit &amp; i) == 0) lefted &lt;&lt;= 1; } return lefted; } int main() { int bit = 11; print_bit(bit); print_bit(set_bits(bit)); return 0; } </code></pre>
[ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-09-04T02:54:27.483", "Id": "48879", "Score": "2", "body": "It's a good algorithm. The code is not bad. I agree with most of what Jamal says, but I don't like combining the `if` with its body on a single line. The standard puts a space between the keywords like `for` and `if` and the open parenthesis; you should too. Your `print_bit()` function should not include the newline; it makes it hard to use in a more general case, such as a loop ranging from 0 to 255 (inclusive) and printing 4 pairs of entries per line of output. It would be better to have the printing function just output the binary value and then have the calling code do the punctuation." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-09-04T05:30:38.287", "Id": "48884", "Score": "0", "body": "@JonathanLeffler: Good point about the single line thing. Although I think using a single line is okay at times, this may not be one of them. I'll change that, along with some other things." } ]
[ { "body": "<p>It appears the correct results are given, which is good. I do see some miscellaneous things, though.</p>\n\n<ul>\n<li><p>The naming and execution in <code>main()</code> seem confusing. Try something like this:</p>\n\n<pre><code>int main()\n{\n // the name \"bit\" is misleading; you're using an integer\n // name it something more accurate (this is just an idea)\n int original = 11;\n\n // why not return the final (shifted) integer?\n // sticking set_bit() into print_bit() is hard to read\n int final = set_bits(original);\n\n // print both integers\n print_bit(original);\n print_bit(final);\n}\n</code></pre></li>\n<li><p>This:</p>\n\n<pre><code>if((bit &amp; i) != 0)\nstd::cout &lt;&lt; \"1\";\nelse std::cout &lt;&lt; \"0\";\n</code></pre>\n\n<p>could become a single-line ternary statement:</p>\n\n<pre><code>// read as: (statement is true?) ? (if so, do this) : (if not, do this)\nstd::cout &lt;&lt; ((bit &amp; i) != 0) ? \"1\" : \"0\";\n</code></pre></li>\n<li><p>This:</p>\n\n<pre><code>if((bit &amp; i) == 0)\n lefted &lt;&lt;= 1;\n</code></pre>\n\n<p>could have curly braces (to allow any additional code for the body):</p>\n\n<pre><code>if ((bit &amp; i) == 0)\n{\n lefted &lt;&lt;= 1;\n}\n</code></pre></li>\n<li><p>I'd probably make your \"magic numbers\" (such as <code>0x80</code>) constants. This could help provide more context for your code, especially when there's no relevant documentation.</p></li>\n<li><p><code>std::cout &lt;&lt; std::endl;</code> doesn't need to be in <code>print_bit()</code>. The display function should only print the values; that's what the user expects. If you want a newline with the displaying, put it around the calling code. That way, the displaying will be easier to adjust.</p></li>\n</ul>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-09-03T18:06:53.230", "Id": "30744", "ParentId": "30740", "Score": "3" } } ]
{ "AcceptedAnswerId": "30744", "CommentCount": "2", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-09-03T15:37:06.687", "Id": "30740", "Score": "3", "Tags": [ "c++", "algorithm", "bitwise" ], "Title": "Take all the bits in a number and shift them to the left end" }
30740
<p>I have a <code>defaultdict</code> being written to file like this:</p> <pre><code>writer = csv.writer(open(locationToSaveFile, 'wb+')) for k,v in dict.iteritems(): writer.writerow([k ,v]) </code></pre> <p>I then have this horribly convoluted text to read it back in:</p> <pre><code>myDict = defaultdict(list) with open(fileLocation, 'rb') as test: reader = csv.DictReader(test, ['processedText', 'date']) for line in reader: myDict[line['processedText']].append(line['date']) textDict = defaultdict(list) for processedText, date in myDict.items(): actual_list = ast.literal_eval(date[0]) for a in actual_list: textDict[processedText].append(a) for processedText, date in textDict.items(): </code></pre> <p>Obviously this looks very wasteful (and looks horrible!) but I don't know how else to import the <code>defaultdict</code>.</p> <p>When opening it with the <code>reader =</code> and <code>for line in reader</code> lines it creates a list within a list. The only way out of this is to use <code>ast</code> to convert it.</p> <p>Could somebody advise me how to tidy this up?</p> <p>Note: I'm <em>very</em> unfamiliar with Python</p>
[]
[ { "body": "<p><code>csv</code> is meant to store rows of data, not a simple dictionary. You can use <a href=\"http://docs.python.org/2/library/json.html\" rel=\"nofollow\"><code>json</code></a> for that:</p>\n\n<pre><code>import json\n\n# writing\njson.dump(yourdict, open(filename, 'w'))\n\n# reading\nyourdict = json.load(open(filename))\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-09-03T16:56:44.910", "Id": "48851", "Score": "0", "body": "How do I read it back from JSON. I can write it using json.dump(filelocation, defaultdict). But how do I import it again?" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-09-08T12:19:12.660", "Id": "49261", "Score": "0", "body": "Andrew, use json.load(filelike_object)" } ], "meta_data": { "CommentCount": "2", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-09-03T16:55:11.903", "Id": "30742", "ParentId": "30741", "Score": "4" } }, { "body": "<p>Your dict's values are lists. A possible approach is to expand those lists into csv columns, producing a file where the number of columns varies from row to row:</p>\n\n<pre><code>#writing\nwith open(locationToSaveFile, 'w') as f:\n writer = csv.writer(f) \n for k,v in mydict.iteritems():\n writer.writerow([k] + v)\n\n#reading\nwith open(locationToSaveFile, 'r') as f:\n reader = csv.reader(f) \n mydict = collections.defaultdict(list)\n for row in reader:\n mydict[row[0]] = row[1:]\n</code></pre>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-09-04T06:21:07.640", "Id": "30753", "ParentId": "30741", "Score": "0" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-09-03T16:38:08.830", "Id": "30741", "Score": "2", "Tags": [ "python", "csv" ], "Title": "Writing defaultdict to CSV file" }
30741
<p>Consider the query given below:</p> <pre><code>SELECT * FROM ((SELECT c.cust_id , c.username , REPLACE(qs.seg_type_ref_key_02, 'N/A', 'Non Vip') casino_group, REPLACE(qs.seg_type_ref_key_03, 'N/A', 'Non Vip') bingo_group, REPLACE(qs.seg_type_ref_key_04, 'N/A', 'Non Vip') games_group, REPLACE(qs.seg_type_ref_key_12, 'N/A', 'Non Vip') poker_group, REPLACE(qs.seg_type_ref_key_01, 'N/A', 'Non ViP') sportsbook_group, c.country , c.contactable , c.email , c.dob , c.[status] , c.first_name , c.last_name , c.[master] , c.[language] , c.gender FROM warehouse.dbo.dim_customer c (nolock) INNER JOIN warehouse . dbo . dim_segmentationcodehistory ( nolock )sc ON sc . cust_id = c . cust_id INNER JOIN warehouse . dbo . q_dim_segments qs ( nolock ) ON sc . seg_code_ref_key = qs . seg_code_ref_key WHERE SC.active=1 and qs.seg_type_ref_key_04 &lt;&gt;'N/A' AND c.active = 1 and (qs.seg_type_ref_key_02 &lt;&gt; 'Prospect' and qs.seg_type_ref_key_03 &lt;&gt; 'Prospect' and qs.seg_type_ref_key_04 &lt;&gt; 'Prospect' and qs.seg_type_ref_key_12 &lt;&gt; 'Prospect' and qs.seg_type_ref_key_01 &lt;&gt; 'Prospect')) A LEFT JOIN( SELECT c.cust_id cust_dup, SUM(fc.turnover) AS Turnover_GBP, SUM(fc.grosswin) AS GrossWin_GBP, SUM(fc.chip_purch_amount_gbp) AS chip_purch_amount_gbp FROM warehouse.dbo.fact_games fc (nolock) INNER JOIN warehouse.dbo.dim_date d (nolock) ON d.date_key = fc.date_ref_key INNER JOIN warehouse.dbo.dim_customer c (nolock) ON c.cust_ref_key = fc.cust_ref_key INNER JOIN warehouse.dbo.dim_gamesgame gg(nolock) ON gg.games_game_ref_key = fc.game_ref_key WHERE d.[date] between getdate()- 10 AND getdate()-9 AND gg.Game_Group_Description &lt;&gt; 'Bingo' GROUP BY c.cust_id )B ON A.cust_id = B.cust_dup) </code></pre> <p>This query takes a little more than an hour. However, I require that this completes in as little time as possible.</p> <p>Below is the level to which I have been able to optimize it:</p> <pre><code>IF OBJECT_ID('tempdb..#temp_shash_A') IS NOT NULL DROP TABLE #temp_shash_A IF OBJECT_ID('tempdb..#temp_shash_B') IS NOT NULL DROP TABLE #temp_shash_B -- A (SELECT c.cust_id , c.username , REPLACE(qs.seg_type_ref_key_02, 'N/A', 'Non Vip') casino_group, REPLACE(qs.seg_type_ref_key_03, 'N/A', 'Non Vip') bingo_group, REPLACE(qs.seg_type_ref_key_04, 'N/A', 'Non Vip') games_group, REPLACE(qs.seg_type_ref_key_12, 'N/A', 'Non Vip') poker_group, REPLACE(qs.seg_type_ref_key_01, 'N/A', 'Non ViP') sportsbook_group, c.country , c.contactable , c.email , c.dob , c.[status] , c.first_name , c.last_name , c.[master] , c.[language] , c.gender INTO #temp_shash_A FROM warehouse.dbo.dim_customer c (nolock) INNER JOIN warehouse . dbo . dim_segmentationcodehistory ( nolock )sc ON sc . cust_id = c . cust_id INNER JOIN warehouse . dbo . q_dim_segments qs ( nolock ) ON sc . seg_code_ref_key = qs . seg_code_ref_key WHERE SC.active=1 and qs.seg_type_ref_key_04 &lt;&gt;'N/A' AND c.active = 1 and (qs.seg_type_ref_key_02 &lt;&gt; 'Prospect' and qs.seg_type_ref_key_03 &lt;&gt; 'Prospect' and qs.seg_type_ref_key_04 &lt;&gt; 'Prospect' and qs.seg_type_ref_key_12 &lt;&gt; 'Prospect' and qs.seg_type_ref_key_01 &lt;&gt; 'Prospect') ) create clustered index S_1 on #temp_shash_A (cust_id) -- B ( SELECT c.cust_id cust_dup, SUM(fc.turnover) AS Turnover_GBP, SUM(fc.grosswin) AS GrossWin_GBP, SUM(fc.chip_purch_amount_gbp) AS chip_purch_amount_gbp INTO #temp_shash_B FROM warehouse.dbo.fact_games fc (nolock) INNER JOIN warehouse.dbo.dim_date d (nolock) ON d.date_key = fc.date_ref_key INNER JOIN warehouse.dbo.dim_customer c (nolock) ON c.cust_ref_key = fc.cust_ref_key INNER JOIN warehouse.dbo.dim_gamesgame gg(nolock) ON gg.games_game_ref_key = fc.game_ref_key WHERE d.[date] between getdate()- 10 AND getdate()-9 AND gg.Game_Group_Description &lt;&gt; 'Bingo' GROUP BY c.cust_id ) create clustered index S_2 on #temp_shash_B (cust_dup) SELECT * FROM #temp_shash_A A LEFT JOIN #temp_shash_B B ON A.cust_id = B.cust_dup </code></pre> <p>This took just around 5-6 minutes when ran initially. However, it took around 35 minutes when ran today. Can anyone suggest a way for me to optimize this? Any help appreciated.</p> <p>PS: I'm working on SQL Server 2008 R2 DB. The query is a dataset query for an SSRS report.</p>
[ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-09-03T18:43:23.783", "Id": "48860", "Score": "0", "body": "Consider also: http://dba.stackexchange.com/" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-09-03T18:51:27.513", "Id": "48862", "Score": "0", "body": "Hi Jamal, I've no experience with SQL Server but that looks like it is doing a a lot! Is there an equivalent of the `Explain` function that can tell your what the DB engine is going to do in order to execute your query? Have you isolated which steps are taking the time (i.e run A in standalone, run A and created index on it...)? What indexes exist on the tables that you are not creating? How big is the dataset? What hardware are you running on?" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-09-04T08:58:22.027", "Id": "48890", "Score": "0", "body": "@JohnMark13 -> The part A take smore time than part B. My hardware is a normal Windows Laptop 32 bit. Indexes I am creating manuaaly in my query itself. ANd about Explain I'm not sure. let me find out and let u know" } ]
[ { "body": "<p>From some research, I have found the <code>&lt;&gt;</code> or <code>does not equal</code> takes longer to run than <code>=</code> operations</p>\n\n<p>In <a href=\"https://stackoverflow.com/a/7419299/1214743\">this answer to <code>SQL Server “&lt;&gt;” operator is very slow compared to “=” on table with a few million rows</code></a> the Poster goes into Detail about the <code>&lt;&gt;</code> operator and why it takes longer than the <code>=</code> operator.</p>\n\n<p>The Poster suggests a <code>LEFT JOIN</code> for the OP's Query that would make it so that they shouldn't have to use the <code>&lt;&gt;</code> operator.</p>\n\n<p>If you could do something similar to weed out the records that you don't want using a <code>LEFT JOIN</code> or something of the sort. I think the post that I linked to should set you in the right direction.</p>\n\n<p><strong>P.S.</strong></p>\n\n<p>It sounds like the same thing happens when you use <code>NOT IN</code></p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-10-29T14:21:44.130", "Id": "33461", "ParentId": "30745", "Score": "2" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "3", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-09-03T18:27:44.103", "Id": "30745", "Score": "3", "Tags": [ "optimization", "performance", "sql", "sql-server" ], "Title": "Querying a warehouse database" }
30745
<p>Today I decided to get into F#. I watched <a href="http://channel9.msdn.com/Blogs/pdc2008/TL11" rel="nofollow noreferrer">this video</a> and had a bit of fun doing some coding examples, I can see that it will be very useful for certain programs that I write. </p> <p>One thing that I was interested in are the explicit member constraints and how they might be used to help with the generic constructor limitation (see <a href="https://stackoverflow.com/a/18565782/746754">here</a> for a summary of the limitation and why none of the current workarounds are adequate). </p> <p>My requirements were: -</p> <ol> <li>That the solution was compile-time safe, i.e. if I add a new parameter to a constructor or method that it won't suddenly fall over at runtime. (This is a problem with a number of the existing workarounds to the problem).</li> <li>That I could know the real type several functions / classes away from where the instance was created. I have an example that makes this clearer.</li> </ol> <p>Anyway, armed with a day of F# knowledge I went delving into explicit member contstraints and statically resolved type parameters and came up with this which seems to work fine (and is the code to review):</p> <pre><code>module FSharpTestModule = let inline createInstance&lt; ^a when ^a : (static member CreateInstance : int -&gt; ^a) &gt;(i:int) = (^a : (static member CreateInstance : int -&gt; ^a)(i)) </code></pre> <p>This will call the static member CreateInstance on the type ^a of which the result will be ^a provided that ^a has a static member CreateInstance that takes an int and returns an ^a. Best described with an example:</p> <pre><code>type GoodFoo(a) = let _a = a static member CreateInstance(a) = new GoodFoo(a) member this.Add(b) = _a + b type BadFoo() = static member CreateInstance() = new BadFoo() member this.Add(a, b) = a + b type TestSimple() = static member public DoSomething() = //let badFoo = FSharpTestModule.createInstance&lt;BadFoo&gt;(1) //This line does not compile - excellent let goodFoo = FSharpTestModule.createInstance&lt;GoodFoo&gt;(1) goodFoo </code></pre> <p>Requirement 1: From this we can see that BadFoo causes a compile time error in createInstance because it has the wrong signature, which is good. Of course, if I added a new parameter to the constructor of GoodFoo, I would have to add the parameter in GoodFoo.CreateInstance which would mean that GoodFoo would cause a similar compile time error which is what I want. </p> <p>Requirement 2: It is possible to to know the type a few hops back down the chain. For example, if we add the following:</p> <pre><code>type Factory&lt;'T when 'T : (static member CreateInstance : int -&gt; 'T)&gt;() = member inline this.Create(i : int) = FSharpTestModule.createInstance&lt;'T&gt;(i) type TestIntermediate&lt;'T when 'T : (static member CreateInstance : int -&gt; 'T)&gt;() = member inline this.DoSomething() = //normally you would do some things here... //ok, lets create the generic type let factory = new Factory&lt;'T&gt;() let ffoo = factory.Create(1) //normally you would do some things here... //lets return it ffoo //This class knows about the real FGoodFoo type Test() = static member public DoSomethingFirst() = //let badFoo = new TestIntermediate&lt;BadFoo&gt;() //This line does not compile - excellent let test = new TestIntermediate&lt;GoodFoo&gt;() let goodFoo = test.DoSomething() goodFoo </code></pre> <p>Then it can be seen that the type is known by Test. TestIntermediate and Factory have no knowledge of the real type only the constraint and the instance is created by createInstance in Factory which is a couple of hops down the chain. </p> <p>So, my questions are: </p> <ol> <li>Is this a good approach or fraught with dangers? If so, what are they? Something I know already is that this does not play well with C#. In C# if I call createaInstance even with GoodFoo as a template type, I get a NotSupportedException and no compile time errors for BadFoo. Which makes me wonder if this is something that you need to be wary of when mixing C# and F# - classes/functions with explicit member constraints.</li> <li>Are there better ways of doing this (for example using delegate constraints)? I noticed that inline starts bubbling through my code, which I guess will increase the size of the resultant executable. </li> </ol> <p><em>Response for Daniel</em></p> <p>This is great for treating a constructor like a function, but doesn't quite fit in this case. For example:</p> <pre><code>type GoodFoo(x:int) = class end let inline New x = (^T : (new : ^U -&gt; ^T) x) let f (g: int -&gt; 'T) = g 0 type Test2&lt;'V&gt;() = //let f (g: int -&gt; 'Z) = g 0 member inline public this.DoSomething() = //normally you would do some things here //let newFoo = f New&lt;_,'V&gt; let v = f New&lt;_,'V&gt; //normally you would do some things here () type Test() = member public this.DoSomething() = let t2 = new Test2&lt;GoodFoo&gt;() t2.DoSomething() () </code></pre> <p>will result in the error for the line <code>type Test2&lt;'V&gt;() =</code>: </p> <blockquote> <p>The signature and implementation are not compatible because the declaration of the type parameter 'V' requires a constraint of the form ^V : (( .ctor ) : int -> ^V)</p> </blockquote> <p>Unfortunately, it is not possible to constrain a generic by a constructor requiring an argument, which is the problem I am trying to solve. I could pass the function as a parameter, but that is already a known workaround that I was trying to avoid. Or is it possible to use this constraint in some way?</p>
[ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-09-04T05:58:44.197", "Id": "48886", "Score": "0", "body": "I don't understand why this is a problem, i.e. I think you're making this more complicated than it really is... Just pass a function." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-09-04T06:06:19.993", "Id": "48887", "Score": "0", "body": "Thanks, yes I maybe I am overboiling things. Agree, passing a function is probably the best of the suggested options, but then you end up passing a function around to interim classes / methods that don't need to know about it. With this approach you still have to put a constraint on the class, but it is done in one place on the class and you don't need to think about it each time you look at the method flow." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-09-06T03:45:41.327", "Id": "49106", "Score": "0", "body": "I would just add that this limitation is not particular to me as per the referenced link and: http://visualstudio.uservoice.com/forums/121579-visual-studio/suggestions/2122427-expand-generic-constraints-for-constructors" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2015-12-15T19:30:18.583", "Id": "211322", "Score": "0", "body": "FYI: in F# 4.0, constructors can be passed as first-class functions, perhaps offering a different / easier solution to problems like these." } ]
[ { "body": "<p>If you're trying to work around the inability to pass a constructor as a first-class function, here's a simpler approach:</p>\n\n<pre><code>let inline New x = (^T : (new : ^U -&gt; ^T) x)\n\n// a function that takes a 'constructor' function\nlet f (g: int -&gt; 'T) = g 0\n\ntype T(i:int) = class end\n\n// call it using the 'New' wrapper\nf New&lt;_,T&gt; //use wildcard to have the constructor arg type inferred\n</code></pre>\n\n<h3>UPDATE</h3>\n\n<p>Class type args require explicit constraints. The error is caused by the use of <code>New</code> implying a different set of constraints than those specified on the class (i.e. none). <code>New</code> is nothing more than a mechanism for passing constructors as first-class functions. If you could change your type to accept a \"factory\" function, you could do this:</p>\n\n<pre><code>type Test2&lt;'V&gt;(factory) =\n //let f (g: int -&gt; 'Z) = g 0 \n member inline public this.DoSomething() = \n //normally you would do some things here\n //let newFoo = f New&lt;_,'V&gt;\n let v : 'V = f factory\n //normally you would do some things here\n ()\n\ntype Test() = \n member public this.DoSomething() =\n let t2 = new Test2&lt;GoodFoo&gt;(New)\n t2.DoSomething()\n ()\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-09-04T15:27:04.993", "Id": "48940", "Score": "0", "body": "Thanks. That looks very interesting on first glance, I will take a closer look later on." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-09-05T03:05:48.400", "Id": "48997", "Score": "0", "body": "I had a look at the code and tried it out, but unless I am missing something it doesn't quite fit what I need. Please see my edited question with _Response for Daniel_. Apologies if I am missing something obvious, I am quite new to this." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-09-05T14:30:17.327", "Id": "49036", "Score": "0", "body": "I included a response to your update in my answer." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-09-06T03:39:15.853", "Id": "49104", "Score": "0", "body": "Thanks Daniel, it is as I thought - can be passed around or a global instantiator. This is the best existing workaround, I was working on something a bit different which is a generic type constraint similar to the new() constraint. I would vote this up as it has been useful for me to know, but I don't have enough rep yet on code review to +1. Will vote up when I do." } ], "meta_data": { "CommentCount": "4", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-09-04T14:28:09.873", "Id": "30775", "ParentId": "30752", "Score": "2" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "4", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-09-04T03:03:11.957", "Id": "30752", "Score": "1", "Tags": [ "f#" ], "Title": "F# solution to generic new() constraint limitation" }
30752
<p>To execute tasks sequentially with a timeout I use <code>ExecutorService.submit()</code> and <code>Future.get()</code>. As I don't want to block calling clients, I implement producer–consumer pattern with a queue into a Thread while(true) loop:</p> <pre><code>import java.util.concurrent.ExecutionException; import java.util.concurrent.ExecutorService; import java.util.concurrent.Executors; import java.util.concurrent.Future; import java.util.concurrent.LinkedBlockingQueue; import java.util.concurrent.TimeUnit; import java.util.concurrent.TimeoutException; public class ExecutorWithQueue { private int timeout = 1; private TimeUnit timeoutUnit = TimeUnit.SECONDS; private LinkedBlockingQueue&lt;Task&gt; queue = new LinkedBlockingQueue&lt;Task&gt;(); ExecutorService executor = Executors.newSingleThreadExecutor(); private TaskProcessor taskProcessor = new TaskProcessor(); public ExecutorWithQueue(int timeout, TimeUnit timeoutUnit) { this.timeout = timeout; this.timeoutUnit = timeoutUnit; taskProcessor.start(); } public void push(Task task) { queue.add(task); } class TaskProcessor extends Thread { public void run() { while (true) { try { final Task queueTask = queue.take(); Future&lt;Boolean&gt; future = executor.submit(queueTask); try { future.get(timeout, timeoutUnit); } catch (TimeoutException e) { System.out.println("TimeoutException"); } catch (ExecutionException e) { System.out.println("ExecutionException"); } } catch (InterruptedException e) { break; } } executor.shutdownNow(); } } } </code></pre> <p>I have two unit tests. The first to check if task is executed, the second to check that a task that takes two long doesn't block the execution flow:</p> <pre><code>import static java.util.concurrent.TimeUnit.MILLISECONDS; import static org.junit.Assert.assertEquals; import org.junit.Test; public class TestExecutorWithQueue { ExecutorWithQueue executor = new ExecutorWithQueue(9, MILLISECONDS); @Test public void fastTaskIsExecuted() throws Exception { assertExecuted(0, true); } @Test public void slowTaskIsNotExecuted() throws Exception { assertExecuted(50, false); } public void assertExecuted(int waiting, boolean expected) throws InterruptedException { WaitingTask task = new WaitingTask(waiting); executor.push(task); Thread.sleep(100); assertEquals(expected, task.executed); } class WaitingTask implements Task { boolean executed; int seconds_to_wait; public WaitingTask(int milliseconds_to_wait) { this.executed = false; this.milliseconds_to_wait = milliseconds_to_wait; } @Override public Boolean call() throws Exception { Thread.sleep(this.milliseconds_to_wait); this.executed=true; return executed; } } } </code></pre> <p>What do you think of this code? </p>
[]
[ { "body": "<p><strong>TaskProcessor</strong></p>\n\n<ul>\n<li>I see little reason why this should extend <code>Thread</code>, rather than simply implement <code>Runnable</code></li>\n<li>as a thread it <em>is</em> responsive to interruption, yet there is no way a client can interrupt this thread, through API nor directly. No, I'm mistaken, a client could push a task that interrupts its own thread, yet that is not an obvious way to shut it down, nor a clean one (as the <code>ExecutorWithQueue</code> will not know its executor has stopped working).</li>\n<li>I would replace <code>while (true)</code> with <code>while (!Thread.currentThread().isInterrupted())</code></li>\n<li>I'm not happy with the way the ExecutionException is eaten. Clients have no way to know about the Exception that occurred in the Task.</li>\n<li>As an extension of the previous point : you deny your clients the benefits of a <code>Future</code> to monitor their submitted tasks.</li>\n<li>you accept only Tasks, yet tere is no reason you couldn't handle all Callables.</li>\n</ul>\n\n<p><strong>ExecutorWithQueue</strong></p>\n\n<ul>\n<li><code>taskProcessor</code> does not need to be a field</li>\n<li>The values supplied to <code>timeout</code> and <code>timeoutUnit</code> in their declaration are always overwritten in the constructor. If you omit these initialization, you can make them final.</li>\n<li>the <code>queue</code> and <code>executor</code> fields can also be final.</li>\n</ul>\n\n<p><strong>Test</strong></p>\n\n<ul>\n<li>Fiddling with sleep() is error prone. The test can fail if the sleep is too short, and all the time that the test sleeps in excess of what is needed delays the swift completion of the unit test suite. (in projects with many thread safety tests this can really make the total suite of tests too slow). Timing combinations are often more reliably simulated using <code>CountDownLatch</code>es, and these will never take longer than needed.</li>\n<li>I find it good practice to add a timeout value to the <code>@Test</code> annotation for these kinds of tests. If at some point deadlock or so occurs, the test will fail gracefully, rather than hold up the test server.</li>\n</ul>\n\n<p><strong>Semantics</strong></p>\n\n<p>I'm completely puzzled by what this class is intended to do. All submitted tasks will simply be executed in sequence. But that could simply be achieved by submitting them to an ExecutorService with just one thread, which already uses a queue to store tasks it has yet to run. When the timeout passes and the task isn't finished, you submit the next task, which will simply be queued by the underlying <code>ExecutorService</code> until the timed out task has finished. I suspect you somehow think the timeout will cancel the task, but it won't. If that is your intention, you'll need to add cancelling logic to handle a timeout, if it isn't there doesn't seem to be much point in this class.</p>\n\n<p>The second test seems to assert that a timed out task does not execute. Yet it only asserts this after having slept a certain amount of time. If you increase the sleep time enough, the assertion will fail. (this is another argument pro <code>CountDownLatch</code> as that will communicate the test's intention better).</p>\n\n<p>Hope you found this useful.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-09-05T18:14:13.477", "Id": "49051", "Score": "0", "body": "I'm trying to implement a \"*fire and forget*\" behavior in my `push()` method and `future.get()` blocks the submission of other task until completion." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-09-05T18:31:28.940", "Id": "49056", "Score": "0", "body": "Nothing forces you to call `future.get()` prior to submitting all tasks, or to call it at all." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-09-06T08:12:10.710", "Id": "49113", "Score": "0", "body": "Some of my tasks never end. I need to set a timeout to prevent them from blocking the next tasks. `Future.get()` has a timeout, `executor.submit()` hasn't." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-09-06T09:08:09.540", "Id": "49117", "Score": "1", "body": "Then your current code does not achieve that, since simply waiting until a certain timeout on the `Future` does not cancel the corresponding task in case of a timeout. You can call `Future.cancel()` and those tasks should be responsive to interruption." } ], "meta_data": { "CommentCount": "4", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-09-04T17:29:50.387", "Id": "30782", "ParentId": "30756", "Score": "4" } } ]
{ "AcceptedAnswerId": "30782", "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-09-04T07:59:31.453", "Id": "30756", "Score": "4", "Tags": [ "java", "unit-testing", "concurrency", "multithreading" ], "Title": "Unit test an ExecutorService in a deamon" }
30756
<p>I needed to perform network communications in my Linux C++ project. I thought that it was a good idea to operate on a higher level of abstraction than raw system calls. Also I love OO design. So I'm implementing an <a href="https://github.com/Kolyunya/Unet/tree/master/src" rel="nofollow">object-oriented high-level Unix network open-source library</a> (There are issues with tab-size if you watch source code on github, but the tabs are aligned well if watching in a text editor).</p> <p>At the moment the library is partially implemented and is in a process of development. I've already tested some parts of it in real project and I find it's high level of abstraction extremely convenient.</p> <p>The library checks all system calls for errors, so user shouldn't worry about checking every function's return status (thou exception system is still under construction). It allows easily convert socket addresses and strings in both directions. <a href="https://github.com/Kolyunya/unet/blob/master/src/Socket/Socket/Socket/src/Socket.hpp" rel="nofollow">Socket</a> classes provide convenient methods to get and set their properties, messages are sent and received as strings. TCP socket can recieve messages separated by terminator character or messages determined by required message size e.t.c.</p> <p><strong>I would like to know community's opinion if I made some design or implementation mistakes, if there could be done some improvements and if the library could be useful in some way to somebody. Any feedback is appreciated.</strong></p> <p>Here is a working example of a UDP echo-server implementation using my library.</p> <pre><code>#include &lt;iostream&gt; #include &lt;Unet/UdpSocket.hpp&gt; #include &lt;Unet/Ipv4Address.hpp&gt; int main ( int argc , char** argv ) { // Check program parameters to be provided if ( argc != 3 ) { std::cout &lt;&lt; "Usage: UdpEchoServer $(SERVER_IP) $(SERVER_PORT)" &lt;&lt; std::endl; return -1; } // Create and open UDP socket with Internet family address Unet::UdpSocket socket; socket.open(); std::cout &lt;&lt; "Server socket was opened successfully." &lt;&lt; std::endl; // Set server socket to reuse address socket.setOption(SO_REUSEADDR,1); std::cout &lt;&lt; "Server socket option \"SO_REUSEADDR\" was set to \"1\"." &lt;&lt; std::endl; // Bind socket to the specified local address socket.bind(Unet::Ipv4Address(argv[1],argv[2])); std::cout &lt;&lt; "Server socket was bound successfully." &lt;&lt; std::endl; // Datagram which will be recieved and sent back Unet::Datagram datagram; while ( true ) { try { if ( socket.hasUnreadData() ) { // Recieve incomming datagram datagram = socket.recieveDatagram(); std::cout &lt;&lt; "[ &lt;-- ] [" &lt;&lt; Unet::Ipv4Address(datagram.address).toString() &lt;&lt; "] - " &lt;&lt; datagram.message &lt;&lt; std::endl; // And send it back socket.sendDatagram(datagram); std::cout &lt;&lt; "[ --&gt; ] [" &lt;&lt; Unet::Ipv4Address(datagram.address).toString() &lt;&lt; "] - " &lt;&lt; datagram.message &lt;&lt; std::endl; } } // Catch and print all exceptions catch ( Unet::Exception exception ) { std::cout &lt;&lt; "Unet exception: " &lt;&lt; exception.getMessage() &lt;&lt; std::endl; } catch ( std::exception exception ) { std::cout &lt;&lt; "Standard exception: " &lt;&lt; exception.what() &lt;&lt; std::endl; } catch ( ... ) { std::cout &lt;&lt; "Unknown exception" &lt;&lt; std::endl; } } } </code></pre> <p><br> P.S. I'm not a Linux specialist, so I doubt which name to choose for the library <code>Unix-net</code>, <code>Linux-net</code> or <code>Posix-net</code>. Which is more appropriate and logical?</p>
[ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-09-04T19:17:12.377", "Id": "48970", "Score": "2", "body": "There are already a million of these. Writting your own is a bad idea as you have to fix all the same mistakes that have been fixed before. Don't re-invent the wheel find one that already works." } ]
[ { "body": "<p>As Loki stated: don't re-invent the wheel. In the interest of learning and sharing, here are some ideas to consider:</p>\n\n<pre><code>if ( argc != 3 )\n</code></pre>\n\n<p>Use an API already designed for parsing the command line. There must be dozens.</p>\n\n<pre><code>socket.setOption(SO_REUSEADDR,1);\n</code></pre>\n\n<p>Since this is an object, I would hide the dependency as follows:</p>\n\n<pre><code>socket.reuseAddress();\n</code></pre>\n\n<p>Since this is a networking object, I would prefer not to write the above statement at all. Rather, if the socket mustn't reuse the address, the API should provide a method to disable the behaviour.</p>\n\n<pre><code>socket.hasUnreadData()\n</code></pre>\n\n<p>A socket typically doesn't offer direct data reading and writing. The reason is that a <em>data stream</em> is a much more reusable concept. Were a developer to use your API, they would have to code functionality separately for reading from a socket vs. reading from a file. This restriction seems to limit the potential of software developed. Rather:</p>\n\n<pre><code>InputStream *dataIn = new SocketInputStream();\nOutputStream *dataOut = new SocketOutputStream();\nsocket.setSource( dataIn );\nsocket.setDestination( dataOut );\n</code></pre>\n\n<p>Now functionality can be written that reads data from any type of stream, making the source of the data independent (socket, file, database). If you absolutely must have the socket read/write datagrams, then use a terser method name:</p>\n\n<pre><code>socket.isReady()\n</code></pre>\n\n<p>This line:</p>\n\n<pre><code>socket.bind(Unet::Ipv4Address(argv[1],argv[2]));\n</code></pre>\n\n<p>Could be:</p>\n\n<pre><code>socket.bind(argv[1],argv[2]);\n</code></pre>\n\n<p>This simplifies the API for the developer. Otherwise all developers of the API will have to reference <code>Ipv4Address</code>. They shouldn't have to care. It's great to have the flexibility of putting in an Ipv6Address, but that can be handled automatically.</p>\n\n<p>Regarding the exception handling:</p>\n\n<pre><code> std::cout &lt;&lt; \"Unet exception: \" &lt;&lt; exception.getMessage() &lt;&lt; std::endl;\n std::cout &lt;&lt; \"Standard exception: \" &lt;&lt; exception.what() &lt;&lt; std::endl;\n</code></pre>\n\n<p>Having the API override <code>what()</code>, eliminates the duplication:</p>\n\n<pre><code> std::cout &lt;&lt; \"Exception: \" &lt;&lt; exception.what() &lt;&lt; std::endl;\n</code></pre>\n\n<p>The <code>what()</code> method will differentiate the exception classes in its message.</p>\n\n<p>One more pet peeve:</p>\n\n<pre><code>while ( true )\n</code></pre>\n\n<p>Since the program doesn't <em>actually</em> continue forever, the loop should have a logical termination condition that tells the next person reading the source code when the program actually terminates. Some examples:</p>\n\n<pre><code>while ( socket.isOpen() ) // Exit upon socket closure\nwhile ( isRunning() ) // Exit upon user request\nwhile ( !command.is( EXIT ) ) // Exit when the QUIT command is received\n</code></pre>\n\n<p>Regarding the bind method, consider the following pseudo-code:</p>\n\n<pre><code>void Socket::bind( String host, String port ) {\n Address *address = AddressFactory.newInstance( host );\n bind( address, atoi( port ) );\n}\n</code></pre>\n\n<p>Since the socket class already knows about <code>Unet::Ipv4Address</code>, adding a convenience method makes the class easier to use. Java gained popularity for a several reasons, including the simplicity of its networking API for trivial tasks. Using an AddressFactory, internally, will allow programs to work with either IPv4, IPv6, or any as-of-yet-invented protocol in the future. In C++, the application might have to be recompiled, but in Java, porting from IPv4 to IPv6 addresses has been mostly <a href=\"http://download.java.net/jdk8/docs/technotes/guides/net/ipv6_guide/index.html\" rel=\"nofollow\">transparent</a>.</p>\n\n<p>If developers are forced to hard-code a reference to IPv4 in their application, then they will have to do extra work to make the software use a different Internet Protocol version.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-12-19T07:28:18.820", "Id": "62605", "Score": "0", "body": "Thank you very much for your response. I agree with you in almost everything except the `socket.bind(argv[1],argv[2]);` idea. Socket could be bound to the Unix address which should be constructed from a single string. That is why the `bind` function expects a reference to an abstract address object. This also implements the dependency inversion principle. Bind is dependent on an abstract object. Regarding the `don't re-invent the wheel` this is an educational project which allowed me to increase my knowledge in C++ and network programming, so I believe I did not waste my time pointlessly." } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-12-19T04:08:30.137", "Id": "37720", "ParentId": "30761", "Score": "2" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "1", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-09-04T10:06:54.457", "Id": "30761", "Score": "3", "Tags": [ "c++", "object-oriented", "linux", "networking" ], "Title": "Object-oriented Linux networking library" }
30761
<p>The code below gets value from a column in an Excel sheet. The values I get are B1, B2, B3, B4...., B100, ...Bn. All I need to do is strip out the char 'B' and convert the numeric string to integer and count how many times a particular integer has repeated.</p> <p>The snippet below shows the string stripping the char 'B'. However I feel it can be done in better way but I don't know how.</p> <pre><code>if (range.Text.ToString() == "BayID") { range = null; range = readSheet.get_Range(cell, Missing.Value); while (range.Text.ToString() != "") { range = null; string A1 = String.Empty, Val = String.Empty; char[] value = null; range = readSheet.get_Range(cell, Missing.Value); A1 = range.Text.ToString(); value = A1.ToCharArray(); j++; cell = "D" + j; for (int i = 1; i &lt; value.Length; i++) { Val += value[i]; } } } </code></pre>
[ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-09-04T11:17:29.763", "Id": "48896", "Score": "0", "body": "I'm confused about the code, I think the end result of it is that it will do nothing. Also, have a look at the `Substring()` method." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-09-04T11:22:52.820", "Id": "48898", "Score": "0", "body": "Its a half baked cookie.. I am still working on it.. before pasting here I displayed a message box which showed the string and I understood that everything is working as expected.." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-09-04T11:33:06.007", "Id": "48901", "Score": "0", "body": "@svick if you would paste that as an answer I would happily accept it.. the `Substring()` method worked greatly for me! :)" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-09-05T16:02:12.780", "Id": "49039", "Score": "0", "body": "@vin please edit the title of your post to make it more Google-searchable & improve the site's visibility :)" } ]
[ { "body": "<p>you have this line</p>\n\n<pre><code>range = null;\n</code></pre>\n\n<p>and this line</p>\n\n<pre><code>range = readSheet.get_Range(cell, Missing.Value);\n</code></pre>\n\n<p>both inside and outside of your <code>While</code> Statement. this seems Odd to me?\nfrom the code that you have given it looks like you can get rid of </p>\n\n<pre><code>range = null; \n</code></pre>\n\n<p>both times that it shows up.</p>\n\n<p>your <code>range</code> variable is already created outside of this <code>if</code> statement, I don't think that you should need to set it to null everytime that you want to change it.</p>\n\n<p>that paired with the <code>Substring()</code> Method that @svick mentioned would clean this up a bit I think. </p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-09-04T14:38:52.937", "Id": "30776", "ParentId": "30762", "Score": "2" } }, { "body": "<p>Don't be afraid of having more variables. I suspect that the value in <code>range</code> has a different contextual meaning when it is used in the first if clause vs the inside of the while loop. If this is the case, make two different variables with names that describe what the contextual meaning is for the specific variable. The type system will help you know the variable is a <code>Range</code>. A name like <code>price</code> or <code>id</code> (it all depends on what you are using it for) will make the code easier to read.</p>\n\n<hr>\n\n<p>Building on what @Malachi said: You don't need to define your variables at the beginning and assign them a default value.</p>\n\n<pre><code>string A1 = String.Empty, Val = String.Empty;\nchar[] value = null;\nrange = readSheet.get_Range(cell, Missing.Value);\nA1 = range.Text.ToString();\nvalue = A1.ToCharArray();\n\n//is the same as\n\nrange = readSheet.get_Range(cell, Missing.Value);\nstring A1 = range.Text.ToString();\nchar[] value = A1.ToCharArray();\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-09-04T15:33:34.930", "Id": "48943", "Score": "0", "body": "Good point, I went with the assumption that the range Variable is being used for the same thing every time." } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-09-04T15:06:41.723", "Id": "30777", "ParentId": "30762", "Score": "3" } }, { "body": "<blockquote>\n <p><strong>strip</strong> out the char 'B' and <strong>convert</strong> the numberic string to integer and <strong>count</strong> how many times a particular integer has repeated</p>\n</blockquote>\n\n<pre><code>// the integer, it's count\nDictionary&lt;int,int&gt; integerCounter = new Dictionary&lt;int,int&gt;;\nRegex stripB = new Regex(@\"\\d+\");\nint capturedNumber;\n\n// may not be correct use of Worksheet properties\nforeach (var cell in range) {\n if (Int32.TryParse(stripB.Match(cell.Text), out capturedNumber)) {\n\n if (!integerCounter.Contains(capturedNumber)) integerCounter.Add(capturedNumber, 1)\n else\n integerCounter[capturedNumber]++;\n }\n}\n</code></pre>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-09-05T15:40:54.233", "Id": "30828", "ParentId": "30762", "Score": "0" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "4", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-09-04T10:21:52.697", "Id": "30762", "Score": "4", "Tags": [ "c#", "strings", ".net", "excel", "interval" ], "Title": "Getting a value from an Excel sheet column" }
30762
<p>My current task is to extend some JavaScript of a framework we are using. A pop-up should slide in, instead of just appear in the middle of the window. So I have overridden one of the framework's methods, and do at the end this:</p> <pre><code>AdfDhtmlPage.prototype.showMessages = function (componentId) { // Some code here function slideIn() { var maxTop = windowHeight - (thisHeight + 18); var tempTop = parseInt(popupElement._rootElement.style.top); if (maxTop &gt;= tempTop) { setTimeout(function () { AdfPage.PAGE.clearMessages(componentId); },5000); return; } popupElement._rootElement.style.top = tempTop - 1 + 'px'; setTimeout(slideIn, 20); } slideIn(); } </code></pre> <p>Everything worked just fine, but then I thought that the <code>slideIn</code> method should somehow be a behavior of the <code>popupElement</code>. During refactoring I encountered a behavior that was new to me and which is <a href="http://alistapart.com/article/getoutbindingsituations" rel="nofollow">here</a> called <em>binding loss</em>. So what I came up with is this:</p> <pre><code>AdfDhtmlPage.prototype.showMessages = function (componentId) { // Some code here popupElement._slideIn(popupElement, componentId); } AdfDhtmlSimpleFloat.prototype._slideIn = function(element, componentId) { var maxTop = AdfAgent.AGENT.getWindowHeight() - (element.getHeight() + 18); var thisTop = parseInt(element._rootElement.style.top); if (maxTop &gt;= thisTop) { setTimeout(function () { AdfPage.PAGE.clearMessages(componentId); },5000); return; } element._rootElement.style.top = thisTop - 1 + 'px'; setTimeout(function() { element._slideIn(element, componentId); }, 20); } </code></pre> <p>So when calling the <code>_slideIn</code> method of <code>popupElement</code> I need to pass <code>popupElement</code> as argument. So I can access the objects properties, after the method has been called via <code>setTimeout</code> (When the binding loss happens).</p> <p>However, this seems odd to me. So I would like to ask you to review my design. Maybe someone comes up with a better solution?</p> <hr> <p>that was, what I wanted to do:</p> <pre><code>AdfDhtmlPage.prototype.showMessages = function (componentId) { // Some code here popupElement._slideIn(componentId); } AdfDhtmlSimpleFloat.prototype._slideIn = function(componentId) { var maxTop = AdfAgent.AGENT.getWindowHeight() - (this.getHeight() + 18); var thisTop = parseInt(this._rootElement.style.top); if (maxTop &gt;= thisTop) { setTimeout(function () { AdfPage.PAGE.clearMessages(componentId); },5000); return; } this._rootElement.style.top = thisTop - 1 + 'px'; setTimeout(this._slideIn, 20); } </code></pre>
[ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-09-04T11:14:00.790", "Id": "48895", "Score": "0", "body": "Why would you assume that your element should be bound inside the AdfDhtmlSimpleFloat object? (is popupElement an AdfDhtmlSimpleFloat?). I notice from the ADF docs that they warn you not to use these classes at all, are you sure you want to?" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-09-04T11:26:05.207", "Id": "48900", "Score": "0", "body": "Yes the `popupElement` is an `AdfDhtmlSimpleFloat` object. We are aware of the possible draw-backs of using their classes, but didn't see any other way." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-09-04T11:53:45.427", "Id": "48903", "Score": "0", "body": "Can you post the broken code? You should not be passing in a reference to the Object explicitly as you are. I suspect that you were missing the `this` for example `this._rootElement.style.top`." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-09-04T14:27:54.327", "Id": "48929", "Score": "0", "body": "OK, did you update the `AdfDhtmlSimpleFloat` prototype before trying to call the function? Here is a super simple example http://jsfiddle.net/yvJfw/2/, comment and uncomment the calls to updateElem to see." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-09-05T05:44:58.443", "Id": "49002", "Score": "0", "body": "Yes, the function is defined, and gets called properly." } ]
[ { "body": "<p>The problem is that <code>this._slideIn</code> refers to a function, not a method invocation. In your third code sample, changing your last line to</p>\n\n<pre><code>var self = this;\nsetTimeout(function() { self._slideIn(componentId) }, 20);\n</code></pre>\n\n<p>should be sufficient. You have to capture <code>this</code> in the closure that you pass to <code>setTimeout()</code>, because when the code runs later, <code>this</code> will refer to something else in that execution context.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-09-05T09:23:57.440", "Id": "49018", "Score": "0", "body": "This did it. Could you please elaborate on this? I debugged it and don't understand it. Now at every call, `this` references the `AdfDhtmlSimpleFloat` object. Why is this so?" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-09-05T09:46:36.600", "Id": "49022", "Score": "0", "body": "You would be better off taking this up on StackOverflow. Here's the [background](http://stackoverflow.com/questions/3127429) and a [reformulation of your question](http://stackoverflow.com/questions/2130241)." } ], "meta_data": { "CommentCount": "2", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-09-05T08:10:11.970", "Id": "30809", "ParentId": "30763", "Score": "1" } } ]
{ "AcceptedAnswerId": "30809", "CommentCount": "5", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-09-04T10:36:50.720", "Id": "30763", "Score": "1", "Tags": [ "javascript", "closure" ], "Title": "JavaScript binding loss with setTimeout" }
30763
<p>I've been studying <a href="http://en.wikipedia.org/wiki/Reservoir_sampling" rel="nofollow noreferrer">Reservoir sampling</a> for a couple of days. What I've tried here is draw a uniformly random sample of size 3 from bigger data (the 26 characters of the English alphabet) via reservoir sampling. Below is what I've come up with.</p> <p>If anyone could review my code and offer some suggestions, that'd be great.</p> <pre><code>import java.util.TreeMap; public class test1 { public test1(){ String[] data = "A B C D E F G H I J K L M O P".split(" "); double[] freq = new double[data.length]; int k = 3; String[] sample = new String[k]; // the tree map stores the count of appearance of each letter during // the total sampling procedure TreeMap&lt;String, Double&gt; dmap = new TreeMap&lt;String, Double&gt;(); for (int index = 0; index &lt; data.length; index++) { dmap.put(data[index], 0.0); } for (int loop = 0; loop &lt; 1000000; loop++) { int i = 0; // initiate the sample while (i &lt; k) { sample[i] = data[i++]; } // start sampling from the reservoir for (; i &lt; data.length; i++) { int r = (int) (Math.random() * (i + 1)); if (r &lt; k) { sample[r] = data[i]; } } // update the count of each entry in the map for (String s : sample) { dmap.put(s, dmap.get(s) + 1); } } int index = 0; for (Double s : dmap.values().toArray(new Double[dmap.size()])) { freq[index++] = s; // System.out.println(s); } // calculate statistics double mean, stddev , cov; mean = stats.mean(freq); stddev = stats.stddev(freq); cov = (stddev / mean) * 100; System.out.println(" mean : " + mean); System.out.println(" coeff of variation(%) : " + cov); } public static void main(String[] args) { new test1(); } } </code></pre> <p><strong>Stats class:</strong></p> <pre><code>final class stats { private stats() {} public static double sum(double[] a) { double sum = 0.0; for (int i = 0; i &lt; a.length; i++) { sum += a[i]; } return sum; } public static double mean(double[] a) { if (a.length == 0) return Double.NaN; double sum = sum(a); return (double) sum / a.length; } public static double stddev(double[] a) { return Math.sqrt(var(a)); } public static double var(double[] a) { if (a.length == 0) return Double.NaN; double avg = mean(a); double sum = 0.0; for (int i = 0; i &lt; a.length; i++) { sum += (a[i] - avg) * (a[i] - avg); } return sum / (a.length); } } </code></pre> <p><strong>My output:</strong></p> <pre><code> mean : 200000.0 coeff of variation(%) : 0.18734211130086761 </code></pre> <p><strong>Edit</strong> </p> <p>I'v received some very helpful suggestions regarding the structure of the code . the generic version provided by <strong>200_success</strong> was really a nice one. But some of the "procedural"-ness i feel that my code has , is mainly because the api for the actual code for which this was a test-case , demanded a static method which only read the input and gave a sample output. Hence to keep things visually similar , i tried putting them all in one method... The constructor ( not an ideal option many would rightly argue ).</p> <p>Why the constructor? Well , it made me get away with just one small line in the main method. ( I was feeling pretty lazy back then .)</p> <p><strong>Edit 2</strong> : Found out about R yesterday, after a little youtube-ing for for tutorials , made a few plots . Thought i'd upload a couple of them , just for fun. (and a better view of the data) </p> <ol> <li><p><strong>Box-plot</strong> of the number of times each letter of the alphabet(A-Z) had come up <img src="https://i.stack.imgur.com/qWvF1.png" alt="box-plot"></p></li> <li><p><strong>Bar-plot</strong> of the same data</p></li> </ol> <p><img src="https://i.stack.imgur.com/k3zAi.png" alt="bar-plot"></p>
[ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-09-14T02:57:21.597", "Id": "49772", "Score": "0", "body": "Nice R plots. R is really powerful for statistics like this. Good language choice for the use case." } ]
[ { "body": "<p>The algorithm itself looks solid, and your code looks good! I just wanted to provide some general style tips for Java.</p>\n\n<p>First, why are you performing the core of your logic in the <code>test1</code> constructor? That's highly irregular for Java. A constructor in general should only perform processing to initialize values unique to each instance of the class. It would be much more object-oriented to either move all that code directly into your <code>main(String[] args)</code> method or into a different <code>static</code> method. Having a <code>test1</code> instance doesn't even make sense here.</p>\n\n<p>Second (and much less importantly), you are breaking with several Java style conventions. I'm assuming you come from a Python background, because your code \"feels\" very Pythonic. That's not a bad thing, but they're two very different languages. Python attempts to always be short and to the point, while Java emphasizes verbosity and long, descriptive names for things. As such, here are a few tips to make your code more Java-esque (if you care):</p>\n\n<ul>\n<li>Class names should have each word capitalized, like in <code>ThisTestClassName</code>. So yours should be <code>Test1</code> and <code>Stats</code>.</li>\n<li>Class names and variable names are also generally not abbreviated. So for example, your <code>stats</code> class would likely be called <code>Statistics</code>.</li>\n<li>Likewise, your method names would likely be renamed to something more descriptive. While anyone with a statistics background will know what you mean by <code>stddev</code>, it's standard for Java methods to be unabbreviated verb phrases. So it would be more appropriate to rename this method as <code>getStandardDeviation()</code>. Believe it or not, this really does make a difference in code readability. For example, when scanning your code, I was very confused by this line at first (<code>Math.sqrt(var(a))</code>) because it seemed like you were trying to do some odd JavaScript casting of <code>a</code> at a glance. A more descriptive method name like <code>getVariation()</code> would have easily avoided that confusion.</li>\n<li>To a lesser degree the \"make things more descriptive\" points from above apply to variable names as well, though it's much more common (if still frowned upon) to see this in local scope variables. For example, your code gets a little obfuscated in your <code>test1()</code> constructor because you use at least four variables which are only one letter: <code>i</code>, <code>k</code>, <code>r</code>, and <code>s</code>. In theory, with well-chosen variable names, I should be able to understand what the code is trying to do at any point without much surrounding context. That's the goal of making \"self-documenting code\".</li>\n</ul>\n\n<p>And finally, one small tip which might clean up your code a little bit concerning this line:</p>\n\n<pre><code>for (Double s : dmap.values().toArray(new Double[dmap.size()]))\n</code></pre>\n\n<p>Here you can actually just use <code>.toArray(new Double[0])</code> if you feel that would make your code less wordy. As you can see in <a href=\"http://docs.oracle.com/javase/6/docs/api/java/util/Collection.html#toArray%28T%5b%5d%29\" rel=\"nofollow\">the documentation</a>, you don't actually have to pass in an array of the appropriate size to the <code>toArray()</code> method; it only uses your array for infer the type to return to you. So by just initializing an empty, zero-length array like this, you may be able to improve code readability a bit (and performance by just a small amount, by saving on memory allocation). There's no consensus or standard on this. Just personal preference.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-09-04T14:32:35.790", "Id": "48930", "Score": "0", "body": "thanks a lot for your time to review my code.\n1st of all , regarding the structure of the code , its a partof an assignment where the api demands a static method for the sampling. so i kept the OO parts to a minimum. \n\nin my eclipse project , i generally have one or two such `test` classes , where i put random blocks of code and test it out. I agree i got a bit lazy there , and naming conventions should have been followed. \n\nregarding your point about `.toArray(new Double[0])` , it appears that only `dmap.values()` would suffice. Noticed it after posting the code." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-09-04T14:38:49.550", "Id": "48932", "Score": "0", "body": "regarding the pythonic part , thats good to hear, im planning to start learning python soon ;)\nunfortunately , i dont have enough rep to give an upvote." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-09-04T14:42:25.173", "Id": "48933", "Score": "0", "body": "@SomjitNag Nice! Good luck with Python. It's a fun language, and it looks like you'll find it intuitive. And yeah, you're right about `dmap.values()`. Wasn't paying enough attention! :)" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-09-04T14:45:36.593", "Id": "48934", "Score": "0", "body": "thanks :) also , i should mention , that while making the code , i found the use of a treemap to be a waste. Mainly because i dont really need sorting to be done at every entry. I wanted to implement a HashMap , and sort it at the end. But everywhere i looked , people were suggesting TreeMaps. What do you say ?" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-09-04T14:51:42.540", "Id": "48935", "Score": "0", "body": "@SomjitNag Yeah, it all depends on what you care about. As far as ease of coding, the `TreeMap` is probably easier, but if you wanted to pick up a small performance gain, `HashMap` would be a better choice as you observed." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-09-04T14:53:28.533", "Id": "48936", "Score": "0", "body": "Yeah , but how do i sort a hashmap ? Any simple solution ? (open to non simple solutions too if it cant be avoided ;) )" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-09-04T14:58:01.843", "Id": "48937", "Score": "0", "body": "I would probably just use [this constructor](http://docs.oracle.com/javase/6/docs/api/java/util/TreeMap.html#TreeMap(java.util.Map)) and do `new TreeMap(myHashMap)` to sort it." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-09-04T15:00:33.463", "Id": "48938", "Score": "0", "body": "I didnt think of that before ! looks good. thanks a lot :)" } ], "meta_data": { "CommentCount": "8", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-09-04T13:36:44.933", "Id": "30771", "ParentId": "30764", "Score": "4" } }, { "body": "<p>Functionally, your code is correct. My main criticisms are:</p>\n\n<ul>\n<li><strong>Separation of concerns.</strong> You've lumped all of the functionality (except some basic math) into one function. (And it's a constructor!) You could, at the very least, split the code into\n<ul>\n<li>The reservoir sampling algorithm</li>\n<li>Statistics gathering and calculation</li>\n<li>Your test case. (By the way, you skipped <code>\"N\"</code> in your test case, probably unintentionally. No big deal.)</li>\n</ul></li>\n<li><strong>Generality.</strong> It would be nice to write a reusable class that lets you reservoir-sample any pool of data, for any data type, for any <em>k</em> items. However, you've made two assumptions that prevent you from generalizing the code to handle any data type:\n<ul>\n<li>Your data are <code>Comparable</code>. A simple way to drop this requirement is to use a <code>HashMap</code> instead of a <code>TreeMap</code>.</li>\n<li>Your data contain no repeats, or that repeated elements are indistinguishable. This is debatable; I've taken the view that if <code>\"A\"</code> appears in the data pool twice, you should be able to count the number of times the first <code>\"A\"</code> is selected separately from when the second <code>\"A\"</code> is selected.</li>\n</ul></li>\n</ul>\n\n<p>With those ideas in mind, here's what I came up with:</p>\n\n<pre><code>import java.lang.reflect.Array;\nimport java.util.Random;\n\npublic class ReservoirSampler&lt;T&gt; {\n\n //////////////////////////////////////////////////////////////////\n\n class Stats {\n private int[] freq;\n\n private Stats(T[] pool) {\n this.freq = new int[pool.length];\n }\n\n private void collect(int[] rawSample) {\n for (int index : rawSample) {\n freq[index]++;\n }\n }\n\n public double mean() {\n if (0 == this.freq.length) {\n return Double.NaN;\n }\n double sum = 0;\n for (int f : this.freq) {\n sum += f;\n }\n return sum / this.freq.length;\n }\n\n public double var() {\n if (0 == this.freq.length) {\n return Double.NaN;\n }\n double avg = mean();\n double sum = 0;\n for (int f : this.freq) {\n sum += (f - avg) * (f - avg);\n }\n return sum / this.freq.length;\n }\n\n public double stddev() {\n return Math.sqrt(this.var());\n }\n }\n\n //////////////////////////////////////////////////////////////////\n\n private T[] pool;\n private Random random;\n public Stats stats;\n\n public ReservoirSampler(T[] pool) {\n this.pool = pool;\n this.random = new Random();\n this.stats = new Stats(pool);\n }\n\n /* Returns indexes of the k items selected from the pool */\n public int[] rawSample(int k) {\n int[] sample = new int[k];\n int i = 0;\n // Initialize the sample\n while (i &lt; k) {\n sample[i] = i++;\n }\n // Sample from the reservoir\n for (; i &lt; pool.length; i++) {\n int r = random.nextInt(i + 1);\n if (r &lt; k) {\n sample[r] = i;\n }\n }\n this.stats.collect(sample);\n return sample;\n }\n\n /* Returns k items selected from the pool */\n public T[] reservoirSample(int k) {\n // We would prefer to say\n // T[] sample = new T[k]\n // but T is unknown at runtime due to type erasure.\n Class c = this.pool.getClass().getComponentType();\n @SuppressWarnings({\"unchecked\"})\n T[] sample = (T[])Array.newInstance(c, k);\n\n int[] sampleIndexes = rawSample(k);\n for (int i = 0; i &lt; k; i++) {\n sample[i] = this.pool[sampleIndexes[i]];\n }\n return sample;\n }\n\n public static void main(String[] args) {\n String[] alphabet = \"A B C D E F G H I J K L M O P\".split(\" \");\n ReservoirSampler&lt;String&gt; rs = new ReservoirSampler&lt;String&gt;(alphabet);\n for (int loop = 0; loop &lt; 1000000; loop++) {\n rs.reservoirSample(3);\n }\n double mean = rs.stats.mean();\n double stddev = rs.stats.stddev();\n System.out.println(\" mean : \" + mean);\n System.out.println(\" coeff of variation(%) : \" + 100 * stddev / mean);\n }\n}\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-09-05T09:06:39.443", "Id": "49016", "Score": "0", "body": "Thanks a lot for your time to review and post a sample of improvement. will keep these in mind the next time i write a code. This time however , the actual code for which i wrote this , the api for it demanded a single static method for the random extraction and subsequent printout. Hence to keep things similar , i made it all a bit \"procedural\"." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-09-05T09:14:10.257", "Id": "49017", "Score": "1", "body": "You may have to code to an ugly API, but that shouldn't stop you from having pretty code behind it. Just plop the contents of my `main()` into your `test1()`." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-09-05T09:51:02.383", "Id": "49023", "Score": "0", "body": "Thank you for the edit , and also for the code.. I'm learning a lot from it, Especially in the type-erasure part. Thanks a lot." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-09-06T07:13:07.240", "Id": "49111", "Score": "0", "body": "About the type-erasure workaround… you don't have to pass the class explicitly. I've amended the code to use reflection to determine the array type." } ], "meta_data": { "CommentCount": "4", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-09-05T07:54:45.780", "Id": "30808", "ParentId": "30764", "Score": "2" } } ]
{ "AcceptedAnswerId": "30808", "CommentCount": "1", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-09-04T11:33:56.553", "Id": "30764", "Score": "4", "Tags": [ "java", "shuffle" ], "Title": "Review of reservoir sampling" }
30764
<p>I have a bunch of IP addresses. I want one IP network that has them all. <code>ipaddr.collapse_address_list</code> already exists, but that gives you a <em>list</em> of all the IP networks that identify your IP addresses, no more, no less, whereas I only need <em>one</em> IP network.</p> <p>I tried at first using XOR, but that fails on some situations (say, 10.0.0.1, 10.0.0.2, 10.0.0.255, 10.0.0.251: <code>bin(1 ^ 2 ^ 255 ^ 251) = 0b111</code>). And'ing has similar problems. This is what I ended up writing.</p> <pre><code>#http://stackoverflow.com/a/3789000/13992 def _AllSame(items): it = iter(items) first = next(it, None) return all(x == first for x in it) def _GetOneNetmaskForAllTheseIPs(ips): """Get the one IP network that covers all IPs in input. ipaddr.collapse_address_list is a little bit TOO smart and gives you the LIST of networks that describe a number of IP addreses. Ceph just wants one netmask. This function tries to get that one netmask. &gt;&gt;&gt; _GetOneNetmaskForAllTheseIPs(("10.0.0.1", "10.0.0.2", ... "10.0.0.251", "10.0.0.255")) 10.0.0.0/24 """ #Turn each IP address in its binary representation, without 0b header num_ip_addresses = [int(ipaddr.IPAddress(ip)) for ip in ips] lowest_ip = ipaddr.IPAddress(min(num_ip_addresses)) bin_ip_addresses = [bin(ip)[2:] for ip in num_ip_addresses] #"Transpose" the list (abc),(def) → (ad),(be),(cf) bit_comparison = zip(*bin_ip_addresses) differing_bits = len(bit_comparison) #Find the first different bit while _AllSame(bit_comparison[-differing_bits]): differing_bits -= 1 #That's the no. of bits that differ. The mask is the number of bits that DON'T mask_length = lowest_ip.max_prefixlen - differing_bits #Return the network network_ip = ipaddr.IPNetwork("%s/%d" % (lowest_ip, mask_length)).network network = ipaddr.IPNetwork("%s/%d" % (network_ip, mask_length), strict = True) return str(network) </code></pre> <p>I tried to be as IP-version agnostic as possible here, but chances are I've overlooked a few more-or-less obvious things here &mdash; or, even more likely, there's already a better inbuilt solution somewhere in the python libraries or even <code>ipaddr</code> itself.</p>
[]
[ { "body": "<p>You don't have to look at all the IPs to catch 'em all. Just looking at the lowest and highest does the trick. This realisation comes in handy when you consider that ipaddr does have a (private) function that gives you the common prefix length between two IP addresses. The code can then be simplified to:</p>\n\n<pre><code>#with many thanks to gfalcon\ndef _GetOneNetmaskForAllTheseIPs(ips):\n \"\"\"Get the one IP network that covers all IPs in input.\n\n ipaddr.collapse_address_list is a little bit TOO smart and gives you the LIST\n of networks that describe a number of IP addreses. Ceph just wants one\n netmask. This function tries to get that one netmask.\n\n &gt;&gt;&gt; _GetOneNetmaskForAllTheseIPs((\"10.0.0.1\", \"10.0.0.2\",\n ... \"10.0.0.251\",\"10.0.0.255\"))\n 10.0.0.0/24\n \"\"\"\n\n #Look at larger and smaller IP addresses\n ips = [ipaddr.IPAddress(ip) for ip in ips]\n lowest_ip, highest_ip = min(ips), max(ips)\n\n mask_length = ipaddr._get_prefix_length(\n int(lowest_ip), int(highest_ip), lowest_ip.max_prefixlen)\n\n #Return the network\n network_ip = ipaddr.IPNetwork(\"%s/%d\" % (lowest_ip, mask_length)).network\n network = ipaddr.IPNetwork(\"%s/%d\" % (network_ip, mask_length), strict = True)\n return str(network)\n</code></pre>\n\n<p>You still can't use public functions like <code>ipaddr.summarize_address_range</code>, because the library will still painstakingly try to avoid any IP address ever so slightly off range.</p>\n\n<pre><code>&gt;&gt;&gt; ipaddr.summarize_address_range(IPv4Address('10.0.0.1'), IPv4Address('10.0.0.255'))\n[IPv4Network('10.0.0.1/32'),\n IPv4Network('10.0.0.2/31'),\n IPv4Network('10.0.0.4/30'),\n IPv4Network('10.0.0.8/29'),\n IPv4Network('10.0.0.16/28'),\n IPv4Network('10.0.0.32/27'),\n IPv4Network('10.0.0.64/26'),\n IPv4Network('10.0.0.128/25')]\n</code></pre>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-09-04T16:24:14.773", "Id": "30780", "ParentId": "30765", "Score": "3" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-09-04T12:00:52.867", "Id": "30765", "Score": "2", "Tags": [ "python", "networking" ], "Title": "Find the single smallest IP network with the given IP addresses" }
30765
<p>Below is how I'm solving the problem of <a href="https://softwareengineering.stackexchange.com/questions/210260/converting-between-data-and-presentation-types">converting between data and presentation types</a>, I'd like to know if that's a good way to go about it, and if not, what would be a better way to go about it.</p> <p>I already had an <code>IViewModel</code> interface:</p> <pre><code>/// &lt;summary&gt; /// An interface for a ViewModel. /// &lt;/summary&gt; public interface IViewModel : INotifyPropertyChanged { /// &lt;summary&gt; /// Notifies listener that the value of the specified property has changed. /// &lt;/summary&gt; void NotifyPropertyChanged&lt;TProperty&gt;(Expression&lt;Func&lt;TProperty&gt;&gt; property); /// &lt;summary&gt; /// Notifies listener that the value of the specified property has changed. /// &lt;/summary&gt; void NotifyPropertyChanged(string propertyName); } </code></pre> <p>So I added an <code>IViewModel&lt;T&gt;</code> interface that extends it:</p> <pre><code>/// &lt;summary&gt; /// An interface for a ViewModel that encapsulates an entity type. /// &lt;/summary&gt; /// &lt;typeparam name="T"&gt;The entity interface type.&lt;/typeparam&gt; public interface IViewModel&lt;T&gt; : IViewModel where T : class { /// &lt;summary&gt; /// A method that returns the encapsulated entity interface. /// &lt;/summary&gt; /// &lt;returns&gt;Returns an interface to the encapsulated entity.&lt;/returns&gt; T ToEntity(); } </code></pre> <p>Then to facilitate usage, I implemented it in a base class:</p> <pre><code>/// &lt;summary&gt; /// Base class to derive ViewModel implementations that encapsulate an Entity type. /// &lt;/summary&gt; /// &lt;typeparam name="T"&gt;The entity type.&lt;/typeparam&gt; public abstract class ViewModelBase&lt;T&gt; : IViewModel&lt;T&gt; where T : class { protected readonly T EntityType; /// &lt;summary&gt; /// Initializes a new instance of the &lt;see cref="ViewModelBase{T}"/&gt; class. /// &lt;/summary&gt; /// &lt;param name="entityType"&gt;An instance of the entity type to encapsulate.&lt;/param&gt; protected ViewModelBase(T entityType) { EntityType = entityType; ReflectTypeProperties(); } public T ToEntity() { return EntityType; } #region INotifyPropertyChanged implementation /// &lt;summary&gt; /// Occurs when a property value changes. /// &lt;/summary&gt; public event PropertyChangedEventHandler PropertyChanged; /// &lt;summary&gt; /// Notifies listener that the value of the specified property has changed. /// &lt;/summary&gt; /// &lt;param name="propertyName"&gt;The name of the property to notify about.&lt;/param&gt; public void NotifyPropertyChanged(string propertyName) { Action notify; _propertyNotifications.TryGetValue(propertyName, out notify); if (notify != null) notify(); } /// &lt;summary&gt; /// Notifies listener that the value of the specified property has changed. /// &lt;/summary&gt; /// &lt;typeparam name="TProperty"&gt;The type of the property (inferred).&lt;/typeparam&gt; /// &lt;param name="property"&gt;An expression that selects a property, like &lt;c&gt;() =&gt; PropertyName&lt;/c&gt;.&lt;/param&gt; public void NotifyPropertyChanged&lt;TProperty&gt;(Expression&lt;Func&lt;TProperty&gt;&gt; property) { NotifyPropertyChanged(PropertyName(property)); } private void NotifyPropertyChanged(object sender, PropertyChangedEventArgs e) { if (PropertyChanged != null) PropertyChanged(sender, e); } private IDictionary&lt;string, Action&gt; _propertyNotifications; /// &lt;summary&gt; /// Loads the names of all properties of the most derived type into a /// Dictionary where each entry (property name) points to a delegate that /// calls &lt;see cref="NotifyPropertyChanged"/&gt; for the corresponding property. /// &lt;/summary&gt; private void ReflectTypeProperties() { var viewModelProperties = GetType().GetProperties().Where(p =&gt; p.CanWrite); // uses reflection (slow) _propertyNotifications = viewModelProperties .Select(property =&gt; new KeyValuePair&lt;string, Action&gt;(property.Name, () =&gt; NotifyPropertyChanged(this, new PropertyChangedEventArgs(property.Name)))) .ToDictionary(kv =&gt; kv.Key, kv =&gt; kv.Value); } /// &lt;summary&gt; /// Returns the name of a property in a LINQ Expression such as '&lt;code&gt;() =&gt; Property&lt;/code&gt;'. /// Used for strongly-typed INotifyPropertyChanged implementation. /// &lt;/summary&gt; protected static string PropertyName&lt;TProperty&gt;(Expression&lt;Func&lt;TProperty&gt;&gt; property) { var lambda = (LambdaExpression)property; MemberExpression memberExpression; var body = lambda.Body as UnaryExpression; if (body == null) memberExpression = (MemberExpression)lambda.Body; else { var unaryExpression = body; memberExpression = (MemberExpression)unaryExpression.Operand; } return memberExpression.Member.Name; } #endregion } </code></pre> <p>This leaves me with clean &amp; focused ViewModel classes that only expose what's meant to be displayed, while retaining the knowledge of the precious encapsulated <code>Id</code>:</p> <pre><code>/// &lt;summary&gt; /// Encapsulates a &lt;see cref="ISomeEntity"/&gt; implementation for presentation purposes. /// &lt;/summary&gt; public class SomeEntityViewModel : ViewModelBase&lt;ISomeEntity&gt;, ISelectable, IDeletable { /// &lt;summary&gt; /// Encapsulates specified entity in a presentation type. /// &lt;/summary&gt; /// &lt;param name="poco"&gt;The entity to be encapsulated.&lt;/param&gt; public SomeEntityViewModel(ISomeEntity poco) : base(poco) { } /// &lt;summary&gt; /// A short description for the thing. /// &lt;/summary&gt; public string Description { get { return EntityType.Description; } set { EntityType.Description = value; NotifyPropertyChanged(() =&gt; Description); } } private bool _isSelected; public bool IsSelected { get { return _isSelected; } set { _isSelected = value; NotifyPropertyChanged(() =&gt; IsSelected); } } private bool _isDeleted; public bool IsDeleted { get { return _isDeleted; } set { _isDeleted = value; NotifyPropertyChanged(() =&gt; IsDeleted); } } } </code></pre> <p>Bonus question: is my implementation of <code>INotifyPropertyChanged</code> overkill?</p>
[ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-09-04T13:44:24.137", "Id": "48920", "Score": "0", "body": "I realize the actual code does not actually have a `SomeEntity` class and that CR guidelines are against such \"placeholders\", however the review I'm requesting is more about the base class and the structure of it all - it just might be *any* entity in my project, *which one it is that I'm showing* is perfectly irrelevant..." } ]
[ { "body": "<pre><code>T ToEntity();\n</code></pre>\n\n<p>To me, <code>ToEntity()</code> implies some sort of conversion action. A better option might be <code>T GetEntity()</code> or even a property called <code>Entity</code>.</p>\n\n<pre><code>protected readonly T EntityType;\n</code></pre>\n\n<p><code>EntityType</code> is a bad name for this field, because it does not contain a type, it contains the entity. Because of that, something like <code>Entity</code> might be better.</p>\n\n<p>Also, you might want to consider making this into a property. The reasons for not using public fields also apply to protected fields (though not as strongly).</p>\n\n<pre><code>private IDictionary&lt;string, Action&gt; _propertyNotifications;\n</code></pre>\n\n<p>This seems completely unnecessary. Unless you know that this actually makes measurable improvement in performance (which I seriously doubt), just raise the event.</p>\n\n<pre><code>var lambda = (LambdaExpression)property;\nvar unaryExpression = body;\n</code></pre>\n\n<p>These two lines are unnecessary and I think they also don't improve readability.</p>\n\n<pre><code>memberExpression = (MemberExpression)unaryExpression.Operand;\n</code></pre>\n\n<p>If you're expecting only some specific <code>UnaryExpression</code>s, then I would check that those are actually what you have. For example, I think your code would work with <code>() =&gt; !BoolProperty</code>, which I think it shouldn't.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-09-04T13:54:17.020", "Id": "30773", "ParentId": "30769", "Score": "7" } }, { "body": "<p>This is a wonderful implementation! Very nice getting boilerplate viewmodel code out of the way. That being said, I have a few tiny bits I'd change in <code>ViewModelBase&lt;T&gt;</code> (and the appropriate changes to <code>IViewModel&lt;T&gt;</code> too) as such (I've commented my changes):</p>\n\n<pre><code>/// &lt;summary&gt;\n/// Base class to derive ViewModel implementations that encapsulate an Entity type.\n/// &lt;/summary&gt;\n/// &lt;typeparam name=\"T\"&gt;The entity type.&lt;/typeparam&gt;\npublic abstract class ViewModelBase&lt;T&gt; : IViewModel&lt;T&gt; where T : class\n{\n // Was protected, now private and accessed by property below.\n private readonly T entity;\n\n // I like my members read-only as much as possible.\n private readonly IDictionary&lt;string, Action&gt; propertyNotifications;\n\n /// &lt;summary&gt;\n /// Initializes a new instance of the &lt;see cref=\"ViewModelBase{T}\"/&gt; class.\n /// &lt;/summary&gt;\n /// &lt;param name=\"entity\"&gt;An instance of the entity type to encapsulate.&lt;/param&gt;\n protected ViewModelBase(T entity)\n {\n this.entity = entity;\n\n // Removed the ReflectTypeProperties() method and consolidated here so the member can be read-only.\n // Loads the names of all properties of the most derived type into a\n // Dictionary where each entry (property name) points to a delegate that\n // calls NotifyPropertyChanged() for the corresponding property.\n this.propertyNotifications = this.GetType().GetProperties()\n .Where(property =&gt; property.CanWrite)\n .Select(property =&gt; new KeyValuePair&lt;string, Action&gt;(\n property.Name,\n () =&gt; this.NotifyPropertyChanged(this, new PropertyChangedEventArgs(property.Name))))\n .ToDictionary(kvp =&gt; kvp.Key, kv =&gt; kv.Value);\n }\n\n /// &lt;summary&gt;\n /// Occurs when a property value changes.\n /// &lt;/summary&gt;\n public event PropertyChangedEventHandler PropertyChanged;\n\n // public property removes need for protected member and ToEntity() method.\n public T Entity\n {\n get\n {\n return this.entity;\n }\n }\n\n /// &lt;summary&gt;\n /// Notifies listener that the value of the specified property has changed.\n /// &lt;/summary&gt;\n /// &lt;param name=\"propertyName\"&gt;The name of the property to notify about.&lt;/param&gt;\n public void NotifyPropertyChanged(string propertyName)\n {\n Action notify;\n\n // Removed need for extra null check as TryGetValue returns a bool. If successful, it should always have a non-null value per constructor.\n if (this.propertyNotifications.TryGetValue(propertyName, out notify))\n {\n notify();\n }\n }\n\n /// &lt;summary&gt;\n /// Notifies listener that the value of the specified property has changed.\n /// &lt;/summary&gt;\n /// &lt;typeparam name=\"TProperty\"&gt;The type of the property (inferred).&lt;/typeparam&gt;\n /// &lt;param name=\"property\"&gt;An expression that selects a property, like &lt;c&gt;() =&gt; PropertyName&lt;/c&gt;.&lt;/param&gt;\n public void NotifyPropertyChanged&lt;TProperty&gt;(Expression&lt;Func&lt;TProperty&gt;&gt; property)\n {\n this.NotifyPropertyChanged(PropertyName(property));\n }\n\n /// &lt;summary&gt;\n /// Returns the name of a property in a LINQ Expression such as '&lt;code&gt;() =&gt; Property&lt;/code&gt;'.\n /// Used for strongly-typed INotifyPropertyChanged implementation.\n /// &lt;/summary&gt;\n /// &lt;returns&gt;The name of a property in a LINQ Expression&lt;/returns&gt;\n protected static string PropertyName&lt;TProperty&gt;(Expression&lt;Func&lt;TProperty&gt;&gt; property)\n {\n // Combination and simplification of statements here.\n var body = property.Body as UnaryExpression;\n var memberExpression = (MemberExpression)(body == null ? property.Body : body.Operand);\n\n return memberExpression.Member.Name;\n }\n\n /// &lt;summary&gt;\n /// Notifies listeners when the property has changed.\n /// &lt;/summary&gt;\n /// &lt;param name=\"sender\"&gt;The sender.&lt;/param&gt;\n /// &lt;param name=\"e\"&gt;The &lt;see cref=\"PropertyChangedEventArgs\"/&gt; instance containing the event data.&lt;/param&gt;\n private void NotifyPropertyChanged(object sender, PropertyChangedEventArgs e)\n {\n // This is for thread safety, in case the event subscribers are removed between statements.\n var propertyChanged = this.PropertyChanged;\n\n if (propertyChanged != null)\n {\n propertyChanged(sender, e);\n }\n }\n}\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-09-04T22:30:18.007", "Id": "48985", "Score": "0", "body": "Thanks! I really appreciate your feedback; doesn't the public `Entity` property make it a leaky encapsulation? A view could bind directly to it and skip all exposed properties (and change notifications)... unless I'm missing something?" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-09-04T22:35:37.887", "Id": "48986", "Score": "0", "body": "Wouldn't the original `ToEntity()` do the exactly same thing? My change only made it to the `Entity` property instead of the method. No change in visibility or what it returns." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-09-04T22:47:47.377", "Id": "48989", "Score": "0", "body": "Hmm I didn't think a view could bind to a VM's method, at least not in WPF... I'm going to look that up! :)" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-09-04T22:51:44.657", "Id": "48991", "Score": "0", "body": "I think I'll grab your `PropertyName` implementation though :)" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-09-05T16:52:12.247", "Id": "49041", "Score": "0", "body": "Interestingly, I found this: http://stackoverflow.com/questions/502250/bind-to-a-method-in-wpf - the top-voted answer uses a custom parameterized `IValueConverter` and reflection to perform the binding, so it looks like binding to a method is possible, ...but rather ugly - shortly put, it's a hack!" } ], "meta_data": { "CommentCount": "5", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-09-04T21:45:03.353", "Id": "30796", "ParentId": "30769", "Score": "3" } }, { "body": "<h3>Design Review</h3>\n\n<p>I am not convinced wrapping business layer entity properties in presentation layer is a good pattern for the following reasons:</p>\n\n<ul>\n<li>It asserts the presentation view of data is strongly related to the business entities. This certainly isn't always the case. Many presentation layers introduce even further denormalized presentation classes than the business entities.</li>\n<li>It is a breach of separation of concerns, in that user interaction can immediately adapt business entity state.</li>\n<li>By keeping presentation and business entities completely separated, you can focus on client-side end-user validation without impacting the business validation and vice versa.</li>\n</ul>\n\n<hr>\n\n<h3>Suggested Alternative</h3>\n\n<p>Create custom presentation classes that have no relation to business entities, even if most properties would include 1-1 mappings. Use a factory, builder or mapper pattern to put boiler-plate mapping code between layers in.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-08-07T17:45:03.627", "Id": "225732", "ParentId": "30769", "Score": "2" } } ]
{ "AcceptedAnswerId": "30773", "CommentCount": "1", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-09-04T13:18:26.127", "Id": "30769", "Score": "10", "Tags": [ "c#", "reflection", "mvvm", "lambda" ], "Title": "Converting between data and presentation types" }
30769
<p>I am having an issue where I am doing a query and it is coming back with about 100 pages, I was hoping to have it come back with 1,2,3...30,31...99,100 instead of 1,2,3,4,5,6,7,8,etc. please see below for working code that returns back results as unwanted format, I am new here so if this question is written wrong please let me know and I will make necessary changes , thanks in advance:</p> <pre><code>function getPage($stmt, $pageNum, $rowsPerPage) { $offset = ($pageNum - 1) * $rowsPerPage; $rows = array(); $i = 0; while(($row = sqlsrv_fetch_array($stmt, SQLSRV_FETCH_NUMERIC, SQLSRV_SCROLL_ABSOLUTE, $offset + $i)) &amp;&amp; $i &lt; $rowsPerPage) { array_push($rows, $row); $i++; } return $rows; } // Set the number of rows to be returned on a page. $rowsPerPage = 30; // Connect to the server. $serverName = 'test'; $connOptions = array("Database"=&gt;"test"); $conn = sqlsrv_connect($serverName, $connOptions); if (!$conn) die( print_r( sqlsrv_errors(), true)); // Define and execute the query. // Note that the query is executed with a "scrollable" cursor. $sql = "select * from info"; $stmt = sqlsrv_query($conn, $sql, array(), array( "Scrollable" =&gt; 'static' )); if ( !$stmt ) die( print_r( sqlsrv_errors(), true)); // Display the selected page of data. echo "&lt;table border='1px' align='center'&gt;"; $pageNum = isset($_GET['pageNum']) ? $_GET['pageNum'] : 1; $page = getPage($stmt, $pageNum, $rowsPerPage); foreach($page as $row) echo "&lt;tr&gt;&lt;td&gt;$row[0]&lt;/td&gt;&lt;td&gt;$row[1]&lt;/td&gt;&lt;td&gt;$row[2]&lt;/td&gt;&lt;td&gt;$row[3]&lt;/td&gt;&lt;/tr&gt;"; echo "&lt;/table&gt;"; ?&gt; &lt;table align='center'&gt; &lt;?php // Get the total number of rows returned by the query. // Display links to "pages" of rows. $rowsReturned = sqlsrv_num_rows($stmt); if($rowsReturned === false) die( print_r( sqlsrv_errors(), true)); elseif($rowsReturned == 0) { echo "No rows returned."; exit(); } else { // Display page links. $numOfPages = ceil($rowsReturned/$rowsPerPage); for($i = 1; $i&lt;=$numOfPages; $i++) { $pageLink = "?pageNum=$i"; print("&lt;a href=$pageLink&gt;$i&lt;/a&gt;&amp;nbsp;&amp;nbsp;"); } echo "&lt;br/&gt;&lt;br/&gt;"; } sqlsrv_close( $conn ); </code></pre>
[]
[ { "body": "<p>Do you just mean the links at the bottom of your page? If so you have this code:</p>\n\n<pre><code>// Display page links.\n$numOfPages = ceil($rowsReturned/$rowsPerPage);\nfor($i = 1; $i&lt;=$numOfPages; $i++)\n{\n $pageLink = \"?pageNum=$i\";\n print(\"&lt;a href=$pageLink&gt;$i&lt;/a&gt;&amp;nbsp;&amp;nbsp;\");\n}\n</code></pre>\n\n<p>Modify this to render just the first three links, then your ellipses (...) separator and then the final page number.</p>\n\n<p><strong>EDIT to add pseudo code</strong><br/>\nThis is messy but hopefully gives you the idea, create your function, make it work and then post a new question asking how to make it prettier (for example tidy up the ifs, add logic to only render a single set of ellipses, don't repeat any rendering code).</p>\n\n<pre><code>$numOfPages = ceil($rowsReturned/$rowsPerPage);\n$renderedEllipses = false;\nfor($i = 1; $i&lt;=$numOfPages; $i++)\n{\n //If you always want to render pages 1 - 3\n if($i &lt; 4) {\n //render link\n }\n\n //If you always want to render current page number\n else if($i == $pageNum) {\n //render link\n //reset ellipses\n $renderedEllipses = false;\n }\n\n //if you always want the last page number\n else if ($i == $numOfPages - 1) {\n //render link\n }\n\n //make sure you only do this once per ellipses group\n else {\n if (!$renderedEllipses){\n print(\"...\");\n $renderedEllipses = true;\n }\n }\n}\n</code></pre>\n\n<p><strong>EDIT added ellipses test</strong><br/>\nThe <code>$renderedEllipses</code> flag will stop hundreds of ellipses being rendered.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-09-04T13:53:35.297", "Id": "48922", "Score": "0", "body": "Hi JohnMark12, I appreciate your help with this unfortunately I am stuck on how to do the ellipses as if user goes to page 8 it will need to change to 1,2,3...8,9...99,100 and if user goes to page 30 then 1,2,3..30,31...,99,100 if that makes sense, any help would be highly appreciated. @JohnMark13" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-09-04T16:15:18.113", "Id": "48949", "Score": "0", "body": "John Awesome , this is very close to what I need however I need to render pages inbetween current page and last page, any idea how to achieve this bud, you are a big help! - @JohnMark13" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-09-04T16:22:29.577", "Id": "48950", "Score": "0", "body": "I am going to mark your answer as correct as it helped me to achieve my end goal, Thanks for your help bud!" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-09-04T16:24:16.820", "Id": "48951", "Score": "0", "body": "Hi. Consider the $i == $pageNum condition which renders a link to the current page. Then consider something like `if(abs($i - $pageNum) == 1)` which will return true for numbers one either side of the current page. Onwards!" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-09-04T16:34:21.497", "Id": "48952", "Score": "0", "body": "1 last question my ellipses is producing alot of dots so for some reason it is got a string like this : 1,2,3...................................65,.................................129,130 any ideas how to achieve this I am satisfied otherwise :)! - @JohnMark13" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-09-04T17:45:39.647", "Id": "48957", "Score": "0", "body": "This question should really be on StackOverflow, but seeing as I've started. I put a comment in the original code (make sure you only do this once...). One way of tracking it would be to have a flag say $renderedElipses set it to false before the loop. In the loop set it to false whenever you render a link, but when you render the ellipses, set it to true. How does that help? Before rendering the ellipses check the state of your flag, don't render ellipses again if it is true." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-09-04T18:04:01.847", "Id": "48962", "Score": "0", "body": "I,ve actually asked this question on StackOverflow as well (dont worry I will copy and paste your answer and give you credit once done unless you would like to) anyway do you mean to put define('$renderedElipss', FALSE); at the beginning and between the else if statements? @JohnMark13" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-09-04T18:24:46.943", "Id": "48965", "Score": "0", "body": "also as a sidenote Ive only done the end else statement once for the whole code block. @JohnMark13" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-09-04T18:45:27.030", "Id": "48966", "Score": "0", "body": "See edit which shows how ellipses could be handled." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-09-04T19:31:08.753", "Id": "48972", "Score": "0", "body": "Perfect, I cant ask for more, your answer is marked correct will copy over to StackOverflow also, thanks again bud. @JohnMark13" } ], "meta_data": { "CommentCount": "10", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-09-04T13:49:47.510", "Id": "30772", "ParentId": "30770", "Score": "1" } } ]
{ "AcceptedAnswerId": "30772", "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-09-04T13:34:36.460", "Id": "30770", "Score": "2", "Tags": [ "php", "sql", "pagination" ], "Title": "PHP Pagination for 1,2,3... vs 1,2,3,4,5,etc" }
30770
<p>What's a concise way of returning <code>true</code> or <code>false</code> along with an error message?</p> <p>Here's a concrete example - I'm building a parser that takes in a file. <code>ParseReplayData</code> does some validation before proceeding with the actual parsing:</p> <pre><code>public class Parser { private const string SUPPORTED_FILE_EXTENSION = "w3g"; private const string ERROR_FILE_DOES_NOT_EXIST = "Replay file does not exist: {0}"; private const string ERROR_FILE_EXTENSION_NOT_SUPPORTED = "File extension is not a w3g replay file: {0}"; private const string ERROR_FILE_BYTE_LENGTH_TOO_SMALL = "Replay file's byte length is too small: {0}"; private const int REPLAY_MINIMUM_BYTE_LENGTH = 288; private ReplayData _replayData; private readonly string _replayFilePath; public ReplayData ReplayData { get { return _replayData; } } public Parser(string replayFilePath) { _replayFilePath = replayFilePath; } public bool ParseReplayData(out string errorReason) { errorReason = String.Empty; if (!File.Exists(_replayFilePath)) { errorReason = String.Format(ERROR_FILE_DOES_NOT_EXIST, _replayFilePath); return false; } if (Path.GetExtension(_replayFilePath) != SUPPORTED_FILE_EXTENSION) { errorReason = String.Format(ERROR_FILE_EXTENSION_NOT_SUPPORTED, _replayFilePath); return false; } byte[] replayFileBytes = File.ReadAllBytes(_replayFilePath); if (replayFileBytes.Length &lt; REPLAY_MINIMUM_BYTE_LENGTH) { errorReason = String.Format(ERROR_FILE_BYTE_LENGTH_TOO_SMALL, _replayFilePath); return false; } _replayData = new ReplayData(); ..... //Parse Replay return true; } } </code></pre> <p>I can't shake the feeling that there's a lot of code smell in this class, and I'd appreciate any other suggestions you could give me.</p>
[ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-09-04T14:12:31.850", "Id": "48926", "Score": "7", "body": "What about throwing an exception instead of returning `false`? You could also define a `Result` class which contains the return-value and the reason." } ]
[ { "body": "<p>An alternative as MrSmith42 suggested could be to use exceptions.</p>\n\n<pre><code>public class ReplayDataParser\n{\n private const string SupportedFileExtension = \"w3g\";\n private const string ErrorFileDoesNotExist = \"Replay file does not exist: {0}\";\n private const string ErrorFileExtensionNotSupported = \"File extension is not a w3g replay file: {0}\";\n private const string ErrorFileByteLengthTooSmall = \"Replay file's byte length is too small: {0}\";\n private const int ReplayMinimumByteLength = 288; \n\n private readonly string _replayFilePath;\n\n public ReplayDataParser(string replayFilePath)\n {\n _replayFilePath = replayFilePath;\n }\n\n public ReplayData Parse()\n {\n if (FileNotFound())\n {\n throw new FileNotFoundException(string.Format(ErrorFileDoesNotExist, _replayFilePath));\n }\n\n if (FileExtensionNotSupported())\n {\n throw new ArgumentException(string.Format(ErrorFileExtensionNotSupported, _replayFilePath));\n }\n\n if (FileNotTooSmall())\n {\n throw new FileTooSmallException(string.Format(ErrorFileByteLengthTooSmall, _replayFilePath));\n }\n\n return ParseFile();\n }\n\n private ReplayData ParseFile()\n {\n return new ReplayData();\n }\n\n private bool FileExtensionNotSupported()\n {\n return Path.GetExtension(_replayFilePath) != SupportedFileExtension;\n }\n\n private bool FileNotFound()\n {\n return !File.Exists(_replayFilePath); \n }\n\n private bool FileNotTooSmall()\n {\n byte[] replayFileBytes = File.ReadAllBytes(_replayFilePath);\n return replayFileBytes.Length &lt; ReplayMinimumByteLength;\n }\n}\n</code></pre>\n\n<p>The downside from this from what I can see is if you use this parser in alot of places then you will need to handle the exceptions accordingly. However the upside is that if you wish to do different things based on the reason why something failed then you can catch individual exceptions as required.</p>\n\n<p>Offered as an alternative for consideration in any event.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-12-18T13:43:22.143", "Id": "134624", "Score": "0", "body": "You could simplify the exception handling by declaring your own exceptions: `public class ReplyParseException : Exception` and sub class ReplyParseException appropriately. That way you can catch `ReplyParseException` or their sub classes to handle specific error conditions if the built in exceptions aren't up to the task." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-12-18T18:38:37.980", "Id": "134712", "Score": "0", "body": "@GregBurghardt good point. I guess that is where I was heading at with the FileTooSmallException. I don't recall there being an exception class of that name already in .net??" } ], "meta_data": { "CommentCount": "2", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-09-04T20:50:46.833", "Id": "30792", "ParentId": "30774", "Score": "7" } }, { "body": "<blockquote>\n <p>returning true/false with an error message?</p>\n</blockquote>\n\n<pre><code>// I want more expressive and clearer code, \"Tuple\" is too generic.\npublic class ErrorInfo : Tuple&lt;bool,string&gt;\n\npublic ErrorInfo ParseReplayData() {}\n</code></pre>\n\n<p>client code:</p>\n\n<pre><code>var parseError= ParseReplayData();\nerrorObject.item1 ? doSomething() : DisplayErrorMessage(parseError.item2);\n</code></pre>\n\n<p>And/Or collect error objects for later processing</p>\n\n<pre><code>List&lt;ErrorInfo&gt; errorsCollection;\nerrorsCollection.Add(parseError);\n</code></pre>\n\n<p><strong>Exceptions as Error Handling</strong></p>\n\n<p>If you do this make your own Exception class; if only to give it a name that conveys intent <code>DataErrorException</code>, for example.</p>\n\n<p>I suggest the above because using exceptions this way is considered poor coding practice. It perverts the intent of exceptions. Further, exception generation &amp; handling is relatively computationally expensive.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-12-06T20:22:42.890", "Id": "60551", "Score": "0", "body": "Please don't do this. This is a class with two properties, implement them with proper naming and forget about inherit from Tuple." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-12-07T19:03:47.300", "Id": "60655", "Score": "0", "body": "@ThomasEyde, yeah,ok. I agree. Whatever possessed me to commit blatant over-design and obfuscation :( ?" } ], "meta_data": { "CommentCount": "2", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-09-05T13:40:48.973", "Id": "30819", "ParentId": "30774", "Score": "1" } }, { "body": "<p>To me, whatever needs to <code>Parse</code> sounds like a crying need for a <code>TryParse</code> method/pattern.</p>\n\n<p>Your <code>Parse</code> method should just throw a <code>ParseException</code> if it fails, and the <code>TryParse</code> method would return a Boolean indicating success or failure, along with an <code>out</code> parameter that returns your successfully parsed value, if any.</p>\n\n<p>A good example of this pattern can be found in the BCL, with <code>int.Parse(string):int</code> and <code>int.TryParse(string, out int result):bool</code>.</p>\n\n<p>The <code>TryParse</code> method <strong>never</strong> throws an exception.</p>\n\n<hr>\n\n<p>Building on @dreza's answer, I would put the custom exceptions as an <code>InnerException</code>, within the outer <code>ParseException</code>.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-09-05T16:32:52.343", "Id": "30830", "ParentId": "30774", "Score": "5" } }, { "body": "<p>You can use an Exceptional Monad to cleanup the code:</p>\n\n<p><a href=\"https://gist.github.com/bradphelan/6154972\" rel=\"nofollow\">https://gist.github.com/bradphelan/6154972</a></p>\n\n<pre><code>public class Parser\n{\n private const string SUPPORTED_FILE_EXTENSION = \"w3g\";\n private const string ERROR_FILE_DOES_NOT_EXIST = \"Replay file does not exist: {0}\";\n private const string ERROR_FILE_EXTENSION_NOT_SUPPORTED = \"File extension is not a w3g replay file: {0}\";\n private const string ERROR_FILE_BYTE_LENGTH_TOO_SMALL = \"Replay file's byte length is too small: {0}\";\n private const int REPLAY_MINIMUM_BYTE_LENGTH = 288;\n private ReplayData _replayData;\n private readonly string _replayFilePath;\n\n public ReplayData ReplayData\n {\n get { return _replayData; }\n }\n\n public Parser(string replayFilePath)\n {\n _replayFilePath = replayFilePath;\n }\n\n public Exceptional&lt;ReplayData&gt; ParseReplayData()\n {\n if (!File.Exists(_replayFilePath))\n return new FileNotFoundException(ERROR_FILE_DOES_NOT_EXIST).ToExceptional&lt;ReplayData&gt;();\n\n if (Path.GetExtension(_replayFilePath) != SUPPORTED_FILE_EXTENSION)\n return new NotSupportedException(ERROR_FILE_EXTENSION_NOT_SUPPORTED).ToExceptional&lt;ReplayData&gt;();\n\n byte[] replayFileBytes = File.ReadAllBytes(_replayFilePath);\n if (replayFileBytes.Length &lt; REPLAY_MINIMUM_BYTE_LENGTH)\n return new InvalidOperationException(ERROR_FILE_BYTE_LENGTH_TOO_SMALL).ToExceptional&lt;ReplayData&gt;();\n\n\n\n _replayData = new ReplayData();\n ..... //Parse Replay \n return new Exceptional(_replayData);\n }\n} \n</code></pre>\n\n<p>usage:</p>\n\n<pre><code>private void UseParser()\n{\nvar parser = new Parser(\"path/to/file\");\n\nvar result = parser.ParseReplayData();\n\nif(result.HasException)\n{\n Console.WriteLine(result.Exception.Message);\n return;\n }\n\n Console.WriteLine(result.Value);\n}\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-09-09T14:01:55.677", "Id": "49306", "Score": "0", "body": "You do realize that the built-in exceptions are basically the same as the exception monad, right? Except they are built-in, so they have better syntax." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-09-10T11:54:43.800", "Id": "49419", "Score": "3", "body": "I think the exception monad is not the same as the build in exceptions. I think a monad is a more composite approach, cause it can either has an error or an result. When you deal with mass operations, it can be handy to select out the error ones, without loosing the generic result type. I think exceptions are only classes, but they are throwable. The tuple monad is basically the same thing as the exception monad, but it doesn't have special semantics." } ], "meta_data": { "CommentCount": "2", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-09-09T11:34:35.227", "Id": "30978", "ParentId": "30774", "Score": "2" } }, { "body": "<p>Some \"error\" states may not be critical during data parsing. In these cases, you want to to be alerted of the error and decide whether to continue or stop parsing.</p>\n\n<p>I recommend using events for this purpose.</p>\n\n<pre><code>public class ParseErrorArgs : EventArgs\n{\n public string Reason {get; private set;}\n public bool Stop {get;set;}\n public ParseErrorArgs(string reason)\n {\n this.Reason = reason;\n }\n}\n\n// in your parser class\npublic event EventHandler&lt;ParseErrorArgs&gt; Error;\n\nprotected virtual void OnError(ParseErrorArgs e)\n{\n if (Error != null) Error(this, e);\n}\n\n// then when you encountered an error\nvar args = new ParseErrorArgs(\"message\");\nthis.OnError(args);\nif (args.Stop) break;\n</code></pre>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-12-18T05:26:59.363", "Id": "74025", "ParentId": "30774", "Score": "2" } } ]
{ "AcceptedAnswerId": "30792", "CommentCount": "1", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-09-04T14:01:50.297", "Id": "30774", "Score": "10", "Tags": [ "c#", "error-handling" ], "Title": "Cleaner way of returning true/false with error message" }
30774
<p>This is my first C++ program with classes, and I don't want to develop bad skills. It's very simple and consists of 3 files. This is an exercise from a book, hence the name of the driver file.</p> <p>Please tell me whether it's proper or not!</p> <p><strong>parity.cpp:</strong></p> <pre><code>#include &lt;iostream&gt; #include "parity.h" void Parity::put(int number) { numbers.push_back(number); } bool Parity::test(void) { if (numbers.size() % 2 == 0) return true; else return false; } </code></pre> <p><strong>parity.h:</strong></p> <pre><code>#ifndef PARITY_H_ #define PATITY_H_ #include &lt;string&gt; #include &lt;vector&gt; class Parity { private: std::vector&lt;int&gt; numbers; public: void put(int number); bool test(void); }; #endif </code></pre> <p><strong>13_1.cpp</strong></p> <pre><code>#include &lt;iostream&gt; #include "parity.h" int main() { int number; bool odd_number; Parity parity_test; while(true) { std::cout &lt;&lt; "Enter an integer: "; std::cin &gt;&gt; number; if (number == 0) { break; } else { parity_test.put(number); odd_number = parity_test.test(); std::cout &lt;&lt; odd_number; } } return 0; } </code></pre>
[]
[ { "body": "<p><a href=\"http://www.cplusplus.com/forum/articles/10627/\" rel=\"nofollow\">Some general guidelines regarding <code>#include</code>s</a>:</p>\n\n<ul>\n<li>only <code>#include</code> in the header when necessary (this reduces potentially unwanted dependencies)</li>\n<li>whenever possible, forward declare in the header instead of using <code>#include</code></li>\n<li>whenever possible, <code>#include</code> in the implementation only (this does not affect dependency)</li>\n<li>never <code>#include</code> a source file (having to do so indicates a hierarchy issue)</li>\n<li>be sure to never allow files to <code>#include</code> each other (sort of in a \"circular\" manner)</li>\n</ul>\n\n<hr>\n\n<ul>\n<li><p>You have a typo in your header guard:</p>\n\n<pre><code>#ifndef PARITY_H_\n#define PATITY_H_ // should be PARITY_H_\n</code></pre></li>\n<li><p>The class isn't doing anything with <code>&lt;iostream&gt;</code> and <code>&lt;string&gt;</code>, so just remove them.</p></li>\n<li><p><code>test()</code> doesn't need the <code>void</code> parameter; that's only for C.</p></li>\n<li><p>This:</p>\n\n<pre><code>if (numbers.size() % 2 == 0)\n return true;\nelse return false;\n</code></pre>\n\n<p>can be shortened to this:</p>\n\n<pre><code>return (numbers.size() % 2 == 0); // the statement's Boolean value is returned\n</code></pre></li>\n<li><p>You can use <a href=\"http://www.cplusplus.com/reference/ios/boolalpha/\" rel=\"nofollow\"><code>std::boolalpha</code></a> to display a <code>bool</code> as \"true\" for <code>1</code> or \"false\" for <code>0</code>:</p>\n\n<pre><code>std::cout &lt;&lt; std::boolalpha &lt;&lt; odd_number;\n</code></pre></li>\n<li><p>The <code>while</code> and <code>if-else</code> don't seem too intuitive. The loop just runs until you <code>break</code> from it, and it's not directly tied to <code>number</code>. One alternative is to do an initial input before the loop:</p>\n\n<pre><code>// initial input before loop-- number may be 0\nstd::cout &lt;&lt; \"Enter an integer: \";\nint number; // move the declaration here\nstd::cin &gt;&gt; number;\n\n// if not 0, proceed until it's 0\nwhile (number != 0)\n{\n parity_test.put(number);\n bool odd_number = parity_test.test(); // initialize here instead\n std::cout &lt;&lt; \"odd number? \" &lt;&lt; std::boolalpha &lt;&lt; odd_number;\n\n // input again\n std::cout &lt;&lt; \"Enter an integer: \";\n std::cin &gt;&gt; number;\n}\n</code></pre></li>\n</ul>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-09-04T17:43:51.877", "Id": "48955", "Score": "0", "body": "thank you :) \nso the usage of classes is okay?" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-09-04T17:49:01.990", "Id": "48958", "Score": "0", "body": "For this objective? I suppose. Even if this could be more concise and/or more logical as a procedural program, it's good to get into classes as soon as possible. I think this is an okay start, and you haven't yet made any serious class-related mistakes. You're free to search for other good examples of classes and do something else like it." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-09-04T18:04:17.663", "Id": "48963", "Score": "1", "body": "Keep up the learning (as I will continue to do as well)! These are good questions." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-09-05T05:23:51.347", "Id": "49001", "Score": "0", "body": "Excellent review. To avoid repeating the prompt code, I would structure it like this: \n\n `while (cout << \"Enter an integer: \",\n cin >> number,\n number != 0) {\n parity_test.put(number);\n }`\n\n(with a newline after each comma, which I can't render in this comment)." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-09-05T05:47:59.213", "Id": "49003", "Score": "0", "body": "@200_success: Yeah, I was thinking about the repeated prompt code. @druciferre's `do-while` loop is a great alternative, but I've also heard some say that such a loop may be less-readable at times (not too sure why, though). Either way, there's different ways to do this." } ], "meta_data": { "CommentCount": "5", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-09-04T16:41:58.367", "Id": "30781", "ParentId": "30779", "Score": "10" } }, { "body": "<p>All of Jamal's points are correct, so I won't repeat those. However, I think two essential things were missed.</p>\n\n<p>First of all, you don't need to store a vector of numbers here, so don't. I'm not sure why you'd want to in the first place; perhaps it eases debugging, or something to that effect. However, if that's the goal, some kind of logging sounds significantly more sensible.</p>\n\n<p>Secondly, <code>test</code> doesn't modify the object it is called on, and should thus be <code>const</code>.</p>\n\n<p>Put together:</p>\n\n<pre><code>// parity.h\n\nclass Parity\n{\n private:\n bool parity = true;\n\n public:\n void put(int number);\n bool test() const;\n};\n</code></pre>\n\n<p>Note that this also saves you some includes.</p>\n\n<pre><code>// parity.cpp\n\nvoid Parity::put(int number) {\n // use number for whatever debugging purposes you had.\n parity = !parity;\n}\n\nbool Parity::test() const {\n return parity;\n}\n</code></pre>\n\n<p>In your <code>main</code> function, you should reduce the scopes of some things, but nothing significant.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-09-04T23:28:44.190", "Id": "48992", "Score": "0", "body": "Ah, I've forgotten about the `const`. I suppose `int number` could also be `const` in `put()`, but that's not as important as the one you've mentioned." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-09-08T21:50:51.007", "Id": "49276", "Score": "0", "body": "If you're not storing ints anymore, then naming the function `put` seems a bit misleading. But eh." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-09-09T15:31:34.713", "Id": "49313", "Score": "0", "body": "@cHao I'm guessing the \"put\" has some kind of semantic in the context this is written in. This is an implementation change, so I'd say either the name was wrong to begin with, or it remains correct." } ], "meta_data": { "CommentCount": "3", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-09-04T21:48:48.350", "Id": "30797", "ParentId": "30779", "Score": "4" } }, { "body": "<p>Did you consider making your <code>Parity</code> class a template class that inherits from <code>std::vector</code>? This would provide your parity class with all of the features of <code>std::vector</code>, prevent you from having to redefine <code>push_back(...)</code>, and allow you to use your <code>Parity</code> class with types other than <code>int</code>. </p>\n\n<h3>Parity.h</h3>\n\n<pre><code>#ifndef PARITY_H_\n#define PARITY_H_\n\n#include &lt;vector&gt;\n\ntemplate&lt;typename _T&gt; class Parity: public std::vector&lt;_T&gt;\n{\n public:\n bool test()\n {\n return this-&gt;size() % 2 == 0;\n }\n};\n\n#endif\n</code></pre>\n\n<p>Rather than breaking out of your loop, or using a <code>while(...)</code> loop and having to write the code for the prompt twice, it would be better to with a <code>do... while(...)</code> loop. Also, something a wise person once told me was to get in the habit of putting literal numbers on the left hand side of logical comparisons. This prevents you from doing this <code>while( number = 0 )</code> when you meant to do this <code>while( number != 0 )</code> or <code>while( number == 0 )</code>. The compiler will throw an error if you do <code>while( 0 = number )</code>. </p>\n\n<h3>13_1.cpp</h3>\n\n<pre><code>#include &lt;iostream&gt;\n#include \"parity.h\"\n\nint main()\n{\n int number;\n Parity&lt;int&gt; parity_test;\n\n do\n {\n std::cout &lt;&lt; \"Enter an integer: \";\n std::cin &gt;&gt; number;\n parity_test.push_back(number);\n std::cout &lt;&lt; std::boolalpha &lt;&lt; parity_test.test() &lt;&lt; \" \";;\n }\n while( 0 != number);\n\n return 0;\n}\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-09-05T05:58:41.430", "Id": "49004", "Score": "0", "body": "@Jamal The do-while loop is not *quite* identical in behaviour to the original, if the first input is `0`." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-09-05T06:23:25.457", "Id": "49005", "Score": "0", "body": "@200_success: Ah, right. Here, if the first input is zero, the functions will still be called. For mine, the entire loop (with the function calls) will be skipped. Compared to the OP's, mine looks more similar (but that doesn't mean it's automatically better)." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-09-05T06:31:40.443", "Id": "49006", "Score": "0", "body": "@Jamal It's important not to introduce subtle bugs during code review. =) If you change the behaviour, it should be intentional." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-09-05T09:01:42.760", "Id": "49013", "Score": "1", "body": "[Inheriting from standard containers is generally not recommended](http://stackoverflow.com/q/2034916/559931); is there a particular reason this is an exception? (Also, `test` should still be `const` and `_T` is a reserved name.)" } ], "meta_data": { "CommentCount": "4", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-09-05T02:30:58.507", "Id": "30802", "ParentId": "30779", "Score": "3" } }, { "body": "<p>Taking the minimalist approach, a class is not necessary since the function itself can contain enough state using a static function variable:</p>\n\n<pre><code>bool put(int)\n{\n static bool hasParity = false;\n return hasParity = !hasParity;\n}\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-09-09T15:32:04.343", "Id": "49314", "Score": "1", "body": "This breaks as soon as you want to store multiple parities. You also can't read the parity without flipping it." } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-09-06T02:55:29.760", "Id": "30850", "ParentId": "30779", "Score": "0" } } ]
{ "AcceptedAnswerId": "30781", "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-09-04T16:04:44.130", "Id": "30779", "Score": "6", "Tags": [ "c++", "beginner", "classes" ], "Title": "Testing parity of number of items" }
30779
<p>I want to ensure that, as much as possible given my skill level, that I'm using relevant patterns correctly and following naming conventions. This is a controller for a poor-mans <a href="http://en.wikipedia.org/wiki/Mud_client" rel="nofollow">MUD client</a> using Apache <code>TelnetClient</code>. The <a href="https://github.com/THUFIR/TelnetConsole" rel="nofollow">project</a> is on GitHub.</p> <p>The <code>startReadPrintThreads</code> starts threads by instantiating workers, which in turn start the I/O threads. When a message is received, the <code>CharacterDataQueueWorker</code> notifies the controller, and the controller will then <code>sendMessages</code> from the <code>ConcurrentLinkedQueue&lt;Command&gt;</code>, to which both i/o threads can add. Only <code>sendCommands</code> can pop, or remove, a <code>Command</code> from the <code>commandsQueue</code>.</p> <ol> <li>Is this producer-consumer, or a backwards producer consumer pattern?</li> <li>Are the naming conventions followed?</li> <li>Are there any glaring mistakes or antipatterns?</li> </ol> <p></p> <pre><code>package telnet; import static java.lang.System.out; import java.io.IOException; import java.io.OutputStream; import java.net.InetAddress; import java.net.SocketException; import java.net.UnknownHostException; import java.util.Iterator; import java.util.Observable; import java.util.Observer; import java.util.Properties; import java.util.concurrent.ConcurrentLinkedQueue; import org.apache.commons.net.telnet.TelnetClient; public final class Controller implements Runnable, Observer { private TelnetClient telnetClient = new TelnetClient(); private InputStreamWorker remoteOutputWorker = new InputStreamWorker(); private ConsoleReader localInputReader = new ConsoleReader(); private CharacterDataQueueWorker remoteDataQueueWorker = new CharacterDataQueueWorker(); private RemoteOutputRegexMessageWorker remoteMessageWorker = new RemoteOutputRegexMessageWorker(); private final ConcurrentLinkedQueue&lt;Character&gt; remoteCharDataQueue = new ConcurrentLinkedQueue(); private final ConcurrentLinkedQueue&lt;Command&gt; commandsQueue = new ConcurrentLinkedQueue(); private Controller() { } public void startReadPrintThreads() throws SocketException, IOException { remoteOutputWorker.print(telnetClient.getInputStream(), remoteCharDataQueue); localInputReader.read(); localInputReader.addObserver(this); remoteDataQueueWorker.read(remoteCharDataQueue); remoteDataQueueWorker.addObserver(this); } private void sendCommands() { String commandString = null; Iterator it = commandsQueue.iterator(); byte[] commandBytes = null; OutputStream outputStream = telnetClient.getOutputStream(); while (it.hasNext()) { try { commandBytes = commandsQueue.remove().getCommand().getBytes(); outputStream.write(commandBytes); outputStream.write(10); outputStream.flush(); } catch (IOException ex) { out.println("sendCommand\n" + ex); } } } @Override public void update(Observable o, Object arg) { if (o instanceof CharacterDataQueueWorker) { String remoteOutputMessage = remoteDataQueueWorker.getFinalData(); remoteMessageWorker.parseWithRegex(remoteOutputMessage); sendCommands(); } if (o instanceof ConsoleReader) { String commandString = localInputReader.getCommand(); Command command = new Command(commandString); commandsQueue.add(command); sendCommands(); } } @Override public void run() { try { Properties props = PropertiesReader.getProps(); InetAddress host = InetAddress.getByName(props.getProperty("host")); int port = Integer.parseInt(props.getProperty("port")); telnetClient.connect(host, port); startReadPrintThreads(); } catch (UnknownHostException ex) { out.println(ex); } catch (SocketException ex) { out.println(ex); } catch (IOException ex) { out.println(ex); } } public static void main(String[] args) throws SocketException, IOException { new Controller().run(); } } </code></pre>
[ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-09-08T07:20:59.633", "Id": "49253", "Score": "0", "body": "By the way... Don't you think, that a comment \"This question came from our site for professional and enthusiast programmers\" visible, when a question has been moved from SO, suggests, that this forum is dedicated for new, unskilled programmers with no enthusiasm ? :( The first one is probably correct, but what with the second one... : )" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-09-08T07:44:00.690", "Id": "49255", "Score": "0", "body": "LOL, yeah, maybe that verbiage allows that inference. OTOH, what's the message going the other way?" } ]
[ { "body": "<p>Member Variables: You define two of them as <code>final</code>, yet never a assign a new value to any of them. Might as well just make them all <code>final</code>.</p>\n\n<hr>\n\n<p><code>sendCommands()</code>:</p>\n\n<ul>\n<li><code>commandString</code> is never being used.</li>\n<li><code>commandBytes</code> define it within the tightest scope as you can. If you define it as the first line of the try, you never have to worry about it being null or having some other value from a previous usage.</li>\n<li>It seems weird that you are using <code>it.hasNext()</code> but never calling <code>it.next()</code> to do the iteration. If all you care about is if the collection has any remaining values, use <code>!commandsQueue.isEmpty()</code>. What you are doing is depending on an implementation detail that might be changed. The returned iterator could be of a snapshot of the collection and not change if the collection is later altered.</li>\n</ul>\n\n<hr>\n\n<p><code>update()</code>:</p>\n\n<p>I prefer to have 2 <code>Observer</code> instances instead of having to check the type of the <code>Observable</code> passed into the method.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-09-04T19:15:40.180", "Id": "48969", "Score": "0", "body": "thanks, in particular, for help with the iterator. Yes, I just want to pop commands until it's empty. Why does a `System.out` from finally, in the iteration of `commandQueue`, keep outputting when running. Is there an uncaught exception?" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-09-04T20:45:58.757", "Id": "48980", "Score": "0", "body": "@Thufir: It's hard to tell what you are asking. However, it sounds like you are asking \"Why doesn't this code work correctly in this specific instance?\" your initial question was moved to Code review because it was asking \"does my code look good?\" This follow up question seems like it would be a better fit for StackOverflow if it was fleshed out with more code, information about the inputs, expected outputs and what the actual output is." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-09-04T21:17:50.520", "Id": "48984", "Score": "0", "body": "The original question could be boiled down to \"am I doing this wrong?\" in a general sense. So that I didn't go too far with bad design choices. The bug mentioned above has been \"fixed\" but maybe not in a good way. It just seems very awkward to keep track of the different objects changing this Queue or that, and what updates what, and what listens to what, etc. I'm going to have read more about what `final` means and its usage. For now, I left out that keyword, because sometimes I *do* want to, for instance, reset the `commandQueue` just by giving it a new reference." } ], "meta_data": { "CommentCount": "3", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-09-04T18:44:26.883", "Id": "30786", "ParentId": "30784", "Score": "1" } } ]
{ "AcceptedAnswerId": "30786", "CommentCount": "2", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-09-04T10:02:59.457", "Id": "30784", "Score": "2", "Tags": [ "java", "design-patterns", "multithreading", "controller", "producer-consumer" ], "Title": "Controller for a MUD client" }
30784
<p>I choose to use a dictionary to store the variables for fast <code>GET</code> and <code>SET</code> commands. In my code, I have saved all of the open transactional blocks in memory. I can't see any way around this since it is always possible to have enough <code>ROLLBACK</code> commands to access all open blocks. </p> <p>One problem I do have is that <code>numequalto_command()</code> is not \$ O(logN) \$. Since I am using a dictionary, I must check each value to count them. So right now it is \$ O(N) \$.</p> <p>Does anyone have any idea how to make this faster? Should I create another dictionary where the keys are the values of the original dictionary and the values are their counts?</p> <p>Anyways, here is my code (written very quickly and not very neat):</p> <pre><code>def set_command(db,name,value): if name not in db: db[name]=[] db[name].append(value) else: db[name].append(value) return db def get_command(db,name): if len(db[name])&gt;0: print db[name][-1] else: print "NULL" def numequalto_command(db,value): count=0 for key in db: if db[key][-1]==value: count+=1 print count def rollback(db,block): for i in block: if (i.split(' ')[0]=='SET') or (i.split(' ')[0]=='UNSET'): del(db[i.split(' ')[1]])[-1] return db def execute_trans_block(block,database): for i in block: if i.split(' ')[0]=='SET': database=set_command(database,i.split(' ')[1],i.split(' ')[2]) elif i.split(' ')[0]=='GET': name=i.split(' ')[1] get_command(database,name) elif i.split(' ')[0]=='UNSET': database=set_command(database,i.split(' ')[1],'NULL') elif i.split(' ')[0]=='NUMEQUALTO': numequalto_command(database,i.split(' ')[1]) def main(): sampleIn1=['SET a 10','GET a','UNSET a','GET a','END'] sampleIn2=['SET a 10','SET b 10','NUMEQUALTO 10','NUMEQUALTO 20','UNSET a','NUMEQUALTO 10','SET b 30','NUMEQUALTO 10','END'] sampleIn3=['BEGIN','SET a 10','GET a','BEGIN','SET a 20','GET a','ROLLBACK','GET a','ROLLBACK','GET a','END'] sampleIn4=['BEGIN','SET a 30','BEGIN','SET a 40','COMMIT','GET a','ROLLBACK','END'] sampleIn5=['SET a 10','BEGIN','NUMEQUALTO 10','BEGIN','UNSET a','NUMEQUALTO 10','ROLLBACK','NUMEQUALTO 10','END'] sampleIn6=['SET a 50','BEGIN','GET a','SET a 60','BEGIN','UNSET a','GET a','ROLLBACK','GET a','COMMIT','GET a','END'] case=sampleIn6 database={} trans_blocks=[] i=0 while (case[i]!='END'): #if there is a 'BEGIN', this means the start of a block that we want to save if case[i]=='BEGIN': block=[] j=i+1 while (case[j]!='BEGIN') and (case[j]!='ROLLBACK') and (case[j]!='COMMIT') : block.append(case[j]) j+=1 execute_trans_block(block,database) trans_blocks.append(block) i=j #'ROLLBACK' means undo SETS and UNSETS from most recent block elif case[i]=='ROLLBACK': if len(trans_blocks)&gt;0: database=rollback(database,trans_blocks[-1]) del(trans_blocks[-1]) else: print 'NO TRANSACTION' i+=1 #'COMMIT' means delete all saved blocks elif case[i]=='COMMIT': trans_blocks=[] i+=1 #for statements written outside a block. Just execute them. else: execute_trans_block([case[i]],database) i+=1 if __name__ == '__main__': main() </code></pre> <p>I made a change by introducing a separate dictionary holding the frequency for that values in the original dictionary. Its pretty ugly but it seems to work</p> <pre><code>def set_command(db,name,value,freq): if name in db: freq[db[name][-1]]-=1 if value not in freq: freq[value]=1 else: freq[value]+=1 if name not in db: db[name]=[] db[name].append(value) else: db[name].append(value) def get_command(db,name): if len(db[name])&gt;0: print db[name][-1] else: print "NULL" def numequalto_command(db,value,freq): if value in freq: print freq[value] else: print 0 def rollback(db,block,freq): for i in block: if (i.split(' ')[0]=='SET') or (i.split(' ')[0]=='UNSET'): del(db[i.split(' ')[1]])[-1] if i.split(' ')[0]=='SET': freq[i.split(' ')[2]]-=1 elif i.split(' ')[0]=='UNSET': freq[db[i.split(' ')[1]][-1]]+=1 return db def execute_trans_block(block,database,freq): for i in block: if i.split(' ')[0]=='SET': set_command(database,i.split(' ')[1],i.split(' ')[2],freq) elif i.split(' ')[0]=='GET': name=i.split(' ')[1] get_command(database,name) elif i.split(' ')[0]=='UNSET': set_command(database,i.split(' ')[1],'NULL',freq) elif i.split(' ')[0]=='NUMEQUALTO': numequalto_command(database,i.split(' ')[1],freq) def main(): sampleIn1=['SET a 10','GET a','UNSET a','GET a','END'] sampleIn2=['SET a 10','SET b 10','NUMEQUALTO 10','NUMEQUALTO 20','UNSET a','NUMEQUALTO 10','SET b 30','NUMEQUALTO 10','END'] sampleIn3=['BEGIN','SET a 10','GET a','BEGIN','SET a 20','GET a','ROLLBACK','GET a','ROLLBACK','GET a','END'] sampleIn4=['BEGIN','SET a 30','BEGIN','SET a 40','COMMIT','GET a','ROLLBACK','END'] sampleIn5=['SET a 10','BEGIN','NUMEQUALTO 10','BEGIN','UNSET a','NUMEQUALTO 10','ROLLBACK','NUMEQUALTO 10','END'] sampleIn6=['SET a 50','BEGIN','GET a','SET a 60','BEGIN','UNSET a','GET a','ROLLBACK','GET a','COMMIT','GET a','END'] case=sampleIn6 freq_dict={} database={} trans_blocks=[] i=0 while (case[i]!='END'): #if there is a 'BEGIN', this means the start of a block that we want to save if case[i]=='BEGIN': block=[] j=i+1 while (case[j]!='BEGIN') and (case[j]!='ROLLBACK') and (case[j]!='COMMIT') : block.append(case[j]) j+=1 execute_trans_block(block,database,freq_dict) trans_blocks.append(block) i=j #'ROLLBACK' means undo SETS and UNSETS from most recent block elif case[i]=='ROLLBACK': if len(trans_blocks)&gt;0: database=rollback(database,trans_blocks[-1],freq_dict) del(trans_blocks[-1]) else: print 'NO TRANSACTION' i+=1 #'COMMIT' means delete all saved blocks elif case[i]=='COMMIT': trans_blocks=[] i+=1 #for statements written outside a block. Just execute them. else: execute_trans_block([case[i]],database,freq_dict) i+=1 if __name__ == '__main__': main() </code></pre>
[]
[ { "body": "<p>Python has a built in dictionary method for <code>numequalto</code>:</p>\n\n<pre><code>print dict.values().count(value)\n</code></pre>\n\n<p>I don't know exactly how fast this is, but am sure it is faster than implementing your own O(N) function. Unfortunately it isn't compatible with your implementation of <code>rollback</code>. It would require you to have only one value for each name in the dictionary, rather than a list. I would anyway consider finding other, more memory-efficient ways to implement rollback which would also allow you to use dictionaries more easily.</p>\n\n<p>By the way, there is no need for functions to return dictionary objects, as Python in any case passes dictionaries by reference, so the original object is being edited. (For illustration, try the following)</p>\n\n<pre><code>def change_dictionary(d):\n d['new_key'] = 'something new'\nd = {'original key': 'something'}\nchange_dictionary(d)\nprint d\n</code></pre>\n\n<p>EDIT: this is how you could do it using an undo list.</p>\n\n<pre><code>def run_database(input_lines):\n def set(name, value):\n if undo:\n undo.append((name, database.get(name)))\n database[name] = value\n def unset(name):\n if undo:\n undo.append((name, database.get(name)))\n del database[name]\n def get(name):\n print database.get(name, 'NULL')\n def begin():\n undo.append('stop')\n def numequalto(value):\n print database.values().count(value)\n def rollback():\n while undo:\n action = undo.pop()\n if action == 'stop':\n break\n name, value = action\n if value is None and name in database:\n del database[name]\n elif value is not None:\n database[name] = value\n else:\n print \"NO TRANSACTION\" \n def commit():\n if undo:\n del undo[:]\n else:\n print \"NO TRANSACTION\" \n\n undo = []\n database = {}\n commands = {'SET': set, 'UNSET': unset, 'GET': get, 'BEGIN': begin, \n 'NUMEQUALTO': numequalto, 'ROLLBACK': rollback, 'COMMIT': commit}\n for line in input_lines:\n if line == 'END':\n break\n else:\n words = line.split()\n commands[words[0]](*words[1:])\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-09-04T19:34:41.033", "Id": "48973", "Score": "0", "body": "I am using the list in the dictionary to keep track of the previous values so I can delete the newest ones when rollback occurs. I'm not really sure of another way to do this." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-09-04T19:38:22.483", "Id": "48974", "Score": "0", "body": "You could have separate dictionaries for each open transaction, for example, or keep a list of 'undo' instructions that would reverse the instructions that have been carried out." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-09-04T19:49:26.690", "Id": "48975", "Score": "0", "body": "If you don't want to do that you could also do `[L[-1] for L in db.values()].count(value)`, which would be faster than what you have. Another possibility: use [collections.Counter](http://docs.python.org/2/library/collections.html#collections.Counter)" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-09-04T20:13:55.597", "Id": "48977", "Score": "0", "body": "I made an edit. This time I added another dictionary to keep track of the frequencies. It seems to work on the test cases" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-09-04T20:37:23.233", "Id": "48979", "Score": "0", "body": "Okay but I think you need to implement rollback differently to solve the problem in a memory-efficient (and less ugly) way. I would try keeping an 'undo list' of instructions that reverse the given instructions." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-09-04T20:54:40.643", "Id": "48982", "Score": "0", "body": "OK. I assume you mean that for each block I should make a list that undoes what is done in that block and if a ROLLBACK occurs I would execute the list of undo instructions. I do agree that this is more elegant, but is it more memory-efficient? It seems like I am just replacing lists of previous values with lists of undo instructions." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-09-04T21:13:50.497", "Id": "48983", "Score": "0", "body": "apologies, you're right. It's no more memory-efficient. Just much neater and easier." } ], "meta_data": { "CommentCount": "7", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-09-04T19:05:01.597", "Id": "30788", "ParentId": "30785", "Score": "1" } } ]
{ "AcceptedAnswerId": "30788", "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-09-04T18:23:46.983", "Id": "30785", "Score": "2", "Tags": [ "python", "database" ], "Title": "Building a simple database in Python" }
30785
<p>The object is to be able to pass some dates (start date, holiday) and the number of days you want to skip. We only want to skip working days, not weekends and holidays. </p> <p>Just let me know what you'd do different than what I have. The code works, but I was told there are issues with it, but not told what issues they are.</p> <pre><code>function getWDays($startDate,$holiday,$wDays){ $d = new DateTime( $startDate ); $t = $d-&gt;getTimestamp(); $h = strtotime($holiday); // loop for $wDays days for($i=0; $i&lt;$wDays; $i++){ // 1 day = 86400 seconds $addDay = 86400; $nextDay = date('w', ($t+$addDay)); if($nextDay == 0 || $nextDay == 6) { $i--; } $t = $t+$addDay; if ($t == $h) { // lets make sure the holiday isn't one of our weekends if(!$nextDay == 0 || !$nextDay == 6) { $t = $t+$addDay; } } } $d-&gt;setTimestamp($t); return $d-&gt;format( 'Y-m-d' ); } echo getWDays("2013-08-29","2013-09-02", 3) </code></pre>
[]
[ { "body": "<p>Here is another way of doing the same thing</p>\n\n<pre><code>&lt;?php\n\nfunction getWDays($startDate,$holiday,$wDays) {\n\n // using + weekdays excludes weekends\n $new_date = date('Y-m-d', strtotime(\"{$startDate} +{$wDays} weekdays\"));\n\n $holiday_ts = strtotime($holiday);\n\n // if holiday falls between start date and new date, then account for it\n if ($holiday_ts &gt;= strtotime($startDate) &amp;&amp; $holiday_ts &lt;= strtotime($new_date)) {\n\n // check if the holiday falls on a working day\n $h = date('w', $holiday_ts);\n if ($h != 0 &amp;&amp; $h != 6 ) {\n // holiday falls on a working day, add an extra working day\n $new_date = date('Y-m-d', strtotime(\"{$new_date} + 1 weekdays\"));\n }\n }\n\n return $new_date;\n}\n\n// here is an example\n$start = \"2013-08-29\";\n$holiday = \"2013-09-02\";\n$wDays = 3;\n\necho \"Start: \",date(\"Y-m-d D\", strtotime($start)),\"&lt;br /&gt;\";\necho \"Holiday: \",date(\"Y-m-d D\", strtotime($holiday)),\"&lt;br /&gt;\";\necho \"WDays: $wDays&lt;br /&gt;\";\n\necho getWDays($start, $holiday, $wDays);\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-09-05T21:59:52.800", "Id": "49087", "Score": "0", "body": "Thanks for the reply. I like your use of Weekdays. I need to use that more often. Much appreciated." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-10-12T18:02:48.333", "Id": "449399", "Score": "0", "body": "what about multiple holidays ?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-11-11T15:13:58.233", "Id": "496186", "Score": "0", "body": "see here : https://stackoverflow.com/questions/21142917/get-3-next-working-dates-skip-weekends-and-holidays" } ], "meta_data": { "CommentCount": "3", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-09-05T10:46:35.283", "Id": "30813", "ParentId": "30791", "Score": "2" } } ]
{ "AcceptedAnswerId": "30813", "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-09-04T20:26:11.867", "Id": "30791", "Score": "2", "Tags": [ "php", "datetime" ], "Title": "Get Next Working Date, skip weekends and holidays" }
30791
<p>I have created a linked list in C++, I suspect there is a good chance I have made some larger errors in this code as I am working with a few concepts new to me. Please be very hard on me as I want to eventually be good at this.</p> <pre><code>#include &lt;iostream&gt; // basic linked list implimentation in C++ using templates template &lt;class T&gt; class linkedList { public: linkedList(); //constructor ~linkedList(); //destructor void push_back(const T &amp;value); void deleteNodes(const T &amp;value); void printList(); void reverseList(); void deleteList(); private: struct _node { T val; linkedList *next; }; struct _node node ; linkedList *root = NULL; }; template&lt;class T&gt; linkedList&lt;T&gt;::linkedList(){}; template&lt;class T&gt; linkedList&lt;T&gt;::~linkedList(){}; template&lt;class T&gt; void linkedList&lt;T&gt;::deleteList() { linkedList *t = root; while (t) { t = root-&gt;node.next; delete root; root = t; } } template&lt;class T&gt; void linkedList&lt;T&gt;::printList() { if(!root) std::cout&lt;&lt;"List is empty"&lt;&lt;std::endl; else { linkedList *t = root; while (t) { std::cout&lt;&lt;t-&gt;node.val&lt;&lt;std::endl; t = t-&gt;node.next; } } } template &lt;class T&gt; void linkedList&lt;T&gt;::reverseList() { linkedList *temp = NULL, *prev = NULL, *current = root; while (current != NULL) { temp = current-&gt;node.next; current-&gt;node.next = prev; prev = current; current = temp; } root = prev; } template &lt;class T&gt; void linkedList&lt;T&gt;::deleteNodes(const T &amp;value) { linkedList *prev = NULL, *active = NULL; if(!root) std::cout&lt;&lt;"List is empty"&lt;&lt;std::endl; else { if (root&amp;&amp; root-&gt;node.val == value) { linkedList *t = root; root = t-&gt;node.next; delete t; } } prev = root; active = root-&gt;node.next; while (active) { if (active-&gt;node.val == value) { prev-&gt;node.next = active-&gt;node.next; delete active; active = prev-&gt;node.next; } else { prev = active; active = active-&gt;node.next; } } } template&lt;class T&gt; void linkedList&lt;T&gt;::push_back(const T &amp;value) { if (!root) { root = new linkedList&lt;T&gt;(); root-&gt;node.val = value; } else { linkedList *ptr = root; while (ptr-&gt;node.next) { ptr = ptr-&gt;node.next; } ptr-&gt;node.next = new linkedList&lt;T&gt;(); ptr = ptr-&gt;node.next; ptr-&gt;node.val = value; } } int main() { linkedList &lt;int&gt; example; for (int i = 1; i&lt;=20; i++) example.push_back(i); example.deleteNodes(20); example.deleteNodes(1); example.deleteNodes(10); example.reverseList(); example.printList(); example.deleteList(); return 0; } </code></pre> <p>Compiled with GCC v 4.7.3 on ubuntu 13.04 with the command:</p> <pre><code>g++ linkedlist.cpp -Wall -std=c++0x -o linkedlist.o </code></pre> <hr> <p>Here is the latest version I have made with the suggested changes. I still need to implement iterators. </p> <pre><code>#include &lt;iostream&gt; // basic linked list implementation in C++ using templates template &lt;class T&gt; class linkedList { public: ~linkedList(); //destructor void push_back(const T &amp;value); void delete_nodes(const T &amp;value); void print_list() const; void reverse_list(); void clear(); void erase(size_t pos); private: struct _node { T val; _node *next; }; _node *root = NULL; }; template &lt;class T&gt; linkedList&lt;T&gt;::~linkedList&lt;T&gt;() { clear(); } template &lt;class T&gt; void linkedList&lt;T&gt;::clear() { struct _node *t =NULL; while (t) { t = root-&gt;next; delete root; root = t; } } template &lt;class T&gt; void linkedList&lt;T&gt;::erase(size_t pos) { struct _node *current = root; struct _node *prev = NULL; size_t i = 0; while (current != NULL) { if (pos == i) { struct _node *t = current-&gt;next; prev-&gt;next = t; delete current; } ++i; prev = current; current=current-&gt;next; } } template &lt;class T&gt; void linkedList&lt;T&gt;::reverse_list() { struct _node *t = NULL, *prev = NULL, *current = root; while (current != NULL) { t = current-&gt;next; current-&gt;next = prev; prev = current; current = t; } root = prev; } template &lt;class T&gt; void linkedList&lt;T&gt;::delete_nodes(const T &amp;value) { struct _node *prev = NULL; struct _node *active = NULL; if (root == NULL) return; //list is empty else { if (root != NULL &amp;&amp; root-&gt;val == value) { struct _node *t = root; root = t-&gt;next; delete t; } } prev = root; active = root-&gt;next; while (active) { if(active-&gt;val == value) { prev-&gt;next = active-&gt;next; delete active; active = prev-&gt;next; } else { prev = active; active = active-&gt;next; } } } template &lt;class T&gt; void linkedList&lt;T&gt;::push_back(const T &amp;value) { if (root == NULL) { root = new _node; root-&gt;val = value; } else { struct _node *ptr = root; while (ptr-&gt;next != NULL) { ptr = ptr-&gt;next; } //now ptr is at the last spot in the list ptr-&gt;next = new _node; ptr = ptr-&gt;next; ptr-&gt;val = value; ptr-&gt;next = NULL; } } template &lt;class T&gt; void linkedList&lt;T&gt;::print_list() const { struct _node *t = root; while (t) { std::cout&lt;&lt;t-&gt;val&lt;&lt;std::endl; t = t-&gt;next; } } int main() { linkedList &lt;int&gt; example; for (int i = 1; i&lt;=20; i++) example.push_back(i); example.delete_nodes(1); example.delete_nodes(10); example.delete_nodes(20); example.erase(2); example.reverse_list(); example.print_list(); return 0; } </code></pre>
[ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-12-25T12:00:41.027", "Id": "63354", "Score": "0", "body": "Your code still doesn’t follow the Rule of Three Anton mentioned. In particular, you should either provide copy-assignment and and copy-constructor or explicitly disable them (C++98: declare private and do not implement). Otherwise, it’s all too easy to get memory freed too early, and multiple times." } ]
[ { "body": "<p>I'll cover the C++-specific issues first, and then move on to the design decisions you make.</p>\n\n<p>First of all, note that C++ has the <a href=\"http://en.wikipedia.org/wiki/Rule_of_three_%28C%2B%2B_programming%29\" rel=\"nofollow\">Rule of Three</a>. It states that if you have a custom destructor, copy-constructor or copy-assignment operator, you almost certainly need custom implementations for all three. In your code, the destructor does nothing, and you have no reason to define a custom one at all; the same goes for the constructor. If your destructors and constructors aren't doing any custom work, and there's no technical reason they have to be defined past the class definition, leave them implicit.</p>\n\n<p>However, you <em>should</em> be doing some work in the destructor: destroying the list! Your user should not have to call <code>deleteList</code> just for it to be cleaned up correctly; make it be called by default in the destructor. If it was already deleted, it won't do any harm, and if it wasn't it'll save you from a memory leak. (Alternatively: assert that it has been deleted in the destructor. I don't think it'll make you many friends, though.)</p>\n\n<p>Moving on; the way you define <code>_node</code> and <code>node</code> means that <code>val</code> and <code>next</code> are effectively just members of <code>linkedList</code>. Why not get rid of the extra struct and make them members directly? It won't impact performance, the things probably compile to the same code, but it will make accessing them easier.</p>\n\n<p>Your <code>printList</code> function hopefully doesn't modify the list, so you should make it <code>const</code>. Otherwise, people will be unable to work with references to const to your list, which will upset anyone who's used to using the standard library.</p>\n\n<p>I understand this is the first version, but only allowing people to print the list is a little limiting. Ideally, you should be providing (forward) iterators for your list; they aren't hard to implement, being just pointers with custom increment and dereference semantics. Failing that, at least allow one to <a href=\"http://en.cppreference.com/w/cpp/algorithm/for_each\" rel=\"nofollow\">apply a function over the list</a>, or to <a href=\"http://en.cppreference.com/w/cpp/algorithm/accumulate\" rel=\"nofollow\">fold it</a>; that would cover most uses.</p>\n\n<p>At the moment, you seem to be treating the <code>val</code> in the first list as not being a real value. This is rather strange; why are you creating a value that nobody can ever access?</p>\n\n<p>This last point brings us to the design questions. All in all, it looks like you end up half-way between representing the linked list and the nodes as a single type, and representing them separately. Here's a suggested rewrite:</p>\n\n<pre><code>template &lt;class T&gt;\nclass linkedList\n{\n public:\n // delete to satisfy rule of 3.\n linkedList(linkedList const&amp;) = delete;\n linkedList&amp; operator=(linkedList const&amp;) = delete;\n ~linkedList();\n\n // I've renamed your members to be snake_case. It doesn't really\n // matter which one you use, but mixing them inside one class just\n // doesn't look right to me.\n void push_back(const T&amp; value);\n void delete_nodes(const T&amp; value);\n void print_list() const;\n void reverse_list();\n void delete_list();\n\n private:\n // Now we have the choice of whether to represent the list with each\n // node being another linked list, or a single linked list with separate\n // nodes:\n\n#ifdef NODES_SEPARATE\n // In this version, the linkedList is responsible for all nodes:\n struct _node {\n T val;\n _node* next;\n };\n\n _node* root = NULL;\n\n#else\n // In this case, every linked list thinks it is the first in the\n // chain. A little weird, but still usable.\n struct _node {\n T val;\n linkedList list;\n };\n\n _node* next = NULL;\n#endif\n};\n</code></pre>\n\n<p>I could be missing something, but I think you meant to have one of these. (They are likely the same in memory, by the way, it's just a matter of different types.)</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-09-04T22:39:52.040", "Id": "48988", "Score": "0", "body": "Thank you for the review I am working on the changes now. Would you recommend that I simply call my deleteList() function from the destructor? Or would it make more sense to not have a deleteList() function, and have that code directly in the destructor?" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-09-04T22:51:27.687", "Id": "48990", "Score": "3", "body": "@r-s: I would try to mimic standard library containers as much as possible, so I'd have a `clear` function which I'd call from the destructor." } ], "meta_data": { "CommentCount": "2", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-09-04T22:03:18.493", "Id": "30798", "ParentId": "30794", "Score": "5" } }, { "body": "<p>Just a quick note:</p>\n\n<p>In the void linkedList::clear() function you probably mean</p>\n\n<pre><code> struct _node *t =root;\n</code></pre>\n\n<p>and not</p>\n\n<pre><code> struct _node *t =NULL;\n</code></pre>\n\n<p>In the latter, you will never enter the while loop if t == NULL</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-12-24T18:33:07.240", "Id": "38039", "ParentId": "30794", "Score": "2" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "1", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-09-04T21:42:47.567", "Id": "30794", "Score": "2", "Tags": [ "c++", "linked-list" ], "Title": "Basic linked list in C++" }
30794
<p>I'm fairly new to MVC concepts and PHP input validation.</p> <p>I'm open to all input, but I'm largely wanting to know if the following:</p> <ol> <li><p>Follows the MVC pattern correctly - if not, how can I change it to better follow that? </p></li> <li><p>Has any huge apparent security flaws with the validation procedure - if so, what are they and do you have any suggestions for how I can address it?</p></li> </ol> <p>The assumptions are that this form will be available to a pre-defined set of persons within my company on our intranet. It connects to a MySQL database through PDO and utilizes only parameterized queries when working with variables. The actual code checks many more fields and does it for Bid, Campus, Contact, and Company (all exist as seperate models and tables).</p> <p><strong>Bid_Controller.php</strong></p> <pre><code>class Bid_Controller extends Controller{ public function index(){ //load default view that contains the initial form, form action targets the Bid_Controller-&gt;process method through routing } public function process(){ $this-&gt;load-&gt;model('Bid_Model', 'bid'); if($this-&gt;bid-&gt;validateBid()){ // try to save the bid // show errors on fail, success message on success }else{ // load default view, pre-populate fields, show form errors } } } </code></pre> <p><strong>Bid_Model.php</strong></p> <pre><code>class Bid_Model extends Model{ public $bid_date_open; // assume a POST of '9/17/2013' for this public $bid_location; // assume a POST of 'Texas' for this public $bid_company; // assume a POST of 'Walmart' for this public $probability; // assume a POST of '50' for this private $errors; public function validateBid(){ $requiredFields = array( // format of 'field_name', FILTER_TYPE, FILTER_OPTIONS, 'Error Message.' array('bid_company', FILTER_SANITIZE_STRING, FILTER_FLAG_STRIP_LOW | FILTER_FLAG_STRIP_HIGH, "You must enter a company."), array('bid_location', FILTER_SANITIZE_STRING, FILTER_FLAG_STRIP_LOW | FILTER_FLAG_STRIP_HIGH, "You must enter a location.") ); foreach ($requiredFields as $i =&gt; $data) { $sanitizedInput = filter_var($_POST[$data[0]], $data[1], $data[2]); if (empty($sanitizedInput)) { $this-&gt;$data[0] = null; array_push($this-&gt;errors, $data[3]); } else { $this-&gt;$data[0] = $sanitizedInput; } } $notRequiredFields = array( // format of 'field_name', FILTER_TYPE, FILTER_OPTIONS, 'default value' array('bid_date_open', FILTER_SANITIZE_STRING, FILTER_FLAG_STRIP_LOW | FILTER_FLAG_STRIP_HIGH, null), array('bid_probability', FILTER_SANITIZE_INT, null, null) ); foreach ($notRequiredFields as $i =&gt; $data) { $sanitizedInput = filter_var($_POST[$data[0]], $data[1], $data[2]); if (empty($sanitizedInput)) { $this-&gt;$data[0] = $data[3]; } else { $this-&gt;$data[0] = $sanitizedInput; } } } public function fetchErrors(){ // if isset this-&gt;errors, return this-&gt;errors } public function saveBid(){ // use the public variables above as parameters in PDO insert query } } </code></pre>
[]
[]
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-09-04T22:06:04.100", "Id": "30799", "Score": "3", "Tags": [ "php", "mvc", "validation" ], "Title": "Tiny MVC - Handling validation / sanitization in a model" }
30799
<p>I am working on a project in which I will be having different Bundles. Let's take an example, Suppose I have 5 Bundles and each of those bundles will have a method name <code>process</code>.</p> <p>Below are the things, I am supposed to do-</p> <ol> <li>I need to call all those 5 Bundles <code>process</code> method in parallel using multithreaded code and then write to the database. Meaning each bundle will return me back Map of String and String and then I am supposed to write that map into the database. I am not sure what is the right way to do that? Should I have five thread? One thread for each bundle? But what will happen in that scenario, suppose if I have 50 bundles, then I will have 50 threads?</li> <li>And also, I want to have timeout feature as well. If any bundles is taking lot of time than the threshold setup by us, then it should get timeout and log as an error that this bundle has taken lot of time.</li> </ol> <p>The following attempt that I have done is most probably flawed and error handling is by no means complete. And I am looking for best and efficient way of doing this problem.</p> <p>Below is the solution I have. And below is my method which will call <code>process method</code> of all the bundles in a multithreaded way.</p> <pre><code>public void processingEvents(final Map&lt;String, Object&gt; eventData) throws InterruptedException { ExecutorService pool = Executors.newFixedThreadPool(5); List&lt;ProcessBundleHolderEntry&gt; entries = new ArrayList&lt;ProcessBundleHolderEntry&gt;(); Map&lt;String, String&gt; outputs = (Map&lt;String, String&gt;)eventData.get(BConstants.EVENT_HOLDER); for (BundleRegistration.BundlesHolderEntry entry : BundleRegistration.getInstance()) { ProcessBundleHolderEntry processBundleHolderEntry = new ProcessBundleHolderEntry(entry, outputs); entries.add(processBundleHolderEntry); } try { List&lt;Future&lt;Map&lt;String, String&gt;&gt;&gt; futures = pool.invokeAll(entries, 30L, TimeUnit.SECONDS); for (int i = 0; i &lt; futures.size(); i++) { // This works since the list of future objects are in the // same sequential order as the list of entries Future&lt;Map&lt;String, String&gt;&gt; future = futures.get(i); ProcessBundleHolderEntry entry = entries.get(i); if (!future.isDone()) { // log error for this entry } } } catch (InterruptedException e) { pool.shutdownNow(); //cancels the tasks //restore interrupted flag and exit Thread.currentThread().interrupt(); //or rethrow the exception throw e; } } </code></pre> <p>Secondly, an implementation of Callable for your threads:</p> <pre><code>public class ProcessBundleHolderEntry implements Callable&lt;Map&lt;String, String&gt;&gt; { private BundleRegistration.BundlesHolderEntry entry; private Map&lt;String, String&gt; outputs; public ProcessBundleHolderEntry(BundleRegistration.BundlesHolderEntry entry, Map&lt;String, String&gt; outputs) { this.entry = entry; this.outputs = outputs; } public Map&lt;String, String&gt; call() throws Exception { final Map&lt;String, String&gt; response = entry.getPlugin().process(outputs); // write to the database. System.out.println(response); return response; } } </code></pre> <p>Can anyone tell me whether there is any problem with the above approach or is there any better and efficient way of doing the same thing? I am not sure whether there is any thread safety issue as well.</p> <p>Any help will be appreciated on this.</p>
[]
[ { "body": "<blockquote>\n <p>I need to call all those 5 Bundles process method in parallel using\n multithreaded code and then write to the database. I am not sure what\n is the right way to do that? Should I have five thread? One thread for\n each bundle? But what will happen in that scenario, suppose if I have\n 50 bundles, then I will have 50 threads?</p>\n</blockquote>\n\n<p>It is recommended not to have more threads than the number of physical cpu's on that machine in order to be efficient. So if you have 50 Bundles and 8 cores for instances than an <code>ExecutorService</code> with 8 threads should be enough. The bundles will be executed 8 at a time and at most there will be 50/8 rounds of execution. (In real world some of the bundles will execute faster, etc.)</p>\n\n<blockquote>\n <p>And also, I want to have timeout feature as well. If any bundles is\n taking lot of time than the threshold setup by us, then it should get\n timeout and log as an error that this bundle has taken lot of time.</p>\n</blockquote>\n\n<p>You could use a <code>Timer (ScheduledExecutor)</code> on which you register the action to take place in case of a timeout.\nOn timeout you should iterate the list of futures and cancel the ones that are not done yet.</p>\n\n<p>Otherwise the code looks good enough. I can't see why should not be optimal.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-09-05T20:43:06.183", "Id": "49073", "Score": "0", "body": "Thanks csoroiu for the suggestion. So you are saying, I can have executorservice with fixedthreadpool size of 8 in general? Right? And also, I am using timeout feature as well. But you are suggesting to use Timer instead? If yes, can you provide an example for that basis on my above code?" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-09-05T20:51:17.870", "Id": "49076", "Score": "0", "body": "And also I am not able to understand- What I am supposed to log here? `if (!future.isDone()) {\n // log error for this entry\n }` meaning what kind of error, I am supposed to log here?" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-09-05T20:52:46.197", "Id": "49077", "Score": "0", "body": "I wasn't paying too much attention to the timeout parameter, but code should be good enough. My suggestion is to use a `ScheduledExecutor` (basically will do the same thing that `timeout` parameter does in case of `invokeAll`).\nThe number 8 is relative to the number of cores available on your machine. So if you have a machine with 8 cores, 8 is a good number." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-09-05T20:54:26.743", "Id": "49078", "Score": "0", "body": "Cool. Thanks. And how about this one- What I am supposed to log here? `if (!future.isDone()) { // log error for this entry }` meaning what kind of error, I am supposed to log here? And also- in the catch block of InterruptedException, Am I doing the right thing?" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-09-05T21:02:49.430", "Id": "49080", "Score": "0", "body": "`if (!future.isDone()) { // log error for this entry }` - here you may log information related to the entry that was not done. You might log the name of the bundle(plugin) that did not finished. This information is useful for debug purposes.\nAdditionally, for same debug purposes, it might be useful to log the execution time for each of the bundles inside `ProcessBundleHolderEntry.call` method. You can use `System.currentTimeMillis()` for this." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-09-05T21:06:29.087", "Id": "49081", "Score": "0", "body": "I see.. So you are saying, I should do something like this- `if (!future.isDone()) {\n LOG.log(Level.WARNING, \"Bundles that didn't finished\" +entry);// log error for this entry\n }` Meaning I should log the entry variable here... Right?" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-09-05T21:09:38.540", "Id": "49082", "Score": "0", "body": "Correct. Either the entry variable or something that gives you a hint about what entry did not execute." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-09-05T21:11:30.997", "Id": "49083", "Score": "0", "body": "let us [continue this discussion in chat](http://chat.stackexchange.com/rooms/10474/discussion-between-techgeeky-and-csoroiu)" } ], "meta_data": { "CommentCount": "8", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-09-05T20:39:47.217", "Id": "30840", "ParentId": "30801", "Score": "2" } } ]
{ "AcceptedAnswerId": "30840", "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-09-05T01:29:49.123", "Id": "30801", "Score": "1", "Tags": [ "java", "multithreading", "thread-safety" ], "Title": "Calling different bundles in parallel using ExecutorService" }
30801
<pre><code>package utils; import java.lang.reflect.Field; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import com.google.gson.Gson; public class JSONUtils { public static final Gson gson = new Gson(); public static String toJSON(Object o, String... fields) { HashMap&lt;String, Object&gt; map = new HashMap&lt;String, Object&gt;(); for (String f : fields) { try { Field field = o.getClass().getField(f); map.put(f, field.get(o)); } catch (Exception e) { e.printStackTrace(); return null; } } return gson.toJson(map); } public static String toJSONForList(List&lt;?&gt; objects, String... fields) { ArrayList&lt;Object&gt; list = new ArrayList&lt;Object&gt;(); for (Object o : objects) { list.add(toJSON(o, fields)); } return gson.toJson(list); } } </code></pre> <p><strong>Note</strong> : I need to convert list to JSON very often.</p>
[]
[ { "body": "<p>Are you changing the fields that you expose from your objects depending on certain conditions? </p>\n\n<p>On the whole it would be best to use reflection only as a last gasp. Gson works fine with collections in general see the documentation over at <a href=\"https://sites.google.com/site/gson/gson-user-guide#TOC-Collections-Examples\" rel=\"nofollow\">Google</a>.</p>\n\n<p>If you want to exclude some fields from serialization then you can use the <code>@Expose</code> annotation, as documented <a href=\"https://sites.google.com/site/gson/gson-user-guide#TOC-Excluding-Fields-From-Serialization-and-Deserialization\" rel=\"nofollow\">here</a>. This requires you to annotate all fields that you want to serialize with the <code>@Expose</code> annotation, and to use a builder to instantiate your Gson Object like so:</p>\n\n<pre><code>Gson gson = GsonBuilder().excludeFieldsWithoutExposeAnnotation().create();\n</code></pre>\n\n<p>In general try to limit how much you are working with the type <code>Object</code> and reduce as far as possible your use of reflection.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-09-05T09:06:36.133", "Id": "30811", "ParentId": "30804", "Score": "3" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-09-05T03:48:02.067", "Id": "30804", "Score": "2", "Tags": [ "java", "json" ], "Title": "Is it a good choice to define my own JSON util class like this?" }
30804
<p>I have spent about 2 weeks reading about hashing passwords and website security. As there seems to be many different ways to achieve this, I'm a bit confused as to whether my code is secure.</p> <p>Can anyone please have a look through and let me know what they think and what needs to be changed?</p> <p>I have not added any error trapping yet, as to allow me to concentrate on just the hashing.</p> <p>The steps I have took are as follows:</p> <ol> <li>Create random salt</li> <li>Add random salt and email together to create salt for password (email will be encrypted in database)</li> <li>Hash password and salt and store in database</li> </ol> <pre><code>public const int HashBytes = 128; public const int DefaultIterations = 10000; //Create random bytes for salt public static string SaltSHA256() { const int minSaltSize = 8; const int maxSaltSize = 16; var random = new Random(); int saltSize = random.Next(minSaltSize, maxSaltSize); byte[] saltBytes = new byte[saltSize]; var rng = new RNGCryptoServiceProvider(); rng.GetNonZeroBytes(saltBytes); HashAlgorithm hash = new SHA256Managed(); byte[] bytes = hash.ComputeHash(saltBytes); return Convert.ToBase64String(bytes); } //Create salt using email and public static string SaltSHA256() //Store email and public static string SaltSHA256() in database public static string SaltRfc2898(string email,string hashedSalt) { var salt = new Rfc2898DeriveBytes(email, Encoding.UTF8.GetBytes(hashedSalt), DefaultIterations); return Convert.ToBase64String(salt.GetBytes(HashBytes)); } //Hash password and salt public static string PasswordHashRfc2898(string password,string salt) { var hashedPassword = new Rfc2898DeriveBytes(password, Encoding.UTF8.GetBytes(salt), DefaultIterations); return Convert.ToBase64String(hashedPassword.GetBytes(HashBytes)); } //Get salt and password from database based on username //Salt in from data created by public static string SaltSHA256() public static bool DoPasswordsMatch(string password,string salt) { //Password would be pulled from db based on username byte[] testPassword = Convert.FromBase64String("basestring"); //Salt would be pulled from database based on username var saltFromDatabase = salt; //Hash password and salt var hashUserInputAndSalt = PasswordHashRfc2898(password, saltFromDatabase); //Convert to byte[] ready for comparison byte[] convertUserInputFromBase64 = Convert.FromBase64String(hashUserInputAndSalt); //Compare and return true or false return convertUserInputFromBase64.SequenceEqual(testPassword); } </code></pre>
[ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-09-05T13:59:24.763", "Id": "49030", "Score": "0", "body": "`RNGCryptoServiceProvider`, `SHA256Managed` and `Rfc2898DeriveBytes` all implement the `IDisposable` interface and therefore should be wrapped in `using` statements." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-09-05T17:14:52.503", "Id": "49046", "Score": "0", "body": "Hi Jesse thanks forgot about that, code updated" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2016-08-26T13:55:26.920", "Id": "261472", "Score": "0", "body": "It looks like your **SaltSHA256** method generates a random `saltBytes` array. Won't this be different every time your method is called? It just seems like one instance will never be able to access a previous instance, so how will you ever be able to check a password later? I'm probably missing something." } ]
[ { "body": "<p>As CodesInChaos pointed out in the comments, a far more secure way to hash passwords is to use a deliberately expensive hash. This will all but eliminate any hope of a successful brute-force attack.</p>\n\n<p>The \"best\" algorithm I know of for this purpose would be <a href=\"https://en.wikipedia.org/wiki/Bcrypt\" rel=\"nofollow noreferrer\">BCrypt</a>. For .NET, you can use <a href=\"https://bcrypt.codeplex.com/\" rel=\"nofollow noreferrer\">BCrypt.Net</a>. <strong>Disclaimer</strong>: I don't know who, if anyone, has verified the integrity of this particular port.</p>\n\n<p>See <a href=\"https://security.stackexchange.com/questions/4781/do-any-security-experts-recommend-bcrypt-for-password-storage\">this StackOverflow question</a> for a full discussion regarding the use of BCrypt as a password hashing algorithm.</p>\n\n<hr>\n\n<h2><strong>Original answer</strong></h2>\n\n<p>So long as the salt is sufficiently unpredictable, the hashing function sufficiently secure, and the user's password is <strong>never</strong> stored in plain-text, emailed, or logged, then your implementation should be adequate.</p>\n\n<p>While your salt is unpredictable, 8 bytes may be short for extremely sensitive information. A salt is stored in plain-text along with the hashed password, so we're not worried about keeping it a secret. What we're worried about is that someone may have already pre-computed SHA-256 hashes for common passwords and salts up to 8 bytes <a href=\"https://stackoverflow.com/questions/9619727/how-long-should-a-salt-be-to-make-it-infeasible-to-attempt-dictionary-attacks\">salt</a> (though unlikely). Having a random length salt really doesn't add much except computational complexity and potentially wasted storage space. I would settle for a consistent-width salt of 16 bytes.</p>\n\n<p>SHA-256 is a suitable hashing algorithm for most purposes at this time.<br>\n<em>Edit: But BCrypt is better for passwords (see above).</em></p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-09-05T14:18:34.097", "Id": "49035", "Score": "0", "body": "Hi Dan, thanks for the info, Tom who replied on http://security.stackexchange.com/ also mentioned using a constistent salt, so I will be modify code." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-09-05T18:01:46.763", "Id": "49049", "Score": "2", "body": "SHA-256 by itself isn't suitable for password hashing. You need some form of iterated scheme, such as `Rfc2898DeriveBytes`" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-09-05T18:23:01.990", "Id": "49053", "Score": "0", "body": "I didn't say it was suitable by itself for password hashing. I said it was a suitable hashing algorithm. The context of the discussion should imply that additional steps, e.g. salting, are required." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-09-06T09:31:04.747", "Id": "49119", "Score": "2", "body": "People use bad solutions like `SHA2(salt||password)` all the time, so mentioning SHA-2 without mentioning that you need to iterate it at least 10k times is dangerous IMO. In practice most .net programmers are best served with PBKDF2-HMAC-SHA-1 since that's the only standard password hash in the BCL." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2015-08-20T21:19:48.393", "Id": "185621", "Score": "0", "body": "@CodesInChaos Sorry I didn't incorporate your feedback sooner. There's no excuse really. I've updated the answer to mention that computationally expensive algorithms should be preferred for password hashing and linked to BCrypt." } ], "meta_data": { "CommentCount": "5", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-09-05T13:49:48.257", "Id": "30820", "ParentId": "30814", "Score": "4" } }, { "body": "<ol>\n<li><p>Random length salt is silly</p>\n</li>\n<li><p>Hashing the salt with SHA-256 is silly. Makes it longer without increasing entropy.</p>\n<p>A salt just needs to be unique. Best practice is using <code>RNGCryptoServiceProvider</code> to get 16 random bytes. Using more than 16 bytes doesn't improve security.</p>\n</li>\n<li><p>It's a bad idea to derive more than 20 bytes with <code>Rfc2898DeriveBytes</code> since that only decreases performance on your system, but not for the attacker. Deriving 20 bytes should speed your code up 7x. More that 20 bytes certainly doesn't improve security, I'd probably even go down a bit. 15 and 18 bytes encode nicely without padding using Base64.</p>\n</li>\n<li><p>If you can afford the performance hit, increase the number of iterations a bit. If you could afford your original code, you should now be able to afford 70000 iterations thanks to the speedup from the previous suggestion.</p>\n</li>\n<li><p>Don't use UTF-8 encoding on the salt. You can pass it to <code>Rfc2898DeriveBytes</code> directly as a <code>byte[]</code>. When you really need to convert it to/from text, use Base64.</p>\n</li>\n<li><p>It's best practice to use a constant time comparison instead of <code>SequenceEquals</code> to avoid timing side-channels.</p>\n</li>\n</ol>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-09-05T18:26:50.100", "Id": "49054", "Score": "0", "body": "Good tips, especially the `DeriveBytes` and increased iteration advice." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-09-05T22:46:18.873", "Id": "49089", "Score": "0", "body": "Hi CodesInChaos, can you please explain number 6, I'm not sure what you mean by constant time comparison. Thanks George" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-09-12T19:56:16.723", "Id": "49636", "Score": "0", "body": "Using advanced timing attacks, described [here](http://en.wikipedia.org/wiki/Side_channel_attack), it _may_ be possible to deduce the approximate character position at which the password match fails based on how long the SequenceEquals comparison takes. [This article](http://codahale.com/a-lesson-in-timing-attacks/) explains the problem and potential solutions in more detail. It is worth noting that the effort required execute a timing attack is high, especially against a poorly optimized website with varying page load times. If timing attacks are your weakest link, you're doing well." } ], "meta_data": { "CommentCount": "3", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-09-05T18:09:26.693", "Id": "30835", "ParentId": "30814", "Score": "4" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "3", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-09-05T10:58:41.920", "Id": "30814", "Score": "4", "Tags": [ "c#", "security", "cryptography" ], "Title": "Hashing passwords for a website" }
30814
<p>Consider the following:</p> <pre><code>If myString = "abc" Or myString = "def" [...] Or myString = "xyz" Then </code></pre> <p>In C# when <code>myString == "abc"</code> the rest of the conditions aren't evaluated. But because of how VB works, <em>the entire expression needs to be evaluated</em>, even if a match is found with the first comparison.</p> <p>Even worse:</p> <pre><code>If InStr(1, myString, "foo") &gt; 0 Or InStr(1, myString, "bar") &gt; 0 [...] Then </code></pre> <p>I hate to see these things in code I work with. So I came up with these functions a while ago, been using them all over the place, was wondering if anything could be done to make them even better:</p> <p><strong>StringContains</strong> is used like <code>If StringContains("this is a sample string", "string")</code>:</p> <pre><code>Public Function StringContains(string_source, find_text, Optional ByVal caseSensitive As Boolean = False) As Boolean 'String-typed local copies of passed parameter values: Dim find As String, src As String find = CStr(find_text) src = CStr(string_source) If caseSensitive Then StringContains = (InStr(1, src, find, vbBinaryCompare) &lt;&gt; 0) Else StringContains = (InStr(1, src, find, vbTextCompare) &lt;&gt; 0) End If End Function </code></pre> <p><strong>StringContainsAny</strong> works in a very similar way, but allows specifying any number of parameters so it's used like <code>If StringContainsAny("this is a sample string", false, "foo", "bar", string")</code>:</p> <pre><code>Public Function StringContainsAny(string_source, ByVal caseSensitive As Boolean, ParamArray find_strings()) As Boolean 'String-typed local copies of passed parameter values: Dim find As String, src As String, i As Integer, found As Boolean src = CStr(string_source) For i = LBound(find_strings) To UBound(find_strings) find = CStr(find_strings(i)) If caseSensitive Then found = (InStr(1, src, find, vbBinaryCompare) &lt;&gt; 0) Else found = (InStr(1, src, find, vbTextCompare) &lt;&gt; 0) End If If found Then Exit For Next StringContainsAny = found End Function </code></pre> <p><strong>StringMatchesAny</strong> will return <code>True</code> if any of the passed parameters exactly matches (case-sensitive) the <code>string_source</code>:</p> <pre><code>Public Function StringMatchesAny(string_source, ParamArray find_strings()) As Boolean 'String-typed local copies of passed parameter values: Dim find As String, src As String, i As Integer, found As Boolean src = CStr(string_source) For i = LBound(find_strings) To UBound(find_strings) find = CStr(find_strings(i)) found = (src = find) If found Then Exit For Next StringMatchesAny = found End Function </code></pre>
[]
[ { "body": "<p>My 2 cents,</p>\n\n<p>the first function seems fine, you could make it a little DRYer by just setting the compareMethod in your if statement and then have only 1 complicated line of logic. And if you are doing that, you might as well put the Cstr's there.</p>\n\n<pre><code>Public Function StringContains(haystack, needle, Optional ByVal caseSensitive As Boolean = False) As Boolean\n\n Dim compareMethod As Integer\n\n If caseSensitive Then\n compareMethod = vbBinaryCompare\n Else\n compareMethod = vbTextCompare\n End If\n 'Have you thought about Null?\n StringContains = (InStr(1, CStr(haystack), CStr(needle), compareMethod) &lt;&gt; 0)\n\nEnd Function\n</code></pre>\n\n<p>Notice as well that I love the idea of searching for needles in haystacks, I stole that from PHP.</p>\n\n<p>For StringContainsAny, you are not using the code you wrote for StringContains, you repeat it. If you were to re-use the first function, you could do this:</p>\n\n<pre><code>Public Function StringContainsAny(haystack, ByVal caseSensitive As Boolean, ParamArray needles()) As Boolean\n\n Dim i As Integer\n\n For i = LBound(needles) To UBound(needles)\n If StringContains(CStr(haystack), CStr(needles(i)), caseSensitive) Then\n StringContainsAny = True\n Exit Function\n End If\n Next\n\n StringContainsAny = False 'Not really necessary, default is False..\n\nEnd Function\n</code></pre>\n\n<p>For the last one I wanted to you consider passing values that you will convert as ByVal, since you are going to make a copy anyway of that variable.</p>\n\n<pre><code>Public Function StringMatchesAny(ByVal string_source, ParamArray potential_matches()) As Boolean\n\n string_source = CStr(string_source)\n\n ... 'That code taught me a new trick ;)\n\nEnd Function\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-09-05T22:13:02.050", "Id": "49088", "Score": "0", "body": "+1 for finding a needle in a haystack! Love it! ...and for reusing StringContains. However your take at the 3rd one changes the semantics. It should be a strict equality comparison (the needle *equals* anything in the stack)." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-09-07T00:59:22.257", "Id": "49186", "Score": "1", "body": "You are right about `ByVal` - actually I think I'll change all `string_source` to `ByVal string_source As String` and let VB do the implicit conversion, if any (in all likelihood a `String` is being passed here anyway)." } ], "meta_data": { "CommentCount": "2", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-09-05T20:58:31.150", "Id": "30844", "ParentId": "30816", "Score": "10" } }, { "body": "<p>I came here after reading a related post in the <strong>retailcoder blog</strong>, <a href=\"https://retailcoder.wordpress.com/2014/10/06/enhancing-vba-string-handling/\" rel=\"nofollow noreferrer\">Enhancing VBA String Handling</a>. <strong>Take into account that in the InStr function if <em>String2</em> is an empty string then the returned value is the <em>Start</em> position (different from 0), so the function may erroneously return True in that case.</strong> Below the way I implement it with that consideration.</p>\n<pre><code>'@Description &quot;Returns True if found an ocurrence of one string within another. False otherwise.&quot;\nPublic Function Contains(ByVal StringToLookIn As String, _\n ByVal StringToLookFor As String, _\n Optional ByVal CaseSensitive As Boolean = False) _\nAs Boolean\n If StringToLookFor &lt;&gt; vbNullString Then\n Dim ComparisonMethod As VbCompareMethod\n If CaseSensitive Then\n ComparisonMethod = vbBinaryCompare\n Else\n ComparisonMethod = vbTextCompare\n End If\n Contains = CBool(InStr(1, StringToLookIn, StringToLookFor, ComparisonMethod))\n End If\nEnd Function\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-11-25T07:55:16.553", "Id": "533897", "Score": "1", "body": "Thanks for editing - it's now a much better review. :)" } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-11-24T00:31:03.657", "Id": "270344", "ParentId": "30816", "Score": "3" } } ]
{ "AcceptedAnswerId": "30844", "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-09-05T12:12:34.683", "Id": "30816", "Score": "10", "Tags": [ "strings", "vba", "vb6" ], "Title": "A more readable InStr: StringContains" }
30816
<p>A while ago I implemented .net's <code>string.Format()</code> method in VB6; it works amazingly well, but I'm sure there has to be a way to make it more efficient.</p> <p>I'll start by listing a simple class called <code>EscapeSequence</code>:</p> <pre><code>Private Type tEscapeSequence EscapeString As String ReplacementString As String End Type Private this As tEscapeSequence Option Explicit Public Property Get EscapeString() As String EscapeString = this.EscapeString End Property Friend Property Let EscapeString(value As String) this.EscapeString = value End Property Public Property Get ReplacementString() As String ReplacementString = this.ReplacementString End Property Friend Property Let ReplacementString(value As String) this.ReplacementString = value End Property 'Lord I wish VB6 had constructors! Public Function Create(escape As String, replacement As String) As EscapeSequence Dim result As New EscapeSequence result.EscapeString = escape result.ReplacementString = replacement Set Create = result End Function </code></pre> <p>...and the actual <code>StringFormat</code> function - there's a global variable <code>PADDING_CHAR</code> involved, which I'd love to find a way to specify and de-globalize:</p> <pre><code>Public Function StringFormat(format_string As String, ParamArray values()) As String 'VB6 implementation of .net String.Format(), slightly customized. Dim return_value As String Dim values_count As Integer 'some error-handling constants: Const ERR_FORMAT_EXCEPTION As Long = vbObjectError Or 9001 Const ERR_ARGUMENT_NULL_EXCEPTION As Long = vbObjectError Or 9002 Const ERR_ARGUMENT_EXCEPTION As Long = vbObjectError Or 9003 Const ERR_SOURCE As String = "StringFormat" Const ERR_MSG_INVALID_FORMAT_STRING As String = "Invalid format string." Const ERR_MSG_FORMAT_EXCEPTION As String = "The number indicating an argument to format is less than zero, or greater than or equal to the length of the args array." Const ERR_MSG_NUMBER_ARGUMENT_EXCEPTION As String = "Invalid number argument." 'use SPACE as default padding character If PADDING_CHAR = vbNullString Then PADDING_CHAR = Chr$(32) 'figure out number of passed values: values_count = UBound(values) + 1 Dim regex As RegExp Dim matches As MatchCollection Dim thisMatch As Match Dim thisString As String Dim thisFormat As String Dim useLiteral As Boolean 'when format_string starts with "@", escapes are not replaced (string is treated as a literal string with placeholders) Dim escapeHex As Boolean 'indicates whether HEX specifier "0x" is to be escaped or not 'validate string_format: Set regex = New RegExp regex.pattern = "{({{)*(\w+)(,-?\d+)?(:[^}]+)?}(}})*" regex.IgnoreCase = True regex.Global = True Set matches = regex.Execute(format_string) 'determine if values_count matches number of unique regex matches: Dim uniqueCount As Integer Dim tmpCSV As String For Each thisMatch In matches If Not StringContains(tmpCSV, thisMatch.SubMatches(1)) Then uniqueCount = uniqueCount + 1 tmpCSV = tmpCSV &amp; thisMatch.SubMatches(1) &amp; "," End If Next 'unique indices count must match values_count: If matches.Count &gt; 0 And uniqueCount &lt;&gt; values_count Then Err.Raise ERR_FORMAT_EXCEPTION, _ ERR_SOURCE, ERR_MSG_FORMAT_EXCEPTION End If useLiteral = StringStartsWith("@", format_string) If useLiteral Then format_string = Right(format_string, Len(format_string) - 1) 'remove the "@" literal specifier If Not useLiteral And StringContains(format_string, "\\") Then _ format_string = Replace(format_string, "\\", Chr$(27)) If matches.Count = 0 And format_string &lt;&gt; vbNullString And UBound(values) = -1 Then 'only format_string was specified: skip to checking escape sequences: return_value = format_string GoTo checkEscapes ElseIf UBound(values) = -1 And matches.Count &gt; 0 Then Err.Raise ERR_ARGUMENT_NULL_EXCEPTION, _ ERR_SOURCE, ERR_MSG_FORMAT_EXCEPTION End If return_value = format_string 'dissect format_string: Dim i As Integer, v As String, p As String 'i: iterator; v: value; p: placeholder Dim alignmentGroup As String, alignmentSpecifier As String Dim formattedValue As String, alignmentPadding As Integer 'iterate regex matches (each match is a placeholder): For i = 0 To matches.Count - 1 'get the placeholder specified index: Set thisMatch = matches(i) p = thisMatch.SubMatches(1) 'if specified index (0-based) &gt; uniqueCount (1-based), something's wrong: If p &gt; uniqueCount - 1 Then Err.Raise ERR_FORMAT_EXCEPTION, _ ERR_SOURCE, ERR_MSG_FORMAT_EXCEPTION End If v = values(p) 'get the alignment specifier if it is specified: alignmentGroup = thisMatch.SubMatches(2) If alignmentGroup &lt;&gt; vbNullString Then _ alignmentSpecifier = Right$(alignmentGroup, LenB(alignmentGroup) / 2 - 1) 'get the format specifier if it is specified: thisString = thisMatch.value If StringContains(thisString, ":") Then Dim formatGroup As String, precisionSpecifier As Integer Dim formatSpecifier As String, precisionString As String 'get the string between ":" and "}": formatGroup = mId$(thisString, InStr(1, thisString, ":") + 1, (LenB(thisString) / 2) - 2) formatGroup = Left$(formatGroup, LenB(formatGroup) / 2 - 1) precisionString = Right$(formatGroup, LenB(formatGroup) / 2 - 1) formatSpecifier = mId$(thisString, InStr(1, thisString, ":") + 1, 1) 'applicable formatting depends on the type of the value (yes, GOTO!!): If TypeName(values(p)) = "Date" Then GoTo DateTimeFormatSpecifiers If v = vbNullString Then GoTo ApplyStringFormat NumberFormatSpecifiers: If precisionString &lt;&gt; vbNullString And Not IsNumeric(precisionString) Then Err.Raise ERR_FORMAT_EXCEPTION, _ ERR_SOURCE, ERR_MSG_INVALID_FORMAT_STRING End If If Not IsNumeric(v) Then Err.Raise ERR_ARGUMENT_EXCEPTION, _ ERR_SOURCE, ERR_MSG_NUMBER_ARGUMENT_EXCEPTION End If If precisionString = vbNullString Then precisionString = 0 Select Case formatSpecifier Case "C", "c" 'CURRENCY format, formats string as currency. 'Precision specifier determines number of decimal digits. 'This implementation ignores regional settings '(hard-coded group separator, decimal separator and currency sign). precisionSpecifier = CInt(precisionString) thisFormat = "#,##0.$" If LenB(formatGroup) &gt; 2 And precisionSpecifier &gt; 0 Then 'if a non-zero precision is specified... thisFormat = _ Replace$(thisFormat, ".", "." &amp; String$(precisionString, Chr$(48))) Else thisFormat = CURRENCY_FORMAT End If Case "D", "d" 'DECIMAL format, formats string as integer number. 'Precision specifier determines number of digits in returned string. precisionSpecifier = CInt(precisionString) thisFormat = "0" thisFormat = Right$(String$(precisionSpecifier, "0") &amp; thisFormat, _ IIf(precisionSpecifier = 0, Len(thisFormat), precisionSpecifier)) Case "E", "e" 'EXPONENTIAL NOTATION format (aka "Scientific Notation") 'Precision specifier determines number of decimals in returned string. 'This implementation ignores regional settings' '(hard-coded decimal separator). precisionSpecifier = CInt(precisionString) thisFormat = "0.00000#" &amp; formatSpecifier &amp; "-#" 'defaults to 6 decimals If LenB(formatGroup) &gt; 2 And precisionSpecifier &gt; 0 Then 'if a non-zero precision is specified... thisFormat = "0." &amp; String$(precisionSpecifier - 1, Chr$(48)) &amp; "#" &amp; formatSpecifier &amp; "-#" ElseIf LenB(formatGroup) &gt; 2 And precisionSpecifier = 0 Then Err.Raise ERR_FORMAT_EXCEPTION, _ ERR_SOURCE, ERR_MSG_INVALID_FORMAT_STRING End If Case "F", "f" 'FIXED-POINT format 'Precision specifier determines number of decimals in returned string. 'This implementation ignores regional settings' '(hard-coded decimal separator). precisionSpecifier = CInt(precisionString) thisFormat = "0" If LenB(formatGroup) &gt; 2 And precisionSpecifier &gt; 0 Then 'if a non-zero precision is specified... thisFormat = (thisFormat &amp; ".") &amp; String$(precisionSpecifier, Chr$(48)) Else 'no precision specified - default to 2 decimals: thisFormat = "0.00" End If Case "G", "g" 'GENERAL format (recursive) 'returns the shortest of either FIXED-POINT or SCIENTIFIC formats in case of a Double. 'returns DECIMAL format in case of a Integer or Long. Dim eNotation As String, ePower As Integer, specifier As String precisionSpecifier = IIf(CInt(precisionString) &gt; 0, CInt(precisionString), _ IIf(StringContains(v, "."), Len(v) - InStr(1, v, "."), 0)) 'track character case of formatSpecifier: specifier = IIf(formatSpecifier = "G", "D", "d") If TypeName(values(p)) = "Integer" Or TypeName(values(p)) = "Long" Then 'Integer types: use {0:D} (recursive call): formattedValue = StringFormat("{0:" &amp; specifier &amp; "}", values(p)) ElseIf TypeName(values(p)) = "Double" Then 'Non-integer types: use {0:E} specifier = IIf(formatSpecifier = "G", "E", "e") 'evaluate the exponential notation value (recursive call): eNotation = StringFormat("{0:" &amp; specifier &amp; "}", v) 'get the power of eNotation: ePower = mId$(eNotation, InStr(1, UCase$(eNotation), "E-") + 1, Len(eNotation) - InStr(1, UCase$(eNotation), "E-")) If ePower &gt; -5 And Abs(ePower) &lt; precisionSpecifier Then 'use {0:F} when ePower &gt; -5 and abs(ePower) &lt; precisionSpecifier: 'evaluate the floating-point value (recursive call): specifier = IIf(formatSpecifier = "G", "F", "f") formattedValue = StringFormat("{0:" &amp; formatSpecifier &amp; _ IIf(precisionSpecifier &lt;&gt; 0, precisionString, vbNullString) &amp; "}", values(p)) Else 'fallback to {0:E} if previous rule didn't apply: formattedValue = eNotation End If End If GoTo AlignFormattedValue 'Skip the "ApplyStringFormat" step, it's applied already. Case "N", "n" 'NUMERIC format, formats string as an integer or decimal number. 'Precision specifier determines number of decimal digits. 'This implementation ignores regional settings' '(hard-coded group and decimal separators). precisionSpecifier = CInt(precisionString) If LenB(formatGroup) &gt; 2 And precisionSpecifier &gt; 0 Then 'if a non-zero precision is specified... thisFormat = "#,##0" thisFormat = (thisFormat &amp; ".") &amp; String$(precisionSpecifier, Chr$(48)) Else 'only the "D" is specified thisFormat = "#,##0" End If Case "P", "p" 'PERCENT format. Formats string as a percentage. 'Value is multiplied by 100 and displayed with a percent symbol. 'Precision specifier determines number of decimal digits. thisFormat = "#,##0%" precisionSpecifier = CInt(precisionString) If LenB(formatGroup) &gt; 2 And precisionSpecifier &gt; 0 Then 'if a non-zero precision is specified... thisFormat = "#,##0" thisFormat = (thisFormat &amp; ".") &amp; String$(precisionSpecifier, Chr$(48)) Else 'only the "P" is specified thisFormat = "#,##0" End If 'Append the percentage sign to the format string: thisFormat = thisFormat &amp; "%" Case "R", "r" 'ROUND-TRIP format (a string that can round-trip to an identical number) 'example: ?StringFormat("{0:R}", 0.0000000001141596325677345362656) ' ...returns "0.000000000114159632567735" 'convert value to a Double (chop off overflow digits): v = CDbl(v) Case "X", "x" 'HEX format. Formats a string as a Hexadecimal value. 'Precision specifier determines number of total digits. 'Returned string is prefixed with "&amp;H" to specify Hex. v = Hex(v) precisionSpecifier = CInt(precisionString) If LenB(precisionString) &gt; 0 Then 'precision here stands for left padding v = Right$(String$(precisionSpecifier, "0") &amp; v, IIf(precisionSpecifier = 0, Len(v), precisionSpecifier)) End If 'add C# hex specifier, apply specified casing: '(VB6 hex specifier would cause Format() to reverse the formatting): v = "0x" &amp; IIf(formatSpecifier = "X", UCase$(v), LCase$(v)) escapeHex = True Case Else If IsNumeric(formatSpecifier) And val(formatGroup) = 0 Then formatSpecifier = formatGroup v = Format(v, formatGroup) Else Err.Raise ERR_FORMAT_EXCEPTION, _ ERR_SOURCE, ERR_MSG_INVALID_FORMAT_STRING End If End Select GoTo ApplyStringFormat DateTimeFormatSpecifiers: Select Case formatSpecifier Case "c", "C" 'CUSTOM date/time format 'let VB Format() parse precision specifier as is: thisFormat = precisionString Case "d" 'SHORT DATE format thisFormat = "ddddd" Case "D" 'LONG DATE format thisFormat = "dddddd" Case "f" 'FULL DATE format (short) thisFormat = "dddddd h:mm AM/PM" Case "F" 'FULL DATE format (long) thisFormat = "dddddd ttttt" Case "g" thisFormat = "ddddd hh:mm AM/PM" Case "G" thisFormat = "ddddd ttttt" Case "s" 'SORTABLE DATETIME format thisFormat = "yyyy-mm-ddThh:mm:ss" Case "t" 'SHORT TIME format thisFormat = "hh:mm AM/PM" Case "T" 'LONG TIME format thisFormat = "ttttt" Case Else Err.Raise ERR_FORMAT_EXCEPTION, _ ERR_SOURCE, ERR_MSG_INVALID_FORMAT_STRING End Select GoTo ApplyStringFormat End If ApplyStringFormat: 'apply computed format string: If thisFormat &lt;&gt; vbNullString Then formattedValue = Format(v, thisFormat) Else formattedValue = v End If AlignFormattedValue: 'apply specified alignment specifier: If alignmentSpecifier &lt;&gt; vbNullString Then alignmentPadding = Abs(CInt(alignmentSpecifier)) If CInt(alignmentSpecifier) &lt; 0 Then 'negative: left-justified alignment If alignmentPadding - Len(formattedValue) &gt; 0 Then _ formattedValue = formattedValue &amp; _ String$(alignmentPadding - Len(formattedValue), PADDING_CHAR) Else 'positive: right-justified alignment If alignmentPadding - Len(formattedValue) &gt; 0 Then _ formattedValue = String$(alignmentPadding - Len(formattedValue), PADDING_CHAR) &amp; formattedValue End If End If 'Replace C# hex specifier with VB6 hex specifier, only if hex specifier was introduced in this function: If (Not useLiteral And escapeHex) And StringContains(formattedValue, "0x") Then formattedValue = Replace$(formattedValue, "0x", "&amp;H") 'replace all occurrences of placeholder {i} with their formatted values: return_value = Replace(return_value, thisString, formattedValue, Count:=1) 'reset before reiterating: thisFormat = vbNullString Next checkEscapes: 'if there's no more backslashes, don't bother checking for the rest: If useLiteral Or Not StringContains(return_value, "\") Then GoTo normalExit Dim escape As New EscapeSequence Dim escapes As New Collection escapes.Add escape.Create("\n", vbNewLine), "0" escapes.Add escape.Create("\q", Chr$(34)), "1" escapes.Add escape.Create("\t", vbTab), "2" escapes.Add escape.Create("\a", Chr$(7)), "3" escapes.Add escape.Create("\b", Chr$(8)), "4" escapes.Add escape.Create("\v", Chr$(13)), "5" escapes.Add escape.Create("\f", Chr$(14)), "6" escapes.Add escape.Create("\r", Chr$(15)), "7" For i = 0 To escapes.Count - 1 Set escape = escapes(CStr(i)) If StringContains(return_value, escape.EscapeString) Then _ return_value = Replace(return_value, escape.EscapeString, escape.ReplacementString) If Not StringContains(return_value, "\") Then _ GoTo normalExit Next 'replace "ASCII (oct)" escape sequence Set regex = New RegExp regex.pattern = "\\(\d{3})" regex.IgnoreCase = True regex.Global = True Set matches = regex.Execute(format_string) Dim char As Long If matches.Count &lt;&gt; 0 Then For Each thisMatch In matches p = thisMatch.SubMatches(0) '"p" contains the octal number representing the ASCII code we're after: p = "&amp;O" &amp; p 'prepend octal prefix char = CLng(p) return_value = Replace(return_value, thisMatch.value, Chr$(char)) Next End If 'if there's no more backslashes, don't bother checking for the rest: If Not StringContains("\", return_value) Then GoTo normalExit 'replace "ASCII (hex)" escape sequence Set regex = New RegExp regex.pattern = "\\x(\w{2})" regex.IgnoreCase = True regex.Global = True Set matches = regex.Execute(format_string) If matches.Count &lt;&gt; 0 Then For Each thisMatch In matches p = thisMatch.SubMatches(0) '"p" contains the hex value representing the ASCII code we're after: p = "&amp;H" &amp; p 'prepend hex prefix char = CLng(p) return_value = Replace(return_value, thisMatch.value, Chr$(char)) Next End If normalExit: Set escapes = Nothing Set escape = Nothing If Not useLiteral And StringContains(return_value, Chr$(27)) Then _ return_value = Replace(return_value, Chr$(27), "\") StringFormat = return_value End Function </code></pre> <p>I'm looking for a way to factor out the two (quite huge) <code>Select...Case</code> blocks, and to improve readability in general.</p> <p>Note that this uses <a href="https://codereview.stackexchange.com/questions/30816/a-more-readable-instr-stringcontains">StringContains</a> functions, and I should add a disclaimer about the fact that most of this code is already posted as an answer of mine at <a href="https://stackoverflow.com/questions/14534360/implementing-string-format-in-vb6">StackOverflow</a>, although I do not consider it <em>multi-posting</em>, since I'm actually asking for a code review here.</p>
[ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-09-06T00:11:27.193", "Id": "49096", "Score": "0", "body": "I'm thinking of moving parts of this into a class, but I want to stick to a `Public Function` in a simple code module, to avoid breaking existing code (and still be able to call it as any other native vb function, without instanciating anything)." } ]
[ { "body": "<h1><strong>Key Points</strong></h1>\n\n<ul>\n<li>Each <code>Case</code> block implements formatting functionality for a specific format specifier.</li>\n<li><code>Goto</code> statements indicate the function <em>wants</em> to be broken down into several smaller functions.</li>\n<li>Local variables such as <code>alignmentSpecifier</code>, <code>alignmentPadding</code>, <code>precisionString</code>, <code>precisionSpecifier</code>, <code>formatSpecifier</code> and all others, could all be eliminated if there was a concept of a \"FormatSpecifier\" object that held all these values.</li>\n<li>Bringing in <code>escapeHex</code> and the C# hex specifier is a hack easily made useless by correctly encapsulating each format specifier.</li>\n<li><code>escapes</code> collection gets rebuilt every time the function is called, which is inefficient; valid escape sequences don't change from one call to the next.</li>\n<li>ASCII (hex &amp; octal) escapes both <em>desperately want</em> to be part of that collection.</li>\n<li>Replacing <code>\\\\</code> with ASCII code for <kbd>Esc</kbd> works nicely to get backslashes escaped.</li>\n</ul>\n\n<hr>\n\n<p><strong>Warning: below code is absolute overkill</strong> - no one in their right minds (I did this just for fun!) would do all this just to format strings in their VB6 or VBA application. However it shows how the monolithic function can be refactored to remove all <code>Select...Case</code> blocks and <code>Goto</code> statements.</p>\n\n<hr>\n\n<h1>Rewrite</h1>\n\n<p>Here's the refactored module-level function - it uses a <code>Private helper As New StringHelper</code>, declared at module level (\"declarations\" section):</p>\n\n<pre><code>Public Function StringFormat(format_string As String, ParamArray values()) As String\n Dim valuesArray() As Variant\n valuesArray = values\n StringFormat = helper.StringFormat(format_string, valuesArray)\nEnd Function\n</code></pre>\n\n<h3>Escape Sequences</h3>\n\n<p>The <code>EscapeSequence</code> class was annoyingly leaving out ASCII escapes, so I tackled this first:</p>\n\n<pre><code>Private Type tEscapeSequence\n EscapeString As String\n ReplacementString As String\n IsAsciiCharacter As Boolean\n AsciiBase As AsciiEscapeBase\nEnd Type\n\nPublic Enum AsciiEscapeBase\n Octal\n Hexadecimal\nEnd Enum\n\nPrivate this As tEscapeSequence\nOption Explicit\n\nPublic Property Get EscapeString() As String\n EscapeString = this.EscapeString\nEnd Property\n\nFriend Property Let EscapeString(value As String)\n this.EscapeString = value\nEnd Property\n\nPublic Property Get ReplacementString() As String\n ReplacementString = this.ReplacementString\nEnd Property\n\nFriend Property Let ReplacementString(value As String)\n this.ReplacementString = value\nEnd Property\n\nPublic Property Get IsAsciiCharacter() As Boolean\n IsAsciiCharacter = this.IsAsciiCharacter\nEnd Property\n\nFriend Property Let IsAsciiCharacter(value As Boolean)\n this.IsAsciiCharacter = value\nEnd Property\n\nPublic Property Get AsciiBase() As AsciiEscapeBase\n AsciiBase = this.AsciiBase\nEnd Property\n\nFriend Property Let AsciiBase(value As AsciiEscapeBase)\n this.AsciiBase = value\nEnd Property\n</code></pre>\n\n<p>The factory <code>Create</code> function was added two optional parameters; one to specify whether the escape sequence indicates an ASCII replacement escape, the other to specify the base (an enum) of the digits representing the ASCII code:</p>\n\n<pre><code>Public Function Create(escape As String, replacement As String, _\n Optional ByVal isAsciiReplacement As Boolean = False, _\n Optional ByVal base As AsciiEscapeBase = Octal) As EscapeSequence\n\n Dim result As New EscapeSequence\n\n result.EscapeString = escape\n result.ReplacementString = replacement\n result.IsAsciiCharacter = isAsciiReplacement\n result.AsciiBase = base\n\n Set Create = result\n\nEnd Function\n</code></pre>\n\n<p>Added an <code>Execute</code> method here - all escape sequences boil down to the same thing: *replace the <code>EscapeString</code> with the <code>ReplacementString</code>, so we might as well encapsulate it here. ASCII escapes are a little bit more complex so I put them in their own method:</p>\n\n<pre><code>Public Sub Execute(ByRef string_value As String)\n\n If this.IsAsciiCharacter Then\n ProcessAsciiEscape string_value, this.EscapeString\n\n ElseIf StringContains(string_value, this.EscapeString) Then\n string_value = Replace(string_value, this.EscapeString, this.ReplacementString)\n\n End If\n\nEnd Sub\n\nPrivate Sub ProcessAsciiEscape(ByRef format_string As String, _\n ByVal regexPattern As String)\n\n Dim regex As RegExp, matches As MatchCollection, thisMatch As Match\n Dim prefix As String, char As Long\n\n If Not StringContains(format_string, \"\\\") Then Exit Sub\n\n Set regex = New RegExp\n regex.pattern = regexPattern\n regex.IgnoreCase = True\n regex.Global = True\n\n Select Case this.AsciiBase\n Case AsciiEscapeBase.Octal\n prefix = \"&amp;O\"\n\n Case AsciiEscapeBase.Hexadecimal\n prefix = \"&amp;H\"\n\n End Select\n\n Set matches = regex.Execute(format_string) \n For Each thisMatch In matches\n char = CLng(prefix &amp; thisMatch.SubMatches(0))\n format_string = Replace(format_string, thisMatch.value, Chr$(char))\n\n Next\n\n Set regex = Nothing\n Set matches = Nothing\n\nEnd Sub\n</code></pre>\n\n<p>This puts escape sequences to bed, at least for now.</p>\n\n<h2>Format Specifiers</h2>\n\n<p>Each match in the main RegEx stands for a placeholder (something potentially looking like \"{0,-10:C2}\"); if we can call those \"format specifiers\", they can probably deserve their own <code>StringFormatSpecifier</code> class as well - the <em>precision specifier</em> is normally an <code>Integer</code>, but in the custom date format it's also taking a <code>String</code> so we'll make <code>Precision</code> a get-only property that's set when assigning <code>CustomSpecifier</code>:</p>\n\n<pre><code>Private Type tSpecifier\n Index As Integer\n identifier As String\n AlignmentSpecifier As Integer\n PrecisionSpecifier As Integer\n CustomSpecifier As String\nEnd Type\n\nPrivate this As tSpecifier\nOption Explicit\n\nPublic Property Get Index() As Integer\n Index = this.Index\nEnd Property\n\nPublic Property Let Index(value As Integer)\n this.Index = value\nEnd Property \n\nPublic Property Get identifier() As String\n identifier = this.identifier\nEnd Property\n\nPublic Property Let identifier(value As String)\n this.identifier = value\nEnd Property\n\nPublic Property Get Alignment() As Integer\n Alignment = this.AlignmentSpecifier\nEnd Property\n\nPublic Property Let Alignment(value As Integer)\n this.AlignmentSpecifier = value\nEnd Property\n\nPublic Property Get Precision() As Integer\n Precision = this.PrecisionSpecifier\nEnd Property\n\nPublic Property Get CustomSpecifier() As String\n CustomSpecifier = this.CustomSpecifier\nEnd Property\n\nPublic Property Let CustomSpecifier(value As String)\n this.CustomSpecifier = value\n If IsNumeric(value) And val(value) &lt;&gt; 0 Then this.PrecisionSpecifier = CInt(value)\nEnd Property\n</code></pre>\n\n<p>All that's missing is a way to put all the pieces back together to perform the actual replacement - either we store the original string or we implement a <code>ToString</code> function:</p>\n\n<pre><code>Public Function ToString() As String\n ToString = \"{\" &amp; this.Index &amp; _\n IIf(this.AlignmentSpecifier &lt;&gt; 0, _\n \",\" &amp; this.AlignmentSpecifier, vbNullString) &amp; _\n IIf(this.identifier &lt;&gt; vbNullString, _\n \":\" &amp; this.identifier, vbNullString) &amp; _\n IIf(this.CustomSpecifier &lt;&gt; vbNullString, _\n this.CustomSpecifier, vbNullString) &amp; \"}\"\nEnd Function\n</code></pre>\n\n<p>This puts another important piece to bed.</p>\n\n<h2>VB6 Interface?</h2>\n\n<p>If we encapsulated how each format specifier works into its own class, odds are we'd get over a dozen of <em>very</em> similar classes. If only we were in .net, we could create an interface for this, right? Very few people know that <em>VB6 also supports interfaces</em>. In fact, any class can be <em>implemented</em> by any other.</p>\n\n<p>So the <code>IStringFormatIdentifier</code> interface/class looks like this:</p>\n\n<pre><code>Option Explicit\n\n'returns a format string suitable for use with VB6's native Format() function.\nPublic Function GetFormatString(specifier As StringFormatSpecifier) As String\nEnd Function\n\n'returns the formatted value.\nPublic Function GetFormattedValue(value As Variant, _\n specifier As StringFormatSpecifier) As String\nEnd Function\n\n'compares specified format identifier with implementation-defined one, \n'returns true if format is applicable.\nPublic Function IsIdentifierMatch(specifier As StringFormatSpecifier) As Boolean\nEnd Function\n</code></pre>\n\n<p>This interface needs an implementation of it for each and every single <code>Case</code> block of the original code - not going to list them all here, but this is <code>GeneralNumericStringFormatIdentifier</code> (the most complicated one); notice that doing this has also eliminated the recursive function calls:</p>\n\n<pre><code>Implements IStringFormatIdentifier\nOption Explicit\n\nPrivate Function IStringFormatIdentifier_GetFormatString(specifier As StringFormatSpecifier) As String\n IStringFormatIdentifier_GetFormatString = vbNullString\nEnd Function\n\nPrivate Function IStringFormatIdentifier_GetFormattedValue(value As Variant, specifier As StringFormatSpecifier) As String\n\n Dim result As String\n Dim exponentialNotation As String\n Dim power As Integer\n Dim exponentialFormat As New ExponentialStringFormatIdentifier\n Dim fixedPointFormat As New FixedPointStringFormatIdentifier\n Dim decimalFormat As New DecimalStringFormatIdentifier\n\n Dim formatSpecifier As New StringFormatSpecifier\n formatSpecifier.Alignment = specifier.Alignment\n formatSpecifier.CustomSpecifier = specifier.CustomSpecifier\n\n If StringMatchesAny(TypeName(value), \"Integer\", \"Long\") Then\n\n formatSpecifier.identifier = IIf(specifier.identifier = \"G\", \"D\", \"d\")\n result = decimalFormat.GetFormattedValue(value, formatSpecifier)\n\n ElseIf TypeName(value) = \"Double\" Then\n\n formatSpecifier.identifier = IIf(specifier.identifier = \"G\", \"E\", \"e\")\n exponentialNotation = exponentialFormat.GetFormattedValue(value, formatSpecifier)\n power = exponentialFormat.GetPower(exponentialNotation)\n\n If power &gt; -5 And Abs(power) &lt; specifier.Precision Then\n\n formatSpecifier.identifier = IIf(specifier.identifier = \"G\", \"F\", \"f\")\n result = fixedPointFormat.GetFormattedValue(value, formatSpecifier)\n\n Else\n\n result = exponentialNotation\n\n End If\n\n End If\n\n IStringFormatIdentifier_GetFormattedValue = result\n Set exponentialFormat = Nothing\n Set fixedPointFormat = Nothing\n Set decimalFormat = Nothing\n Set formatSpecifier = Nothing\n\nEnd Function\n\nPublic Function GetFormattedValue(value As Variant, specifier As StringFormatSpecifier) As String\n GetFormattedValue = IStringFormatIdentifier_GetFormattedValue(value, specifier)\nEnd Function\n\nPrivate Function IStringFormatIdentifier_IsIdentifierMatch(specifier As StringFormatSpecifier) As Boolean\n IStringFormatIdentifier_IsIdentifierMatch = UCase$(specifier.identifier) = \"G\"\nEnd Function\n</code></pre>\n\n<p>Once every format identifier (\"C\", \"D\", \"N\", etc.) has its implementation of the <code>IStringFormatIdentifier</code> interface, we're ready to initialize everything we need, <strong>once</strong>.</p>\n\n<h2>The StringHelper class</h2>\n\n<p>Diving into the <code>StringHelper</code> class, the \"declarations\" section contains the error-handling constants, the default padding character and a private type that defines the encapsulated properties (I just do that in every class I write):</p>\n\n<pre><code>Private Const ERR_FORMAT_EXCEPTION As Long = vbObjectError Or 9001\nPrivate Const ERR_SOURCE As String = \"StringHelper\"\nPrivate Const ERR_MSG_INVALID_FORMAT_STRING As String = \"Invalid format string.\"\nPrivate Const ERR_MSG_FORMAT_EXCEPTION As String = \"The number indicating an argument to format is less than zero, or greater than or equal to the length of the args array.\"\n\nPrivate Type tString\n PaddingCharacter As String * 1\n EscapeSequences As New Collection\n NumericSpecifiers As New Collection\n DateTimeSpecifiers As New Collection\nEnd Type\n\nPrivate Const PADDING_CHAR As String * 1 = \" \"\n\nPrivate this As tString\nOption Base 0\nOption Explicit\n</code></pre>\n\n<p>Method <code>Class_Initialize</code> is where all the one-time stuff happens - this is where escape sequences, numeric and datetime specifiers are initialized:</p>\n\n<pre><code>Private Sub Class_Initialize()\n\n If this.PaddingCharacter = vbNullString Then this.PaddingCharacter = PADDING_CHAR\n\n InitEscapeSequences\n InitNumericSpecifiers\n InitDateTimeSpecifiers\n\nEnd Sub\n\nPrivate Sub InitEscapeSequences()\n\n Dim factory As New EscapeSequence\n Set this.EscapeSequences = New Collection\n\n this.EscapeSequences.Add factory.Create(\"\\n\", vbNewLine)\n this.EscapeSequences.Add factory.Create(\"\\q\", Chr$(34))\n this.EscapeSequences.Add factory.Create(\"\\t\", vbTab)\n this.EscapeSequences.Add factory.Create(\"\\a\", Chr$(7))\n this.EscapeSequences.Add factory.Create(\"\\b\", Chr$(8))\n this.EscapeSequences.Add factory.Create(\"\\v\", Chr$(13))\n this.EscapeSequences.Add factory.Create(\"\\f\", Chr$(14))\n this.EscapeSequences.Add factory.Create(\"\\r\", Chr$(15))\n this.EscapeSequences.Add factory.Create(\"\\\\x(\\w{2})\", 0, True, Hexadecimal)\n this.EscapeSequences.Add factory.Create(\"\\\\(\\d{3})\", 0, True, Octal)\n\n Set factory = Nothing\n\nEnd Sub\n\nPrivate Sub InitNumericSpecifiers()\n\n Set this.NumericSpecifiers = New Collection\n this.NumericSpecifiers.Add New CurrencyStringFormatIdentifier\n this.NumericSpecifiers.Add New DecimalStringFormatIdentifier\n this.NumericSpecifiers.Add New GeneralNumericStringFormatIdentifier\n this.NumericSpecifiers.Add New PercentStringFormatIdentifier\n this.NumericSpecifiers.Add New FixedPointStringFormatIdentifier\n this.NumericSpecifiers.Add New ExponentialStringFormatIdentifier\n this.NumericSpecifiers.Add New HexStringFormatIdentifier\n this.NumericSpecifiers.Add New RoundTripStringFormatIdentifier\n this.NumericSpecifiers.Add New NumericPaddingStringFormatIdentifier\n\nEnd Sub\n\nPrivate Sub InitDateTimeSpecifiers()\n\n Set this.DateTimeSpecifiers = New Collection\n this.DateTimeSpecifiers.Add New CustomDateFormatIdentifier\n this.DateTimeSpecifiers.Add New FullDateLongStringFormatSpecifier\n this.DateTimeSpecifiers.Add New FullDateShortStringFormatIdentifier\n this.DateTimeSpecifiers.Add New GeneralLongDateTimeStringFormatIdentifier\n this.DateTimeSpecifiers.Add New GeneralShortDateTimeStringFormatIdentifier\n this.DateTimeSpecifiers.Add New LongDateFormatIdentifier\n this.DateTimeSpecifiers.Add New LongTimeStringFormatIdentifier\n this.DateTimeSpecifiers.Add New ShortDateFormatIdentifier\n this.DateTimeSpecifiers.Add New SortableDateTimeStringFormatIdentifier\n\nEnd Sub\n</code></pre>\n\n<p>To make the <code>PaddingCharacter</code> configurable, it only needs to be exposed as a property.</p>\n\n<p>So let's recap here, we have:</p>\n\n<ul>\n<li>A collection of escape sequences that know how to to process themselves</li>\n<li>A collection of numeric specifiers that know how to process themselves</li>\n<li>A collection of date/time specifiers that know how to process themselves</li>\n</ul>\n\n<p>All we're missing is a function that will take a <code>format_string</code>, validate it and return a collection of <code>StringFormatSpecifier</code>. The regular expression we're using to do this can also be simplified a bit - unfortunately this doesn't make it run any faster (performance-wise, this function is really where the bottleneck is):</p>\n\n<pre><code>Private Function GetFormatSpecifiers(ByVal format_string As String, valuesCount As Integer) As Collection\n'executes a regular expression against format_string to extract all placeholders into a MatchCollection\n\n Dim regex As New RegExp\n Dim matches As MatchCollection\n Dim thisMatch As Match\n\n Dim result As New Collection\n Dim specifier As StringFormatSpecifier\n\n Dim csvIndices As String\n Dim uniqueCount As Integer\n Dim largestIndex As Integer\n\n regex.pattern = \"\\{(\\w+)(\\,\\-?\\d+)?(\\:[^}]+)?\\}\"\n\n ' literal {\n ' [1] numbered captured group, any number of repetitions (Index)\n ' alphanumeric, one or more repetitions\n ' [2] numbered captured group, zero or one repetitions (AlignmentSpecifier)\n ' literal ,\n ' literal -, zero or one repetitions\n ' any digit, one or more repetitions\n ' [3] numbered captured group, zero or one repetitions (FormatSpecifier)\n ' literal :\n ' any character except '}', one or more repetitions\n ' literal }\n\n regex.IgnoreCase = True\n regex.Global = True\n\n Set matches = regex.Execute(format_string)\n For Each thisMatch In matches\n\n Set specifier = New StringFormatSpecifier\n specifier.Index = CInt(thisMatch.SubMatches(0))\n\n If Not StringContains(csvIndices, specifier.Index &amp; \",\") Then\n uniqueCount = uniqueCount + 1\n csvIndices = csvIndices &amp; specifier.Index &amp; \",\"\n End If\n If specifier.Index &gt; largestIndex Then largestIndex = specifier.Index\n\n If Not thisMatch.SubMatches(1) = vbEmpty Then specifier.Alignment = CInt(Replace(CStr(thisMatch.SubMatches(1)), \",\", vbNullString))\n If Not thisMatch.SubMatches(2) = vbEmpty Then\n specifier.identifier = Left(Replace(CStr(thisMatch.SubMatches(2)), \":\", vbNullString), 1)\n specifier.CustomSpecifier = Replace(CStr(thisMatch.SubMatches(2)), \":\" &amp; specifier.identifier, vbNullString)\n End If\n\n result.Add specifier\n Next\n\n If matches.Count &gt; 0 And (uniqueCount &lt;&gt; valuesCount) Or (largestIndex &gt;= uniqueCount) Or valuesCount = 0) Then Err.Raise ERR_FORMAT_EXCEPTION, ERR_SOURCE, ERR_MSG_FORMAT_EXCEPTION\n\n Set GetFormatSpecifiers = result\n Set regex = Nothing\n Set matches = Nothing\n\nEnd Function\n</code></pre>\n\n<p>The actual <code>StringFormat</code> function takes an array of <code>Variant</code> sent from the module function's <code>ParamArray values()</code> parameter; taking a <code>ParamArray</code> here as well would make things more complicated than they already are.</p>\n\n<p>So all the function really needs to do, is loop through all specifiers in <code>format_string</code>, and apply the appropriate format specifier's formatting. Then apply the alignment specifier and execute escape sequences (unless <code>format_string</code> starts with a \"@\") - with everything properly encapsulated in specialized objects, this should leave a pretty readable implementation:</p>\n\n<pre><code>Public Function StringFormat(format_string As String, values() As Variant) As String\n\n Dim result As String\n result = format_string\n\n Dim specifiers As Collection\n Dim specifier As StringFormatSpecifier\n Set specifiers = GetFormatSpecifiers(result, UBound(values) + 1)\n\n Dim useLiteral As Boolean \n 'when format_string starts with \"@\", escapes are not replaced \n '(string is treated as a literal string with placeholders)\n useLiteral = StringStartsWith(\"@\", result)\n\n 'remove the \"@\" literal specifier from the result string\n If useLiteral Then result = Right(result, Len(result) - 1) \n\n\n 'replace escaped backslashes with 'ESC' character [Chr$(27)] \n 'to optimize escape sequences evaluation:\n If Not useLiteral And StringContains(result, \"\\\\\") Then _\n result = Replace(result, \"\\\\\", Chr$(27))\n\n Dim formattedValue As String\n Dim alignmentPadding As Integer\n Dim identifier As IStringFormatIdentifier\n Dim identifierFound As Boolean\n\n For Each specifier In specifiers\n\n formattedValue = values(specifier.Index)\n identifierFound = (specifier.identifier = vbNullString)\n\n If IsNumeric(values(specifier.Index)) Then\n\n For Each identifier In this.NumericSpecifiers\n If identifier.IsIdentifierMatch(specifier) Then\n\n identifierFound = True\n formattedValue = identifier.GetFormattedValue(values(specifier.Index), specifier)\n\n End If\n Next\n\n ElseIf TypeName(values(specifier.Index)) = \"Date\" Then\n\n For Each identifier In this.DateTimeSpecifiers\n If identifier.IsIdentifierMatch(specifier) Then\n\n identifierFound = True\n formattedValue = identifier.GetFormattedValue(values(specifier.Index), specifier)\n\n End If\n Next\n\n End If\n\n If Not identifierFound Then Err.Raise ERR_FORMAT_EXCEPTION, ERR_SOURCE, ERR_MSG_INVALID_FORMAT_STRING\n\n alignmentPadding = Abs(specifier.Alignment)\n If specifier.Alignment &lt; 0 Then\n\n 'negative: left-justified alignment\n If alignmentPadding - Len(formattedValue) &gt; 0 Then _\n formattedValue = formattedValue &amp; String$(alignmentPadding - Len(formattedValue), this.PaddingCharacter)\n\n ElseIf specifier.Alignment &gt; 0 Then\n\n 'positive: right-justified alignment\n If alignmentPadding - Len(formattedValue) &gt; 0 Then _\n formattedValue = String$(alignmentPadding - Len(formattedValue), this.PaddingCharacter) &amp; formattedValue\n\n End If\n\n 'replace all occurrences of placeholder {i} with their formatted values:\n result = Replace(result, specifier.ToString, formattedValue)\n\n Next\n\n Dim escape As EscapeSequence\n If Not useLiteral And StringContains(result, \"\\\") Then\n For Each escape In this.EscapeSequences\n escape.Execute result\n Next\n End If\n\n If Not useLiteral And StringContains(result, Chr$(27)) Then result = Replace(result, Chr$(27), \"\\\")\n StringFormat = result\n\nEnd Function\n</code></pre>\n\n<p>Feel free to comment below! :)</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-09-09T18:52:39.670", "Id": "49341", "Score": "1", "body": "I should add that performance tests calling `StringFormat(\"{0,20}\", \"test string\")` 10,000 times in a loop, with the monolithic function average at around 2730 (2703-2797) milliseconds, while the refactored and definitely more object-oriented version averages at around 2390 (2312-2594) milliseconds, which is a subtle but welcome improvement!" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-09-10T00:31:56.087", "Id": "49378", "Score": "5", "body": "And I thought Winston Ewert was the only one here with the longest answers. :-P Kudos for such a lengthy (and assumably great) self-answer contribution. It's a shame I have no idea what any of this means." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-09-10T00:40:31.453", "Id": "49379", "Score": "0", "body": "Thanks! Check this out: http://msdn.microsoft.com/en-us/library/fht0f5be(v=vs.95).aspx - I think this implementation is the most useful code I've ever written in VB6 (works in VBA - Alt+F11 in Excel, insert a new code module and enjoy .net-like string formatting :)). I didn't really mean to self-answer, it's just rewriting it in a more OOP way was itching... so I figured I'd post the refactored version as a self-answer, but I'm not self-accepting it just yet - in case I actually get a review... I take it as some sort of \"practice review\" :)" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-09-10T00:47:42.640", "Id": "49380", "Score": "2", "body": "As this IS an answer, no one can properly do a full review if needed. Any criticisms and such would be limited to comments. Moreover, don't be afraid to self-answer (as long as it's still intended to be an answer). I've done so before, but haven't received votes on any of them. I think it's kinda hard to self-answer on CR, especially if you yourself can't figure out one of the best reviewed versions of your code." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-09-10T00:56:28.987", "Id": "49382", "Score": "0", "body": "I'm sure there are a couple nasty bugs lurking in there... The thing with a self-answer on CR is that the self-answer could be subject to another code review on its own - self-answering sounds like saying \"okay nevermind what's above; I made it better, take a look at this instead\"... interestingly, \"self-answer\" yields only 2 irrelevant results on meta..." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-09-10T01:00:08.190", "Id": "49383", "Score": "4", "body": "In that case, there would have to be another answer to review that answer. [Answerception](http://en.wikipedia.org/wiki/Inception)?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-06-05T18:56:30.273", "Id": "377272", "Score": "0", "body": "I would like to use this code because it's darn fantastic. However you've missed some of the definitions out for the sake of the review, and so as it stands I can't use this fully. Would you be willing to share the complete code or provide a link to it? Maybe a cheeky .xlam ;) if it's kicking around" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-06-05T18:57:54.197", "Id": "377274", "Score": "2", "body": "@Greedo I had it all on an old computer.. which died in 2015. This is all that's left of it :-/ the original function on the SO post is self-contained though, no?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-09-22T09:25:46.327", "Id": "528930", "Score": "1", "body": "I think I already mentioned to you Matt but I was reminded of this recently. I resurrected this code and [put it on github](https://github.com/Greedquest/VBA-Gems), and also here is a [downloadable .xlam](https://github.com/Greedquest/VBA-Gems/blob/main/CSharpish%20String%20Format/String%20Format.xlam?raw=true) version which can be referenced from an excel project, and gives both `StringFormat` (updated) and `FormerStringFormat` (original) functions. I seem to remember the escape sequences may not be working correctly, I had to make some guesses, but this is 90% of the way there" } ], "meta_data": { "CommentCount": "9", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-09-09T16:20:29.560", "Id": "31000", "ParentId": "30817", "Score": "16" } }, { "body": "<p>Two small things I noticed at a glance, both involve this code and it looks like it made it into your refactored version as well.</p>\n\n<blockquote>\n<pre><code> 'some error-handling constants:\n Const ERR_FORMAT_EXCEPTION As Long = vbObjectError Or 9001\n Const ERR_ARGUMENT_NULL_EXCEPTION As Long = vbObjectError Or 9002\n Const ERR_ARGUMENT_EXCEPTION As Long = vbObjectError Or 9003\n</code></pre>\n</blockquote>\n\n<p>Why on Earth are you bitwise <code>Or</code>ing these? Just add them like <s>in the documentation</s> every other sane developer.</p>\n\n<pre><code> 'some error-handling constants:\n Const ERR_FORMAT_EXCEPTION As Long = vbObjectError + 9001\n Const ERR_ARGUMENT_NULL_EXCEPTION As Long = vbObjectError + 9002\n Const ERR_ARGUMENT_EXCEPTION As Long = vbObjectError + 9003\n</code></pre>\n\n<p>While you're at it, why isn't this an <code>Enum</code>? </p>\n\n<pre><code>'some error-handling constants:\nPublic Enum FormatError\n ERR_FORMAT_EXCEPTION = vbObjectError + 9001\n ERR_ARGUMENT_NULL_EXCEPTION\n ERR_ARGUMENT_EXCEPTION\nEnd Enum \n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-08-15T20:08:59.887", "Id": "108834", "Score": "4", "body": "Dude, where have you been all this time!" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-08-15T20:10:23.257", "Id": "108835", "Score": "10", "body": "Wasting time on Stack Overflow." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2016-06-06T13:23:40.247", "Id": "244691", "Score": "0", "body": "\"Because bitwise `Or` is 'correct'.\" I agree with the `Enum` though." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2016-06-06T13:32:56.133", "Id": "244693", "Score": "1", "body": "How is the `Or` correct @MarkHurd? Sure, it works and is completely equivalent in this scenario, but your average VB dev is going to stare at the screen uttering \"WTF\". In my mind, the correct way is the way that's easy to understand." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2016-06-06T14:40:44.613", "Id": "244720", "Score": "1", "body": "@RubberDuck You've caused me to go back and quickly review my VB6 code: I used `Or` mostly, but sometimes I did something like `Const ErrBase = vbObjectError Or 1000 : Err.Raise ErrBase + 19`. Anyway, the other [facility codes](https://msdn.microsoft.com/en-us/library/cc231198.aspx) mostly aren't relevant to VB6 code, although we should probably now use &hA0000000 instead anyway." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-08-17T06:48:55.333", "Id": "439699", "Score": "0", "body": "in the Enum why does only the first have the + \\d{4} please?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-08-17T10:00:36.163", "Id": "439707", "Score": "0", "body": "@QHarr the rest of them increment by 1 automatically. Omitting the +2, +3, etc just makes for easier maintenance." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-08-17T11:49:53.663", "Id": "439717", "Score": "0", "body": "@RubberDuck Thanks. I was guessing something like that. And is there a reason for the number being 9001 ? As opposed to say 901 ?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-08-17T11:53:25.477", "Id": "439718", "Score": "0", "body": "You always add some number to the `vbObjectError` constant, but there’s no real meaning to what that number is other than what we assign to it. You want it to be unique so that it’s easy to find the error code. When I was regularly developing VBA, my dept kept a spreadsheet full of the custom error codes we had created so we didn’t duplicate and they were easy to look up." } ], "meta_data": { "CommentCount": "9", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-08-15T20:06:35.720", "Id": "60187", "ParentId": "30817", "Score": "12" } }, { "body": "<p>As mentioned in the comments, note that this is \"reviewing\" the code in the self-answer:</p>\n\n<p>The <code>Replace</code> calls effectively implementing the missing <code>RemoveFrom</code> method isn't needed here. You could add extra brackets to the <code>RegEx</code>, and just extract the captures you want, but here you know the position and length of what you're skipping, so just use <code>Mid$</code>. I.e. this: </p>\n\n<pre><code> If Not thisMatch.SubMatches(1) = vbEmpty Then specifier.Alignment = CInt(Replace(CStr(thisMatch.SubMatches(1)), \",\", vbNullString))\n If Not thisMatch.SubMatches(2) = vbEmpty Then\n specifier.identifier = Left(Replace(CStr(thisMatch.SubMatches(2)), \":\", vbNullString), 1)\n specifier.CustomSpecifier = Replace(CStr(thisMatch.SubMatches(2)), \":\" &amp; specifier.identifier, vbNullString)\n End If\n</code></pre>\n\n<p>becomes this:</p>\n\n<pre><code> If Not thisMatch.SubMatches(1) = vbEmpty Then specifier.Alignment = CInt(Mid$(CStr(thisMatch.SubMatches(1)), 2))\n If Not thisMatch.SubMatches(2) = vbEmpty Then\n specifier.identifier = Mid$(CStr(thisMatch.SubMatches(2)), 2, 1)\n specifier.CustomSpecifier = Mid$(CStr(thisMatch.SubMatches(2)), 3)\n End If\n</code></pre>\n\n<p><em>BUG</em></p>\n\n<p>To avoid counting wrong for the pedantic case of <code>\"{2}{11}{1}...\"</code>, initialise <code>csvIndices</code> to <code>\",\"</code> and search for <code>\",\" &amp; specifier.Index &amp; \",\"</code>.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2016-06-06T13:42:53.770", "Id": "131235", "ParentId": "30817", "Score": "3" } } ]
{ "AcceptedAnswerId": "31000", "CommentCount": "1", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-09-05T12:43:12.027", "Id": "30817", "Score": "19", "Tags": [ "strings", "vba", "formatting", "vb6" ], "Title": "A CSharpish String.Format formatting helper" }
30817
<p>I need to make sure the correct menu item is highlighted according to which URL is currently being viewed. </p> <p>Now the problem with our site is that each menu item can represent several pages. So the Client menu will show the client list - but should still be highlighted when you go to the edit client page. So I can't parse the current URL and match it against the menu item to determine if it should be highlighted.</p> <p>Instead I have decided to add a custom field - <code>menu</code> - to the $routeProvider setup. So when setting up the routes :</p> <pre><code>$routeProvider .when( '/SecurityGroup/Index', { templateUrl: '/SecurityGroup/IndexPartial', controller: 'GroupListController', menu: 'group' } ) .when( '/SecurityGroup/MemberClients/:groupId&amp;:groupName', { templateUrl: '/SecurityGroup/MemberClientsPartial', controller: 'MemberClientsController', menu: 'group' } ) </code></pre> <p>Then in the HTML, the menus are specified as (the tr-menu attribute matches against the name field in the route) :</p> <pre><code>&lt;li menuitem tr-menu="group" href='/SecurityGroup/IndexPartial'&gt;Groups&lt;/li&gt; &lt;li menuitem tr-menu="client" href='/Clients/IndexPartial'&gt;Clients&lt;/li&gt; </code></pre> <p>Then I have a directive that manages the menu highlighting - essentially adding and removing the Active class if the current route contains the correct name :</p> <pre><code>(function() { 'use strict'; angular.module('Administration') .directive('menuitem', ['$location', function($location) { return { restrict: 'A', scope: false, transclude: true, replace: false, template: '&lt;a ng-transclude&gt;&lt;/a&gt;', link: function (scope, element, attrs) { var href = attrs.href; var name = attrs.trMenu; var link = element.find('a'); link.attr('href', href); scope.$on('$routeChangeSuccess', function (event, currentRoute, previousRoute) { var menu = currentRoute.$$route.menu; if (menu === name) element.addClass('active'); else element.removeClass('active'); }); } }; }]); }()); </code></pre> <p>Is this a clever solution, or a terrible abuse of javascripts dynamic abilities? Is there a more Angular way of doing things rather than relying on adding my own fields to the existing Angular data structures?</p>
[]
[ { "body": "<p>I'm not sure if my solution is relevant to your problem, but I had a similar problem with keeping the correct page selected on page refresh as refresh was resetting defaults and home would be selected on what ever page you refreshed from.</p>\n\n<p>This is how I solved it:</p>\n\n<p><strong>page controllers</strong></p>\n\n<pre><code>app.controller('aboutCtrl', ['$rootScope', function($rootScope){\n $rootScope.$broadcast('pageSelected', \"about\");\n}]);\n\napp.controller('stuffCtrl', ['$rootScope', function($rootScope){\n $rootScope.$broadcast('pageSelected', \"stuff\");\n}]);\n\napp.controller('homeCtrl', ['$rootScope', function($rootScope){\n $rootScope.$broadcast('pageSelected', \"home\");\n}]); \n</code></pre>\n\n<p>When the page controller is initiated, it broadcasts <code>pageSelected</code> with the name of the page as the value (important to use <code>$rootScope</code> to avoid parent/child cases).</p>\n\n<p><strong>navigation menu controller</strong></p>\n\n<pre><code>app.controller('headerCtrl', ['$scope', '$rootScope', function($scope, $rootScope){\n $scope.$on('pageSelected', function(e, val){\n $scope.selected = val;\n });\n}]);\n</code></pre>\n\n<p>The menu controller is listening for the <code>pageSelected</code> broadcast and will set <code>$scope.selected</code> to the value received.</p>\n\n<p><strong>navigation menu html</strong></p>\n\n<pre><code>&lt;a ui-sref=\"home\"&gt;&lt;div ng-class=\"{selected: selected=='home'}\"&gt;Home&lt;/div&gt;&lt;/a&gt;\n&lt;a ui-sref=\"toDo\"&gt;&lt;div ng-class=\"{selected: selected=='todo'}\"&gt;To Do&lt;/div&gt;&lt;/a&gt;\n&lt;a ui-sref=\"stuff\"&gt;&lt;div ng-class=\"{selected: selected=='stuff'}\"&gt;Stuff&lt;/div&gt;&lt;/a&gt;\n&lt;a ui-sref=\"about\"&gt;&lt;div ng-class=\"{selected: selected=='about'}\"&gt;About&lt;/div&gt;&lt;/a&gt;\n</code></pre>\n\n<p>Finally, the menu will update which item has the <code>selected</code> class dynamically based on <code>$scope.selected</code>.</p>\n\n<p>In your case, you could maybe have the page controllers that need the same menu item selected to broadcast the same value?</p>\n\n<p>Although not necessary, I also recommend using <code>ui-router</code>. It is state-based instead of URL-based; that's why I have <code>ui-sref=\"home\"</code> ect.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-08-12T04:15:34.557", "Id": "59762", "ParentId": "30823", "Score": "3" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-09-05T14:16:28.570", "Id": "30823", "Score": "2", "Tags": [ "javascript", "angular.js" ], "Title": "Adding a custom field to Routes - clever solution or terrible hack?" }
30823
<p>I am trying to evaluate if someone has read and seen all the questions of a book.</p> <p>I am using PHP to average everything out after I get the data. I know MySQL can avg, but I can't seem to wrap my head around how I can average the box number of the questions (similar to spaced repetition learning) if they haven't seen every question.</p> <p>How can this function be better? I feel there might be a more elegant way of doing it.</p> <pre><code>SELECT COUNT(s.id), (SELECT COUNT(u.id) FROM user_sections u WHERE u.chpt_id = ? &amp;&amp; u.user_id = ? ), (SELECT COUNT(q.id) FROM question q WHERE q.chapter_id = ? &amp;&amp; (q.module = 1 || q.module = ?) ), (SELECT COUNT(v.id) FROM user_questions v WHERE v.chpt_id = ? &amp;&amp; u.user_id = ? ), (SELECT AVG(v.box) FROM user_questions v WHERE v.chapter_id = ? &amp;&amp; u.user_id=? ), (SELECT AVG(m.$mkts_col) FROM mkts m WHERE m.chapter_id = ? &amp;&amp; (m.module = 1 || m.module = ?) ) FROM sections s WHERE s.chapter_id = ? &amp;&amp; (s.module = 1 || s.module = ?) </code></pre>
[]
[ { "body": "<p>What you have written is essentially six independent queries. Let's drop the pretense that these are correlated subqueries. Let's also reorder the output columns. We can also simplify <code>col = A || col = B</code> as <code>col in (A, B)</code>.</p>\n\n<pre><code>SELECT (SELECT COUNT(s.id)\n FROM sections s\n WHERE s.chapter_id = ? AND s.module IN (1, ?)\n ),\n (SELECT COUNT(q.id)\n FROM question q\n WHERE q.chapter_id = ? AND q.module IN (1, ?)\n ),\n (SELECT AVG(m.$mkts_col)\n FROM mkts m\n WHERE m.chapter_id = ? AND m.module IN (1, ?)\n ),\n (SELECT COUNT(u.id)\n FROM user_sections u\n WHERE u.chpt_id = ? AND u.user_id = ?\n ),\n (SELECT COUNT(v.id)\n FROM user_questions v\n WHERE v.chpt_id = ? AND u.user_id = ?\n ),\n (SELECT AVG(v.box)\n FROM user_questions v\n WHERE v.chapter_id = ? AND u.user_id = ?\n );\n</code></pre>\n\n<p>That's about all you can do to rewrite this particular query. Depending on how your application works, it might make sense to obtain all of these statistics globally, instead of for particular user + chapter + module combinations. In that case, you would write two queries, each with <code>JOIN</code> and <code>GROUP BY</code> clauses. One query be joined by chapter and module conditions, and the other would be joined by chapter and user.</p>\n\n<p>After rearranging the columns, it becomes more obvious that you used both <code>user_questions.chpt_id</code> and <code>user_questions.chapter_id</code>. One of them is probably an error.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-09-19T08:41:31.807", "Id": "50270", "Score": "0", "body": "Never use \"AVG()\" function, its perfome as crap, :) sorry to say it." } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-09-05T20:36:22.177", "Id": "30838", "ParentId": "30824", "Score": "1" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-08-24T04:52:57.833", "Id": "30824", "Score": "1", "Tags": [ "performance", "sql", "mysql", "mysqli" ], "Title": "Determining if someone has read and seen all the questions of a book" }
30824
<p>Every coder knows that if you give six developers an assignment to write a bit of code that will perform some specific task, you will end up with at least six different ways of doing it.</p> <p>I recently realized/discovered a radical example of this. I wrote some code to calculate check digits for barcodes. I then found some legacy code of ours to do the same thing. I have tested both with several barcodes, and so far they produce the same results, but I find it rather fascinating just how different the "how" of the solutions are.</p> <p>If anybody wants to play around with it, I'll add the entire code below (you will see in the button click event what you will need to name the few labels and buttons and the edit control); but first: the two methods that calculate the check value (actually, my solution uses several functions, which are called by the primary function).</p> <p>First, the legacy function:</p> <pre><code>public static char CalculateChkDigit(string CheckValue) { if (CheckValue.Length &gt; 6) { char ch; int a, b, i, j; a = 0; b = 0; j = ((int)CheckValue.Length) - 1; i = j; while (i &gt;= 0) { a = a + (int)(CheckValue[i]) - 48; i = i - 2; } j = ((int)CheckValue.Length) - 2; i = j; while (i &gt;= 0) { b = b + (int)(CheckValue[i]) - 48; i = i - 2; } a = 3 * a + b; b = a % 10; if (b != 0) b = 10 - b; ch = (char)(48 + b); return ch; } else return ' '; } </code></pre> <p>Actually, this was cleaned up using Resharper to become this in my test/comparison utility:</p> <pre><code>private static char GetBarcodeChecksumWithLegacyCode(string barcodeWithoutCzechSum) { if (barcodeWithoutCzechSum.Length &gt; 6) { int a = 0; int b = 0; int j = barcodeWithoutCzechSum.Length - 1; int i = j; while (i &gt;= 0) { a = a + barcodeWithoutCzechSum[i] - 48; i = i - 2; } j = barcodeWithoutCzechSum.Length - 2; i = j; while (i &gt;= 0) { b = b + barcodeWithoutCzechSum[i] - 48; i = i - 2; } a = 3 * a + b; b = a % 10; if (b != 0) b = 10 - b; var ch = (char)(48 + b); return ch; } return ' '; } </code></pre> <p>Now, here's my code:</p> <pre><code>public static string GetBarcodeChecksum(string barcode) { int oddTotal; int oddTotalTripled; int evenTotal; // Which positions are odd or even depend on the length of the barcode, // or more specifically, whether its length is odd or even, so: if (isStringOfEvenLen(barcode)) { oddTotal = sumInsideOrdinals(barcode); oddTotalTripled = oddTotal * 3; evenTotal = sumOutsideOrdinals(barcode); } else { oddTotal = sumOutsideOrdinals(barcode); oddTotalTripled = oddTotal * 3; evenTotal = sumInsideOrdinals(barcode); } int finalTotal = oddTotalTripled + evenTotal; int modVal = finalTotal%10; int czechSum = 10 - modVal; if (czechSum == 10) { return "0"; } return czechSum.ToString(); } private static bool isStringOfEvenLen(string barcode) { return (barcode.Length % 2 == 0); } // "EvenOrdinals" instead of "EvenVals" because values at index 0,2,4,etc. are seen by the // checkdigitmeisters as First, Third, Fifth, ... (etc.), not Zeroeth, Second, Fourth private static int sumInsideOrdinals(string barcode) { int cumulativeVal = 0; for (int i = barcode.Length-1; i &gt; -1; i--) { if (i % 2 != 0) { cumulativeVal += Convert.ToInt16(barcode[i] - '0'); } } return cumulativeVal; } // "OddOrdinals" instead of "OddVals" because values at index 1,3,5,etc. are seen by the // checkdigitmeisters as Second, Fourth, Sixth, ..., not First, Third, Fifth, ... private static int sumOutsideOrdinals(string barcode) { int cumulativeVal = 0; for (int i = barcode.Length - 1; i &gt; -1; i--) { if (i % 2 == 0) { cumulativeVal += Convert.ToInt16(barcode[i] - '0'); } } return cumulativeVal; } </code></pre> <p>As is probably understandable, I prefer my code, because, although more verbose/less "elegant", it seems easier to grok to me AND -- the reason why N coders will come up with N+N solutions to a challenge -- I think differently than the other cat/come from a different "place" in approaching a solution to this challenge. As long as they both work, it's hard to say one way is better than the other; however, I do find it quite interesting just how different the two approaches are. The legacy code looks to me like something from "A Beautiful Mind" - impressive, but (for me, at least) practically impenetrable.</p> <p>Finally, here's all the code, for the tinkerers in the audience:</p> <pre><code>using System; using System.Windows.Forms; namespace BarcodeCzechDigitTester { public partial class Form1 : Form { public Form1() { InitializeComponent(); } private void button1_Click(object sender, EventArgs e) { string barcodeWithoutCzechSum = textBox1.Text.Trim(); // calculate check sum using my code string czechSum = GetBarcodeChecksum(barcodeWithoutCzechSum); string barcodeWithCzechSum = string.Format("{0}{1}", barcodeWithoutCzechSum, czechSum); label1.Text = barcodeWithCzechSum; // calculate check sum using legacy code (which I had been avoiding due to its seemingly overly complex logic) char checkSumLegacy = GetBarcodeChecksumWithLegacyCode(barcodeWithoutCzechSum); string barcodeWithCheckFromSumLegacyCode = string.Format("{0}{1}", barcodeWithoutCzechSum, checkSumLegacy); labelLegacy.Text = barcodeWithCheckFromSumLegacyCode; textBox1.Focus(); } private static char GetBarcodeChecksumWithLegacyCode(string barcodeWithoutCzechSum) { if (barcodeWithoutCzechSum.Length &gt; 6) { int a = 0; int b = 0; int j = barcodeWithoutCzechSum.Length - 1; int i = j; while (i &gt;= 0) { a = a + barcodeWithoutCzechSum[i] - 48; i = i - 2; } j = barcodeWithoutCzechSum.Length - 2; i = j; while (i &gt;= 0) { b = b + barcodeWithoutCzechSum[i] - 48; i = i - 2; } a = 3 * a + b; b = a % 10; if (b != 0) b = 10 - b; var ch = (char)(48 + b); return ch; } return ' '; } public static string GetBarcodeChecksum(string barcode) { int oddTotal; int oddTotalTripled; int evenTotal; // Which positions are odd or even depend on the length of the barcode, // or more specifically, whether its length is odd or even, so: if (isStringOfEvenLen(barcode)) { oddTotal = sumInsideOrdinals(barcode); oddTotalTripled = oddTotal * 3; evenTotal = sumOutsideOrdinals(barcode); } else { oddTotal = sumOutsideOrdinals(barcode); oddTotalTripled = oddTotal * 3; evenTotal = sumInsideOrdinals(barcode); } int finalTotal = oddTotalTripled + evenTotal; int modVal = finalTotal%10; int czechSum = 10 - modVal; if (czechSum == 10) { return "0"; } return czechSum.ToString(); } private static bool isStringOfEvenLen(string barcode) { return (barcode.Length % 2 == 0); } // "EvenOrdinals" instead of "EvenVals" because values at index 0,2,4,etc. are seen by the // checkdigitmeisters as First, Third, Fifth, ... (etc.), not Zeroeth, Second, Fourth private static int sumInsideOrdinals(string barcode) { int cumulativeVal = 0; for (int i = barcode.Length-1; i &gt; -1; i--) { if (i % 2 != 0) { cumulativeVal += Convert.ToInt16(barcode[i] - '0'); } } return cumulativeVal; } // "OddOrdinals" instead of "OddVals" because values at index 1,3,5,etc. are seen by the // checkdigitmeisters as Second, Fourth, Sixth, ..., not First, Third, Fifth, ... private static int sumOutsideOrdinals(string barcode) { int cumulativeVal = 0; for (int i = barcode.Length - 1; i &gt; -1; i--) { if (i % 2 == 0) { cumulativeVal += Convert.ToInt16(barcode[i] - '0'); } } return cumulativeVal; } private void button2_Click(object sender, EventArgs e) { string bcVal = textBox1.Text.Trim(); bool validCzechDigit = isValidBarcodeWithCheckDigit(bcVal); MessageBox.Show(validCzechDigit ? string.Format("{0} is valid", bcVal) : string.Format("{0} invalid", bcVal)); } private static bool isValidBarcodeWithCheckDigit(string barcodeWithCheckDigit) { string barcodeSansCheckDigit = barcodeWithCheckDigit.Substring(0, barcodeWithCheckDigit.Length - 1); string czechDigit = barcodeWithCheckDigit.Substring(barcodeWithCheckDigit.Length - 1, 1); //MessageBox.Show(string.Format("raw barcode portion is {0}", barcodeSansCheckDigit)); //MessageBox.Show(string.Format("czech portion is {0}", czechDigit)); return GetBarcodeChecksum(barcodeSansCheckDigit) == czechDigit; } } } </code></pre> <p>To help visualize the GUI:</p> <p><img src="https://i.stack.imgur.com/KU4aW.png" alt="enter image description here"></p> <p>Any comments/observations?</p>
[ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-09-05T16:36:26.643", "Id": "49040", "Score": "1", "body": "I'm happy everyone kept the CzechSum." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-09-05T17:35:50.520", "Id": "49047", "Score": "0", "body": "@JohnMark13 Well, barcodes were invented by the Czech mathematician Barbora Coděláš, that's why it's called Czech sum. :-)" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-09-05T20:03:13.930", "Id": "49065", "Score": "0", "body": "Love lateral thinking." } ]
[ { "body": "<p><strong>Caveat: I've never written a line of C#, nor do I know anything about its compiler.</strong></p>\n\n<p>I think that the approach taken in your code could be considered the more modern approach. It is definitely more suitable for human consumption, and it makes it more easy to test individual parts of the algorithm. With luck it will compile down to very similar byte code too.</p>\n\n<p>But, your code is inelegant in that you loop twice skipping alternate elements. You also have a bit of smell where you have the code <code>if (isStringOfEvenLen(barcode))</code>. I'm not sure what the accepted usage of Tuples is in C# but for internal use I'd have thought a single function that returns you an (insides, outsides) would be acceptable - if not a little helper class with two elements. This would modify you code to begin (pseudo-ish):</p>\n\n<pre><code>Tuple&lt;int, int&gt; sums = sumOrdinals();\nint finalTotal = generateTotal(sums);\n</code></pre>\n\n<p>Where generateTotal looks like this:</p>\n\n<pre><code>private static int generateTotal(Tuple&lt;int, int&gt; sums)\n{\n\n if (isStringOfEvenLen(barcode)) {\n return (sums.Item1 * 3) + sums.Item2;\n }\n\n return (sums.Item2 * 3) + sums.Item1;\n}\n</code></pre>\n\n<p>Then onwards. Arguably this is borderline procedural but with these few steps I think that is acceptable.</p>\n\n<p><strong>Edit: Less readable, more old school</strong></p>\n\n<pre><code>public static string Check(string barcode)\n{\n int sum = 0;\n for (int i = 0; i &lt; barcode.Length; i++)\n {\n sum += i &amp; 0x01 == 1 ? barcode[i] - '0' : (barcode[i] - '0') * 3;\n }\n\n int mod = sum % 10;\n return mod == 0 ? 0 : 10 - mod;\n}\n</code></pre>\n\n<p>Now what you really want to do of course is collapse down that <code>for</code> loop. I found that if you have LINQ (which I see you do not) you can use the <a href=\"http://msdn.microsoft.com/en-us/library/bb548651.aspx\" rel=\"nofollow\"><code>Aggregate</code></a> operator, very simple e.g:</p>\n\n<pre><code>int sum = barcode.ToCharArray().Aggregate(0, (sum, value) =&gt; sum.Add(value - '0'));\n</code></pre>\n\n<p>So, if you're clever about getting an index in there you could write the algorithm (without validation) in just 3 lines and you'd have done a bit of functional programming which sets you up nicely for playing with a new language.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-09-05T17:07:35.253", "Id": "30833", "ParentId": "30829", "Score": "1" } }, { "body": "<p>The first thing that caught my eye, was that they are not functionally equivalent. Yours is missing the case when a barcode is below 7 in lenght.\nAnother thing that strikes me as odd about both solutions is the verbosity and inefficiency involved in both. Both needlessly iterate twice, and im not sure the names of variables and methods in your rewrite, are accurately portraying what they are actually doing.\nAs you encouraged people to tinker with it, heres is my shot at it:</p>\n\n<pre><code>public static string Check(string barcode)\n {\n if (barcode.Length &lt;= 6) return \" \";\n\n var sums = new int[2];\n for (int i = 0; i &lt; barcode.Length; i++)\n {\n sums[(i+1)%2] += barcode[i] - '0';\n }\n\n sums[barcode.Length%2] *= 3;\n\n int mod = sums.Sum()%10;\n return (mod == 0 ? mod : 10 - mod).ToString();\n }\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-09-05T19:16:16.137", "Id": "49059", "Score": "0", "body": "Actually, mine is the one that *does* deal with any length of barcode, from 1 to 42Googleplex (give or take). Whether that matters or not (are there barcodes less than 7 in length?), I don't know. Thanks for your tinkering/tweaking." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-09-05T19:17:05.843", "Id": "49060", "Score": "1", "body": "As far as naming goes, I consider \"Check\" to be too vague." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-09-05T19:17:39.750", "Id": "49061", "Score": "0", "body": "Oh, I see what you're saying - mine *shouldn't\" allow barcodes below 7. Okay, point taken." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-09-05T19:19:06.510", "Id": "49062", "Score": "0", "body": "Touché about the vague naming :)" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-09-05T20:23:37.973", "Id": "49068", "Score": "1", "body": "And to be frank, Frank is kind of a frank name, too." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-09-05T20:36:25.967", "Id": "49070", "Score": "0", "body": "I think this example is doubtless more elegant than both of those provided; I tested all of them on several barcodes, and they all agree. So to the user they are six of one, half a dozen of the other, and 3 couples of a third, but to the jaundiced eye of the cynical coder, Frank's takes the cake." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-09-05T20:37:57.043", "Id": "49071", "Score": "0", "body": "Although this question doesn't really have an *answer* per se - I was primarily asking more for opinions, and showing off how different two cats can think - I marked this as the answer as it is definitely the work of a very clever cat (even though he probably will name his children John and Mary). HOWEVER, alas, unfortunately I cannot use this code, because away back in the days of VS2003 and .NET1-1 (where I am currently trapped), the compiler knew nothing about LINQ." } ], "meta_data": { "CommentCount": "7", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-09-05T19:01:51.593", "Id": "30836", "ParentId": "30829", "Score": "2" } } ]
{ "AcceptedAnswerId": "30836", "CommentCount": "3", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-09-05T16:28:10.560", "Id": "30829", "Score": "3", "Tags": [ "c#", "comparative-review", "checksum" ], "Title": "Calculating Czechsum digits for barcodes" }
30829
<p>I'm not a great JS coder so I need your expertises to look into my code (although nothing very special and it works fine) to see if it is good practise or not because I heard that dodgy JS coding might slow down the site especially when it comes to reading mouse or user events.</p> <p><div class="snippet" data-lang="js" data-hide="false"> <div class="snippet-code"> <pre class="snippet-code-js lang-js prettyprint-override"><code>function textbox_clear_default(form_field, mouse_event) { var field_data = (document.getElementById(form_field).value).replace(/ /gi, ''); var lower_case = field_data.toLowerCase(); if (form_field == 'text_site_search') { if (lower_case == 'sitesearch') { document.getElementById(form_field).value = ''; } } if (mouse_event == 'onclick') { if (lower_case == 'sitesearch') { document.getElementById(form_field).value = ''; } } if (mouse_event == 'onblur') { if (lower_case == 'sitesearch' || lower_case == '') { document.getElementById(form_field).value = 'Site Search'; } } }</code></pre> <pre class="snippet-code-html lang-html prettyprint-override"><code>&lt;input id="text_site_search" type="text" name="text_site_search" value="Site Search" onclick="textbox_clear_default(this.id, 'onclick')" onblur="textbox_clear_default(this.id, 'onblur')" /&gt;</code></pre> </div> </div> </p>
[ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-09-06T09:45:11.693", "Id": "49120", "Score": "2", "body": "In modern browsers you can simply use `<input placeholder=\"Site Search\">`. For older browsers you might be able to use a [polyfill](https://github.com/Modernizr/Modernizr/wiki/HTML5-Cross-Browser-Polyfills#web-forms--input-placeholder)." } ]
[ { "body": "<p>This is the way I would approach it. Live demo here: <a href=\"http://jsbin.com/iHEgalU/3/edit\" rel=\"nofollow\">http://jsbin.com/iHEgalU/3/edit</a>\nSure, bad js can slow your site down. Something like this is going to be pretty fast no matter what you do (unless you go out of your way to make it slow), but better is better and I say it's good to write the best, fastest, and most totally rock-sauce code you possibly can. So here goes.</p>\n\n<p>Some people may consider it overkill considering the simplicity of your task, but I prefer writing in a manner that allows me to easily expand my script while keeping everything tidy and following good practices. You can extract the improved logic and use it in whatever style you like. I have commented this quite a bit. Refer to the live demo where there are no comments if you'd rather see it that way.</p>\n\n<pre><code>&lt;input id=\"text_site_search\" type=\"text\" name=\"text_site_search\" value=\"Site Search\"&gt;\n</code></pre>\n\n<p>Avoid inline event functions! Notice that I have removed them from the html and put them in the js where they belong! This is much cleaner! HTML can't \"do\" things, so it doesn't need to know about click functions.</p>\n\n<pre><code>var myStuff = {\n options: { //these will be defaults, used if a parameter is not passed to init()\n sel: '',\n placeholder: 'My Placeholder'\n },\n init: function(sel, placeholder) { //this will kick everything off, that's all we need to run, you can pass options in like this or by object. I tend to use objects, but no need here.\n if (sel) { this.options.sel = sel }\n if (placeholder) { this.options.placeholder = placeholder }\n //there are several ways you could replace the passed in options...this is just an example that's ok for this case. jQuery has a method called $.extend, for example\n\n var obj = this; //cache a reference to \"this\" which currently refers to \"myStuff\"\n var inputSearch = document.getElementById(sel); //search the dom for the element and cache the reference\n //no need to keep searching the dom for an element. Search once and store the result.\n\n inputSearch.addEventListener('focus', function() {\n if (this.value === obj.defaultValue) { //\"this\" refers to the element when inside an event handler\n this.value = '';\n }\n });\n\n inputSearch.addEventListener('blur', function() {\n if (this.value === \"\") {\n this.value = obj.defaultValue; \n }\n });\n }\n};\n\nmyStuff.init('text_site_search', 'Site Search');\n</code></pre>\n\n<p>The options thing here isn't really all that helpful given the simplicity. If this is all this will ever do, I'd probably just use the parameters directly (just use <code>sel</code> where you need it), but I wanted to demonstrate the concept.</p>\n\n<p>Note: IE8 and lower do not support addEventListener. Look up the conditional that deals with that issue if needed.</p>\n\n<p>The funny thing about this whole script is that it is remarkably similar to html5 placeholders, though older browsers won't support that.</p>\n\n<pre><code>&lt;input type=\"text\" name=\"text_site_search\" placeholder=\"Site Search\"&gt;\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-09-05T18:27:39.390", "Id": "49055", "Score": "2", "body": "Other than making it a little more generic (not binding explicitly to text_site_search) I do not think that this is overkill. It's certainly less overkill than reaching for the jQuery. Could mention HTML 5 placeholders here." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-09-05T18:56:34.580", "Id": "49057", "Score": "1", "body": "aren't there some browser compatibility issues with `addEventListener`?" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-09-05T20:04:30.437", "Id": "49066", "Score": "0", "body": "@JohnMark13 Oops! You know, I was meaning to make a note about options and I totally forgot. Doh. Great call. I'll update." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-09-05T20:05:48.413", "Id": "49067", "Score": "0", "body": "@Stuart older IE doesn't support it, but that's an easily discoverable issue (when it throws the error, lol) and I hate to ugly up my sample code with fail browser workarounds. Anyway, good note. I'll add something in my answer." } ], "meta_data": { "CommentCount": "4", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-09-05T17:33:50.110", "Id": "30834", "ParentId": "30832", "Score": "2" } }, { "body": "<p>I'll just be short and blunt because I'm on a mobile phone:</p>\n\n<p>Your JS solution is not reusable and quite naive. Consider for instance a user tabbing into your input. </p>\n\n<p>Please just use the HTML placeholder attribute, it is meant for that.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2015-12-27T01:55:54.900", "Id": "115150", "ParentId": "30832", "Score": "0" } } ]
{ "AcceptedAnswerId": "30834", "CommentCount": "1", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-09-05T16:53:05.297", "Id": "30832", "Score": "2", "Tags": [ "javascript", "html", "form", "event-handling" ], "Title": "Placeholder text for HTML search field" }
30832
<p>I am trying to implement strings tokenizer in Excel via UDF using C# and Excel-Dna. Personally I found the mIRC's function <a href="http://www.mirchelp.net/helpfile/token_identifiers.htm" rel="nofollow"><code>$gettok</code></a> pretty useful due to the lack of string functions in Excel.</p> <p><strong>Examples</strong></p> <pre><code>getTok("Aquel que no espera vencer ya esta vencido", 1, 32) -&gt; "Aquel" getTok("Aquel que no espera vencer ya esta vencido", -1, 32) -&gt; "vencido" getTok("Aquel que no espera vencer ya esta vencido", 2-4, 32) -&gt; "que no espera" getTok("Aquel que no espera vencer ya esta vencido", 0, 32) -&gt; "Aquel que no espera vencer ya esta vencido" </code></pre> <p><strong>Code</strong></p> <pre><code>[ExcelFunction(Category="String Utilities", Name = "getTok")] public static string getTok(string text, string token, int delimiter) { int from = 0; int to = 0; string tokenPatter = @"(\d+)(-)(\d+)?"; string[] tokens = text.Split(new char[] { (char)delimiter }); Regex tokenRegex = new Regex(tokenPatter, RegexOptions.IgnoreCase); Match tokenMatch = tokenRegex.Match(token); if (tokenMatch.Success) { StringBuilder sb = new StringBuilder(); from = short.Parse(tokenMatch.Groups[0].Value); if (tokenMatch.Groups.Count == 1) to = from; else if (tokenMatch.Groups.Count == 2) to = (short)tokens.Length; else to = short.Parse(tokenMatch.Groups[2].Value); for (int i = from; i &lt;= to; i++) { sb.Append(tokens[i - 1] + ((char)delimiter)); } return sb.ToString(); } int index = int.Parse(token); if (index &gt; 0) return tokens[index - 1]; else return tokens[tokens.Length + index]; } </code></pre> <p><strong>Questions</strong></p> <ul> <li>What would you improve on?</li> <li>Have you tried something similar with Excel?</li> </ul>
[]
[ { "body": "<p>In this statement:</p>\n\n<pre><code>for (int i = from; i &lt;= to; i++)\n {\n sb.Append(tokens[i - 1] + ((char)delimiter));\n }\n</code></pre>\n\n<p>The way that you have it written, I don't think that <code>i</code> will ever hit <code>to</code>.</p>\n\n<p>Also, I would change some variable names to make it more readable. <code>from</code> and <code>to</code> got confusing, I had to keep telling myself that those are variables. I recommend doing something like:</p>\n\n<pre><code>int intFrom;\nint intTo;\n</code></pre>\n\n<p>at the very least, so that you automatically know that those are integer variables. </p>\n\n<p>Also you have an <code>int</code> for a delimiter? Why not just pass a <code>char</code> as a delimiter?</p>\n\n<p>Other than that I think the code looks good.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-09-05T23:52:03.037", "Id": "49093", "Score": "1", "body": "+1 for renaming the variables; I think `from` cause issues if you're `using System.Linq`?" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-09-06T01:17:17.727", "Id": "49101", "Score": "1", "body": "@retailcoder I believe a variable called `from` won't cause any issues, unless you try to use it in an LINQ expression." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-09-06T02:38:28.150", "Id": "49103", "Score": "6", "body": "I don't think prefixing `from` and `to` with the types make very good variable names. If you're going to be more verbose, you might as well use names like `fromIndex` and `toIndex`." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-09-06T13:53:28.803", "Id": "49139", "Score": "0", "body": "it was more of an `at least prefix the variables` type of thing, not `this is the best practice` type of thing." } ], "meta_data": { "CommentCount": "4", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-09-05T20:51:20.393", "Id": "30841", "ParentId": "30837", "Score": "6" } }, { "body": "<p>First off, <code>getTok</code> should be <code>GetToken</code> or <code>Tokens</code>. Don't overly abbreviate things, this goes doubly for any public API. However, even the verbose forms of those aren't good names. This function doesn't really tokenize things, or return tokens. </p>\n\n<p>From the point of view of an Excel user, it seems to just be an odd way of getting a substring and it's not obvious how I'm supposed to call your function or what it should return to me. </p>\n\n<p>I recommend putting more thought into your public API and utilizing the <code>[ExcelArgument]</code> attribute to better document it. </p>\n\n<p>As a quick aside, I found this nifty looking tool that generates actual documents from ExcelDna attributes. \nYou may find it of interest. </p>\n\n<p><a href=\"http://mndrake.github.io/ExcelDnaDoc/index.html\" rel=\"nofollow\">http://mndrake.github.io/ExcelDnaDoc/index.html</a></p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2016-05-14T13:05:50.147", "Id": "128353", "ParentId": "30837", "Score": "1" } } ]
{ "AcceptedAnswerId": "30841", "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-09-05T19:48:04.490", "Id": "30837", "Score": "7", "Tags": [ "c#", ".net", "excel" ], "Title": "String tokenizer via UDF" }
30837
<h2>The Problem</h2> <p>As an ASP.NET MVC4 developper, I'm using Entity Framework a lot. Considering performance I often use lazy loading for my models.</p> <pre><code>public class Result { public int Id { get; set; } public decimal Grade { get; set; } public virtual Skill Skill { get; set; } public int SkillId { get; set; } public virtual Player Player { get; set; } public int PlayerId { get; set; } public virtual Category { get; set; } public int CategoryId { get; set; } } </code></pre> <p>If I want to include all navigation models I'll have to include all those models.</p> <pre><code>public ActionResult Details(int id = 0) { Result result = db.Results .Include(r =&gt; r.Skill) .Include(r =&gt; r.Player) .Include(r =&gt; r.Category) .SingleOrDefault(r =&gt; r.Id == id); //some viewmodel mapping return View(viewmodel); } </code></pre> <h2>My solution</h2> <p>I built an extension method to remove this from my controller code.</p> <pre><code>public static class IncludeExtensions { public static IQueryable&lt;Result&gt; IncludeAll(this IQueryable&lt;Result&gt; results) { return results.Include(r =&gt; r.Skill) .Include(r =&gt; r.Player) .Include(r =&gt; r.Category); } public static Result IncludedFind(this IQueryable&lt;Result&gt; results, int id) { return results.IncludeAll().SingleOrDefault(r =&gt; r.Id == id); } } public ActionResult Details(int id = 0) { Result result = db.Results.IncludedFind(id); //some viewmodel mapping return View(viewmodel); } </code></pre> <p>There are a few problems with this:</p> <ol> <li>I can't create an abstract extension class to force <code>IncludeAll()</code> and <code>IncludedFind()</code> method.</li> <li>I still have to update the extension method if my models change.</li> <li>I'll have a proliferation of extension methods/classes.</li> <li>Isn't there an <code>IncludeAll()</code> like method available for Entity Framework? <ul> <li>Is there something like this on <a href="http://www.nuget.org/">NuGet</a>?</li> </ul></li> <li>It just feels wrong...</li> </ol>
[ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-09-05T20:42:16.627", "Id": "49072", "Score": "0", "body": "Could you perhaps use AutoMapper or some other existing mapping service to do what you are wanting? I haven't used AutoMapper but sounds like what you might be looking for." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-09-05T20:45:26.243", "Id": "49074", "Score": "0", "body": "Automapper maps models to viewmodels. I don't think it helps loading entities from the database." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-09-06T01:38:51.840", "Id": "49102", "Score": "1", "body": "It doesn't map models to view models. It maps anything to anything from what understand. Just happens that that is a common usage for VM => M and vice versa. But if you have considered and discarded it then no worries." } ]
[ { "body": "<p>A simple option would be to use reflection to check for properties that are virtual and has the Id-suffix. This is where I came up with, working for me;</p>\n\n<pre><code>public static IQueryable&lt;T&gt; IncludeAll&lt;T&gt;(this IQueryable&lt;T&gt; queryable) where T : class\n{\n var type = typeof (T);\n var properties = type.GetProperties();\n foreach (var property in properties)\n {\n var isVirtual = property.GetGetMethod().IsVirtual;\n if (isVirtual &amp;&amp; properties.FirstOrDefault(c =&gt; c.Name == property.Name + \"Id\") != null)\n {\n queryable = queryable.Include(property.Name);\n }\n }\n return queryable;\n}\n</code></pre>\n\n<p>I hope this answers your question.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-09-06T12:01:56.590", "Id": "49127", "Score": "0", "body": "This would solve my problem, but isn't reflection something you should avoid? As far as I know it's bad for performance and therefore it's condemned by many programmers. I would like to hear your opinion @martijnlentink!" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-09-06T13:45:41.417", "Id": "49138", "Score": "3", "body": "Reflection does affect performance, but to be honest I don't think you'll ever experience any issues. Try googling for 'Reflection bad' or 'slow', you will find that most peeps agree that reflection isn't that bad after all. It's just too powerful not to use imho." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-05-03T01:33:00.933", "Id": "371917", "Score": "0", "body": "What about the children of children?" } ], "meta_data": { "CommentCount": "3", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-09-06T08:19:27.607", "Id": "30867", "ParentId": "30839", "Score": "11" } }, { "body": "<p>Include uses when you want to include <code>ICollection</code> properties or <strong>not</strong> <code>int</code>, <code>string</code>, <code>bool</code>, etc. types. I use this in my base repository that precedes all my entities.</p>\n\n<pre><code>public IQueryable&lt;T&gt; GetIncludes(IQueryable&lt;T&gt; Queryable)\n{\n var normal_types = new List&lt;Type&gt;() {\n typeof(int),\n typeof(string),\n typeof(bool)\n };\n\n var ty = typeof(T);\n\n foreach (var item in ty.GetProperties())\n {\n if (!normal_types.Contains(item.GetType()))\n {\n Queryable.Include(item.Name);\n }\n }\n\n return Queryable;\n}\n\npublic IQueryable&lt;T&gt; GetIncludes(DbSet&lt;T&gt; Queryable)\n{\n return GetIncludes(Queryable.AsQueryable());\n}\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-05-06T23:58:09.313", "Id": "424672", "Score": "0", "body": "Welcome to Code Review, could you rephrase your introduction a bit to make it clearer? Right now the code itself is a better explanation to me than the text. I've also taken the liberty and fixed a few typos, I could only guess at one of the words though, please take a look if I got it wrong. Enjoy your stay!" } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-05-06T10:04:18.120", "Id": "219801", "ParentId": "30839", "Score": "2" } }, { "body": "<p>EF knows about all navigation properties. So, instead of using reflection and try to figure it out by myself, I can just ask the <code>DbContext</code> about navigation properties.</p>\n\n<p><a href=\"https://stackoverflow.com/a/49597502/331281\">Here</a>'s a wonderful SO answer that does exactly that.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-04-07T15:45:42.507", "Id": "240105", "ParentId": "30839", "Score": "1" } } ]
{ "AcceptedAnswerId": "30867", "CommentCount": "3", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-09-05T20:36:33.053", "Id": "30839", "Score": "11", "Tags": [ "c#", "entity-framework", "asp.net-mvc-4" ], "Title": "DbSet<T> IncludeAll method" }
30839
<p>We are starting a new web project using C# / MVC4 and Entity Framework 5 for data access. I've decided to go with an n-layered approach for the structure of the project and I would like some feedback on my design decisions.</p> <p>This is how the solution is structured:</p> <ul> <li>Project.Model (Class Library): Contains EF .edmx, entity models, and viewmodels</li> <li>Project.DAL (Class Library): Contains EF DbContext and Repository classes</li> <li>Project.BLL (Class Library): Contains business logic classes</li> <li>Project (MVC Project)</li> </ul> <p><strong>DAL</strong></p> <p>The Data Access Layer is only concerned with simple CRUD like operations. I've decided to go with a repository approach. Here are the Repository interfaces:</p> <pre><code>public interface IRepository { } public interface IRepository&lt;T&gt; : IRepository, IDisposable where T : class, new() { T Add(T item); T Get(object id); T Get(Expression&lt;Func&lt;T, bool&gt;&gt; predicate); IQueryable&lt;T&gt; GetAll(); IQueryable&lt;T&gt; GetAll(Expression&lt;Func&lt;T, bool&gt;&gt; predicate); void Update(T item); void Delete(T item); } </code></pre> <p>After doing some research on using Entity Framework in web projects, the general consensus is that there should only be one <code>DbContext</code>/<code>ObjectContext</code> per request. So to create and dispose the single context for each request, I've written an <code>HttpModule</code> that injects the <code>DbContext</code> into the <code>HttpContext</code>.</p> <pre><code>public class DbContextModule : IHttpModule { public void Init(HttpApplication context) { context.BeginRequest += context_BeginRequest; context.EndRequest += context_EndRequest; } public void Dispose() { } private void context_BeginRequest(object sender, EventArgs e) { HttpApplication application = (HttpApplication)sender; HttpContext httpContext = application.Context; httpContext.Items.Add(Repository.ContextKey, new ProjectEntities()); } private void context_EndRequest(object sender, EventArgs e) { HttpApplication application = (HttpApplication)sender; HttpContext httpContext = application.Context; var entities = (ProjectEntities)httpContext.Items[Repository.ContextKey]; entities.Dispose(); entities = null; application.Context.Items.Remove(Repository.ContextKey); } } </code></pre> <p>Next is the <code>Repository</code> base class. Note that the constructor utilizes the injected DbContext from the <code>HttpModule</code> above.</p> <pre><code>public abstract class Repository&lt;T&gt; : IRepository&lt;T&gt; where T : class, new() { protected Repository() { if (HttpContext.Current == null) { throw new Exception("Cannot create repository - current HttpContext is null."); } _entities = (ProjectEntities)HttpContext.Current.Items[Repository.ContextKey]; if (_entities == null) { throw new Exception("Cannot create repository - no DBContext in the current HttpContext."); } } private ProjectEntities _entities; public T Add(T item) { _entities.Set&lt;T&gt;().Add(item); _entities.SaveChanges(); return item; } public T Get(object id) { return _entities.Set&lt;T&gt;().Find(id); } public T Get(Expression&lt;Func&lt;T, bool&gt;&gt; predicate) { return _entities.Set&lt;T&gt;().AsQueryable().FirstOrDefault(predicate); } public IQueryable&lt;T&gt; GetAll() { return _entities.Set&lt;T&gt;().AsQueryable(); } public IQueryable&lt;T&gt; GetAll(Expression&lt;Func&lt;T, bool&gt;&gt; predicate) { return _entities.Set&lt;T&gt;().AsQueryable().Where(predicate); } public void Update(T item) { _entities.Entry(item).State = EntityState.Modified; _entities.SaveChanges(); } public void Delete(T item) { _entities.Set&lt;T&gt;().Remove(item); _entities.SaveChanges(); } } </code></pre> <p>And a simple example of an implementation:</p> <pre><code>public class AdminRepository : Repository&lt;Admin&gt; { public Admin GetByEmail(string email) { return Get(x =&gt; x.Email == email); } } </code></pre> <p><strong>BLL</strong></p> <p>The Business Logic Layer encapsulates all business logic. To keep constraints, I've written the base <code>Logic</code> class like this:</p> <pre><code>public abstract class Logic&lt;TRepository&gt; where TRepository : class, IRepository, new() { private static Expression&lt;Func&lt;TRepository&gt;&gt; _x = () =&gt; new TRepository(); private static Func&lt;TRepository&gt; _compiled = _x.Compile(); protected Logic() { Repository = _compiled(); } protected internal TRepository Repository { get; private set; } } </code></pre> <p>The constructor automatically creates the needed <code>Repository</code> class, so no additional code is needed in child classes to instantiate the repository. Here is a simple example of an implementation:</p> <pre><code>public class AdminLogic : Logic&lt;AdminRepository&gt; { public ADMIN Add(ADMIN admin) { return Repository.Add(admin); } public ADMIN Get(object id) { return Repository.Get(id); } public ADMIN GetByEmail(string email) { return Repository.GetByEmail(email); } public IQueryable&lt;ADMIN&gt; GetAll() { return Repository.GetAll(); } public void Update(ADMIN admin) { Repository.Update(admin); } } </code></pre> <p>This example is more of a pass-through for the DAL repository, but adding a business logic layer won't be a problem. I'm choosing to return <code>IQueryable&lt;T&gt;</code> from the BLL because we are using some third party tools that require an <code>IQueryable&lt;T&gt;</code> for deferred execution.</p> <p><strong>Project (MVC Project)</strong></p> <p>Finally, here is what a simple controller action will look like:</p> <pre><code> public ActionResult Index(int? page) { // Instantiate logic object AdminLogic logic = new AdminLogic(); // Call GetAll() and use AutoMapper to project the results to the viewmodel IQueryable&lt;AdminModel&gt; admins = logic.GetAll().Project().To&lt;AdminModel&gt;(); // Paging (using PagedList https://github.com/TroyGoode/PagedList) IPagedList&lt;AdminModel&gt; paged = admins.ToPagedList(page ?? 1, 25); return View(paged); } </code></pre> <p>Everything works as expected, and tests show that the EF context is properly disposed and the overall speed is good.</p> <p>Is this a pretty good way to go about this? </p>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-08-28T11:19:02.193", "Id": "390518", "Score": "0", "body": "Related post - [ASP.NET MVC (Domain Model, Repository, Fluent, Services - Structure for my Project)](https://stackoverflow.com/q/1349640/465053) & [Best Structure for ASP.NET MVC Solution](https://stackoverflow.com/q/16455870/465053)" } ]
[ { "body": "<p>It looks like you have dependencies hard coded into each layer.</p>\n\n<p>Service layer:\nHow do you plan to inject a mocked repository into your Logic Layer when unit testing it?\nWouldn't it make sense to inject these dependencies in via the constructor into your services once you've registered them in your dependency injection container?</p>\n\n<pre><code>public class AdminLogic \n {\n private readonly IRepository&lt;User&gt; _userRepository;\n\n public AdminLogic(IRepository&lt;User&gt; userRepository)\n {\n _userRepository = userRepository;\n }\n\n public User GetByEmail(string email)\n {\n return _userRepository.GetByEmail(email);\n }\n }\n</code></pre>\n\n<p>Another issue is that sometimes a service class will need to consume many repositories in order to do its work..Not sure how you intend to handle those scenarios given that they appear to only use a single repo. </p>\n\n<p>Presentation layer:\nSame again, inject the dependancy on the admin service and register it in your container and have your controller factory build your controllers for you.</p>\n\n<pre><code> public class AdminController : Controller\n{\n private readonly IAdminLogic _adminLogic;\n\n public AdminController(IAdminLogic adminLogic)\n {\n _adminLogic = adminLogic;\n }\n\n public ActionResult Index(int? page)\n {\n // Call GetAll() and use AutoMapper to project the results to the viewmodel\n IQueryable&lt;AdminModel&gt; admins = _adminLogic.GetAll().Project().To&lt;AdminModel&gt;();\n\n // Paging (using PagedList https://github.com/TroyGoode/PagedList)\n IPagedList&lt;AdminModel&gt; paged = admins.ToPagedList(page ?? 1, 25);\n\n return View(paged);\n }\n\n}\n</code></pre>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-10-04T06:02:46.397", "Id": "32222", "ParentId": "30843", "Score": "2" } }, { "body": "<p>Have a look on the <a href=\"http://jeffreypalermo.com/blog/onion-architecture-part-4-after-four-years/\">Onion Architecture</a> series by Jeffrey Palermo</p>\n\n<p>How about this for a structure </p>\n\n<ul>\n<li><p>Project.Domain (Class Library)</p>\n\n<ul>\n<li>has no deppendencies on any other projects</li>\n<li>represents the core business of your app/service</li>\n<li>any external dependecies are abstracted away via DI (adapter pattern)</li>\n<li>you might want to define an IDataContext/ISession that abstracts away the storage mechanism for example</li>\n<li>contains both your entities and your business logic</li>\n</ul></li>\n<li><p>Project.Reports (Class Library)</p>\n\n<ul>\n<li>references Project.Domain</li>\n<li>contains view models or projections or however you want to call them</li>\n<li>these models are crafted to serve the views in the UI</li>\n<li>i prefer to keep it separate from domain as ui requirements tend to change a lot more often then my core business</li>\n<li>you might want to have distinct dedicated view models for different platforms</li>\n</ul></li>\n<li><p>Project.Data.Sql (Class Library)</p>\n\n<ul>\n<li>references Project.Domain</li>\n<li>contains EF DbContext, mappings, migrations</li>\n<li>the dbcontext implements the IDataContext/ISession defined in the domain</li>\n<li>do you really need repositories? <a href=\"http://ayende.com/blog/3955/repository-is-the-new-singleton\">Repository is the new singleton</a> </li>\n<li>how about relying on the fact that the dbcontext already implements the unit of work and the repository patterns out of the box</li>\n</ul></li>\n<li><p>Project.Service (Optional)</p>\n\n<ul>\n<li>web api or wcf would fit in here</li>\n<li>wires everything via a dependency injection container</li>\n</ul></li>\n<li><p>Project.UI.Web (MVC Project)</p>\n\n<ul>\n<li>wires what it needs via a dependency injection container</li>\n</ul></li>\n</ul>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-05-20T08:30:15.630", "Id": "88359", "Score": "0", "body": "I like how you structured the project. Can you provide more details or articles?" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2016-09-13T13:42:02.513", "Id": "264623", "Score": "0", "body": "We have just released an application for a customer mostly using this guideline. However we've just faced a dilema : We need som kind of variable scope per request and the HttpCurrent is not an option in this kind of architecture when we are in Domain. I curious if you have any solution for this need ?" } ], "meta_data": { "CommentCount": "2", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-10-04T08:03:24.270", "Id": "32230", "ParentId": "30843", "Score": "17" } }, { "body": "<p>I think you have a number of problems with this design.</p>\n\n<p>1: Generic DAL and Repository classes. In my view this is a big mistake. you are guaranteed to need some GetModelsBySpecialCriteria Method at some point which will force you to jump through hoops trying to define it in your generic way. The reason for the repository is to hide all the stuff you have to do to get the data away from the calling class. Not to provide a query language for calling classes.</p>\n\n<p>2: Generic BLL classes. It looks like you are just repeating the DAL layer? what if your logic requires multiple repositories?</p>\n\n<p>Somewhere in your project you will have actual requirements to implement. these will be effectively random and open to constant change. You dont help yourself by creating an extra generic framework to cram them all into.</p>\n\n<p>How To do it right: (short version)</p>\n\n<p>You already have EF (although i hate it) this provides your generic query DB DAL layer. hide it behind a repository! calling classes should not have to construct queries.</p>\n\n<p>Models : Should have no external dependencies.</p>\n\n<p>Business logic : two choices. OOP - hide it in Model methods, ADM - put it in services, keep models as data structs.</p>\n\n<p>Website : Instantiate Repositories, Get models, call services, display result</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2015-05-10T10:25:44.673", "Id": "90297", "ParentId": "30843", "Score": "0" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "1", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-09-05T20:52:45.087", "Id": "30843", "Score": "20", "Tags": [ "c#", "design-patterns", "entity-framework", "asp.net-mvc-4" ], "Title": "MVC Layered Project Structure" }
30843
<p>I am very new to Scala. I have done an exercise using Scala to solve the maximum path problem. </p> <p>Basically, I have a triangle of integers, I want to find the path from the top to bottom which the numbers on the route produces the largest sum. For example:</p> <pre><code> 5 12 3 2 4 9 1 9 12 7 </code></pre> <p>Should return:</p> <pre><code>5 -&gt; 12 -&gt; 4 -&gt; 12 Sum = 33 </code></pre> <p>Could someone please help review the code and make some suggestions about:</p> <ol> <li>Better algorithm</li> <li>Writing better scala code</li> </ol> <p>Here is the code:</p> <pre><code>import scala._ class MaxPath { def sumTree(input : List[List[Int]], tempResult : List[List[Int]], currentlevel : Int) : List[List[Int]] = { if(currentlevel == input.size) return tempResult val updatedRow : List[Int] = currentlevel match { case 0 =&gt; input(currentlevel) case _ =&gt; { val lastRow = tempResult(currentlevel - 1) val currentRow = input(currentlevel) val newHead = currentRow.head + lastRow.head val newLast = currentRow.last + lastRow.last val middleSection = currentRow.drop(1).dropRight(1) val newMiddle : List[Int] = for { (value, index) &lt;- middleSection.zipWithIndex middle = value + Math.max(lastRow(index), lastRow(index + 1)) } yield middle newHead::newMiddle:::List(newLast) } } sumTree(input, tempResult:::List(updatedRow), currentlevel + 1) } def traceBack(input : List[List[Int]], transformed : List[List[Int]], index : Int, currentLevel : Int) : List[Int] = { if(currentLevel == input.size) return Nil val row = input(currentLevel) val rowTransformed = transformed(currentLevel) val max = index match { case -1 =&gt; { val maxIndex = rowTransformed.zipWithIndex.maxBy(_._1)._2 (row(maxIndex), maxIndex) } case x =&gt; { val rowSize = row.size x match { case 0 =&gt; (row.head, 0) case `rowSize` =&gt; (row.last, 0) case _ =&gt; { val maxIndex = List(rowTransformed(index-1), rowTransformed(index)).zip(List(index - 1, index)).maxBy(_._1)._2 (row(maxIndex), maxIndex) } } } } traceBack(input, transformed, max._2, currentLevel + 1) ::: List(max._1) } def calcualte(input : List[List[Int]]) : (List[Int], Int) = { val transformed = sumTree(input, Nil, 0) val path = traceBack(input.reverse, transformed.reverse, -1, 0) (path, path.sum) } } object MaxPath { val input : List[List[Int]] = List( List(5), List(12, 3), List(2, 4, 9), List(1, 9, 12, 7) ) def main(args : Array[String]) = { val mp = new MaxPath val result = mp.calcualte(input) println(result._1.mkString(" -&gt; ")) println("Sum = " + result._2) } } </code></pre>
[ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-09-07T06:57:35.713", "Id": "49228", "Score": "0", "body": "I also used a similar approach to the one above, but added dynamic programming to speed up the algorithm so that you can use it to solve Problem 67 where the data set is pretty large. I have a [video](http://youtu.be/R9sIqhANsio) where I live code and explain the solution. You can see the final solution on [github](https://github.com/shadaj/euler/blob/master/src/euler/Euler18-67.scala)." } ]
[ { "body": "<p>In terms of algorithm, I think it is best to focus on the answer you are after. In This case you want the sum, but I notice your result returns the path and the sum.</p>\n\n<p>If you want to focus on the sum think about starting from the bottom, and accessing the best path in terms of the bottom two rows and merging the results up.</p>\n\n<p>Here is an example:</p>\n\n<pre><code>5\n12, 3\n2, 4, 9\n1, 9, 12, 7\n</code></pre>\n\n<p>merge last 2 lines (lines 3 and 4)</p>\n\n<pre><code>2 + 9, 4 + 12, 9 + 12\n</code></pre>\n\n<p>merge the next line (line 2 and the merged result of 3 and 4)</p>\n\n<pre><code>12 + (4 + 12), 3 + (9 + 12)\n</code></pre>\n\n<p>merge the fist line (line 1 and the merged result of the 2, 3, and 4)</p>\n\n<pre><code>5 + (12 + (4 + 12))\n</code></pre>\n\n<p>some specific observations about your code</p>\n\n<ul>\n<li>If you are going to access an element by index, use an indexed collection like Vector</li>\n<li>Consider using fold or reduce instead of recursion with an accumulator</li>\n<li>Props for using immutable variables and data structures </li>\n</ul>\n\n<p>here is a link to my solution to the problem:\n<a href=\"https://gist.github.com/dholbrook/6244448#file-euler18-scala\" rel=\"nofollow\">https://gist.github.com/dholbrook/6244448#file-euler18-scala</a></p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-09-06T15:44:28.880", "Id": "30883", "ParentId": "30845", "Score": "2" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "1", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-09-05T22:00:15.293", "Id": "30845", "Score": "6", "Tags": [ "scala" ], "Title": "Maximum path problem using Scala" }
30845
<p>My goal was to get the following code to work:</p> <pre><code>#include&lt;iostream&gt; #include&lt;vector&gt; #include&lt;list&gt; #include&lt;algorithm&gt; #include&lt;array&gt; #include"functional.hpp" int main( ) { std::vector&lt;double&gt; a{1.0, 2.0, 3.0, 4.0}; std::list&lt;char&gt; b; b.push_back('a'); b.push_back('b'); b.push_back('c'); b.push_back('d'); std::array&lt;int,5&gt; c{5,4,3,2,1}; auto d = zip(a, b, c); for (auto i : zip(a, b, c) ) { std::cout &lt;&lt; std::get&lt;0&gt;(i) &lt;&lt; ", " &lt;&lt; std::get&lt;1&gt;(i) &lt;&lt; ", " &lt;&lt; std::get&lt;2&gt;(i) &lt;&lt; std::endl; } for (auto i : d) { std::cout &lt;&lt; std::get&lt;0&gt;(i) &lt;&lt; ", " &lt;&lt; std::get&lt;1&gt;(i) &lt;&lt; ", " &lt;&lt; std::get&lt;2&gt;(i) &lt;&lt; std::endl; std::get&lt;0&gt;(i) = 5.0; //std::cout &lt;&lt; i1 &lt;&lt; ", " &lt;&lt; i2 &lt;&lt; ", " &lt;&lt; i3 &lt;&lt; std::endl; } for (auto i : d) { std::cout &lt;&lt; std::get&lt;0&gt;(i) &lt;&lt; ", " &lt;&lt; std::get&lt;1&gt;(i) &lt;&lt; ", " &lt;&lt; std::get&lt;2&gt;(i) &lt;&lt; std::endl; //std::cout &lt;&lt; i1 &lt;&lt; ", " &lt;&lt; i2 &lt;&lt; ", " &lt;&lt; i3 &lt;&lt; std::endl; } } </code></pre> <p><strong>With the output:</strong></p> <pre><code>1, a, 5 2, b, 4 3, c, 3 4, d, 2 5, a, 5 5, b, 4 5, c, 3 5, d, 2 </code></pre> <p><strong>The source for "functional.hpp" is:</strong></p> <pre><code>#pragma once #include&lt;tuple&gt; #include&lt;iterator&gt; #include&lt;utility&gt; /*************************** // helper for tuple_subset and tuple_tail (from http://stackoverflow.com/questions/8569567/get-part-of-stdtuple) ***************************/ template &lt;size_t... n&gt; struct ct_integers_list { template &lt;size_t m&gt; struct push_back { typedef ct_integers_list&lt;n..., m&gt; type; }; }; template &lt;size_t max&gt; struct ct_iota_1 { typedef typename ct_iota_1&lt;max-1&gt;::type::template push_back&lt;max&gt;::type type; }; template &lt;&gt; struct ct_iota_1&lt;0&gt; { typedef ct_integers_list&lt;&gt; type; }; /*************************** // return a subset of a tuple ***************************/ template &lt;size_t... indices, typename Tuple&gt; auto tuple_subset(const Tuple&amp; tpl, ct_integers_list&lt;indices...&gt;) -&gt; decltype(std::make_tuple(std::get&lt;indices&gt;(tpl)...)) { return std::make_tuple(std::get&lt;indices&gt;(tpl)...); // this means: // make_tuple(get&lt;indices[0]&gt;(tpl), get&lt;indices[1]&gt;(tpl), ...) } /*************************** // return the tail of a tuple ***************************/ template &lt;typename Head, typename... Tail&gt; inline std::tuple&lt;Tail...&gt; tuple_tail(const std::tuple&lt;Head, Tail...&gt;&amp; tpl) { return tuple_subset(tpl, typename ct_iota_1&lt;sizeof...(Tail)&gt;::type()); // this means: // tuple_subset&lt;1, 2, 3, ..., sizeof...(Tail)-1&gt;(tpl, ..) } /*************************** // increment every element in a tuple (that is referenced) ***************************/ template&lt;std::size_t I = 0, typename... Tp&gt; inline typename std::enable_if&lt;I == sizeof...(Tp), void&gt;::type increment(std::tuple&lt;Tp...&gt;&amp; t) { } template&lt;std::size_t I = 0, typename... Tp&gt; inline typename std::enable_if&lt;(I &lt; sizeof...(Tp)), void&gt;::type increment(std::tuple&lt;Tp...&gt;&amp; t) { std::get&lt;I&gt;(t)++ ; increment&lt;I + 1, Tp...&gt;(t); } /**************************** // check equality of a tuple ****************************/ template&lt;typename T1&gt; inline bool not_equal_tuples( const std::tuple&lt;T1&gt;&amp; t1, const std::tuple&lt;T1&gt;&amp; t2 ) { return (std::get&lt;0&gt;(t1) != std::get&lt;0&gt;(t2)); } template&lt;typename T1, typename... Ts&gt; inline bool not_equal_tuples( const std::tuple&lt;T1, Ts...&gt;&amp; t1, const std::tuple&lt;T1, Ts...&gt;&amp; t2 ) { return (std::get&lt;0&gt;(t1) != std::get&lt;0&gt;(t2)) &amp;&amp; not_equal_tuples( tuple_tail(t1), tuple_tail(t2) ); } /**************************** // dereference a subset of elements of a tuple (dereferencing the iterators) ****************************/ template &lt;size_t... indices, typename Tuple&gt; auto dereference_subset(const Tuple&amp; tpl, ct_integers_list&lt;indices...&gt;) -&gt; decltype(std::tie(*std::get&lt;indices-1&gt;(tpl)...)) { return std::tie(*std::get&lt;indices-1&gt;(tpl)...); } /**************************** // dereference every element of a tuple (applying operator* to each element, and returning the tuple) ****************************/ template&lt;typename... Ts&gt; inline auto dereference_tuple(std::tuple&lt;Ts...&gt;&amp; t1) -&gt; decltype( dereference_subset( std::tuple&lt;Ts...&gt;(), typename ct_iota_1&lt;sizeof...(Ts)&gt;::type())) { return dereference_subset( t1, typename ct_iota_1&lt;sizeof...(Ts)&gt;::type()); } template&lt; typename T1, typename... Ts &gt; class zipper { public: class iterator : std::iterator&lt;std::forward_iterator_tag, std::tuple&lt;typename T1::value_type, typename Ts::value_type...&gt; &gt; { protected: std::tuple&lt;typename T1::iterator, typename Ts::iterator...&gt; current; public: explicit iterator( typename T1::iterator s1, typename Ts::iterator... s2 ) : current(s1, s2...) {}; iterator( const iterator&amp; rhs ) : current(rhs.current) {}; iterator&amp; operator++() { increment(current); return *this; } iterator operator++(int) { auto a = *this; increment(current); return a; } bool operator!=( const iterator&amp; rhs ) { return not_equal_tuples(current, rhs.current); } typename iterator::value_type operator*() { return dereference_tuple(current); } }; explicit zipper( T1&amp; a, Ts&amp;... b): begin_( a.begin(), (b.begin())...), end_( a.end(), (b.end())...) {}; zipper(const zipper&lt;T1, Ts...&gt;&amp; a) : begin_( a.begin_ ), end_( a.end_ ) {}; template&lt;typename U1, typename... Us&gt; zipper&lt;U1, Us...&gt;&amp; operator=( zipper&lt;U1, Us...&gt;&amp; rhs) { begin_ = rhs.begin_; end_ = rhs.end_; return *this; } zipper&lt;T1, Ts...&gt;::iterator&amp; begin() { return begin_; } zipper&lt;T1, Ts...&gt;::iterator&amp; end() { return end_; } zipper&lt;T1, Ts...&gt;::iterator begin_; zipper&lt;T1, Ts...&gt;::iterator end_; }; //from cppreference.com: template &lt;class T&gt; struct special_decay { using type = typename std::decay&lt;T&gt;::type; }; //allows the use of references: template &lt;class T&gt; struct special_decay&lt;std::reference_wrapper&lt;T&gt;&gt; { using type = T&amp;; }; template &lt;class T&gt; using special_decay_t = typename special_decay&lt;T&gt;::type; //allows template type deduction for zipper: template &lt;class... Types&gt; zipper&lt;special_decay_t&lt;Types&gt;...&gt; zip(Types&amp;&amp;... args) { return zipper&lt;special_decay_t&lt;Types&gt;...&gt;(std::forward&lt;Types&gt;(args)...); } </code></pre> <p>I'm asking for a few things: </p> <ul> <li><p><strong>References and performance:</strong> Theoretically, the only things that (I believe) should be copied are iterators, but I'm not sure how to confirm this. I'm hoping that this has very little overhead (A couple of pointer dereferences maybe?), but I'm not sure how to check something like this.</p></li> <li><p><strong>Correctness:</strong> Are there any hidden bugs that aren't showing up in my use case? Technically, the code isn't really working as "expected" (it should spit out copies of the values for "<code>auto i</code>", and only allow modification of the original containers values with "<code>auto&amp; i</code>", and there should be a version that allows you to look, but not touch: "<code>const auto&amp; i</code>"), but I'm not sure how to fix that. I expect I need to create a <code>const</code> version for the <code>const auto&amp; i</code> mode, but I'm not sure how to make a copy for the <code>auto i</code> version.</p></li> <li><p><strong>Code Cleanliness, Best practices:</strong> My code is pretty much never read by another human being, so any recommendations of best practices or commenting would be appreciated. I'm also not sure what to do about the move constructors: should I be deleting them, or ignoring them?</p></li> </ul>
[ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2018-02-23T16:21:22.310", "Id": "359370", "Score": "0", "body": "I like the `special_decay` trick." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-09-28T08:23:26.117", "Id": "394422", "Score": "0", "body": "I don't get the purpose of `std::get<0>(i) = 5.0;` line. Was it supposed to modify the tuple? My output for the third loop is still\n\n*1, a, 5 \\n 2, b, 4 \\n 3, c, 3 \\n 4, d, 2*" } ]
[ { "body": "<p>I have not much to say. Your code reads quite good, which is rather pleasant. Here are a few tidbits though:</p>\n\n<h2><code>typedef</code></h2>\n\n<p>If you are willing to write modern code, you should consider dropping <code>typedef</code> and using <code>using</code> everywhere instead. It helps to be consistent between regular alias and alias template. Moreover, the <code>=</code> symbol help to visually split the new name and the type it refers to. And the syntax is also consistent towards the way you can declare variables:</p>\n\n<pre><code>auto i = 1;\nusing some_type = int;\n</code></pre>\n\n<h2>Perfect forwarding</h2>\n\n<p>It's clear that you already used it. But there are some other places where it would make sense to use it:</p>\n\n<pre><code>template &lt;size_t... indices, typename Tuple&gt;\nauto tuple_subset(Tuple&amp;&amp; tpl, ct_integers_list&lt;indices...&gt;)\n -&gt; decltype(std::make_tuple(std::get&lt;indices&gt;(std::forward&lt;Tuple&gt;(tpl))...))\n{\n return std::make_tuple(std::get&lt;indices&gt;(std::forward&lt;Tuple&gt;(tpl))...);\n // this means:\n // make_tuple(get&lt;indices[0]&gt;(tpl), get&lt;indices[1]&gt;(tpl), ...)\n}\n</code></pre>\n\n<h2><code>std::enable_if</code></h2>\n\n<p>While using <code>std::enable_if</code> in the return type of the functions, I find that it tends to make it unreadable. Therefore, you may probably want to move it to the template parameters list instead. Consider your code:</p>\n\n<pre><code>template&lt;std::size_t I = 0, typename... Tp&gt;\ninline typename std::enable_if&lt;(I &lt; sizeof...(Tp)), void&gt;::type\nincrement(std::tuple&lt;Tp...&gt;&amp; t)\n{\n std::get&lt;I&gt;(t)++ ;\n increment&lt;I + 1, Tp...&gt;(t);\n}\n</code></pre>\n\n<p>And compare it to this one:</p>\n\n<pre><code>template&lt;std::size_t I = 0, typename... Tp,\n typename = typename std::enable_if&lt;I &lt; sizeof...(Tp), void&gt;::type&gt;\ninline void increment(std::tuple&lt;Tp...&gt;&amp; t)\n{\n std::get&lt;I&gt;(t)++ ;\n increment&lt;I + 1, Tp...&gt;(t);\n}\n</code></pre>\n\n<h2>Pre-increment vs. post-increment</h2>\n\n<p>Depending on the type, <code>++var</code> may be faster than <code>var++</code>. It does not change anything for <code>int</code> but if your container contains large type, remember that the <code>++</code> in <code>var++</code> is generally defined as:</p>\n\n<pre><code>auto operator++(int)\n -&gt; T&amp;\n{\n auto res = var;\n ++var;\n return res;\n}\n</code></pre>\n\n<p>As you can see, yet another copy of the incremented variable is made and <code>++var</code> is called. Therefore, you may want to use <code>++var</code> instead of <code>var++</code> in a generic context.</p>\n\n<h2>Miscellaneous tidbits</h2>\n\n<pre><code>template&lt;typename U1, typename... Us&gt;\nzipper&lt;U1, Us...&gt;&amp; operator=(zipper&lt;U1, Us...&gt;&amp; rhs) { ... }\n</code></pre>\n\n<p>You may want to pass a <code>const zipper&lt;U1, Us...&gt;&amp;</code> instead of a <code>zipper&lt;U1, Us...&gt;&amp;</code>.</p>\n\n<pre><code>zipper&lt;T1, Ts...&gt;::iterator&amp; begin() {\n return begin_;\n}\n\nzipper&lt;T1, Ts...&gt;::iterator&amp; end() {\n return end_;\n}\n</code></pre>\n\n<p>You may also want to provide the functions <code>begin() const</code>, <code>end() const</code>, <code>cbegin() const</code> and <code>cend() const</code> if you want this set of functions to be complete and consistent towards the STL. Also, some <code>operator==</code> would be great for <code>zipper::iterator</code>.</p>\n\n<p>Also, I like the new function syntax which IMHO helps to separate the function return type and its name, which is especially useful when the said return type is long. However, I read that some people don't like it, so it's up to your own preferences.</p>\n\n<h2>Conclusion</h2>\n\n<p>Generally speaking, your code was good and it works, which is even better. I've provided a few tips, but there are probably many other things that you could do to improve it. It will always be up to you when it concerns the readability though, preferences matter in that domain :)</p>\n\n<p><strong>Edit:</strong> ok, so apparently yout example worked fine, but @Barry's answer seem to highlight more serious problems. You might want to accept it instead.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-11-15T10:46:20.233", "Id": "35429", "ParentId": "30846", "Score": "15" } }, { "body": "<p>Some of your metaprogramming machinery is a bit over-complicated for C++11.</p>\n\n<p>Compare:</p>\n\n<pre><code>template &lt;size_t... n&gt;\nstruct ct_integers_list {\n template &lt;size_t m&gt;\n struct push_back\n {\n typedef ct_integers_list&lt;n..., m&gt; type;\n };\n};\n\ntemplate &lt;size_t max&gt;\nstruct ct_iota_1\n{\n typedef typename ct_iota_1&lt;max-1&gt;::type::template push_back&lt;max&gt;::type type;\n};\n\ntemplate &lt;&gt;\nstruct ct_iota_1&lt;0&gt;\n{\n typedef ct_integers_list&lt;&gt; type;\n};\ntemplate&lt;std::size_t I = 0, typename... Tp&gt;\ninline typename std::enable_if&lt;I == sizeof...(Tp), void&gt;::type\nincrement(std::tuple&lt;Tp...&gt;&amp; t)\n{ }\n\ntemplate&lt;std::size_t I = 0, typename... Tp&gt;\ninline typename std::enable_if&lt;(I &lt; sizeof...(Tp)), void&gt;::type\nincrement(std::tuple&lt;Tp...&gt;&amp; t)\n{\n std::get&lt;I&gt;(t)++ ;\n increment&lt;I + 1, Tp...&gt;(t);\n}\n</code></pre>\n\n<p>Versus:</p>\n\n<pre><code>template&lt;size_t... n&gt; struct ct_integers_list {};\n\ntemplate&lt;size_t... acc&gt; struct ct_iota_1;\ntemplate&lt;size_t max, size_t... acc&gt; struct ct_iota_1 : ct_iota_1&lt;max-1, max-1, acc...&gt; {};\ntemplate&lt;size_t... acc&gt; struct ct_iota_1&lt;0, acc...&gt; : ct_integers_list&lt;acc...&gt; {};\n\ntemplate&lt;size_t... Indices, typename Tuple&gt;\ninline void increment_helper(Tuple&amp; t, ct_integers_list&lt;Indices...&gt;)\n{\n std::initializer_list&lt;int&gt;{\n [&amp;]{ ++std::get&lt;Indices&gt;(t); return 0; }()...\n };\n}\n\ntemplate&lt;typename... Tp&gt;\ninline void increment(std::tuple&lt;Tp...&gt;&amp; t)\n{\n increment_helper(t, ct_iota_1&lt;sizeof...(Tp)&gt;());\n}\n</code></pre>\n\n<p>The idea is to let parameter-pack expansion do for you all the things that in C++03 you had to do via <code>foo&lt;T&gt;::type</code> typedefs and <code>std::enable_if</code> and so on.</p>\n\n<p>Basically, you can replace a lot of recursion with iteration (as in my <code>increment_helper</code>); and for the stuff that has to remain recursion, you can make it look a bit neater and avoid the proliferation of entities (à la Occam's Razor). If you don't need all those intermediate <code>ct_iota_1&lt;...&gt;::type</code> entities, get rid of them!</p>\n\n<p>However, if you want a production-quality <code>ct_integers_list</code>, you should be using C++14's predefined <code>std::integer_sequence</code>, or at least an efficient implementation such as <a href=\"https://stackoverflow.com/a/17426611/1424877\">this one by Xeo</a>. Compilers often limit template recursion to something like 256 levels; both your version and mine will quickly run into this limit, whereas Xeo's will work fine, because its recursion is O(log <code>max</code>) rather than O(<code>max</code>).</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-12-24T01:03:02.340", "Id": "38003", "ParentId": "30846", "Score": "3" } }, { "body": "<p>There are a few serious things that haven't been brought up by the other two answers yet.</p>\n\n<p><strong>Dereferencing issues</strong></p>\n\n<p>Let's say I am zipping a <code>vector&lt;T&gt;</code> and a <code>vector&lt;U&gt;</code>. Your iterator's <code>current</code> member will have type <code>std::tuple&lt;std::vector&lt;T&gt;::iterator, std::vector&lt;U&gt;::iterator&gt;</code> and its <code>value_type</code> will be <code>std::tuple&lt;T, U&gt;</code> and its <code>reference</code> type will be <code>std::tuple&lt;T, U&gt;&amp;</code>. </p>\n\n<p>First of all, the latter makes no sense. There is no <code>std::tuple&lt;T,U&gt;</code> for you to give a <code>reference</code> to, so you should change that particular typedef to refer to <code>value_type</code> (simply provide all the types for <code>std::iterator</code> instead of using defaults).</p>\n\n<p>Secondly, take a look at this:</p>\n\n<pre><code>typename iterator::value_type operator*() {\n return dereference_tuple(current);\n}\n</code></pre>\n\n<p><code>dereference_tuple</code> does the right thing here - it gives you all the references, so the type of that expression is <code>std::tuple&lt;T&amp;, U&amp;&gt;</code>. But that isn't what you're returning! So rather than yielding references, you're yielding values. This means you're <strong>copying every element</strong> on every iteration, and you're not allowing any kind of modification. </p>\n\n<p>But the lack of modification is hidden. Your original example compiles fine:</p>\n\n<pre><code>for (auto i : d) {\n std::get&lt;0&gt;(i) = 5.0;\n}\n</code></pre>\n\n<p>but doesn't actually modify anything in <code>a</code>, which still retains <code>{1.0, 2.0, 3.0, 4.0}</code>. This would be very surprising to your users. You definitely want to make sure that you give back a tuple of <em>references</em>. </p>\n\n<p><strong>Forwarding isn't <em>really</em> supported</strong></p>\n\n<p>Your main function is:</p>\n\n<pre><code>template &lt;class... Types&gt;\nzipper&lt;special_decay_t&lt;Types&gt;...&gt; zip(Types&amp;&amp;... args)\n</code></pre>\n\n<p>but your constructor is:</p>\n\n<pre><code>explicit zipper( T1&amp; a, Ts&amp;... b):\n begin_( a.begin(), (b.begin())...), \n end_( a.end(), (b.end())...) {};\n</code></pre>\n\n<p>You can't call that with rvalues. If I tried to do <code>zip(foo(), bar())</code>, it wouldn't compile. Which is better than not working! But it'd be great if it could in fact be supported.</p>\n\n<p>If you're not going to support it, you should change the signature to make that obvious:</p>\n\n<pre><code>template &lt;class... Cs&gt;\nzipper&lt;special_decay_t&lt;Cs&gt;...&gt; zip(Cs&amp;... containers)\n</code></pre>\n\n<p><strong><code>const</code> <em>definitely</em> isn't supported</strong></p>\n\n<p>Currently, a <code>const</code> container cannot be zipped. Say this example:</p>\n\n<pre><code>std::vector&lt;int&gt; v{1, 2, 3};\nconst std::vector&lt;char&gt; c{'a', 'b', 'c'};\nzip(v, c); // error\n</code></pre>\n\n<p>This will fail to compile, for several reasons. First, you <code>decay</code> the types, so you're constructing a <code>zipper&lt;std::vector&lt;int&gt;, std::vector&lt;char&gt;&gt;</code>, so you can only fail from there - there's no way to ever get the right types. Next, you're using <code>T::iterator</code> when in this case we need <code>const_iterator</code>. And lastly, you're yielding <code>value_type</code>. Firstly, we want to yield <code>reference</code> (see first section), but in this case we need <code>const_reference</code>. So this will all need to be handled. </p>\n\n<p>With C++11, you can use <code>declval</code> to get all of these more directly:</p>\n\n<pre><code>template &lt;typename T&gt;\nusing iter_t = decltype(std::declval&lt;T&amp;&gt;().begin());\n\ntemplate &lt;typename T&gt;\nusing ref_t = decltype(*std::declval&lt;iter_t&lt;T&gt;&gt;());\n</code></pre>\n\n<p>And then <code>current</code> be <code>std::tuple&lt;iter_t&lt;Ts...&gt;&gt;</code> (see later on why I dropped <code>T1</code>), and you can yield <code>std::tuple&lt;ref_t&lt;Ts...&gt;&gt;</code>. </p>\n\n<p><strong>begin() and end() by ref?</strong></p>\n\n<p>This works fine if all you want to do is support iteration in a range-based for expression, but can lead to all sorts of broken code if people start using <code>zipper</code> as a normal container somewhere else. I think it'd be better to return by value. </p>\n\n<p><strong>Default Operations where possible</strong></p>\n\n<p>Your copy constructor does exactly what the default would do, so just make that clear:</p>\n\n<pre><code>zipper(const zipper&amp; rhs) = default;\n</code></pre>\n\n<p>Your assignment operator is misleading. First, it is <em>not</em> the copy assignment operator (that one will be defaulted by the compiler, since the copy assignment operator is never a template). And why do you want to support assignment from arbitrary other zippers anyway? Is that ever going to be viable? Let's just default it:</p>\n\n<pre><code>zipper&amp; operator=(const zipper&amp; rhs) = default;\n</code></pre>\n\n<p><strong>Simplify the template</strong></p>\n\n<p>You have <code>zipper&lt;T1, Ts...&gt;</code>, but <code>T1</code> is never special. You just use it to indicate you can't have <code>zipper&lt;&gt;</code>. But if you just make that a <code>static_assert</code>, you can shorten the rest of your code a lot:</p>\n\n<pre><code>template &lt;class... Ts&gt;\nclass zipper {\n static_assert(sizeof...(Ts) &gt; 0, \"!\");\n\npublic:\n class iterator \n : std::iterator&lt;std::forward_iterator_tag,\n std::tuple&lt;typename Ts::value_type...&gt;\n &gt;\n {\n ...\n };\n\n explicit zipper(Ts&amp;... containers)\n : begin_(containers.begin()...)\n , end_(containers.end()...)\n { }\n\n // etc.\n};\n</code></pre>\n\n<p><strong>Iterator comparison</strong></p>\n\n<p>Your <code>not_equals_tuple</code> makes lots of intermediate objects. This is totally unnecessary. Rather than making a whole new pair of tuples for each element, just chop off the next index:</p>\n\n<pre><code>template &lt;class Tuple&gt;\nbool any_equals(Tuple const&amp;, Tuple const&amp;, std::index_sequence&lt;&gt; ) {\n return false;\n}\n\ntemplate &lt;class Tuple, std::size_t I, std::size_t Is...&gt;\nbool any_equals(Tuple const&amp; lhs, Tuple const&amp; rhs, std::index_sequence&lt;I, Is...&gt; ) {\n\n return std::get&lt;I&gt;(lhs) == std::get&lt;I&gt;(rhs) || // this one\n any_equals(lhs, rhs, std::index_sequence&lt;Is...&gt;{}); // rest of them\n}\n\nbool operator==(iterator const&amp; rhs) {\n return any_equals(current, rhs.current, std::index_sequence_for&lt;Ts...&gt;{});\n}\n\nbool operator!=(iterator const&amp; rhs) { return !(*this == rhs); }\n</code></pre>\n\n<p><strong>The Expander Trick</strong></p>\n\n<p>First of all, <code>ct_integers_list</code> and <code>ct_iota_1</code> is reinventing the wheel. We have <a href=\"http://en.cppreference.com/w/cpp/utility/integer_sequence\"><code>std::integer_sequence</code></a>. If you don't have a C++14 compiler, just copy an implement of it from the web somewhere. It's super useful in all things metaprogramming, so it's helpful if everybody's using the same terms.</p>\n\n<p>Next, you can write all sorts of \"iterating-over-a-sequence\" functions without having them be recursive. Take for instance <code>increment</code>:</p>\n\n<pre><code>template &lt;class... Ts, std::size_t... Is&gt;\nvoid increment(std::tuple&lt;Ts...&gt;&amp; tpl, std::index_sequence&lt;Is...&gt; ) {\n using expander = int[];\n expander{0,\n (void(\n ++std::get&lt;Is&gt;(tpl)\n ), 0)...\n };\n}\n\ntemplate &lt;class... Ts&gt;\nvoid increment(std::tuple&lt;Ts...&gt;&amp; tpl) {\n increment(tpl, std::index_sequence_for&lt;Ts...&gt;{});\n}\n</code></pre>\n\n<p>It takes a while to get used to, but once you do, everything is in the same place, and no <code>enable_if</code> necessary.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2015-11-30T22:40:37.463", "Id": "112388", "ParentId": "30846", "Score": "14" } } ]
{ "AcceptedAnswerId": "35429", "CommentCount": "2", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-09-05T22:26:56.717", "Id": "30846", "Score": "29", "Tags": [ "c++", "functional-programming", "c++11", "iterator" ], "Title": "\"Zip-like\" functionality with C++11's range-based for-loop" }
30846
<p>Can someone improve this for me? It seems ugly. </p> <p>The method should test whether an incoming number is a palindrome and return a Boolean result.</p> <pre><code>private static bool IsPalindrome(int value) { var inverseValue = string.Concat(value.ToString().Reverse()); return inverseValue == value.ToString(); } </code></pre>
[ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-09-06T00:03:37.303", "Id": "49094", "Score": "5", "body": "What's ugly? Looks pretty succinct to me." } ]
[ { "body": "<p>Looks o.k. and clear to me.\nBut you can reduce it to one line, if you want.</p>\n\n<pre><code>private static bool IsPalindrome(int value){\n return string.Concat(value.ToString().Reverse()) == value.ToString();\n}\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-09-11T23:45:43.667", "Id": "49559", "Score": "0", "body": "Clever one-liners are rarely the most readable way to go, imho." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-09-12T09:35:46.803", "Id": "49582", "Score": "0", "body": "@retailcoder: I think this one-liner is quite easy to read. But I agree, you should always prefer easy to read variants." } ], "meta_data": { "CommentCount": "2", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-09-06T04:23:38.487", "Id": "30854", "ParentId": "30847", "Score": "1" } }, { "body": "<p>Not much there to be ugly to be honest. I guess all I might consider would be the reverse of MrSmith42 and adding functionality to avoid the duplication of <code>ToString()</code>.</p>\n\n<pre><code>private static bool IsPalindrome(int value)\n{\n var valueStr = value.ToString(); \n return valueStr == string.Concat(valueStr.Reverse());\n}\n</code></pre>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-09-06T04:35:52.997", "Id": "30855", "ParentId": "30847", "Score": "6" } }, { "body": "<p>Well it totally depends on what you want as a \"clean\" result.</p>\n\n<p>If the conversion to string for the reverse bothers you, you can make an extension method to hide it :</p>\n\n<pre><code>public static class Extensions\n{\n public static int Reverse(this int input)\n {\n return Convert.ToInt32(string.Concat(input.ToString().Reverse()));\n }\n}\n</code></pre>\n\n<p>so the original method is reduced to :</p>\n\n<pre><code>private static bool IsPalindrome(int value)\n{\n return value == value.Reverse();\n}\n</code></pre>\n\n<hr>\n\n<p>If you prefer Fluent expressions, you can use <code>.Equals</code> and make it a one liner :</p>\n\n<pre><code>private static bool IsPalindrome(int value)\n{\n return string.Concat(value.ToString().Reverse()).Equals(value.ToString());\n}\n</code></pre>\n\n<hr>\n\n<p>If the duplicate <code>ToString()</code> calls bothers you, you can put it in a temporary variable :</p>\n\n<pre><code>private static bool IsPalindrome(int value)\n{\n string valueString = value.ToString();\n string inverse = string.Concat(valueString.Reverse());\n\n return inverse == valueString;\n}\n</code></pre>\n\n<hr>\n\n<p>And of course if you want to leave it like that (and maybe change the <code>var</code> to <code>string</code>) it would be correct too, as the original method is truly not horrible.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-09-11T21:11:37.953", "Id": "31121", "ParentId": "30847", "Score": "1" } }, { "body": "<p>Yes, you can do much better! You don't need to use <code>string</code>. I don't know C#, so feel free to edit my answer.</p>\n\n<p>Here is an idea for a function:</p>\n\n<pre><code>function int reverse(int myNumber)\n{\n int lastDigit = myNumber % 10;\n if (lastDigit == myNumber)\n {\n return myNumber;\n }\n else\n {\n int myNumberWithLastDigitDeleted = (myNumber - lastDigit) / 10;\n return lastDigit + 10 * reverse(myNumberWithLastDigitDeleted);\n }\n}\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-09-11T22:47:38.390", "Id": "49555", "Score": "0", "body": "This answer is downvoted: I don't have the same opinion as you on what is elegant ! Converting an `int` to a `string` to test whether it is a palindrome is IMO not elegant at all!" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-09-11T23:38:33.293", "Id": "49557", "Score": "1", "body": "I don't know C# either, but converting an `int` to a `string` can be elegant if done well. I wasn't the one who downvoted you, by the way." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-09-12T00:07:59.603", "Id": "49562", "Score": "1", "body": "Not my downvote either, but how is a cryptic, recursive function with variables named `i`, `j` and `n` anywhere near being more elegant than the OP's solution?" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-09-12T00:22:58.637", "Id": "49564", "Score": "0", "body": "I agree that it is cryptic. Maybe with other names it more clear ! What do you think of the following: to test whether a number is a multiple of 10, I convert it to a string, get the last character and test if it is equal to the character \"0\" ?" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-09-12T00:28:42.287", "Id": "49565", "Score": "0", "body": "@colas: If you're not too confident with this code being an answer, you're free to post it as a new question. However, you may be directed back here anyway." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-09-12T00:33:55.137", "Id": "49566", "Score": "0", "body": "@Jamal I think I am confident that my answer is the best answer, from my point of view. Nevertheless, I understand your point of view (but don't agree)!" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-09-12T00:36:38.570", "Id": "49567", "Score": "0", "body": "@colas: That's fine, then. Since this is still technically an answer, it can stay. Just be aware that anyone can still downvote if they disagree with this (or upvote if they agree)." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-09-07T02:17:22.387", "Id": "113230", "Score": "1", "body": "+1 for using math on numbers instead of string manipulation. It would need to be benchmarked, but certainly a viable option." } ], "meta_data": { "CommentCount": "8", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-09-11T21:25:31.577", "Id": "31123", "ParentId": "30847", "Score": "0" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "1", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-09-05T23:27:09.467", "Id": "30847", "Score": "6", "Tags": [ "c#", "palindrome" ], "Title": "Determining whether a number is a palindrome" }
30847
<h3>Background</h3> <ul> <li>Python (version 2.7.2)</li> </ul> <h3>Problem</h3> <ul> <li>You want to specify an array in your code.</li> <li>You want to use the 'syntax sugar' available in Ruby and Perl.</li> <li>You are a fanatic about readable code but also saving keystrokes.</li> </ul> <h3>Solution</h3> <ul> <li>Python Triple-quoted string</li> <li>Python splitlines</li> <li>Python list comprehension</li> </ul> <h3>Pitfalls</h3> <ul> <li>The solution may look ugly or un-Python-ish</li> </ul> <h3>Question</h3> <p>Are there any refactorings, suggestions or comments on this approach?</p> <pre><code>### ******************** ## setup an array using append ary_names = [] ary_names.append('alpha') ary_names.append('bravo') ary_names.append('charlie') ary_names.append('delta') ary_names.append('echo') ### ******************** ## setup an array using triple-quoted string ary_names = [ item.strip() for item in """ alpha bravo charlie delta echo """ .splitlines() if(not item.strip()=='') ] """ Here is a ruby example for comparison ary_names = %w[ alpha bravo charlie delta echo ] """ </code></pre>
[]
[ { "body": "<p>This will work as written. You could shorten it slightly by replacing </p>\n\n<pre><code>if(not item.strip()=='')\n</code></pre>\n\n<p>with </p>\n\n<pre><code> if item.strip()\n</code></pre>\n\n<p>You're also calling strip twice, you could skip that with:</p>\n\n<pre><code>array_names = [i for i in map(str.strip, my_big_string.splitlines()) if i]\n</code></pre>\n\n<p>I would avoid inlining the actual constants in the list comprehension tool - that's bad for readability if it's not sitting on the outermost outline level.</p>\n\n<p>On the philosophical level, I'm ambivalent. I hate all the quotes etc too, but this only works for strings, so it's not a general purpose idiom. You could extend it with exec or eval to get non-string values, but that's a whole big can o' worms :)</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-09-06T05:51:34.380", "Id": "49109", "Score": "2", "body": "`strip` isn't a top-level function; you'd have to use `str.strip` or `lambda s: s.strip()` if you want to pass it to `map`." } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-09-06T05:48:44.820", "Id": "30860", "ParentId": "30849", "Score": "3" } }, { "body": "<p>If you call <code>split</code> with no arguments, it will split on any whitespace and drop any empty elements. Knowing that, it's as simple as this:</p>\n\n<pre><code>ary_names = \"\"\"\n alpha\n bravo\n charlie\n delta\n echo\n\"\"\".split()\n</code></pre>\n\n<p>If you have only five short elements, you may want to put them all on one line:</p>\n\n<pre><code>ary_names = 'alpha bravo charlie delta echo'.split()\n</code></pre>\n\n<p>Of course, you'd only want to do that if it fits easily on one line.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-09-06T15:28:17.997", "Id": "49142", "Score": "3", "body": "its worth noting this won't worth string tokens including multiple words, unlike OP's answerr" } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-09-06T05:53:26.343", "Id": "30861", "ParentId": "30849", "Score": "5" } } ]
{ "AcceptedAnswerId": "30861", "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-09-06T02:05:52.430", "Id": "30849", "Score": "1", "Tags": [ "python", "python-2.x" ], "Title": "Python array literal syntax sugar similar to Perl and Ruby" }
30849
<p>I recently had to write a function to return characters missing from an input string. Here is the snippet</p> <pre><code>#include &lt;bitset&gt; #include &lt;string&gt; template&lt;class Iterator&gt; std::string getMissingLetters(Iterator begin, Iterator end) { std::bitset&lt;26&gt; letters; for (auto it = begin; it != end; ++it) { size_t c = tolower(*it) - char('a'); // normalized to start at 'a' if (c &gt; 26) continue; letters.set(c); if (letters.to_ulong() == ((1 &lt;&lt; 26) - 1)) break; // all 26 bits set } std::string missing; for (int i = 0; i &lt; letters.size(); ++i) { if (!letters[i]) missing.push_back(char('a' + i)); } return missing; } </code></pre> <p>I thought of couple things to improve, for example avoiding branch by clamping characters, eg.</p> <pre><code>letters.set(std::min(c, 26)); </code></pre> <p>and perhaps blocking the loop s.t. the line</p> <pre><code>if (letters.to_ulong() == ((1 &lt;&lt; 26) - 1)) break; </code></pre> <p>is executed every N iterations rather than each iteration.</p> <p>What do you think one could have done better?</p>
[ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-09-06T03:44:58.213", "Id": "49105", "Score": "0", "body": "I'd use `std::size_t` specifically, especially in the second `for`-loop." } ]
[ { "body": "<p>Bug, should be:</p>\n\n<pre><code>if (c &gt;= 26) continue;\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-09-06T05:03:48.783", "Id": "49107", "Score": "0", "body": "Not sure why this was down voted. It could have (maybe) used a tiny bit of explanation, but yes, `'z' - 'a' == 25` (`'(' - 'a' == 26`), and calling `set(26)` on a bitset of size 26 is rather bad." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-09-06T05:43:42.207", "Id": "49108", "Score": "1", "body": "@Corbin: It wasn't me, but I do agree that this should've been explained." } ], "meta_data": { "CommentCount": "2", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-09-06T03:57:14.030", "Id": "30853", "ParentId": "30851", "Score": "1" } }, { "body": "<p>Instead of starting from a zero-ed bitset and then set them to <code>true</code> one by one, you could start with all <code>true</code>, set to <code>false</code> one by one and then use <code>std::bitset::none()</code> to break the loop.</p>\n\n<p>But, apart from this small thing, <code>std::string</code> will probably preallocate memory (on the heap or on the stack; it's implementation dependent), whether or not you add a letter. My advice would be to use an <code>std::array</code> with a fixed size of 26 (or your own stack implementation of a string) to directly store the letters, and remove the bitset and <code>std::string</code>.</p>\n\n<p>That should simplified the code. As the 26 <code>char</code>s will be stored in 7 <code>int</code>, copying or overwriting that size from the stack should be blazing fast (the cache lines of a modern processor is 32 bytes) compared to multiple math operations and a potential heap allocation.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-09-06T12:18:19.940", "Id": "30874", "ParentId": "30851", "Score": "2" } }, { "body": "<p>Why not use:</p>\n\n<pre><code>std::bitset&lt;26&gt; letters_r ((1 &lt;&lt; 26)-1);\n...\nfor (it = begin; it != end; ++it) {\n ...\n letters_r.reset(c);\n if (letters_r.to_ulong() == 0 ) break; // all 26 bits reset\n}\n</code></pre>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-09-06T14:14:37.873", "Id": "30878", "ParentId": "30851", "Score": "2" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "1", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-09-06T03:09:13.693", "Id": "30851", "Score": "4", "Tags": [ "c++" ], "Title": "Review of a C++ missing characters snippet" }
30851
<p>I have the following HTTP reply saved in a local file called <code>source.txt</code>:</p> <blockquote> <pre class="lang-none prettyprint-override"><code>HTTP/1.1 301 Moved Connection: close Content-length: 111 Location: https://11.12.13.14:81/ Content-type: text/html; charset="utf-8" &lt;html&gt;&lt;head&gt;&lt;META HTTP-EQUIV="refresh" CONTENT="0;URL=https://11.12.13.14:81/"&gt;&lt;/head&gt;&lt;body&gt;&lt;/body&gt;&lt;/html&gt; </code></pre> </blockquote> <p>Source code:</p> <pre class="lang-c prettyprint-override"><code>#include &lt;stdio.h&gt; #include &lt;stdlib.h&gt; #define MAXBUFLEN 1024 char* getLocation(char* source) { const char *p1 = strstr(source, "Location:")+10; const char *p2 = strstr(p1, "\n"); size_t len = p2-p1; char *res = (char*)malloc(sizeof(char)*(len+1)); strncpy(res, p1, len); res[len] = '\0'; return res; } char* getData(char* source) { const char *p1 = strstr(source, "://")+3; const char *p2 = strstr(p1, "\n"); size_t len = p2-p1; char *res = (char*)malloc(sizeof(char)*(len+1)); strncpy(res, p1, len); res[len] = '\0'; return res; } int main() { char source[MAXBUFLEN]; char host[100]; int port; FILE *fp = fopen("source.txt", "r"); if (fp != NULL) { size_t newLen = fread(source, sizeof(char), MAXBUFLEN, fp); if (newLen == 0) { fputs("Error reading file", stderr); } else { source[++newLen] = '\0'; //extraction code char* res = getLocation(source); printf("getLocation result: %s\n", res); if (strstr(res, "://")) { res = getData(source); printf("getData result: %s\n", res); if (strstr(res, ":")) { sscanf(res, "%[^:]:%d[^/]", host, &amp;port); printf("host: %s | port: %d\n", host, port); } else printf("delimiter not found\n"); } else printf("no link\n"); // } } fclose(fp); } </code></pre> <p>The program is working well, but it's very ugly. Is there any way to improve the code to avoid doing so many operations? I mean somehow merging the two functions, <code>getLocation()</code> and <code>getData()</code>.</p>
[ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-09-07T16:15:44.173", "Id": "49214", "Score": "0", "body": "What about at least a minimal description on what this functions should do?" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-09-08T12:35:42.600", "Id": "49262", "Score": "0", "body": "you really need a description for that short code?" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-09-08T12:37:27.767", "Id": "49263", "Score": "0", "body": "Please excuse, I do not need nothing, not even to read your posting. I just tried to kindly mention that an introduction to an issue, raises the chances of keeping a possible reader attracted." } ]
[ { "body": "<p>Your <code>getLocation</code> can be improved a little:</p>\n\n<p>For a start, the call parameter should be <code>const</code> (although if you were happy\nmodifying the string you could avoid the memory allocation).</p>\n\n<p>Moving on:</p>\n\n<pre><code>const char *p1 = strstr(source, \"Location:\")+10;\n</code></pre>\n\n<p>This is ok, except that <code>p1</code> is cryptic and it is better to avoid embedded constants such as 10. Since this is the length of \"Location:\", we can extract that:</p>\n\n<pre><code>#define LOC \"Location:\"\nconst char *loc = strstr(source, LOC) - 1 + sizeof LOC;\n</code></pre>\n\n<p>Note the -1 for the \\0 at the end of LOC. But it is now uglier still. And of\ncourse it might fail, returning NULL. So we need to protect the next line:</p>\n\n<pre><code>const char *p2 = strstr(p1, \"\\n\");\n</code></pre>\n\n<p>in which you are looking for just one character; <code>strchr</code> is more appropriate and <code>eol</code> is a more descriptive name:</p>\n\n<pre><code>if (loc) {\n const char *eol = strchr(loc, '\\n');\n}\n</code></pre>\n\n<p>So next you get the length</p>\n\n<pre><code>size_t len = p2-p1;\n</code></pre>\n\n<p>which needs a cast to avoid a sign-conversion warning:</p>\n\n<pre><code>size_t len = (size_t) (eol - loc);\n</code></pre>\n\n<p>You allocate memory next:</p>\n\n<pre><code>char *res = (char*)malloc(sizeof(char)*(len+1));\n</code></pre>\n\n<p>but you should omit the cast and note that sizeof(char) is 1 by definition,\nso:</p>\n\n<pre><code>char *res = malloc(len + 1);\n</code></pre>\n\n<p>and of course allocation could also fail, so you must check before copying the\naddress into it. You copy the address thus:</p>\n\n<pre><code>strncpy(res, p1, len);\nres[len] = '\\0';\n</code></pre>\n\n<p>but as you already know the length of the string, memcpy would be better, as\n<code>strncpy</code> must check each char in the input string for \\0</p>\n\n<pre><code>if (res) {\n memcpy(res, loc, len);\n res[len] = '\\0';\n}\n</code></pre>\n\n<p>Putting it all together, we get:</p>\n\n<pre><code>static char* getLocation(const char* source)\n{\n#define LOC \"Location:\"\n size_t len = 0;\n char *eol = NULL;\n const char *loc = strstr(source, LOC) - 1 + sizeof LOC;\n if (loc) {\n eol = strchr(loc, '\\n');\n }\n if (eol &amp;&amp; loc) {\n len = (size_t) (eol - loc);\n }\n if (len) {\n char *res = malloc(len + 1);\n if (res) {\n memcpy(res, loc, len);\n res[len] = '\\0';\n }\n return res;\n }\n return NULL;\n}\n</code></pre>\n\n<p>Yes, string handling in C is ugly. </p>\n\n<p>My conclusion from this ugliness is that another approach is needed. Why not\nmodify the input string by putting a \\0 at <code>eol</code> and returning <code>loc</code>? Then\nyou could extract the address and port directly from that:</p>\n\n<pre><code>static char* getLocation(char* source)\n{\n#define LOC \"Location:\"\n char *loc = strstr(source, LOC) - 1 + sizeof LOC;\n if (loc) {\n char *eol = strchr(loc, '\\n');\n if (eol) {\n *eol = '\\0';\n }\n }\n return loc;\n}\n</code></pre>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-12-02T11:47:31.793", "Id": "36498", "ParentId": "30852", "Score": "2" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "3", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-09-06T03:42:08.850", "Id": "30852", "Score": "2", "Tags": [ "c", "strings", "http", "socket" ], "Title": "Extract location from HTTP socket" }
30852
<p>I know that the <code>DBContext</code> represents a session (Unit-Of-Work and Repository) with the database, however I an unsure as to when I should have a different <code>DBContext</code>. Currently, I have a separate <code>DBContext</code> for each table with a single <code>DBSet</code> for each <code>DBContext</code>.</p> <p>Something like this (<code>Blogs</code> and <code>Posts</code> are in the same database): </p> <pre><code>public class BlogContext : DbContext { public DbSet&lt;Blog&gt; Blogs { get; set; } } public class PostContext : DbContext { public DbSet&lt;Post&gt; Posts { get; set; } } </code></pre> <p>I'm not sure why I had a separate <code>DBContext</code>. I think that it is a sample I followed that was like this. However, I recently found that I get an exception when trying to do queries involving both contexts:</p> <blockquote> <p>The specified LINQ expression contains references to queries that are associated with different contexts.</p> </blockquote> <p>So, it seems that the obvious solution is for a single <code>DBContext</code> and multiple <code>DBSets</code>: </p> <pre><code>public class BlogContext : DbContext { public DbSet&lt;Blog&gt; Blogs { get; set; } public DbSet&lt;Post&gt; Posts { get; set; } } </code></pre> <p>Is there any guideline for when to use different <code>DBContext</code>s and the pros and cons of each approach?</p>
[ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-09-06T06:56:35.307", "Id": "49110", "Score": "0", "body": "I suppose one option is to use the Repository and Unit of Work Patterns to manage this across a single repository, but that starts to look like quite a lot of work for a simple site." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-09-06T08:40:50.603", "Id": "49116", "Score": "2", "body": "Not sure about pros and cons but I have always used one DBContext. I don't think I have ever seen your first example in practice (doesn't mean it's not valid though)" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-09-06T16:01:07.653", "Id": "49148", "Score": "0", "body": "Thanks, not sure where I picked it up. One DBContext makes sense." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-09-12T21:03:31.107", "Id": "49644", "Score": "0", "body": "My rule of thumb would be to use a single context per app; use multiple contexts when you could be breaking down your app into multiple smaller apps. 99% of the time you would be using a single context." } ]
[ { "body": "<p>As you have already mentioned, DbContext <em>is</em> a UoW, and DbSet <em>is</em> a repository -- there is no need to reimplement those patterns, unless you're into ridiculously useless complexity.</p>\n\n<p>Entity Framework wraps all pending changes in a transaction for you already, so each DbContext in an application contains DbSets that are somehow related. Blogs and Posts are <em>definitely</em> related, so they belong under the same context.</p>\n\n<p>If your app had a blog module and a completely distinct chat module, you could use separate contexts, as your app would never be using both in the same controller.</p>\n\n<p>I have an app with dozens of absolutely unrelated modules; either I defined a single context with 650 entity types (and only used a fraction of it every time), or I broke it down into <em>much</em> smaller and sanely manageable modules... I went for the second option. (the app is an ERP extension)</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-09-13T06:06:39.690", "Id": "49689", "Score": "1", "body": "DbSet can not be a repository. A repository should always be an aggragate root and a Blog and Post entity collections belong to one aggreagte root becouse they can not exists without each other. And yes the DbContext is a UoW but this is a wrong implementation and should not rely on it." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-09-13T10:52:10.900", "Id": "49705", "Score": "0", "body": "Then what, ditch EF and reinvent the wheel?" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-10-08T17:12:38.297", "Id": "51794", "Score": "0", "body": "@PeterKiss sorry to unearth this, but doesn't a navigation property fulfill the aggregate root requirement? You can do `context.Blogs.Where(e => e.Posts.Any())`, I don't see where it lacks. At all." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-10-08T19:53:56.187", "Id": "51808", "Score": "3", "body": "@retailcoder: no we don't need to ditch the EF but we have to create another small abstraction layer above it. Image this: we are calling methods which are saving entities to the database, when to call SaveChanges()? Always? Never? If we call it always then we can end up whith a situation when we only saving the half the currently running business transaction. And we havn't talked about that we can have transaction without a database how to handle that? A unit of work belongs to the business logic not (only) to the database abstraction." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-07-24T03:56:44.710", "Id": "103644", "Score": "2", "body": "@PeterKiss I definitely see the case for a business layer, which is what it sounds like you're describing, which would in turn leverage EF. However, I don't see how repository pattern would be the appropriate pattern for exposing the business layer. A repository pattern represents a set of data. A business layer represents actions that can be performed." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2015-10-21T02:47:36.780", "Id": "198817", "Score": "0", "body": "\"there is no need to reimplement those patterns, unless you're into ridiculously useless complexity.\" I'm not sure I agree. I don't like having calls to a dbcontext directly in my controllers. I like having it hide inside of a business layer that sort of, kind of, implements these patterns (with some additional business rules)." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2016-08-22T14:14:49.247", "Id": "260666", "Score": "1", "body": "@RubberDuck you can happily wrap the DbContext with an interface and call it a day. You can even name it `IUnitOfWork` if you want, and expose a `Commit` method that calls `SaveChanges` - a UoW wraps a transaction, and so does a `DbContext`: they're one and the same. What people want to achieve with the patterns is just a layer between EF and the controller - fine; just saying an interface does exactly that for a fraction of the complexity. I simply cannot see what the problem is with a constructor-injected `IUnitOfWork` that exposes `IDbSet<T>` for the controller to play with." } ], "meta_data": { "CommentCount": "7", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-09-12T20:47:32.023", "Id": "31165", "ParentId": "30856", "Score": "15" } } ]
{ "AcceptedAnswerId": "31165", "CommentCount": "4", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-09-06T04:36:23.720", "Id": "30856", "Score": "17", "Tags": [ "c#", "asp.net", "entity-framework", "asp.net-mvc-3", "asp.net-mvc-4" ], "Title": "Using separate DBContext classes" }
30856
<p>I have this piece of code:</p> <pre><code>List&lt;myItem&gt; items = (from x in db.myItems join y in db.tblParents on x.item_parent equals y.id where !y.hidden orderby x.name select x).ToList(); </code></pre> <p>And it is really slow. How can I optimize it? I need it to be faster. I have no idea how to do this.</p>
[ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-09-06T15:48:12.430", "Id": "49145", "Score": "2", "body": "Does the equivalent TSQL join run any faster in SSMS?" } ]
[ { "body": "<p>I honestly don't see anything particularly wrong with that Linq query, but there are a number of other things you should consider:</p>\n\n<ul>\n<li>Converting the query to a <code>List&lt;T&gt;</code> forces immediate evaluation of the query and requires the allocation of an single, contiguous portion of memory to store the results. If there are several thousand records, this can be fairly costly. If you later filter / re-order / group this list, it must be done in memory, which is usually much slower than allowing the database to filter / re-order / group the results. Generally, you should try to put off evaluating results until as late as possible. </li>\n<li>Even if you're not doing any further processing on the list, it may not be necessary to actually store the result set as a <code>List&lt;T&gt;</code>. You really should only use a <code>List&lt;T&gt;</code> when you need to be able to add or remove items from the result set dynamically. If you only need to be able to access elements in the result set by index (particularly in O(<em>n</em>) time), I'd recommend using an array instead (with <a href=\"http://msdn.microsoft.com/en-us/library/bb298736.aspx\" rel=\"nofollow\"><code>ToArray</code></a>). If all you need to do is iterate through the result set one item at a time, I'd <strong>strongly</strong> recommend using an <code>IEnumerable&lt;T&gt;</code> instead (with <a href=\"http://msdn.microsoft.com/en-us/library/bb335435.aspx\" rel=\"nofollow\"><code>AsEnumerable</code></a>). This way, your application doesn't need to pull <em>all</em> items in at once, and it doesn't have to allocate a single, contiguous portion of memory to store them.</li>\n<li>If you've done all you can to speed up the C# code, and it still runs slowly, you should look at optimizing the database&mdash;your code can't run any faster than the back-end database, after all. Perhaps you need to add an index to the <code>item_parent</code> column (and probably a foreign key as well). </li>\n</ul>\n\n<p>If you've setup a proper <a href=\"http://msdn.microsoft.com/en-us/library/ee382841.aspx\" rel=\"nofollow\">navigation property</a> you could write your query a bit more cleanly, although I doubt this would run any faster, since this will still translate to an <code>INNER JOIN</code> in SQL:</p>\n\n<pre><code>List&lt;myItem&gt; items = \n (from x in db.myItems\n where !x.tblParent.hidden\n orderby x.name\n select x)\n .ToList();\n</code></pre>\n\n<p>Or in fluent syntax:</p>\n\n<pre><code>List&lt;myItem&gt; items = db.myItems\n .Where(x =&gt; !x.tblParent.hidden)\n .OrderBy(x =&gt; x.name)\n .ToList();\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-09-06T20:17:52.923", "Id": "49176", "Score": "1", "body": "Somehow the second fluent option in this case just looks cleaner..." } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-09-06T06:32:13.830", "Id": "30863", "ParentId": "30862", "Score": "7" } }, { "body": "<p>It may be the performance issue of SQL Server itself, not C# code. Try to check execution plan of this query to see what's going on. Additional indexes may help, or database defragmentation.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-09-11T18:35:56.847", "Id": "31119", "ParentId": "30862", "Score": "1" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "1", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-09-06T06:19:11.630", "Id": "30862", "Score": "4", "Tags": [ "c#", "linq", "database", "join" ], "Title": "Optimizing join statement" }
30862
<h1><code>static</code> in OO context</h1> <p><code>static</code> methods, are methods defined in the context of a type, or class, that can be invoked without having to create an instance of that type. As a result, the method has access to hidden (<code>protected</code> or <code>private</code>) properties and methods. A <code>static</code> method allows for a number of patterns (like Singleton, Factory and Registry to name a few).</p> <p>Static properties are properties that, though bound to the context of a given type (or Class), do not reside in the memory that was allocated for an instance. Instead, they reside in a global storage area, which each instance accesses. As a result, if the value is changed via one instance, or (if the property is <code>public</code>) directly through the type definition, all instances will reflect that change.</p> <blockquote> <pre><code> some static field / | \ / | \ instance1 | instance3 instance2 </code></pre> </blockquote> <p>A simple example, using pseudo-code:</p> <pre><code>//assign using instance1 instance1::someStaticField = 1; //increment using instance2 instance2::someStaticField++; //get value using instance3 for(i=0;i&lt;instance3::someStaticField;i++) { the loop body will be executed 2 times, the value is 2 for all instances } </code></pre> <p>The <code>static</code> keyword is found in many of the well-know, widely used design patterns like the Singleton, Factory or Service Locator patterns. It's also used as a means to store global values (eg configuration data), that need to be available throughout the code-base, without having to resort to global variables. The component containing this data is often referred to as the <em>Registry</em>.</p> <p><em>Special case: <code>static class</code></em><br> C# allows the programmer to define a class as a <code>static class</code>. These classes are meant to bundle related functions together, to be called freely. A <code>static class</code> cannot be instantiated. Their main use-cases are to create fire-n'-forget methods, and to avoid having too many (often redundant) methods lying around. However, <code>static class</code>'s <a href="http://stackoverflow.com/a/206481/1230836">come at a cost</a>, use with care. Moderation is key.</p> <h1><code>static</code> storage class</h1> <p>The keyword <code>static</code> is also used in C, as a storage class specifier. The default storage class for global variables is the static storage class. This means that these global statics will be visible to all functions within that source file, but not to any other modules that may be brought in at link time. Local variables can also be defined as being <code>static</code>. This means that these variables will be initialized at runtime, and <strong><em>not</em></strong> be re-initialized each time the function is called. Their value remains <code>static</code> throughout.</p> <p><em>Example 1 - static global variable</em></p> <pre><code>#include &lt;stdio.h&gt; static int foo = 123; const char *bar = "Global, too";//or even without static int main ( void ) { void another_func( void ); printf("I can see foo = %d\n, bar is %s\n", foo, bar); ++foo; another_func(); another_func(); return 0; } void another_func( void ) { static i = 0; ++i; printf("I can see foo = %d\n, bar is %s\nI was called %d times\n", foo, bar,i); } </code></pre> <p>The output will look like this:</p> <blockquote> <pre><code>I can see foo = 123 bar is Global, too I can see foo = 124 bar is Global, too I was called 1 times I can see foo = 124 bar is Global, too I was called 2 times </code></pre> </blockquote> <p>So all functions can see/use the global statics, and if at any point their value is changed, then that change will be noticed by all other functions, too (obviously). A <code>static</code> variable in a function (as <code>i</code> in this case) retains its value in between calls, but cannot be accessed from outside that function's scope.</p>
[]
[]
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-09-06T06:56:20.883", "Id": "30864", "Score": "0", "Tags": null, "Title": null }
30864
The static keyword, in object-oriented programming languages, is used to define a function/method or field/property as bound to the context of a type/class, but not to any specific instance. Unlike constants, static properties can usually be changed at runtime. static also refers to the storage class in languages like C. static variables are initialized once, at run-time, and persist in between function calls (i.e. they aren't re-initialized).
[]
[]
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-09-06T06:56:20.883", "Id": "30865", "Score": "0", "Tags": null, "Title": null }
30865
<p>I'm developing and app that communicates via Bluetooth with another PCB. It consists of 3 seekbars that regulates the value of 3 parameters of the PCB.</p> <p>The structure is this:</p> <ol> <li>Send petition string for read the first value</li> <li>Receive the first value</li> <li>Send petition string for read the second value</li> <li>Receive the second value</li> <li>Send petition string for the third value</li> <li>Receive the third value</li> </ol> <p>The first thing that I want to do, but I don't know how is, when it enters on an <code>if</code>, if this is true, then it must continue executing the code. But if it isn't true, then it should get out of the function and stop executing the code. But the way I've done it, it continues executing.</p> <p>Then, other times it crashes because the way I implemented it to wait 1 second between each communication I know that isn't the best way, and few times instead of doing it right this way:</p> <ol> <li>Send petition string for read the first value</li> <li>Receive the first value</li> <li>Send petition string for read the second value</li> <li>Receive the second value</li> </ol> <p>It does something like:</p> <ol> <li>Send petition string for read the first value</li> <li>Send petition string for read the second value</li> <li>Receive the first value</li> </ol> <p>Here I receive a null string and it crashes. Now I've implemented a condition to check that is there any null string, but the solution is that I never get any null string.</p> <p>When I press the "read values" button, this is what it happens:</p> <pre><code>public void receiveValues() { /**Petition string that is sent to the PCB to request the variable's value*/ final String message_full1 = 2b e1 b4 e9 ff 1f b5; //variable 1 final String message_full2 = 2b e1 b8 e9 ff 1f b3; //variable 2 final String message_full3 = 2b e1 bc e9 ff 1f b1; //variable 3 final String message_full4 = 2b e0 bc f3 ff 1f 7c; //save request final String message_full5 = 2b e0 be f3 ff 1f 7a; //save status /*Send the first string to the PCB*/ byte[] send1 = message_full1.getBytes(); GlobalVar.mTransmission.write(send1); /**Delay of 1 second to let some time to receive the confirmation*/ read1_handler.postDelayed(new Runnable() { @Override public void run() { /**Read write confirmation after 1s = 1000ms*/ String inpuRead = "2b 00 ff fe c7 80"; //This string is what I receive as an answer via bluetooth /**We check that the received string is not null, to avoid program crash*/ if (inpuRead != null) { //|| !inpuRead.equals("")) { /*If it nos null, then we call the next function*/ int splitInt = splitReceivedString (inpuRead); //This function is declared below and extracts from the string , only the chars that we need. receive1 = splitInt; Toast.makeText(getApplicationContext(), "Loading values", Toast.LENGTH_LONG).show(); } else { Toast.makeText(getApplicationContext(), "Communication error", Toast.LENGTH_SHORT).show(); } } }, 1000); /**Delay to wait to send de second petition string*/ write2_handler.postDelayed(new Runnable() { @Override public void run() { /**write message 2 after 1s = 1000ms*/ byte[] send2 = message_full2.getBytes(); GlobalVar.mTransmission.write(send2); } }, 2000); /**Delay of 1 second to let some time to receive the confirmation*/ read2_handler.postDelayed(new Runnable() { @Override public void run() { /**Read write confirmation after 1s = 1000ms*/ String inpuRead = "2b 00 ff fe c7 80"; if (inpuRead != null) { int splitInt = splitReceivedString (inpuRead); receive2 = splitInt; } else { Toast.makeText(getApplicationContext(), Communication error, Toast.LENGTH_SHORT).show(); } } }, 3000); /**Delay to wait to send de third petition string*/ write3_handler.postDelayed(new Runnable() { @Override public void run() { /**write message 3 after 1s = 1000ms*/ byte[] send3 = message_full3.getBytes(); GlobalVar.mTransmission.write(send3); } }, 4000); /**Delay of 1 second to let some time to receive the confirmation*/ read3_handler.postDelayed(new Runnable() { @Override public void run() { /**Read write confirmation after 1s = 1000ms*/ String inpuRead = "2b 00 ff fe c7 80"; if (inpuRead != null) { int splitInt = splitReceivedString (inpuRead); receive3 = splitInt; /**Set loaded values on seekbars*/ bar1.setProgress(receive1); bar2.setProgress(receive2); bar3.setProgress(receive3); /**Message indicating the end of the transmission*/ Toast.makeText(getApplicationContext(), "Values loaded!", Toast.LENGTH_SHORT).show(); } else { Toast.makeText(getApplicationContext(), "Communication error", Toast.LENGTH_SHORT).show(); } } }, 5000); /**This makes a save request on the pCB*/ write4_handler.postDelayed(new Runnable() { @Override public void run() { /**write message 3 after 1s = 1000ms*/ byte[] send4 = message_full4.getBytes(); GlobalVar.mTransmission.write(send4); } }, 6000); /**This request a save statos on the PCB*/ write5_handler.postDelayed(new Runnable() { @Override public void run() { /**write message 3 after 1s = 1000ms*/ byte[] send5 = message_full5.getBytes(); GlobalVar.mTransmission.write(send5); /**Reset out string buffer to zero*/ GlobalVar.mOutStringBuffer.setLength(0); } }, 7000); } /** * FUNCTION THAT SPLITS THE RECEIVED STRING TO GET THE DESIRED VALUES */ private int splitReceivedString (String s) { //For example, s = 2b 00 ff fe c7 80 StringTokenizer tokens = new StringTokenizer(s," "); String one = tokens.nextToken(); String two = tokens.nextToken(); String three = tokens.nextToken(); String four = tokens.nextToken(); String five = tokens.nextToken(); String six = tokens.nextToken(); /**The next strings are whose got the seekbar's value*/ //f.e: "fffec780" received_hexValue = three + four + five + six; received_hexValue = received_hexValue.trim(); /**Conversion from hex to int to set the seekbar's values*/ int_value_receive = (int)Long.parseLong(received_hexValue, 16); int_value_receive = -200000 - int_value_receive; newIntValue = (int_value_receive * 100) / (200000 * (-1)); return newIntValue; //For this hex value, the int value to introduce in the seekbar is "60" } </code></pre> <p>One user on Stack Overflow has recommended me to write the code this way more clearly, and not to set a 1 second wait time because isn't the best way to do it. But I have to do something like this, because I don't have a condition to set. When i send the petition string to have the value returned, the condition would be to have this value returned, but If I don't set a time to wait between the petition sent and the returned string, mostly for sure that I'm getting a null string from the Bluetooth's input socket.</p> <p>Proposed code:</p> <pre><code>private Handler handler = new Handler(); //TODO: don't call functions read1, write2 etc, call it something like "readSomeValue" where "SomeValue" is what you're trying to read private void read1() throws IOException { String inpuRead = "2b 00 ff fe c7 80"; //This string is what I receive as an answer via bluetooth if (inpuRead != null) { //|| !inpuRead.equals("")) { int splitInt = splitReceivedString (inpuRead); receive1 = splitInt; Toast.makeText(getApplicationContext(), "Loading values", Toast.LENGTH_LONG).show(); } else { throw new IOException("Error in read1"); } } private void write2() { byte[] send2 = message_full2.getBytes(); GlobalVar.mTransmission.write(send2); } private void read2() throws IOException { String inpuRead = "2b 00 ff fe c7 80"; if (inpuRead != null) { int splitInt = splitReceivedString (inpuRead); receive2 = splitInt; } else { throw new IOException("Error in read2"); } } public void receiveValues() { handler.post(new Runnable() { @Override public void run() { try { read1(); read2(); read3(); } catch (IOException e) { Toast.makeText(getApplicationContext(), "Communication error! " + e.getMessage(), Toast.LENGTH_SHORT).show(); } } }); } </code></pre>
[]
[ { "body": "<p>It is quite hard to see what you are trying to achieve from your code. I think that you have two separate applications communicating over Bluetooth and that is working. However the way that you are coding the read/write methods is never going to work. Whoever said not to code the 1 second wait is entirely right, it might work if the planets are aligned, but it is a poor solution.</p>\n\n<p>If you need messages to be sent received in sequence I think that you need to develop something much more smart. You should already have a Thread controlling your reading and writing of data to the Input/Output streams - probably <code>mTransmission</code>. I would consider adding a flag or sequence variable to each message - so you are no longer writing a String, you are writing a String that identifies itself as something, say message2. Importantly reading and writing to streams are both blocking operations, so you can use this to drive triggering the next message - it is critical that this all happens in a separate thread or you application will hang. Your logic is now more like this:</p>\n\n<ol>\n<li>Devices paired, sockets opened.</li>\n<li>App 1 - Send petition Object (string, seq) to request the first value.</li>\n<li>App 1 - Trigger read in anticipation of a response (set socket timeout to a sensible value).</li>\n<li>App 1 - Receive something.</li>\n<li>App 1 - Validate received object is what you were expecting, process.</li>\n<li>App 1 - Rinse, repeat for other messages in sequence.</li>\n</ol>\n\n<p>All the while on your other application</p>\n\n<ol>\n<li>Devices paired, sockets opened.</li>\n<li>App 2 - Socket with long timeout set to read in anticipation of message.</li>\n<li>App 2 - Reads first message.</li>\n<li>App 2 - Checks seq number to determine what to do with data.</li>\n<li>App 2 - Writes data back with new seq number.</li>\n<li>App 2 - Goto 1.</li>\n</ol>\n\n<p>Applications should be coded to handle out of sequence messages, but I suspect Application 2 doesn't even care, if you were to repeatedly send request 1 it should just keep replying with response 1.</p>\n\n<p>In order to not have code hanging around waiting for each of these reads you should consider using a callback or listener which you can pass into your <code>mTransmission</code> object. When a read is successful or times out this can then be communicated back to the calling class.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-09-09T07:07:45.417", "Id": "49290", "Score": "0", "body": "Thanks for your answer. I have to say that I can only work with this app, the aplication on the PCB is done by other person and I can't modify it. The app i'm doing is based on the \"BluetoothChat example\", but I modified to work sending the value of 3 seekbar's instead of being a chat app. I'm not an expert android developer, I'm just starting with it. I would have liked to learn some of java before starting this project, but I haven't had time and I'm learning on the way. So I now that is hard work, but I would apreciate a lot an example of what you are proposing to do." } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-09-06T10:05:54.657", "Id": "30869", "ParentId": "30866", "Score": "2" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-09-06T07:25:11.227", "Id": "30866", "Score": "2", "Tags": [ "java", "android", "bluetooth" ], "Title": "App for communicating with another PCB via Bluetooth" }
30866
<p>The program listens to the Altera FPGA DE2 board's keys that can start and stop and reset a counter:</p> <pre><code>#include &lt;stdio.h&gt; #include "system.h" #include "altera_avalon_pio_regs.h" extern void puttime(int* timeloc); extern void puthex(int time); extern void tick(int* timeloc); extern void delay(int millisec); extern int hexasc(int invalue); #define TRUE 1 #define KEYS4 ( (unsigned int *) 0x840 ) int timeloc = 0x5957; /* startvalue given in hexadecimal/BCD-code */ int RUN = 0; void pollkey() { int action = IORD_ALTERA_AVALON_PIO_DATA(DE2_PIO_KEYS4_BASE); putchar(action); if (action == 7) { // 2^0+2^1+2^2 timeloc = 0x0; } else if (action == 13) { // 2^0+2^2+2^3 RUN = 0; } else if (action == 14) { // 2^1+2^2+2^3 RUN = 1; } else if (action == 11) { // 2^0+2^1+2^3 tick(&amp;timeloc); } } int main() { while (TRUE) { pollkey(); puttime(&amp;timeloc); delay(1000); IOWR_ALTERA_AVALON_PIO_DATA(DE2_PIO_REDLED18_BASE, timeloc); if (RUN == 1) { tick(&amp;timeloc); puthex(timeloc); } } return 0; } int hex7seg(int digit) { int trantab[] = { 0x40, 0x79, 0x24, 0x30, 0x19, 0x12, 0x02, 0x78, 0x00, 0x10, 0x08, 0x03, 0x46, 0x21, 0x06, 0x0e }; register int tmp = digit &amp; 0xf; return (trantab[tmp]); } void puthex(int inval) { unsigned int hexresult; hexresult = hex7seg(inval); hexresult = hexresult | (hex7seg(inval &gt;&gt; 4) &lt;&lt; 7); hexresult = hexresult | (hex7seg(inval &gt;&gt; 8) &lt;&lt; 14); hexresult = hexresult | (hex7seg(inval &gt;&gt; 12) &lt;&lt; 21); IOWR_ALTERA_AVALON_PIO_DATA(DE2_PIO_HEX_LOW28_BASE, hexresult); } int hex7seg2(int digit) { int trantab[] = { 0x40, 0x79, 0x24, 0x30, 0x19, 0x12, 0x02, 0x78, 0x00, 0x10, 0x08, 0x03, 0x46, 0x21, 0x06, 0x0e }; register int tmp = digit &amp; 0xf0; return (trantab[tmp]); } </code></pre> <p>I also use Nios 2 assembly for the delay:</p> <pre><code> .equ delaycount, 16911 #set right delay value here! .text # Instructions follow .global delay # Makes "main" globally known delay: beq r4,r0,fin # exit outer loop movi r8,delaycount # delay estimation for 1ms inner: beq r8,r0,outer # exit from inner loop subi r8,r8,1 # decrement inner counter br inner outer: subi r4,r4,1 # decrement outer counter #call pollkey br delay fin: ret </code></pre> <h2>Update</h2> <p>I have updated the program which behaves as expected. The changes is that I needed one action every millisecond and one action every second, so I used a modulo 1000 count.</p> <pre><code>#include &lt;stdio.h&gt; #include "system.h" #include "altera_avalon_pio_regs.h" extern void puttime(int* timeloc); extern void puthex(int time); extern void tick(int* timeloc); extern void delay(int millisec); extern int hexasc(int invalue); #define TRUE 1 #define KEYS4 ( (unsigned int *) 0x840 ) int timeloc = 0x5957; /* startvalue given in hexadecimal/BCD-code */ int RUN = 0; void pollkey() { int action = IORD_ALTERA_AVALON_PIO_DATA(DE2_PIO_KEYS4_BASE); if (action == 7) { timeloc = 0x0; puttime(&amp;timeloc); puthex(timeloc); delay(200); } else if (action == 13) { RUN = 0; } else if (action == 14) { RUN = 1; } else if (action == 11) { tick(&amp;timeloc); puttime(&amp;timeloc); puthex(timeloc); delay(200); } } int main() { int counter = 0; while (TRUE) { pollkey(); delay(1); ++counter; if (counter % 1000 == 0) { IOWR_ALTERA_AVALON_PIO_DATA(DE2_PIO_REDLED18_BASE, timeloc); if (RUN == 1) { tick(&amp;timeloc); puttime(&amp;timeloc); puthex(timeloc); } } } return 0; } int hex7seg(int digit) { int trantab[] = { 0x40, 0x79, 0x24, 0x30, 0x19, 0x12, 0x02, 0x78, 0x00, 0x10, 0x08, 0x03, 0x46, 0x21, 0x06, 0x0e }; register int tmp = digit &amp; 0xf; return (trantab[tmp]); } void puthex(int inval) { unsigned int hexresult; hexresult = hex7seg(inval); hexresult = hexresult | (hex7seg(inval &gt;&gt; 4) &lt;&lt; 7); hexresult = hexresult | (hex7seg(inval &gt;&gt; 8) &lt;&lt; 14); hexresult = hexresult | (hex7seg(inval &gt;&gt; 12) &lt;&lt; 21); IOWR_ALTERA_AVALON_PIO_DATA(DE2_PIO_HEX_LOW28_BASE, hexresult); } int hex7seg2(int digit) { int trantab[] = { 0x40, 0x79, 0x24, 0x30, 0x19, 0x12, 0x02, 0x78, 0x00, 0x10, 0x08, 0x03, 0x46, 0x21, 0x06, 0x0e }; register int tmp = digit &amp; 0xf0; return (trantab[tmp]); } .equ delaycount, 5800 #set 16911 right delay value here! .text # Instructions follow .global delay # Makes "delay" globally known delay: beq r4,r0,fin # exit outer loop movi r8,delaycount # delay estimation for 1ms inner: beq r8,r0,outer # exit from inner loop subi r8,r8,1 # decrement inner counter br inner outer: subi r4,r4,1 # decrement outer counter br delay fin: ret </code></pre>
[ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-09-06T13:02:35.140", "Id": "49134", "Score": "3", "body": "Too many magic numbers, it's hard to understand the purpose of the program." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-09-07T15:11:14.633", "Id": "49208", "Score": "1", "body": "@busy_wait He pretty much summarized its working in the first sentence. It's related to electronics - [FPGA](http://en.wikipedia.org/wiki/Field-programmable_gate_array). He could have used `typedef` or comments for the magic numbers but they couldn't have been avoided as they are according to the data sheets." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-09-07T15:44:33.503", "Id": "49210", "Score": "1", "body": "@AseemBansal They're magic in the sense that simple named constants could have made the code much more readable, like `timeloc`, `KEYS4`, etc." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-09-07T15:46:57.420", "Id": "49211", "Score": "1", "body": "@busy_wait Agreed. He could have used `typedef`s for them." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-09-07T15:53:48.313", "Id": "49212", "Score": "1", "body": "Also in the third line of the assembly code, the comment is wrong." } ]
[ { "body": "<p>You need to change the naming convention. Obviousy you can't do that for the API provided for the FPGA but for the function's name as well as variable names you need to change that a bit.</p>\n\n<p>Like <code>hex7seg</code> should be changed <code>hex7seg_lower</code> and <code>hex7seg2</code> should be changed to <code>hex7seg_upper</code>. Obviously you can use different conventions but making them descriptive would be helpful. Anyone familiar with what you are doing wouldn't need to read through the functions to find which one is for the upper hex digit and which is for the lower digit. Otherwise you can use comments which you are lacking.</p>\n\n<p>The naming convention problem is apparent in <code>trantab</code>. It should have been <code>tran_tab</code>. Much more readable and easier to interperet as <code>translation_table</code>. <code>hexresult</code>, <code>puthex</code> are all confusing. You know what you are doing but if you want anyone else to be able to guess what the program is doing you need to change the names.</p>\n\n<p>The <code>transtab</code> is a constant. So why not define it as a global constant. I know it is bad to define global variables but if you define it as </p>\n\n<pre><code>const int tran_tab[] = //The values\n</code></pre>\n\n<p>it will be easier to access it everywhere. Also you should be putting such constants in a header file for easy modification.</p>\n\n<p>Don't use the <code>register</code> keyword unless you are very much sure. If you are using any modern compiler it would be better at optimizing the use of register variables than you the programmer. I had confusion about that also and used them. See <a href=\"https://softwareengineering.stackexchange.com/questions/206378/when-is-the-register-keyword-actually-useful-in-c\">this</a> for clarification.</p>\n\n<p>I am not sure whether you need the values of both hexadecimal digits separately or not. If you want both then it would be easier to use this. Assuming Global constant variable for the translation table I removed the variable.</p>\n\n<pre><code>void hex7seg(int digit, int *lower, int *upper) {\n *lower = tran_tab[digit &amp; 0x0f];\n *upper = tran_tab[digit &amp; 0xf0];\n}\n</code></pre>\n\n<p>You can use <code>switch</code> statement in <code>pollkey</code> instead of <code>if-else ladder</code> . Might make the thing more readable.</p>\n\n<p>Other than that I don't think I can tell more. I'll have a look again but that's nearly all I can say.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-09-07T15:03:24.303", "Id": "30915", "ParentId": "30870", "Score": "5" } }, { "body": "<p>Your external prototypes would be better located in a header shared by the file that defines them. If they are all defined in assembler (like <code>delay</code>) then they still need to be put in a header if they are used by more than one C file. On the prototypes:</p>\n\n<ul>\n<li><p>It seems odd for <code>puttime</code> to take a non-constant pointer. Does it modify the referenced value or could it be passed by value?</p></li>\n<li><p>Similarly, <code>tick</code> might be more normal if it takes a <code>timeloc</code> value and returns a new one.</p></li>\n<li><p>Some of the <code>int</code> values should probably be <code>unsigned</code> (eg if they are bitmaps or such like).</p></li>\n</ul>\n\n<p>If your global variables (<code>timeloc</code> or <code>RUN</code>) are ever updated from assembler, or asynchronously, be sure to mark them <code>volatile</code>. And <code>RUN</code> would normally be <code>run</code> (upper-case normally being used for constants). Both should be <code>static</code> if only accessed here.</p>\n\n<p>And TRUE seems redundant. It gains nothing (<code>while (1)</code> is as understandable as <code>while (TRUE)</code> to me) and you don't even use it for the <code>RUN</code> state.</p>\n\n<hr>\n\n<p>In <code>pollkey</code> (which should have a <code>void</code> parameter list) you are interpreting a value that is an active-low bitmap. Your way of testing values is not immediately obvious - if you had inverted/masked the value and tested against 1, 2, 4 and 8 it would have been. By testing only for these values you are assuming that they cannot be active together. Maybe that is true. I'd rather see some constants, but not those you have (better 1,2,4,8).</p>\n\n<hr>\n\n<p>In your <code>hex7seg</code> the <code>int</code>s should probably be <code>unsigned</code>. I'd put the size in <code>trantab</code> to make it more likely the compiler will warn you if there are too many/few initialisers (depends on compiler warning level) and line-up the values for the same reason and for readability. And the temporary variable is unnecessary.</p>\n\n<pre><code>unsigned hex7seg(unsigned digit)\n{ \n unisgned trantab[16] = {0x40, 0x79, 0x24, 0x30, 0x19, 0x12, 0x02, 0x78, \n 0x00, 0x10, 0x08, 0x03, 0x46, 0x21, 0x06, 0x0e};\n return trantab[digit &amp; 0xf];\n}\n</code></pre>\n\n<p>Since you don't use <code>hex7seg2</code>, delete it. If you need it (which seems unlikely) then an Aseem says you should not duplicate <code>trantab</code></p>\n\n<hr>\n\n<p>In your <code>delay</code> code, each loop has two branches instead of one. As a rule, I'd expect to see only one branch in each loop (inner and outer) </p>\n\n<pre><code>outer: movi r8, delaycount \ninner: subi r8, r8, 1\n bneq r8, r0, inner\n subi r4, r4, 1 \ndelay: bneq r4, r0, outer \n ret\n</code></pre>\n\n<p>(assuming <code>bneq</code> exists in Nios2). Note: is it right to test against <code>r0</code> in the inner loop and not against 0? Also, if you prefer, put the entry point at the beginning with an explicit test for 0 call parameter before the loops</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-09-08T20:19:01.610", "Id": "30963", "ParentId": "30870", "Score": "2" } } ]
{ "AcceptedAnswerId": "30915", "CommentCount": "5", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-09-06T10:25:03.153", "Id": "30870", "Score": "3", "Tags": [ "c", "assembly", "fpga" ], "Title": "Polling for Nios 2" }
30870
<p>I have a solution in which I instantiate a class with various types inside of it. I feel it is becoming to cumbersome to instantiate and then create variables for each of the types I want to access in the class (Option 2 in the code), so I've come up with a custom return type so I only have to return data once for use (option 1).</p> <p>So with the struct my code is more readible in the MAIN block, but is there a better way to do this?</p> <pre><code>using System; using System.Collections.Generic; using System.Linq; using System.Text; namespace retclass { class Program { static void Main(string[] args) { //Option 1 Struct and function //create struct ret x = new ret(); x = goofie(3, "this is the struct string"); Console.WriteLine("The String is {0}, the int is {1} and the value is {2}", x.str, x.num, x.yesno); //Option 2 Class //Instantiate retclass retclass retins = new retclass(); retins.num = 3; retins.str = "this is the class string"; if ((retins.num &gt; 0) &amp;&amp; retins.str != "") { retins.yesno = true; } Console.WriteLine("The String is {0}, the int is {1} and the value is {2}", retins.str, retins.num, retins.yesno); Console.ReadLine(); } public struct ret { public int num { get; set; } public string str { get; set; } public bool yesno { get; set; } } public static ret goofie(int isn, string ss) { ret dex = new ret(); dex.str = ss; dex.num = isn; if ((dex.str != "") &amp;&amp; (dex.num &gt; 0)) { dex.yesno = true; } return dex; } } public class retclass { public int num { get; set; } public string str { get; set; } public bool yesno { get; set; } } } </code></pre>
[ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-09-06T12:51:42.757", "Id": "49133", "Score": "1", "body": "For immutable types its mostly a performance choice depending on the size of the class/struct. For mutable types, go with the class." } ]
[ { "body": "<p>This <a href=\"http://msdn.microsoft.com/en-us/library/ms229017.aspx\" rel=\"nofollow\"><code>MSDN Page</code></a> states:</p>\n\n<blockquote>\n <p><strong>CONSIDER</strong> defining a struct instead of a class</p>\n \n <ul>\n <li>if instances of the type are small and commonly short-lived or are commonly embedded in other objects.</li>\n </ul>\n \n <p><strong>AVOID</strong> defining a struct unless the type has all of the following characteristics:</p>\n \n <ul>\n <li>It logically represents a single value, similar to primitive types (int, double, etc.). </li>\n <li>It has an instance size under 16 bytes. </li>\n <li>It is immutable. </li>\n <li>It will not have to be boxed frequently. </li>\n </ul>\n</blockquote>\n\n<p>So if you want to use a class instead of a structure, you can just add the same static <code>goofy</code> method, to get the same <code>style</code> like you get with the structure: </p>\n\n<pre><code> public static retclass goofie(int isn, string ss)\n {\n retclass dex = new retclass();\n dex.str = ss;\n dex.num = isn;\n if ((dex.str != \"\") &amp;&amp; (dex.num &gt; 0))\n {\n dex.yesno = true;\n }\n return dex;\n }\n</code></pre>\n\n<p>You can either add this to the <code>Main</code> or better inside the class itself. If you consider the second, you can call it like: </p>\n\n<pre><code>retclass x = retclass.goofie(3, \"this is the reclass string\");\n\nConsole.WriteLine(\"The String is {0}, the int is {1} and the value \n is {2}\", x.str, x.num, x.yesno);\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-09-06T12:32:36.140", "Id": "49131", "Score": "0", "body": "Thanks, that does make it a bit more readable. I like the way it is called." } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-09-06T12:15:49.647", "Id": "30873", "ParentId": "30872", "Score": "2" } }, { "body": "<p>A structure can be used when you want a type that represents a single entity. A structure is more complicated to implement correctly, so unless there is any special reason, just stick to classes.</p>\n\n<p>You dont need to make it a struct to get a conventient way to create it. Make the constructor take the values.</p>\n\n<p>The <code>YesNo</code> property doesn't even need to be stored in the type. Just calculate it when needed.</p>\n\n<pre><code>public class ReturnValue {\n\n public int Num { get; private set; }\n public string Str { get; private set; }\n\n public bool YesNo { get { return Str != \"\" &amp;&amp; Num &gt; 0; } }\n\n public ReturnValue(int num, string str) {\n Num = num;\n Str = str;\n }\n\n}\n</code></pre>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-09-06T16:58:23.450", "Id": "30886", "ParentId": "30872", "Score": "2" } } ]
{ "AcceptedAnswerId": "30873", "CommentCount": "1", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-09-06T11:58:36.667", "Id": "30872", "Score": "3", "Tags": [ "c#", "design-patterns", "classes" ], "Title": "Is the use of Struct or Class personal preference?" }
30872
<p>I need to inject same variables into settings.py for multiple django apps.hence i wrote a module which takes in output of local() and modifies. This works but is it the right way to do things?</p> <pre><code>def enable_theme(theme_name, container): """ Enable the settings for a custom theme, whose files should be stored in ENV_ROOT/themes/THEME_NAME (e.g., edx_all/themes/stanford). The THEME_NAME setting should be configured separately since it can't be set here (this function closes too early). An idiom for doing this is: THEME_NAME = "stanford" enable_theme(THEME_NAME) """ container["THEME_NAME"] = theme_name container['MITX_FEATURES']['USE_CUSTOM_THEME'] = True # Calculate the location of the theme's files theme_root = container['THEME_ROOT'] / "themes" / theme_name # Include the theme's templates in the template search paths container['TEMPLATE_DIRS'].append(theme_root / 'templates') container['THEME_SASS_DIRECTORY'] = theme_root / 'static/saas' container['MAKO_TEMPLATES']['main'].append(theme_root / 'templates') # Namespace the theme's static files to 'themes/&lt;theme_name&gt;' to # avoid collisions with default edX static files container['STATICFILES_DIRS'].append((u'themes/%s' % theme_name, theme_root / 'static')) container['FAVICON_PATH'] = 'themes/%s/images/favicon.ico' % theme_name #Test case from theming_utils.template_customizer import enable_theme THEME_NAME = "sokratik" PIPELINE = False MITX_FEATURES['USE_DJANGO_PIPELINE'] = False DEBUG = True TEMPLATE_DEBUG = True enable_theme(THEME_NAME, locals()) </code></pre>
[ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-09-06T13:15:29.060", "Id": "49135", "Score": "0", "body": "The code you posted doesn't use `local()`. Also, you need to format your code so that it shows up correctly." } ]
[ { "body": "<p>You're not trying to modify a local environment, you're trying to modify the module's dictionary, which you can access by calling <a href=\"http://docs.python.org/2/library/functions.html#globals\" rel=\"nofollow\"><code>globals()</code></a>.</p>\n\n<p>Note: the dictionary returned by <a href=\"http://docs.python.org/2/library/functions.html#locals\" rel=\"nofollow\"><code>locals()</code></a> isn't meant to be modified.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-09-06T19:29:34.683", "Id": "49167", "Score": "0", "body": "that explains a bit of stuff, in case I am actually using globals, is it fine to modify globals in this way??" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-09-06T20:07:53.233", "Id": "49173", "Score": "0", "body": "It's okay to modify a module's dictionary, I don't know whether or not it's the right way to handle themes in Django." } ], "meta_data": { "CommentCount": "2", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-09-06T15:33:51.897", "Id": "30882", "ParentId": "30875", "Score": "1" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "1", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-09-06T13:00:16.247", "Id": "30875", "Score": "1", "Tags": [ "python", "django" ], "Title": "modifying local environment in python" }
30875
<p>I am using VBA to manipulate the global address book in Outlook. My method takes a contact and returns a complete list of everyone who reports through that person based on the Outlook org structure.</p> <p>Unfortunately it takes quite some time to run, even for a single manager. I'm not really sure what is the best way to improve the performance here - it sees the <code>getDirectReports</code> method takes some time, but, I don't see an easy way to determine if a user <em>has</em> reports prior to calling it first.</p> <pre><code>Public Sub printAllReports() Dim allReports As Collection Set allReports = New Collection Dim curLevelReports As Collection Set curLevelReports = New Collection Dim nextLevelReports As Collection Set nextLevelReports = New Collection Dim myTopLevelReport As ExchangeUser 'this method returns an exchange user from their "outlook name" Set myTopLevelReport = getExchangeUserFromString("outlook resolvable name here") 'add to both the next level of reports as well as all reports allReports.Add myTopLevelReport curLevelReports.Add myTopLevelReport Dim tempAddressEntries As AddressEntries Dim newExUser As ExchangeUser Dim i, j As Integer 'flag for when another sublevel is found Dim keepLooping As Boolean keepLooping = False Dim requireValidUser As Boolean requireValidUser = False 'this is where the fun begins Do 'get current reports for the current level For i = curLevelReports.Count To 1 Step -1 Set tempAddressEntries = curLevelReports.item(i).GetDirectReports 'add all reports (note .Count returns 0 on an empty collection) For j = 1 To tempAddressEntries.Count Set newExUser = tempAddressEntries.item(j).getExchangeUser 'isExchangeUserActualEmployee has some short boolean heuristics to make sure 'the user has at least a title and an email address If (isExchangeUserActualEmployee(newExUser) = True Or requireValidUser = False) Then allReports.Add newExUser nextLevelReports.Add newExUser keepLooping = True End If Next j Set tempAddressEntries = Nothing Next i 'reset for next iteration Set curLevelReports = nextLevelReports Set nextLevelReports = New Collection 'no more levels to keep going If keepLooping = False Then Exit Do End If 'reset flag for next iteration keepLooping = False Loop Dim oMail As Outlook.MailItem Set oMail = Application.CreateItem(olMailItem) 'do stuff with this information (currently just write to new email, could do other cool stuff) For i = 1 To allReports.Count oMail.Body = oMail.Body + allReports.item(i).name + ";" + allReports.item(i).JobTitle Next i oMail.Display End Sub </code></pre>
[ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-09-06T16:09:34.097", "Id": "49149", "Score": "1", "body": "See the remarks section here : http://msdn.microsoft.com/en-us/library/office/ff866704.aspx I dont think your code is the problem." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-09-11T23:40:24.393", "Id": "49558", "Score": "1", "body": "Not going to help performance in any way, but I can't help mentioning that `If (bool_expression) = true` can (read: *should*) be rewritten as `If (bool_expression)` and `If (bool_expression) = false` can (read: *should*) be rewritten as `If Not (bool_expression)`." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-10-30T00:54:56.497", "Id": "53648", "Score": "2", "body": "@enderland hey, I just noticed, you're this guy on StackOverflow I answered an Outlook VBA question to and we had the exact same rep score! Hi there, welcome to CodeReview!" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-10-30T01:57:07.077", "Id": "53657", "Score": "1", "body": "@retailcoder indeed :) Not very many people who are comfortable or confident in Outlook VBA that's for sure." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-10-31T18:48:57.853", "Id": "53837", "Score": "0", "body": "@enderland did you try the *HierarchicalUser* approach yet?" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-10-31T18:50:09.023", "Id": "53840", "Score": "0", "body": "@retailcoder I've not yet, no. I might this afternoon, I'm finally getting caught up on other VBA work :-)" } ]
[ { "body": "<p>not sure that this will help with the Speed/Performance of the script but I am thinking that you should change your <code>do while</code> like this</p>\n\n<pre><code>Dim keepLooping as boolean \nkeepLooping = True\nDo While keepLooping = True\n keepLooping = False\n</code></pre>\n\n<p>and then the rest of the code the same. (except for changes to make it more efficient)</p>\n\n<p>I also noticed this</p>\n\n<pre><code> 'add all reports (note .Count returns 0 on an empty collection)\n For j = 1 To tempAddressEntries.Count\n Set newExUser = tempAddressEntries.item(j).getExchangeUser\n</code></pre>\n\n<p>if there was an empty collection passed into this for some reason, wouldn't this cause an infinite loop?</p>\n\n<p>you should instead write it with a <code>Foreach</code></p>\n\n<pre><code>foreach item In temAddressEntries\n Set newExUser = item.getExchangeUser\n.....\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-10-29T20:48:40.780", "Id": "53624", "Score": "0", "body": "No infinite loop, just no iteration (vba's weird!)" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-10-29T21:00:37.607", "Id": "53625", "Score": "1", "body": "I don't think I would even want to write my code like that. I think I would still surround it with an If Statement. that seems like it could be a really bad habit to accidentally fall into." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-10-30T01:06:24.590", "Id": "53650", "Score": "1", "body": "Totally agree, except I wouldn't *surround it* with an `If` - the code is already nested deep enough as it is! Using `For Each` to iterate collections completely circumvents this problem." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-10-30T13:49:38.087", "Id": "53695", "Score": "1", "body": "duh. why did I say that.... you are totally Right @retailcoder, and i am going to steal that comment. :)" } ], "meta_data": { "CommentCount": "4", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-10-29T20:42:39.147", "Id": "33479", "ParentId": "30876", "Score": "4" } }, { "body": "<p>Your <code>printAllReports</code> method does almost everything that's possible to do with the Outlook API (ok maybe not), <em>except</em> printing anything. You basically have what we call a <em>monolith</em>, and that's bad because as your program changes, you are tempted to just keep adding and adding and adding, until the thing becomes an unmanageable, tangled mess. If you're going to call a method <code>printAllReports</code>, give it a signature like this: <code>Sub printAllReports(allReports As Collection)</code>, so its intent is clear at first glance - and then make it do one thing; <em>print all reports</em>.</p>\n\n<p>Performance-wise, the major hit is going to be hitting the Exchange server, so your code needs to make sure it hits the server only when it's necessary. If that's already the case, chances are you've already got it as good as it gets.</p>\n\n<hr>\n\n<p>I think your multiple collections and 3-layer deep nested loop approach isn't the easiest way to make your code readable and maintainable, let alone to fine-tune its performance.</p>\n\n<p><H2>HierarchicalUser</H2></p>\n\n<p>The beautiful thing about a language that allows you to define objects, is that doing so actually <em>adds vocabulary to that language</em>, so no matter how lame VBA/VB6 is, with your own objects you can add new <em>nouns</em>, and with your own methods you can add new <em>verbs</em>, and with enough of them you actually end up crafting a language (ok, an API) that's beautiful in its own way.</p>\n\n<p>You have the concept of an ExchangeUser, that can <em>report to</em> another ExchangeUser, and that can have ExchangeUser underlings. I call that a <em>hierarchy</em>, and I'd recommend you encapsulate that <code>ExchangeUser</code> into your very own <code>HierarchicalUser</code> class, something along those lines:</p>\n\n<pre><code>private type tHierarchicalUser\n User As ExchangeUser\n Superior As HierarchicalUser\n Underlings As New Collection\nend type\n\nprivate this As tHierarchicalUser\nOption Explicit\n\nPublic Property Get User() As ExchangeUser\n Set User = this.User\nEnd Property\n\nPublic Property Set User(value As ExchangeUser)\n Set this.User = value\nEnd Property\n\nPublic Property Get Superior() As HierarchicalUser\n Set Superior = this.Superior\nEnd Property\n\nPublic Property Set Superior(value As HierarchicalUser)\n Set this.Superior = value\nEnd Property\n\nPublic Property Get Underlings As Collection\n 'DO NOT return a reference to the encapsulated collection, you'll regret it!\n Dim result As New Collection, underling As HierarchicalUser\n For Each underling In this.Underlings\n result.Add underling\n Next\n Set Underlings = result\nEnd Property\n\nPublic Sub AddUnderling(underling As HierarchicalUser)\n Set underling.Superior = Me\n this.Underlings.Add underling 'you can use a key here to ensure uniqueness\nEnd Sub\n\n'almost forgot!\nPublic Function FlattenHierarchy() As Collection\n Dim result As New Collection\n\n 'traverse whole hierarchy and add all items to a collection that you return\n\n Set FlattenHierarchy = result\nEnd Sub\n</code></pre>\n\n<p>Then you'll need a way to create instances of this class, and populate them. Enter the <code>HierarchicalUserFactory</code> (well, I know I would put that in its own class, but that's just me) - instead of nesting <em>code</em> we're going to be nesting <em>method calls</em>, recursively:</p>\n\n<pre><code>Public Function CreateHierarchicalUser(exUser As ExchangeUser) As HierarchicalUser\n Dim result As New HierarchicalUser\n Dim entry As AddressEntry\n Dim underling As ExchangeUser\n\n set result.User = exUser\n\n For Each entry In exUser.GetDirectReports() '&lt;&lt; For Each won't loop if there's nothing in the collection\n\n 'if possible, run the isExchangeUserActualEmployee logic off this 'entry' object,\n 'so you can only call the expensive GetExchangeUser method if needed:\n set underling = entry.GetExchangeUser\n result.AddUnderling CreateHierarchicalUser(underling) '&lt;&lt;&lt; recursive call!\n\n Next\n\n Set CreateHierarchicalUser = result\nEnd Function\n</code></pre>\n\n<p>Haven't tested any of this, but I believe an approach along those lines <em>could</em> possibly help you reduce the amount of <code>GetExchangeUser</code> calls and thus increase performance... not to mention <code>readability++</code> :)</p>\n\n<p>So your <code>printAllReports</code> method could possibly look like this now:</p>\n\n<pre><code>Public Function getHierarchy(topLevelUserName As String) As HierarchicalUser\n Dim factory As New HierarchicalUserFactory\n Dim topLevelUser As ExchangeUser\n\n Set topLevelUser = getExchangeUserFromString(topLevelUserName)\n Set GetHierarchy = factory.CreateHierarchicalUser(topLevelUser)\nEnd Sub\n\nPublic Sub printAllReports(hierarchy As HierarchicalUser)\n\n Dim reports As Collection\n Set reports = hierarchy.FlattenHierarchy()\n\n 'do all that cool stuff you wanted to do!\n\nEnd Sub\n</code></pre>\n\n<hr>\n\n<p><H2>Nitpicks</H2></p>\n\n<ul>\n<li>When you declare an object variable and assign it to a <code>New</code> instance on the next line, consider combining the two statements into one: <code>Dim X As New Y</code>.</li>\n<li>When you declare a <code>Boolean</code>, it's automatically initialized to <code>False</code> so your post-declaration assignments are redundant.</li>\n<li>When you evaluate a <code>Boolean</code> expression in an <code>If</code> statement, you don't need to specify <code>=True</code> or <code>=False</code> - rather, just say <code>If SomeBooleanExpression Then</code> or <code>If Not SomeBooleanExpression Then</code>.</li>\n<li>When looping through objects in a collection, <strong>ALWAYS</strong> use a <code>For Each</code> construct. This will avoid weird stuff like <code>For i = 1 To MyCollection.Count</code> when <code>.Count</code> is 0, even someone that knows the VBA/VB6 collection base rules like the palm of their hand will go \"huh?\". <code>For...Next</code> has been around <em>since before objects even existed</em>, that construct is for traversing <em>arrays</em>. Collections deserve a <code>For Each</code>.</li>\n</ul>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-10-30T00:45:37.620", "Id": "53647", "Score": "0", "body": "One thing though, if you have a very complex organization with dozens of hierarchy levels, there's a chance you run into a *stack overflow* error with this recursive approach. Not sure how deep the VBA call stack is allowed to get." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-10-30T01:49:31.800", "Id": "53655", "Score": "2", "body": "Hah, your #3 nitpick is so true, but I've gotten into the habit of doing this because... unfortunately a lot of the VBA I write in my job may be looked at by non-programmers and sometimes the \"if bool then\" can be confusing. C'est la vie." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-10-30T01:56:46.073", "Id": "53656", "Score": "0", "body": "I like the idea of making more functions for this... I've also avoided doing #1, because it's really easy to get caught up on weird things with it (see [here](http://stackoverflow.com/q/2478097/1048539) for some discussion). Definitely torn on that one because of the extra typing :) I've gotten into the habit of initing my booleans even as false so it's more clear what's happening and why, somehwhat a personal preference I guess?" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-10-30T01:58:33.210", "Id": "53658", "Score": "0", "body": "This sort of approach would make it look a million times nicer though, that's for sure." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-10-30T02:00:03.063", "Id": "53659", "Score": "2", "body": "Thanks - and a couple dozen times easier to follow, too! As for your comment just before this last one, I find it clutters up the code more than anything - it makes more to read and adds zero value. If non-programmers *need* to look at the code, then they *need* to learn the language. :) (I've never had any issues with inline initialization)" } ], "meta_data": { "CommentCount": "5", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-10-30T00:29:35.917", "Id": "33484", "ParentId": "30876", "Score": "6" } } ]
{ "AcceptedAnswerId": "33484", "CommentCount": "6", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-09-06T13:54:03.897", "Id": "30876", "Score": "6", "Tags": [ "performance", "vba", "outlook" ], "Title": "Manipulating the global address book in Outlook" }
30876
<p>I need to optimize this code so it can execute faster, even if that means using more memory:</p> <pre><code>for (int t = 0; t &lt; Clientes[0].ChildNodes.Count; t++) { for (int i = 0; i &lt; Clientes[0].ChildNodes.Item(t).ChildNodes.Count; i++) { if (Clientes[0].ChildNodes.Item(t).ChildNodes.Item(i).Name.Contains("Service")) { int a = 0; int.TryParse(Clientes[0].ChildNodes.Item(t).ChildNodes.Item(i).Name.ToUpper().Replace("SERVICE", ""), out a); if (a.Equals(Type)) { Queues[t].Send(QueueMessage); } } } } </code></pre> <p>I have decided to avoid accessing <code>Clientes[0]</code> and its <code>ChildNodes.Item(t)</code> over and over in each loop by keeping them in new variables like this:</p> <pre><code>XmlNodeList clientZeroChildNodes ; int clientZeroChildCount ; XmlNodeList clientZeroItemTchildNodes ; int clientZeroItemTchildCount; string clientZeroItemTchildIname; clientZeroChildNodes = Clientes[0].ChildNodes; clientZeroChildCount = clientZeroChildNodes.Count; for (int t = 0 ; t &lt; clientZeroChildCount ; t++) { clientZeroItemTchildNodes = clientZeroChildNodes.Item(t).ChildNodes; clientZeroItemTchildCount = clientZeroItemTchildNodes.Count; for (int i = 0; i &lt; clientZeroItemTchildCount; i++) { clientZeroItemTchildIname = clientZeroItemTchildNodes.Item(i).Name; if (clientZeroItemTchildIname.Contains("Service")) { int a = 0; int.TryParse(clientZeroItemTchildIname.ToUpper().Replace("SERVICE", ""), out a); if (a.Equals(Type)) { try { Queues[t].Send(QueueMessage); } catch (MessageQueueException mqe) { //log error about mqe } } } } } </code></pre> <p>As you can see, the second <code>for</code> loop only takes certain items of the <code>ChildNodes</code> based on its name. I have tried to use LINQ so that the second <code>for</code> only iterates the list of <code>ChildNodes</code> that match both of the if conditions that are inside the loop but have not been able to do it.</p> <p>Can you show me how would you improve the speed of the original code focusing on an efficient way to improve the loops and nested <code>if</code>s? I am not trying to determine which line of code is taking longer and the performance of the <code>Queues</code> is not relevant for me.</p>
[ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-09-06T15:50:55.273", "Id": "49146", "Score": "1", "body": "“let me know if you think that my approach will improve the speed” You need to measure that yourself. Guessing about speed is night impossible." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-09-06T15:52:35.513", "Id": "49147", "Score": "0", "body": "Also, are you sure this is the code that takes the most time in your application? Which part causes slowdown (a profiler will tell you that)? Isn't it `Queues[t].Send(QueueMessage);`?" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-09-06T16:14:01.473", "Id": "49150", "Score": "0", "body": "so if I post this question on regular stackoverflow is OFF-TOPIC because is not a \"programming question/problem\" and If I post it nobody helps me ? I am sure that accesing and arrays of arrays each time on a for loop is less eficcient I am just asking for other ways people will improve this" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-09-06T16:18:54.160", "Id": "49151", "Score": "0", "body": "the title clearly says that I want to improve the NESTED LOOPS not really related to the Queues" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-09-06T16:38:08.160", "Id": "49152", "Score": "0", "body": "@MauricioGracia The 'Queues[t].Send(QueueMessage);' is within the nested loops, thus relevant." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-09-06T16:49:39.987", "Id": "49153", "Score": "0", "body": "I voted to leave this open, since @MauricioGracia posted working code. The fact that he also told us about a failed optimization attempt is a bonus; reviewers can choose to ignore that part." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-09-06T20:48:29.300", "Id": "49178", "Score": "0", "body": "the way you have it written you have to go through all the nodes to evaluate the if statements inside the second for loop. there isn't really a way around that, unless you create a new set of nodes altogether that doesn't include any of the nodes that don't pass the if statements. but that would be rather counter productive I think" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-09-06T21:38:56.033", "Id": "49180", "Score": "0", "body": "@Malachi Its a legacy code that somebody else wrote and I am trying to improve and if posible make it more readable" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-09-06T21:41:24.950", "Id": "49181", "Score": "0", "body": "I too am dealing with some Legacy code right now, rather frustrating. some code is better left alone..." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-09-07T02:06:44.637", "Id": "49188", "Score": "2", "body": "@Malachi or even better write it from scratch keeping the functionality but improving readability and performance" } ]
[ { "body": "<ul>\n<li><p>Make <code>Queues[t].Send(QueueMessage);</code> asynchronous if it is not. This will be the best means to speed up your looping. Then have it handle the exception rather than this loop.</p></li>\n<li><p>If you're not expecting exceptions when calling Send, then having the <code>Try/Catch</code> does not slow you down. However, if you're catching multiple exceptions while processing, it is faster to perform sanity checks on the data before processing.</p></li>\n<li><p>You're doing a case-sensitive check on \"Service\" in the IF, but then you're doing a case-insensitive replace via <code>.ToUpper()</code> and \"SERVICE\". Remove the <code>.ToUpper()</code> if it is in fact case-sensitive. Otherwise that is a bug and should be checked in both places - for which you'd make a variable to house the result of <code>.ToUpper()</code> rather than calling it twice.</p></li>\n</ul>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-09-06T16:53:08.937", "Id": "49154", "Score": "0", "body": "thanks for your feedback, and does using intermediate variables helps in order to over the hierachy of objects again and again ?" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-09-06T19:03:12.303", "Id": "49161", "Score": "0", "body": "@MauricioGracia Implement DanLyons' answer. He noted the speed in enumerating the list rather than accessing items by index, whereas I focused on the Queues. Index by integer is faster than by string (Name) for nodes and attributes, but I think he is right in general to move to the foreach and if you're here trying to speed up then either Async the Send or you have well over 100 items to iterate." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-09-07T22:21:44.680", "Id": "49243", "Score": "0", "body": "Just making something asynchronous won't magically improve performance." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-09-09T13:23:23.627", "Id": "49305", "Score": "0", "body": "@bland the send on a queue can fail if the the contents of the message are checked. about the ToUpper it was a typo y int the code I provided. and the main idea is about how to improve the loops not so much the queue performance itself" } ], "meta_data": { "CommentCount": "4", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-09-06T16:46:23.410", "Id": "30885", "ParentId": "30881", "Score": "4" } }, { "body": "<p><strong>I would highly suggest profiling your code to see where the bottleneck lies.</strong></p>\n\n<p>That said, one thing to note (aside from what has already been mentioned) is that <code>XmlNodeList.Item(int)</code> is typically \\$O(n)\\$ <sup>*</sup>. As a result, your loops are \\$O(n^2)\\$.</p>\n\n<p>If your elements have a large number of children (100+), you may want to switch to <code>foreach</code> loops, which will be \\$O(n)\\$:</p>\n\n<pre><code>foreach (XmlNode node in foo.ChildNodes)\n{\n // Do stuff.\n}\n</code></pre>\n\n<hr>\n\n<p><sup>*</sup> The IL for <code>System.Xml.dll</code> reveals that <code>XmlNode.ChildNodes</code> returns type <code>XmlChildNodes</code>, and <code>XmlChildNodes.Item(int)</code> is \\$O(n)\\$.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-09-06T18:11:28.317", "Id": "30887", "ParentId": "30881", "Score": "7" } }, { "body": "<p>it looks like you are doing a lot with making all sorts of variables that are really confusing to look at, maybe I am simple minded and that is why I can't figure it all out.</p>\n\n<p>not really sure what you are doing with the <code>t</code> but I changed it to <code>i</code></p>\n\n<pre><code> XmlNodelist ClientNodes;\nClientNodes = Clientes[0].ChildNodes;\nXmlNode ChildNode;\n\nint i = 0;\n\nforeach ChildNode in ClienteNodes\n{\n i++\n XmlNodeList ClientChildNodes;\n XmlNode ClientChildNodeChild; //don't keep my name scheme\n foreach ClientChildNodeChild in ClientChildNodes\n {\n string clientZeroItemTchildIname; \n clientZeroItemTchildIname = (ClientChildNodeChild.Item.Name).ToUpper();\n if ( ClientZeroItemTchildIname.Contains(\"SERVICE\"))\n {\n int a = 0;\n int.TryParse(ClientZeroItemTchildIname.Replace(\"SERVICE\",\"\"),out a);\n\n if (a.Equals(Type))\n {\n try\n {\n Queues[i].Send(QueueMessage)\n }\n catch (MessageQueueException mqe)\n {\n //log Error about mqe\n }\n }\n }\n }\n}\n</code></pre>\n\n<p>not sure that I made it any faster, but this is way more readable. </p>\n\n<p>there is one less Variable in my code than there is in your 'optimized' code.</p>\n\n<p><strong>Which is faster, <code>foreach</code> or a <code>for</code> loop?</strong></p>\n\n<p>Here is an answer to that question, where someone actually went through testing <code>for</code> loops against <code>foreach</code> loops. and it looks like the <code>foreach</code> is faster in some instances.</p>\n\n<p><a href=\"https://stackoverflow.com/a/1124936/1214743\">Answer to Performance difference for control structures 'for' and 'foreach' in C# (2009)</a></p>\n\n<p>I also found a page where someone claims that a <code>foreach</code> loop takes longer and is generally good for collections, but then he recommends against it anyway.</p>\n\n<p><a href=\"http://www.codeproject.com/Articles/6759/FOREACH-Vs-FOR-C\" rel=\"nofollow noreferrer\">Code Project Article \"FOREACH Vs. FOR (C#)\" (2004)</a></p>\n\n<p>Threw that one in there in case you thought that I was biased. I still think the <code>foreach</code> would be better for readability, but I don't know what your code is doing so I don't know what is going to be more efficient for you. Readable/maintainable vs. faster? maybe. not sure though.</p>\n\n<p><strong>Something else to think about</strong></p>\n\n<p>Take the Send out of the Loop. </p>\n\n<p>keep track of which <code>Queues</code> that you want to send in a variable outside of the loop and then once you are finished looping then send them all at the same time, outside of the loop. </p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-09-06T20:09:56.043", "Id": "30894", "ParentId": "30881", "Score": "7" } }, { "body": "<p>Before spending too much time optimizing the if's and for's, check if it will make any difference at all.</p>\n\n<pre><code>var queueIndexes = new List&lt;int&gt;();\n</code></pre>\n\n<p>In your inner loop:</p>\n\n<pre><code>//Queues[t].Send(QueueMessage)\nqueueIndexes.Add(t);\n</code></pre>\n\n<p>Then time this code:</p>\n\n<pre><code>foreach(var t in queueIndexes) {\n Queues[t].Send(QueueMessage);\n}\n</code></pre>\n\n<p>The above for loop is as fast as you can get. How does this compare with the original? This will tell you if it's worth optimizing.</p>\n\n<p>As a side note, I find it odd that you only use \"t\" from the outer loop, and don't do anything with the information from the inner loop, other than deciding whether to call Send. Is that intentional?</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-09-09T13:08:20.170", "Id": "49304", "Score": "0", "body": "I also find it odd, but what this two loops are acomplishing is to replicate one message in many different queues as many times as needed (consider one message that arrives and needs to be notified to different clients)" } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-09-08T10:10:13.893", "Id": "30947", "ParentId": "30881", "Score": "5" } } ]
{ "AcceptedAnswerId": "30894", "CommentCount": "10", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-09-06T14:45:05.193", "Id": "30881", "Score": "7", "Tags": [ "c#", "performance", "linq" ], "Title": "How to optimize these nested loops for better performance?" }
30881
<p>The array is dynamic, can be with 7 or more keys, except the first key never changes.</p> <pre><code>Array ( [0] =&gt; Array ( [ProviderID] =&gt; 1010 [ProviderName] =&gt; HAMZEPOUR, SHOKOUFEH ) [1] =&gt; Array ( [ContactName] =&gt; ABC XYZ [Address1] =&gt; New York [AddressType] =&gt; Physical ) [2] =&gt; Array ( [ContactName] =&gt; ABC XYZ [Address1] =&gt; New York [AddressType] =&gt; Billing ) [3] =&gt; Array ( [ContactName] =&gt; ABC XYZ [Address1] =&gt; New York [AddressType] =&gt; Mailing ) [4] =&gt; Array ( [AlgorithmID] =&gt; 1 [AlgoTitle] =&gt; Retro-Term ) [5] =&gt; Array ( [AlgorithmID] =&gt; 2 [AlgoTitle] =&gt; Modifier 25 errors ) [6] =&gt; Array ( [HoldType] =&gt; HoldType [StatusID] =&gt; 1 ) [7] =&gt; Array ( [HoldType] =&gt; HoldType [StatusID] =&gt; 1 ) [8] =&gt; Array ( [HoldType] =&gt; Hold [StatusID] =&gt; 2 ) ) </code></pre> <p>The first array is what I fetch from db as result of SP with four result sets</p> <p>I'm doing this:</p> <pre><code> $newArray = array(); foreach($array as $arr) { $keys = array_keys($arr); switch($keys[0]) { case "PORAProviderID": if(!isset($newArray["ProviderInfo"])) { $newArray["ProviderInfo"] = array(); } $newArray["ProviderInfo"]["PORAProviderID"] = $arr["PORAProviderID"]; $newArray["ProviderInfo"]["ProviderName"] = $arr["ProviderName"]; break; case "ContactName": if(!isset($newArray["ProviderAddress"])) { $newArray["ProviderAddress"] = array(); } $newArray["ProviderAddress"][$arr['AddressType']] = array(); $newArray["ProviderAddress"][$arr['AddressType']]["ContactName"] = $arr["ContactName"]; $newArray["ProviderAddress"][$arr['AddressType']]["Address1"] = $arr["Address1"]; $newArray["ProviderAddress"][$arr['AddressType']]["AddressType"] = $arr["AddressType"]; break; case "AlgorithmID": if(isset($newArray["ProviderAlgorithm"])) { $count = count($newArray["ProviderAlgorithm"]); } else { $newArray["ProviderAlgorithm"] = array(); $count = 0; } $newArray["ProviderAlgorithm"][$count] = array(); $newArray["ProviderAlgorithm"][$count]["AlgorithmID"] = $arr["AlgorithmID"]; $newArray["ProviderAlgorithm"][$count]["AlgoTitle"] = $arr["AlgoTitle"]; break; case "HoldType": if(isset($newArray["ProviderException"])) { $count = count($newArray["ProviderException"]); } else { $newArray["ProviderException"] = array(); $count = 0; } $newArray["ProviderException"][$count] = array(); $newArray["ProviderException"][$count]["HoldType"] = $arr["HoldType"]; $newArray["ProviderException"][$count]["StatusID"] = $arr["StatusID"]; break; } } </code></pre> <p>And this is what I'm getting:</p> <pre><code> Array ( [ProviderInfo] =&gt; Array ( [PORAProviderID] =&gt; 1010 [ProviderName] =&gt; HAMZEPOUR, SHOKOUFEH ) [ProviderAddress] =&gt; Array ( [Physical] =&gt; Array ( [ContactName] =&gt; ABC XYZ [Address1] =&gt; New York [AddressType] =&gt; Physical ) [Billing] =&gt; Array ( [ContactName] =&gt; ABC XYZ [Address1] =&gt; New York [AddressType] =&gt; Billing ) [Mailing] =&gt; Array ( [ContactName] =&gt; ABC XYZ [Address1] =&gt; New York [AddressType] =&gt; Mailing ) ) [ProviderAlgorithm] =&gt; Array ( [0] =&gt; Array ( [AlgorithmID] =&gt; 1 [AlgoTitle] =&gt; Retro-Term ) [1] =&gt; Array ( [AlgorithmID] =&gt; 2 [AlgoTitle] =&gt; Modifier 25 errors ) ) [ProviderException] =&gt; Array ( [0] =&gt; Array ( [HoldType] =&gt; HoldType [StatusID] =&gt; 1 ) [1] =&gt; Array ( [HoldType] =&gt; HoldType [StatusID] =&gt; 1 ) [2] =&gt; Array ( [HoldType] =&gt; Hold [StatusID] =&gt; 2 ) ) ) </code></pre> <p>It's the best way to reorganize the array</p>
[]
[ { "body": "<p>The answer depends on what you want when you say 'efficient'. In my opinion, you should be using either a stdClass object with an array of Contacts, an array of Algorithms, etc. This will be more memory-intensive, but unless you are running in crazy looping structures then you will not notice any performance hit. What you would be gaining is readability and maintainability, which is far more valuable down the road.</p>\n\n<p>Of course, if you are hitting a specific bottleneck for which you feel that you need \"more efficient code\" then please do describe the issue.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-09-08T10:24:48.003", "Id": "30949", "ParentId": "30884", "Score": "1" } }, { "body": "<p>This function can be used for array with <code>n</code> length</p>\n\n<pre><code> $key_search = array(\n 'PORAProviderID' =&gt; 'ProviderInfo',\n 'ContactName' =&gt; 'ProviderAddress',\n 'HoldType' =&gt; 'ProviderException',\n 'AlgorithmID' =&gt; 'ProviderAlgorithm'\n);\n\n/**\n* Reorganize array by categories\n* @param array $array\n* @param array $key_search keyToSearch=&gt;NewArrayKey\n* @return array \n*/\nfunction organizeArray($array, $key_search) {\n $new_array = array();\n if (count($array) == count($array, COUNT_RECURSIVE)) {\n //single array\n foreach ($key_search as $key =&gt; $key_data) {\n if (array_key_exists($key, $array)) {\n $new_array[$key_data] = array($array);\n } \n }\n } else {\n //nested array\n foreach ($array as $array_data) {\n foreach ($key_search as $key =&gt; $key_data) {\n if (array_key_exists($key, $array_data)) {\n if (isset($new_array[$key_data])) {\n $temp = $new_array[$key_data];\n array_push($temp, $array_data);\n $new_array[$key_data] = $temp;\n }else\n $new_array[$key_data] = array($array_data);\n }\n }\n }\n }\n return $new_array;\n}\n\n\n $array = array(\n 0 =&gt; array\n (\n 'PORAProviderID' =&gt; '1010',\n 'ProviderName' =&gt; 'HAMZEPOUR, SHOKOUFEH',\n ),\n 1 =&gt; array\n (\n 'ContactName' =&gt; 'ABC XYZ',\n 'Address1' =&gt; 'New York',\n 'AddressType' =&gt; 'Physical'\n ),\n 2 =&gt; array\n (\n 'ContactName' =&gt; 'ABC XYZ',\n 'Address1' =&gt; 'New York',\n 'AddressType' =&gt; 'Billing'\n ),\n 3 =&gt; array\n (\n 'ContactName' =&gt; 'ABC XYZ',\n 'Address1' =&gt; 'New York',\n 'AddressType' =&gt; 'Mailing'\n ),\n 4 =&gt; array\n (\n 'AlgorithmID' =&gt; 1,\n 'AlgoTitle' =&gt; 'Retro-Term'\n ),\n 5 =&gt; array\n (\n 'AlgorithmID' =&gt; 1,\n 'AlgoTitle' =&gt; 'Retro-Term'\n ),\n 6 =&gt; array\n (\n 'HoldType' =&gt; 'HoldType',\n 'StatusID' =&gt; 1\n ),\n 7 =&gt; array\n (\n 'HoldType' =&gt; 'HoldType',\n 'StatusID' =&gt; 1\n ),\n 8 =&gt; array\n (\n 'HoldType' =&gt; 'Hold',\n 'StatusID' =&gt; 2\n )\n );\n</code></pre>\n\n<p>Otuput</p>\n\n<pre><code>print_r(organizeArray($array, $key_search));\n</code></pre>\n\n<hr>\n\n<pre><code>Array\n(\n [ProviderInfo] =&gt; Array\n (\n [0] =&gt; Array\n (\n [PORAProviderID] =&gt; 1010\n [ProviderName] =&gt; HAMZEPOUR, SHOKOUFEH\n )\n\n )\n\n [ProviderAddress] =&gt; Array\n (\n [0] =&gt; Array\n (\n [ContactName] =&gt; ABC XYZ\n [Address1] =&gt; New York\n [AddressType] =&gt; Physical\n )\n\n [1] =&gt; Array\n (\n [ContactName] =&gt; ABC XYZ\n [Address1] =&gt; New York\n [AddressType] =&gt; Billing\n )\n\n [2] =&gt; Array\n (\n [ContactName] =&gt; ABC XYZ\n [Address1] =&gt; New York\n [AddressType] =&gt; Mailing\n )\n\n )\n\n [ProviderAlgorithm] =&gt; Array\n (\n [0] =&gt; Array\n (\n [AlgorithmID] =&gt; 1\n [AlgoTitle] =&gt; Retro-Term\n )\n\n [1] =&gt; Array\n (\n [AlgorithmID] =&gt; 1\n [AlgoTitle] =&gt; Retro-Term\n )\n\n )\n\n [ProviderException] =&gt; Array\n (\n [0] =&gt; Array\n (\n [HoldType] =&gt; HoldType\n [StatusID] =&gt; 1\n )\n\n [1] =&gt; Array\n (\n [HoldType] =&gt; HoldType\n [StatusID] =&gt; 1\n )\n\n [2] =&gt; Array\n (\n [HoldType] =&gt; Hold\n [StatusID] =&gt; 2\n )\n\n )\n\n)\n</code></pre>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-09-19T23:13:08.123", "Id": "31567", "ParentId": "30884", "Score": "0" } } ]
{ "AcceptedAnswerId": "31567", "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-09-06T16:21:53.317", "Id": "30884", "Score": "0", "Tags": [ "php", "array", "php5" ], "Title": "Is this an efficient way of organize an array?" }
30884
<p>I previously posted a <a href="https://codereview.stackexchange.com/questions/30764/review-of-reservoir-sampling">Reservoir-Sampling program</a>, which was basically a test version of this one. This is an assignment. In the code below, I use <code>RunTimeException</code> to control when scanner finishes reading data. Reasons for this being:</p> <ol> <li>I cannot use any other library than java.lang. </li> <li>I cannot use Scanner, either. We have been provided a StdIn class which has a static <code>scanner.next()</code> method only for reading strings.</li> </ol> <p><strong>Note</strong>: All the code is inside <code>main()</code> because that is how the API demands it. </p> <p>Can someone review my code, and possibly tell if there's some way I can improve this?</p> <pre><code>import java.io.BufferedInputStream; import java.util.Scanner; public class Subset { public static void main(String[] args) { int k = Integer.parseInt(args[0]); String[] arr = new String[k]; int i = 0; String str; while((str=stdin.readString())!=null &amp;&amp; i &lt; arr.length){ arr[i++] = str; // System.out.println(str); } try{ for(; (str=stdin.readString())!=null; i++){ int r = (int)(Math.random()*(i + 1)); if(r &lt; k){ arr[r] = str; //System.out.println(str); } } }catch(RuntimeException e){ // do nothing } for(String s : arr){ System.out.print(s + " "); } System.out.println("\n"); } } class stdin{ private stdin(){} private static Scanner sc = new Scanner(new BufferedInputStream(System.in)); public static String readString(){ return sc.next(); } } </code></pre> <p><strong>Command line input</strong>: <code>echo A B C D E F G H I J | java Subset 3</code><br> <strong>Output:</strong> <code>A F C</code> </p> <p>To clear out confusion, I am posting what the API and the instructor demands:</p> <pre class="lang-none prettyprint-override"><code>Subset client. Write a client program Subset.java that takes a command-line integer k, reads in a sequence of N strings from standard input using StdIn.readString(), and prints out exactly k of them, uniformly at random. Each item from the sequence can be printed out at most once. You may assume that k = 0 and no greater than the number of string on standard input. % echo A B C D E F G H I | java Subset 3 % echo AA BB BB BB BB BB CC CC | java Subset 8 C BB G AA A BB CC % echo A B C D E F G H I | java Subset 3 BB E BB F CC G BB Your client should use only constant space plus one object either of type Deque or of type RandomizedQueue; use generics properly to avoid casting and compiler warnings. It should also use time and space proportional to at most N in the worst case, where N is the number of strings on standard input. (For an extra challenge, use space proportional to k.) It should have the following API. public class Subset { public static void main(String[] args) } </code></pre>
[ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-09-06T19:16:37.863", "Id": "49162", "Score": "0", "body": "Well possibly the task is bananas. Could you edit the post with what you are trying to achieve and the exact limitations of the question. If `stdin` is nothing to do with your solution maybe delete it and define the interface you have been given. A few easy things to tidy up though are the naming, there is no limit of characters - i, r, k, s do not convey enough information. Making it clear regarding the unusual reuse of `i`. Using a `while` loop in the second instance once we've discovered that `i` is being weirdly used. Are you just picking a random sample of 3 from stdin?" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-09-06T19:20:38.240", "Id": "49163", "Score": "0", "body": "Just saw your edit. There are some excellent answers on the other thread. Sorry I know nothing about Resevoir Sampling but it seems that you got some great feedback. The use of the RTE is wrong, if you could update the question to make it very clear why you have to use it, and why everything has to be in the main method (as if required a separate function that catches the RTE, logs it (in your case as `Unusual termination of stream` to System.out I guess) and returns null to terminate your loop in the manner intended." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-09-06T19:21:13.130", "Id": "49164", "Score": "0", "body": "I'v edited my original post a bit. What i'm trying to do here is implement [Reservoir Sampling](http://en.wikipedia.org/wiki/Reservoir_sampling)\n\nedit : i know ,those were great solutions , but im stuck with this api. And iv never used exceptions to control flow. So i was asking if that part was ok..\nbtw, what is RTE ?" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-09-06T19:27:38.263", "Id": "49165", "Score": "0", "body": "The entire structure is because of the api that i have to maintain. This is an assignment for a princeton MOOC going on at coursera , and the api they gave allows only the main() method. Trust me , It was a pain to mould to the api." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-09-06T19:50:54.003", "Id": "49170", "Score": "0", "body": "You said `I cannot use any other library than java.lang`. Then why are you using `java.io` and `java.util`?" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-09-06T19:52:20.197", "Id": "49171", "Score": "0", "body": "I think that the 'stdin' class is a distraction which is why I suggested it were removed from the example." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-09-06T19:54:30.463", "Id": "49172", "Score": "0", "body": "@tintinmj i also mentioned that iv created the stdin class as a stand in for the class provided to us , and to make this an SSCCE. Im editing this back to the actual thing. SSCCE attempt is causing more confusion i suppose." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-09-07T08:47:32.807", "Id": "49199", "Score": "2", "body": "You have misunderstood at least some of the question, just because your public API is limited to the main method I do not see a restriction on what you can do beyond that. I do not see a restriction on Java packages either. So now, are you sure StdIn doesn't have a hasNext() method too?" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-09-07T09:19:08.507", "Id": "49201", "Score": "0", "body": "I feel extremely embarrassed to say that it does. I searched so many times in that class , i only found it now , inside a method called isEmpty(). Kindly accept my apology. Problem solved i guess." } ]
[ { "body": "<p>Finished in the comments, can you post the part of the assignment question pertinent to your limited library usage and main method only code? Anyway, if you have been told that a RTE will signify the end of the reading (rather than the null) then this seems marginally better as it makes it clear why you are doing what you are doing:</p>\n\n<pre><code>while (true) {\n try {\n str = stdin.readString();\n if (str == null) {\n break;\n }\n int r = (int)(Math.random()*(i++ + 1));\n if(r &lt; k){\n arr[r] = str;\n }\n }\n catch(RuntimeException rte) {\n //Log the crazy break condition\n break;\n }\n} \n</code></pre>\n\n<p>It is always a discussion point whether <code>while(true)</code> is acceptable and is normally held up against using a <code>running</code> loop variable. In this case you can intialise a boolean to true and use it as your while condition - setting it to false where the <code>break</code>s are. It involves extra checks, and makes for harder to read code in my eyes, but hey!</p>\n\n<p>Now, give your variables meaningful names.</p>\n\n<p><strong>EDIT: Post clarification in the comments</strong></p>\n\n<p>So importantly you do not know the length of the input but you want to randomly sample it, and a RumtimeException is unexpected and can make your code blow up? In which case why anymore complex than this?:</p>\n\n<pre><code>public class Subset {\n\n public static void main(String[] args) {\n int sampleSize = Integer.parseInt(args[0]);\n String[] samples = new String[sampleSize];\n int current = 0;\n String str; \n\n //make sure you have at least sampleSize number of samples\n while((str=stdin.readString())!=null &amp;&amp; current &lt; sampleSize){\n samples[current++] = str;\n }\n\n //this will read until the end of the input\n while((str=stdin.readString())!=null) {\n int randomIndex = (int)(Math.random()*(current++));\n if(randomIndex &lt; sampleSize){\n samples[randomIndex] = str;\n }\n }\n\n for(String sample : samples){\n System.out.print(sample + \" \");\n }\n System.out.println(\"\\n\");\n }\n}\n</code></pre>\n\n<p><strong>EDIT post comments</strong>\nIn your original question on <a href=\"https://codereview.stackexchange.com/questions/30764/review-of-reservoir-sampling\">Reservoir Sampling</a> it was important to add <code>+1</code> to you possible random number as you wanted to pick a value from an array of known size without excluding the final element . However in this version you are using the random number to dictate (with decreasing probability of a hit) where to write the next value read from <code>Stdin</code> into your array of samples.</p>\n\n<p>If you know that the <code>Stdin</code> implementation and that it will through an Exception and that is the only thing you have been told or advised will signify an end to the data (no special characters, no nulls, no maximum length, etc) then the only thing that you can do is catch and handle it and that is perfectly acceptable - in this instance it is not really an Exception condition, it is the norm! Maybe he exercise is in working with bad APIs (which is very common)!</p>\n\n<p>In the latest (very different) version of your code you have this:</p>\n\n<pre><code>for(; ; i++){ \n int randomIndex = (int)(Math.random()*(i + 1));\n if(randomIndex &lt; sampleSize){\n sample[randomIndex] = StdIn.readString();\n }\n }\n</code></pre>\n\n<p>You should replace this with code more like my first example where the exception state is handled within the loop. So:</p>\n\n<ul>\n<li>Replace <code>for</code> loop with <code>while</code> loop</li>\n<li>Because you are using the <code>randomIndex</code> to determine whether to read a value at all into the array you are no longer random sampling, you are just random inserting. Every value read from the pool will get written to the array. It is also important that this could run for a long time or more likely run to an error state when i > MAX_INT, which would be possible with a large dataset and a small sample.</li>\n</ul>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-09-06T20:24:15.187", "Id": "49177", "Score": "0", "body": "[the docs](http://docs.oracle.com/javase/7/docs/api/java/util/Scanner.html#next()) dont say anything about a `null` getting returned , so i went the way of the RTE.( I cant use `NoSuchElementException` as its part of the \"forbidden\" `java.util` pack)" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-09-06T20:51:23.790", "Id": "49179", "Score": "0", "body": "How do you know it is a scanner? Why does your code already have this test `(str=stdin.readString())!=null` and what makes you think a RTE will be thrown (other than that the Scanner API says it might, but how do you know it is a scanner?), you could just be blocking forever :)" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-09-07T04:11:29.323", "Id": "49192", "Score": "0", "body": "in your code . `int randomIndex = (int)(Math.random()*(current++));` this should be `(++current)` , else the last position will never be reached. Also , by the docs , When scanner reads past the last valid token , and tries to read again , It Throws the `NoSuchElementException`. Have you run the edited version you posted above from command line ? I ask this because when i tried to run your suggestion , it throws NSEE and exits. quite understandable i suppose." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-09-07T06:54:13.737", "Id": "49195", "Score": "0", "body": "There is more to your question than you have said. My postfix increment will not affect how far into the data you can read as all it is used for is decreasing the likelihood of inserting something into the array. Your updated code above does something different too, it writes every value from stdin into the array, which I believe is wrong. Use the code I first posted to avoid the exception." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-09-07T09:22:00.940", "Id": "49202", "Score": "0", "body": "I'm looking into the last point you said about the random sampling part. Thanks a lot for pointing these things out." } ], "meta_data": { "CommentCount": "5", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-09-06T19:54:55.410", "Id": "30892", "ParentId": "30888", "Score": "2" } }, { "body": "<p>Before we deal with style, let's consider the substance. I don't think that the following code leads to unbiased sampling as you intend:</p>\n\n<pre><code>for(; ; i++){ \n int randomIndex = (int)(Math.random()*(i + 1));\n if(randomIndex &lt; sampleSize){\n sample[randomIndex] = StdIn.readString();\n }\n}\n</code></pre>\n\n<p>That raises the issue, are you not able to reuse the classes already developed from your previous exercise? In software development, it would be much preferable to call existing code than to reimplement an algorithm using copy-and-paste. Had you done so, this sampling error would have been avoided completely.</p>\n\n<p>Next, I question your statement</p>\n\n<blockquote>\n <p>All the code is inside the main() because that is how the api demands it.</p>\n</blockquote>\n\n<p>As I <a href=\"https://codereview.stackexchange.com/questions/30764/review-of-reservoir-sampling?lq=1#comment49017_30808\">commented in the previous exercise</a>, the API demands that your <code>main()</code> take a single string parameter that will be parsed as an integer representing the number of samples to take, out of the pool of data that will be read from standard input. The API does not demand that all of your code live inside <code>main()</code>. (Your <em>instructor</em> might demand it, but that would just be silly, in my opinion.)</p>\n\n<p>To address your specific question of flow control, catching <code>RuntimeException</code> is a horrible idea. It's much too unspecific; who knows what kind of <code>RuntimeException</code> actually triggered the premature termination of your loop? Furthermore, it's unclear to anyone looking at the code that it is the intended behaviour; exceptions (especially <code>RuntimeException</code>s) usually signify for unexpected events. Let's face it, you're catching <code>RuntimeException</code> instead of <code>NoSuchElementException</code> to work around the silly artificial constraint of your exercise that you must not use anything outside <code>java.lang.*</code>.</p>\n\n<p>The correct way to detect the end of input from <code>java.util.Scanner</code> is to call <code>Scanner.hasNext()</code>, and the next best way is to catch <code>NoSuchElementException</code>. If both of those options are artificially closed off from you, then your question is dangerously close to being <a href=\"https://codereview.stackexchange.com/help/on-topic\">off-topic</a> for this site, as it would violate the \"Do I want the code to be good code\" rule.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-09-07T08:41:46.887", "Id": "49198", "Score": "0", "body": "Thank you for the detailed answer. The rules imposed are really something i had a hard time working around. I understand what you say about `hasNext()` and `NoSuchElementException`. I also understand the problem posed by RunTimeException. I shall raise these topics in the course discussion forums. Thank you all for your answers.\n\nRegarding the unbiased sampling part , why do you say that ? ill try plotting out some data for convincing evidence." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-09-07T09:18:31.200", "Id": "49200", "Score": "0", "body": "@JohnMark13 explained the sampling error in more detail than I would have, considering that this is a homework problem. I would simply have asked you, what is the maximum possible value of *i* in your original code? and the maximum possible *i* in this exercise?" } ], "meta_data": { "CommentCount": "2", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-09-07T08:11:37.590", "Id": "30908", "ParentId": "30888", "Score": "1" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "9", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-09-06T18:38:21.857", "Id": "30888", "Score": "2", "Tags": [ "java", "homework", "error-handling" ], "Title": "Exceptions to control data read flow" }
30888
<p>I'm trying to design a <code>Shader</code> class. For now, I'm just trying to get basic outline for handling uniforms. Some design goals I aimed for is to avoid passing a string to a function as this is error prone and has no type checking. There's really only one place this can go wrong: if you mistype the name of the uniform when defining it.</p> <p>There is a lot of potential for code bloat. I could potentially move the <code>Name</code> out of the template parameters for <code>Parameter</code> and store it as a member variable, which would get assigned in the default constructor.</p> <pre><code>template&lt;typename ParamType&gt; class Shader { public: template&lt;typename Type, const char* (*Name)()&gt; class Parameter { static const char* name; static GLuint location; static GLuint program; template&lt;typename&gt; friend class Shader; }; template&lt;typename Type, const char* (*Name)()&gt; void SetParameter(const Parameter&lt;Type,Name&gt;&amp;, const Type&amp; value ) { // static_assert(!std::is_same&lt;Type,Type&gt;::value, "Unsupported type, needs specialization."); typedef Parameter&lt;Type,Name&gt; Param; if(program != -1 &amp;&amp; Param::program != program) { // set Param::location Param::program = program; } std::cout &lt;&lt; Param::name &lt;&lt; std::endl; } private: GLuint program; }; template&lt;typename ParamType&gt; template&lt;typename Type, const char* (*Name)()&gt; const char* Shader&lt;ParamType&gt;::Parameter&lt;Type, Name&gt;::name = Name(); template&lt;typename ParamType&gt; template&lt;typename Type, const char* (*Name)()&gt; GLuint Shader&lt;ParamType&gt;::Parameter&lt;Type, Name&gt;::program = -1; #include "shaderparameters.inl" </code></pre> <p><strong>shaderparameters.inl:</strong></p> <pre><code>#define MY_PARAMETER(shader, type, name) \ private: static const char* ShaderParameterStr##shader##type##name##() { return #name ; } \ public: typedef Shader&lt; shader &gt;::Parameter&lt; type, &amp;ShaderParameterStr##shader##type##name &gt; name; struct ShaderParam { struct Generic { MY_PARAMETER( Generic, Vec4, position ) MY_PARAMETER( Generic, Mat4, projection ) }; }; #undef MY_PARAMETER </code></pre> <p><strong>Usage:</strong></p> <pre><code>Shader&lt;ShaderParam::Generic&gt; s; s.SetParameter(ShaderParam::Generic::projection(), Mat4()); s.SetParameter(ShaderParam::Generic::position(), Vec4()); </code></pre> <p>What are you thoughts on this implementation? Do you have suggestions for improvements or perhaps an entirely different system?</p> <p>I know I've seen people use hash maps and such, but there's still the problem of continuously using a string literal to set the uniforms and such (I don't really like the thought of using a Macro to define the string, either).</p>
[]
[ { "body": "<blockquote>\n <p>What are you thoughts on this implementation?</p>\n</blockquote>\n\n<p>It is simply awful. Besides code bloat, just look how you declare such objects, and how you call methods on such objects.</p>\n\n<blockquote>\n <p>Do you have suggestions for improvements or perhaps an entirely different system?</p>\n</blockquote>\n\n<p>So, to fix your implementation :</p>\n\n<ul>\n<li>add an interface for your Shader class. Like that, you can have different shader classes for vertex, geometric and pixel shaders</li>\n<li>remove all templates</li>\n<li>pass the shader's program id to constructor, and remove it from the Parameter class</li>\n<li>move 'class Parameter' out of the 'class Shader', and make it a structure. It's member variables do not need to be static. By the way, name should be <code>std::string</code> - not <code>const char*</code></li>\n</ul>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-09-23T23:30:33.290", "Id": "50597", "Score": "0", "body": "I think it is rather elegant how it all works, there is code bloat, but as I've said it can be reduced quite significantly. You miss the point of why this was done in the first place. The only difference between shaders are the values passed to them, creating a new class for every shader and defining functions to set each parameter is redundant. Shader's program exists in Parameter incase the context is destroyed along with the shader and the shader needs to be reloaded and thus the Parameter location. It shouldn't be std::string, you'd just be wasting twice as much memory." } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-09-07T22:30:30.387", "Id": "30933", "ParentId": "30893", "Score": "2" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-09-06T20:02:58.757", "Id": "30893", "Score": "4", "Tags": [ "c++", "classes", "opengl" ], "Title": "Shader class implementation" }
30893
<p>I wrote this class to make cookie management easier.</p> <p>I know it makes use of <code>serialize()</code>, but I have no intention of storing very much data in the cookie, and it seemed a cleaner solution than, say, the JSON functions (like, even if a class implements the <code>JSONSerializable</code> interface, it doesn't retain the class name by default, etc.). <code>serialize()</code> seemed more robust, although if there's a way to compress the output without it losing its integrity, please share. Probably the worst pitfall is that, if the cookie is messed with, <code>unserialize()</code> will trigger a notice and who knows what else -- but I don't feel I need to cater to the user experience of users who mess with cookies. (Although if the cookie is maxed out at a number of bytes, like 4,096, and it truncates, that could be an issue....)</p> <p>I am in the process of writing a class to put on top of this one for managing user sessions implementing <a href="https://codereview.stackexchange.com/questions/2715/critique-request-php-cookie-library">Charles Miller's solution</a>.</p> <p>I decided against implementing exceptions because it was simple enough to just return constants.</p> <pre><code>&lt;?php /** * Cookie.class.php, the Cookie class * * Contains a class for making cookies easier to manage via PHP * @author Miller &lt;wyattstorch42 at outlook dot com&gt; * @version 1.0 * @package Miller * @subpackage Utils */ namespace Miller\Utils; if (!function_exists('array_copy')) { /** * array_copy Properly and recursively clones an array * @param array $source The original array * @return array The clone */ function array_copy ($source) { $return = array (); $keys = array_keys($source); $values = array_values($source); for ($i = 0; $i &lt; count($keys); ++$i) { if (is_object($values[$i])) { $return[$keys[$i]] = clone $values[$i]; } else if (is_array($values[$i])) { $return[$keys[$i]] = array_copy($values[$i]); } else { $return[$keys[$i]] = $values[$i]; } } return $return; } } /** * A class for making cookies easier to manage via PHP * @package Miller\Utils */ class Cookie { /** * Class constants * SESSION, EXPIRE, DAY, WEEK, MONTH, and YEAR are used to define the life of the cookie * ERROR_HEADERS_SENT, ERROR_SET_COOKIE, and ERROR_NONE are possible return values for the sent() method. */ const SESSION = 0, EXPIRE = -3600, DAY = 86400, WEEK = 604800, MONTH = 2592000, YEAR = 31536000, ERROR_HEADERS_SENT = -1, ERROR_SET_COOKIE = -2, ERROR_NONE = 1; protected /** * Holds the name of the cookie * @var string */ $name, /** * Holds the expiration timestamp of the cookie * @var integer */ $expiry, /** * Holds the path of the cookie * @var string */ $path, /** * Holds the domain of the cookie * @var string */ $domain, /** * A flag that sets the secure option for the cookie * @var boolean */ $secure, /** * A flag that sets the httponly option for the cookie * @var boolean */ $httponly, /** * An array that holds the current unserialized properties stored in the cookie * @var array */ $properties, /** * An array that holds the properties that will be stored and serialzed in the cookie on send() * @var string */ $internalProperties; public function __construct ($name, $expiry = self::WEEK, $path = '', $domain = '', $secure = null, $httponly = false) { /** * Constructor * @param string $name The name of the cookie * @param null|integer|string $expiry The expiration timestamp of the cookie (if null, sets a session cookie; if string, converts using strtotime()) * @param string $path The path of the cookie * @param string $domain The domain of the cookie * @param null|boolean $secure The flag that sets the secure option for the cookie (if null, sets to true if $_SERVER['HTTPS'] is set, false otherwise) * @param boolean $httponly The flag that sets the httponly option for the cookie */ $this-&gt;name = (string) $name; if ($expiry === self::SESSION) { $this-&gt;expiry = $expiry; } else if (is_numeric($expiry)) { $this-&gt;expiry = time()+$expiry; } else { $this-&gt;expiry = strtotime($expiry); } $this-&gt;path = (string) $path; $this-&gt;domain = (string) $domain; $this-&gt;secure = $secure === null ? isset($_SERVER['HTTPS']) &amp;&amp; $_SERVER['HTTPS'] : (bool) $secure; $this-&gt;httponly = (bool) $httponly; $this-&gt;properties = array (); $this-&gt;internalProperties = array (); if (isset($_COOKIE[$this-&gt;name])) { $properties = unserialize($_COOKIE[$this-&gt;name]); $this-&gt;internalProperties = array_copy($properties); $this-&gt;properties = array_copy($properties); } } public function exists () { /** * Checks if the cookie was sent from the last browser request * @return bool True if the cookie is set, false otherwise */ return (bool) $this-&gt;properties; } public function __isset ($property) { /** * Checks if the given property is set on the cookie * @param string $property The property key * @return bool True if the property is set, false otherwise */ return isset($this-&gt;properties[$property]); } public function __get ($property) { /** * Returns the value of the given property on the cookie * @param string $property The property key * @return bool The value of the property if it is set, null otherwise (use __isset() to differentiate a null value from an undefined value) */ return $this-&gt;__isset($property) ? $this-&gt;properties[$property] : null; } public function __set ($property, $value) { /** * Sets or overrides the given property (will not be accessible until the cookie is sent) * @param string $property The property key * @param mixed $value The value * @return void */ $this-&gt;internalProperties[$property] = $value; } public function __unset ($property) { /** * Unsets the given property (will not be accessible until the cookie is sent) * @param string $property The property key * @return void */ if (isset($this-&gt;internalProperties[$property])) { unset($this-&gt;internalProperties[$property]); } } public function send () { /** * Serializes the properties and sends the cookie to the browser. On success, updates the values of the properties. * @return integer ERROR_HEADERS_SENT if the headers have already been sent, ERROR_SET_COOKIE if the setcookie() function failed, or ERROR_NONE on success */ if (headers_sent()) { return self::ERROR_HEADERS_SENT; } $value = $this-&gt;expiry === self::SESSION ? false : serialize($this-&gt;internalProperties); if (setcookie($this-&gt;name, $value, $this-&gt;expiry, $this-&gt;path, $this-&gt;domain, $this-&gt;secure, $this-&gt;httponly)) { $this-&gt;properties = array_copy($this-&gt;internalProperties); return self::ERROR_NONE; } return self::ERROR_SET_COOKIE; } } ?&gt; </code></pre> <p>Example usage:</p> <pre><code>&lt;?php namespace Miller\Utils; error_reporting(E_ALL); require 'Cookie.class.php'; ob_start(); $cookie = new Cookie('example_cookie', Cookie::SESSION); var_dump($cookie-&gt;exists()); // true if cookie is stored in the browser already, false otherwise var_dump(isset($cookie-&gt;example_prop)); // true if example_prop exists in cookie, false otherwise var_dump($cookie-&gt;example_prop); // the value of example_prop, or null if it is not set $cookie-&gt;example_prop = 123; var_dump($cookie-&gt;example_prop); // will still be the previous value, because the cookie hasn't been sent var_dump($cookie-&gt;example_prop_2); // the value of example_prop_2, or null if it is not set unset($cookie-&gt;example_prop_2); var_dump($cookie-&gt;example_prop_2); // will still be previous value, because cookie hasn't been sent $cookie-&gt;current_time = new \DateTime('now', new \DateTimeZone('America/Phoenix')); // will serialize objects using PHP native function and unserialize automatically var_dump($cookie-&gt;send()); // -1, -2, or 0 (ERROR_HEADERS_SENT, ERROR_SET_COOKIE, or ERROR_NONE) var_dump($cookie-&gt;example_prop); // if send() was successful, this will now be 123 var_dump(isset($cookie-&gt;example_prop_2)); // if send() was successful, this will now be false var_dump($cookie-&gt;current_time); // if send() was successful, this will now be the recorded time ob_end_flush(); ?&gt; </code></pre>
[ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-09-07T16:51:56.357", "Id": "49219", "Score": "0", "body": "Don't use the closing `?>` in definition files (PHP recommends not using the closing tag!). If a file is called `something.class.php`, I'd expect it to contain _only_ a class definition, not functions, too... Implement one of the `Travesable` interfaces, so you can use the _real_ `isset`, not your pseudo-magic `__isset` method" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-09-08T02:12:40.763", "Id": "49246", "Score": "0", "body": "@EliasVanOotegem: I think your comment would be worth an answer (with some references). I'd upvote it." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-09-09T08:10:55.280", "Id": "49292", "Score": "0", "body": "@palacsint: Posted a rand/answer there's quite a lot more that needs doing in this code, come to think of it... sorry if I put things bluntly, but [You have to, when doing code-review](http://meta.codereview.stackexchange.com/questions/810/guidelines-for-new-users-proposal-tag)" } ]
[ { "body": "<p>First off, I've posted a fairly length answer on the subject of request classes, which can be found <a href=\"https://codereview.stackexchange.com/questions/29469/critique-request-php-request-method-class/29485#29485\">here</a>. Because you state you're thinking of writing a <code>Session</code> class on top of this one, I'm posting a link to my answer here.<br/>\nIn that answer, I discuss what you should keep in mind when doing so. For example: using setters and getters, sanitize all request data etc...</p>\n\n<p>Then, as I said in the comment, I noticed you're using the <code>?&gt;</code> closing tag, which is optional. Omitting it, especially in those files that will be <code>include</code> or <code>require</code>-ed is considered <em>good practice</em>. It's, amoungst other things, to avoid excess whitespace. <a href=\"http://www.php.net/basic-syntax.instruction-separation\" rel=\"nofollow noreferrer\">Read more here</a><br/>\nAnother part of <em>good practice</em> is to write the doc-blocks just <em>before</em> the method definition, not in the function body. As soon as you start using <a href=\"http://www.php.net/manual/en/class.reflectionclass.php\" rel=\"nofollow noreferrer\">the <code>ReflectionClass</code></a> (especially the <code>getDocBlock</code> method), you'll see the value of this. Even if you don't use it, other libs might (like <code>Doctrine</code> to name one, not unimportant example)</p>\n\n<p>You're also defining a method called <code>__isset</code>. The double underscore would suggest this is a magic-method, that enables the user of this class to write something like:</p>\n\n<pre><code>if (isset($instance['cookieName']))\n</code></pre>\n\n<p>And that php will convert that into <code>if ($instance-&gt;__isset('cookieName'))</code>. That's not the case. The magic <code>isset</code> method only works when you write <code>isset($instance-&gt;cookieName)</code>, which, to all intents and purpouses still is a different syntax.<br/>\nIf I were in your shoes, I'd implement a <a href=\"http://www.php.net/manual/en/class.traversable.php\" rel=\"nofollow noreferrer\"><code>Travesable</code> interface</a>, or <a href=\"http://www.php.net/manual/en/class.arrayaccess.php\" rel=\"nofollow noreferrer\">the <code>ArrayAccess</code> interface</a>. read through the examples, and you'll see array-like usage of <code>isset</code> is possible thanks to this interface.</p>\n\n<p>The last remark I'd like to make is the fact that your file is called <code>Cookie.class.php</code>, so I'd expect its contents to be <em>just</em> a class definition. It isn't, though: you're defining a function, too. That's just <em>not nice</em>. I'd suggest you read, and make sure to comply with the unofficial <a href=\"https://github.com/php-fig/fig-standards/tree/master/accepted\" rel=\"nofollow noreferrer\">PHP-FIG standards</a>. Though not official, all major players (check <a href=\"https://github.com/php-fig/fig-standards\" rel=\"nofollow noreferrer\">list here</a>) subscribe to these standards. If your code complies, too, autoloaders from any of the major frameworks will <em>just work</em> with your classes.<br/>\nWhile I'm on the subject of autoloaders: implement them, use them, rely on them. If your classes are defined according to the aforementioned standards, you can do away with all those pesky <code>require</code>'s. Even if you do need the occasional <code>require</code>: use the safer <code>require_once</code> variant. Sure it's a tad slower, but at least it's safe.</p>\n\n<p>Oh, and if you <em>still</em> need that <code>array_copy</code> in the <code>Miller\\Utils</code> namespace, you <em>could</em> use a static method, since PHP statics are just globals in drag, or declare a global function and call it with a leading <code>\\</code>.<br/>\nStill, look at <em>where</em> you're using it:</p>\n\n<pre><code>public function __construct ($name, $expiry = self::WEEK, $path = '', $domain = '', $secure = null, $httponly = false)\n{\n $this-&gt;name = (string) $name;\n if ($expiry === self::SESSION) {\n $this-&gt;expiry = $expiry;\n }\n else if (is_numeric($expiry)) {\n $this-&gt;expiry = time()+$expiry;\n }\n else {\n $this-&gt;expiry = strtotime($expiry);\n }\n\n $this-&gt;path = (string) $path;\n $this-&gt;domain = (string) $domain;\n $this-&gt;secure = $secure === null ? isset($_SERVER['HTTPS']) &amp;&amp; $_SERVER['HTTPS'] : (bool) $secure;\n $this-&gt;httponly = (bool) $httponly;\n\n $this-&gt;properties = array ();\n $this-&gt;internalProperties = array ();\n if (isset($_COOKIE[$this-&gt;name])) {\n $properties = unserialize($_COOKIE[$this-&gt;name]);\n $this-&gt;internalProperties = array_copy($properties);\n $this-&gt;properties = array_copy($properties);\n }\n}\n</code></pre>\n\n<p>You're clearly using it to set properties inside the class, so why isn't this function <em>a private method</em>?</p>\n\n<p>Moving on to some actual code review: Your constructor is doing <em>way</em> to much work. Besides, when I create a cookie, I'd like to be able to set the data <em>when I choose</em>, not passing it all to the constructor. I'd like to use a <code>Cookie</code> class to check if a given cookie exists, and if it does, check when it expires, if it doesn't I'd like to create it and <em>maybe</em> determine its expiration date/time later on. Implement setters and getters for that.<Br/>\nAlso use these setters to sanitize whatever data is being passed to the constructor. Sure:</p>\n\n<pre><code>$this-&gt;name = (string) $name;\n</code></pre>\n\n<p>Assures you that the name property is bound to be a string. Good, but what if I passed an object. I'm not going to get an exception thrown, though I clearly passed an argument that is a good reason to throw an <code>InvalidArgumentException</code>. Don't just cast to the types you want, check if the arguments passed are:</p>\n\n<ol>\n<li>Castable to the type without loss of data</li>\n<li>Valid types in the first place</li>\n</ol>\n\n<p>By the second I mean that, if I were to accidentally pass an instance of <code>PDO</code> as name, I should be notified of the error in <em>my</em> code. Basically: your class is too reliant on magic-methods, it allows <em>overloading of properties</em>, which is <em>terrible</em>, especially with <em>request objects</em> (the request shouldn't be subject to change, unless there's a good <em>method</em> defined for it). Some constants (like the <code>SESSION</code> constant indicate a class of responsability, check first link to find out more).<br/>\nAs ever: don't hush-up/work around errors. Throw exceptions when something is not quite right. You don't know why or how the name property was passed, and why it's not a string, nor does your class need to know. Just throw an exception. Let the user of your class fix his code.</p>\n\n<p>On the use of <code>serialize</code>: Since you're thinking about a session object: if you're going to use <code>serialize</code>, save it for the session, just <em>don't use a cookie</em>.</p>\n\n<p>On the <code>__set</code> method: check what the value is. If I'm setting something like:</p>\n\n<pre><code>$instance-&gt;connection = $pdo;\n</code></pre>\n\n<p>Your code won't complain, but you <em>can't serialize a DB connection</em>! In fact, there are quite a few things that can't be serialized. Google around a bit</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-09-11T16:36:17.907", "Id": "49536", "Score": "0", "body": "What would you suggest in place of `serialize()` on unserializable objects? I think it would make more sense to include in the documentation that the `serialize()` function is called on properties and leave it up to the user to implement the `Serializable` interface, etc., because I can't accommodate an unlimited number of classes that are unserializable." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-09-12T07:21:16.233", "Id": "49576", "Score": "1", "body": "@MMiller: Personally, I'm not a big fan of `serialize` calls, especially when the serialized data ends up in a cookie or session, but that's just me. If you're keen on using it, though, I, too, would add it in the doc-block, and do something like `if (is_object($param) && !($param instanceof Serializable || $param instanceof stdClass)) throw new InvalidArgumentException('cannot be serialized safely');`" } ], "meta_data": { "CommentCount": "2", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-09-09T08:09:35.710", "Id": "30975", "ParentId": "30895", "Score": "2" } } ]
{ "AcceptedAnswerId": "30975", "CommentCount": "3", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-09-06T20:30:35.363", "Id": "30895", "Score": "4", "Tags": [ "php", "object-oriented", "classes", "recursion", "php5" ], "Title": "Cookie Management Class" }
30895
<p>Please review the following Clojure tokenizer. The goal is to study Clojure, so sometimes I re-implement functions (it will be nice to see standard functions for this). Beyond of this, code seems quite cumbersome.</p> <pre><code>(defn space? [^Character c] (Character/isWhitespace c)) (defn digit? [^Character c] (= (Character/getType c) (Character/DECIMAL_DIGIT_NUMBER))) (defn to-int [ds] (reduce #(+ (* 10 %1) %2) (map #(- (int %) (int \0)) ds))) (defn take-int [s] (when (digit? (first s)) (let [[digits rs] (split-with digit? s)] [rs {:int (to-int digits)}]))) (defn take-sym [s] (case (first s) \+ [(rest s) {:sym :plus}] \- [(rest s) {:sym :minus}] \* [(rest s) {:sym :star}] \/ [(rest s) {:sym :slash}] nil)) (defn take-error [msg] [nil {:error msg}]) (defn tokens [expr] (loop [ex expr, ts []] (let [nsp (drop-while space? ex)] (if (empty? nsp) (conj ts {:eof nil}) (if-let [[rs t] (or (take-int nsp) (take-sym nsp) (take-error (str "Invalid symbol " (first nsp))))] (if (:error t) t (recur rs (conj ts t)))))))) (defn -main [&amp; args] ; Work around dangerous default behavior in Clojure. (alter-var-root #'*read-eval* (constantly false)) (println (tokens (seq " 20 + 32 * 4 "))) ) </code></pre>
[]
[ { "body": "<p>I don't know if you're still at it (given it's been a few months) ; in any case, here's my answer (it could be useful to someone, who knows).</p>\n\n<ul>\n<li><p>speaking of standard functions, maybe you could leverage the Clojure reader e.g.:</p>\n\n<pre><code>(def to-int (comp read-string #(apply str %)))\n;; the str bit is ugly, but necessary (read-string consumes Strings)\n</code></pre>\n\n<p>Depending on what you're attempting to do, you could parse your chain of characters directly into a stream of Clojure symbols, data structures and basic types or use it more precisely, like above.</p>\n\n<p>Otherwise, you could save yourself the trouble of reimplementing integer parsing in <code>to-int</code> by using <code>Integer/parseInt</code> on the substring directly.</p></li>\n<li><p>performance-wise, <code>char</code> sequences consume a lot of memory (even lazy ones), not to mention the risks of holding onto heads ; you should consider using <code>String</code> manipulation techniques over sequences: <code>subs</code> over <code>rest</code>/<code>next</code>, regular expressions over <code>split-with</code>/<code>drop-while</code>, etc. .</p>\n\n<ul>\n<li><p>for example, <code>drop-while space?</code> screams <code>trim</code>, <code>ltrim</code> or <code>(subs (re-find \"\\S\" ...) ...)</code>.</p></li>\n<li><p><code>when (digit? (first ...))</code>/<code>split-with digit?</code> would become <code>when-let [[_ digits rs] (re-find \"^(\\d+)(.*)$\" ...)]</code></p></li>\n</ul></li>\n<li><p>BTW -assuming input is big- feeding the whole input to the lexer feels like a waste of memory ; you should instrument a <code>Reader</code> or something, and tokenize as you read.</p></li>\n<li><p><code>-main</code>: if you don't use <code>read-string</code>, you don't need your <code>*read-eval*</code> bit ; besides, <code>alter-var-root</code> is not the way to do it: local rebinding is (e.g. with <code>binding</code>).</p></li>\n<li><p><code>tokens</code>: sequence returning function using <code>loop</code>/<code>recur</code> with an accumulator screams <code>lazy-seq</code>:</p>\n\n<pre><code>(defn tokens [expr]\n (lazy-seq\n ...\n (if (empty? nsp)\n [{:eof nil}]\n ...\n (cons t\n (if-not (:error t)\n (tokens rs)))\n</code></pre>\n\n<p>The only difference in behaviour is with errors, that get appended last instead of returned directly, which feels more flexible (the lexer stops on an error token instead of returning an error token) ; a test for errors would become <code>(:error (last ...))</code> instead of <code>(:error ...)</code>.</p></li>\n<li><p><code>take-sym</code> : this <code>case</code> screams hashmap to me and all those <code>first</code>/<code>rest</code> call for a little destructuring ; what about:</p>\n\n<pre><code>(def char-&gt;sym {\\+ :plus\n \\- :minus\n \\* :star\n \\/ :slash})\n\n(defn take-sym [[c &amp; r]]\n (if-let [sym (char-&gt;sym c)]\n [r {:sym sym}]))\n</code></pre>\n\n<p>AFAIK <code>case</code> performs comparisons based on hash code, so it should have the same (poor) performance as a hashmap. If it becomes a performance bottleneck, you may choose to reimplement it on the Java side (as a <code>switch</code> statement) or use a <code>char</code>-keys optimized map instance (like <a href=\"http://fastutil.di.unimi.it/docs/it/unimi/dsi/fastutil/chars/Char2ObjectMap.html\">this one</a> from <a href=\"http://fastutil.di.unimi.it/\">fastutil</a> or <a href=\"http://trove4j.sourceforge.net/javadocs/index.html?gnu/trove/map/TCharObjectMap.html\">that one</a> from <a href=\"http://trove.starlight-systems.com/\">Trove</a>).</p>\n\n<p>Another idea would be to <code>keyword</code>-ify the characters directly (though it would put the burden of filtering unrecognized symbols on the parser).</p></li>\n<li><p><code>digit?</code>: <code>Character/isDigit</code> does the trick.</p></li>\n</ul>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-11-30T05:18:06.900", "Id": "36396", "ParentId": "30899", "Score": "6" } } ]
{ "AcceptedAnswerId": "36396", "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-09-07T00:38:51.070", "Id": "30899", "Score": "10", "Tags": [ "parsing", "clojure" ], "Title": "Clojure tokenizer" }
30899
<p>Aspects of combinatorics include:</p> <ul> <li><strong>enumerative combinatorics</strong>: counting the structures of a given kind and size</li> <li><strong>combinatorial designs</strong> and <strong>matroid theory</strong>: deciding when certain criteria can be met, and constructing and analyzing objects meeting the criteria</li> <li><strong>extremal combinatorics</strong> and <strong>combinatorial optimization</strong>: finding "largest", "smallest", or "optimal" objects</li> <li><strong>algebraic combinatorics</strong>: <ul> <li>studying combinatorial structures arising in an algebraic context</li> <li>applying algebraic techniques to combinatorial problems</li> </ul></li> </ul>
[]
[]
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-09-07T02:35:26.243", "Id": "30902", "Score": "0", "Tags": null, "Title": null }
30902
Combinatorics is a branch of mathematics concerning the study of finite or countable discrete structures.
[]
[]
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-09-07T02:35:26.243", "Id": "30903", "Score": "0", "Tags": null, "Title": null }
30903
<pre><code>module A def methodInA # do stuff methodInB # do stuff end end module B def methodInB puts "this is a B method!" end end class C extend A extend B def initialize methodInA end end c = new C </code></pre> <p>I'm not feeling good about this. Is this a good idea in general? Any pointers as to where I can learn the best pattern for this?</p>
[ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-09-10T16:24:34.640", "Id": "49450", "Score": "2", "body": "Not a real answer, but a lot of people use [`ActiveSupport::Concern`](http://api.rubyonrails.org/classes/ActiveSupport/Concern.html) to manage module dependencies. The linked page has some examples/use cases." } ]
[ { "body": "<p>Since inheritance and interface both has some problems of their own, high level languages like ruby, python supports a different way for organizing code- Mixin. </p>\n\n<p>The code you have written involves mixin, you can see this as interface with implemented methods.When a class can inherit features from more than one parent class, the class is supposed to show multiple inheritance.</p>\n\n<p>Ruby does not suppoprt mutiple inheritance directly but Ruby Modules have another, wonderful use. At a stroke, they pretty much eliminate the need for multiple inheritance, providing a facility called a mixin.</p>\n\n<p>Mixins give you a wonderfully controlled way of adding functionality to classes. However, their true power comes out when the code in the mixin starts to interact with code in the class that uses it.</p>\n\n<p>say we have a module for debugging. we want to use this in many classes and modules. we can just include this debug module to our classes and all methods for debugging will be added in the code as own method of our class. </p>\n\n<p>see the code bellow:</p>\n\n<pre><code>module Debugger\n def log\n #do stuff\n puts \"#{Time.now}: This is a log\"\n end\nend\n\n\nclass C\n include Debugger\n\n def initialize\n #do stuff\n end\n\n def run\n #do stuff\n log\n end\n\nend\n\nc = C.new\nc.run\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-09-18T21:11:44.537", "Id": "50234", "Score": "0", "body": "i think you mean `log` instead of `Debugger.log` in `run`. Otherwise it's a service and no need to include it." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-09-24T16:30:36.117", "Id": "50653", "Score": "0", "body": "you are right @m_x, it was a mistake. I have updated the code snippet. thanks :)" } ], "meta_data": { "CommentCount": "2", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-09-10T19:18:45.940", "Id": "31070", "ParentId": "30909", "Score": "3" } }, { "body": "<p>+1 for <code>ActiveSupport::Concern</code>.</p>\n\n<p>As to the best practices, i'd recommend if possible to clearly state dependency of module A on module B :</p>\n\n<pre><code>module A\n include B\n def method_in_a\n method_in_b\n end\nend\n\nclass C\n include A\nend\n</code></pre>\n\n<p>or : </p>\n\n<pre><code>module A\n def self.included( base )\n base.send :include, B\n end\n\n def method_in_a\n method_in_b\n end\nend\n\nclass C\n include A\nend\n</code></pre>\n\n<p>...and that's why <code>ActiveSupport::Concern</code> is cool, because it helps <a href=\"http://api.rubyonrails.org/classes/ActiveSupport/Concern.html\" rel=\"nofollow\">managing such dependencies</a>. </p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-09-18T21:15:38.440", "Id": "31509", "ParentId": "30909", "Score": "1" } } ]
{ "AcceptedAnswerId": "31509", "CommentCount": "1", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-09-07T09:30:45.877", "Id": "30909", "Score": "3", "Tags": [ "ruby" ], "Title": "Calling methods of another module from a module, from a class extending both?" }
30909
<p>We have two log files in which one is generated from a process. We compare one file(golden file) to another file to check if file correct or not. It should have same value. We generally use diff utility to compare two files. I have got enhancement to add machine information into process generated File. So I want to compare upto previous line and ignore new changes. Could Anyone provide me any utility which I can use in python.</p> <p>Golden File</p> <pre><code>CMD gen -vdd 0.99 -vss 0 -sinps 0.02 -slew 0.1 -temp -40 -rise -data CMD gen -vdd 0.99 -vss 0 -sinps 0.06 -slew 0.1 -temp -40 -rise -clock CMD gen -vdd 0.99 -vss 0 -sinps 0.02 -slew 0.1 -temp -40 -fall -data CMD gen -vdd 0.99 -vss 0 -sinps 0.02 -slew 0.1 -temp -40 -fall -data CMD gen -vdd 0.99 -vss 0 -sinps 0.06 -slew 0.1 -temp -40 -rise -clock CMD gen -vdd 0.99 -vss 0 -sinps 0.02 -slew 0.1 -temp -40 -rise -data Temp1 Temp2 Temp3 Temp4 Temp5 Temp6 -31.00 -19.00 -3.00 -8.00 43.00 61.00 </code></pre> <p>Process File</p> <pre><code>CMD gen -vdd 0.99 -vss 0 -sinps 0.02 -slew 0.1 -temp -40 -rise -data CMD gen -vdd 0.99 -vss 0 -sinps 0.06 -slew 0.1 -temp -40 -rise -clock CMD gen -vdd 0.99 -vss 0 -sinps 0.02 -slew 0.1 -temp -40 -fall -data CMD gen -vdd 0.99 -vss 0 -sinps 0.02 -slew 0.1 -temp -40 -fall -data CMD gen -vdd 0.99 -vss 0 -sinps 0.06 -slew 0.1 -temp -40 -rise -clock CMD gen -vdd 0.99 -vss 0 -sinps 0.02 -slew 0.1 -temp -40 -rise -data Temp1 Temp2 Temp3 Temp4 Temp5 Temp6 -31.00 -19.00 -3.00 -8.00 43.00 61.00 Adding machine name( ignore machine name) </code></pre> <p>I have write code in following.Can we better way for improve code</p> <pre><code>data = None with open("Golden_File",'r+') as f: data = f.readlines() del data[-1] data_1 = None with open("cp.log",'r+') as f: data_1 = f.readlines() del data_1[-1] print cmp(data, data_1) </code></pre> <p>[Question]: Does cmp function works fine in list also. I have used first time and not sure how internally works. </p>
[ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-09-07T14:11:18.030", "Id": "49206", "Score": "2", "body": "Just to be sure, you want to compare the 2 files after deleting the last line from `Process File`. Correct? If correct then why are you deleting the last line in data. Wouldn't that delete the last line from what you have read from the `Golden File`?" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-09-07T15:00:50.217", "Id": "49207", "Score": "1", "body": "`cmp` does indeed work for lists - see http://docs.python.org/2/tutorial/datastructures.html#comparing-sequences-and-other-types and http://docs.python.org/2/library/functions.html#cmp. But you could just as easily type `print data == data_1`" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-09-07T15:32:35.297", "Id": "49209", "Score": "0", "body": "@AseemBansal, correct Ya I am planning to remove last line from golden also" } ]
[ { "body": "<p>There is no need for python here, you can use the <code>head</code> command to filter out the last line of a file:</p>\n\n<pre><code>diff &lt;(head -n -1 \"Golden_File\") &lt;(head -n -1 \"cp.log\")\n</code></pre>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-09-07T14:33:26.583", "Id": "30913", "ParentId": "30912", "Score": "1" } }, { "body": "<p>If you don't mind reading the entire files into memory at once (as you are currently doing), you can just compare them as lists of lines:</p>\n\n<pre><code>with open(\"Golden_File\", \"r\") as golden, open(\"cp.log\", \"r\") as log:\n if golden.readlines() == log.readlines()[:-1]:\n print \"files match\"\n</code></pre>\n\n<p>Otherwise you can use <code>itertools</code> and compare one line at a time:</p>\n\n<pre><code>from itertools import izip\nwith open(\"Golden_File\", \"r\") as golden, open(\"cp.log\", \"r\") as log:\n lines_match = all(a == b for a, b in izip(golden, log))\n one_line_left = len(list(log)) == 1 and list(golden) == []\n if lines_match and one_line_left:\n print \"files match\"\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-09-07T16:09:50.590", "Id": "49213", "Score": "0", "body": "Agree, But As I am doing operation on the last line. And I know only last line will be change than it will be overhead for me" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-09-07T16:16:56.157", "Id": "49215", "Score": "0", "body": "Not sure what you mean - one way or another, you have to read the whole file in. If you don't need to check that there is a remaining line in the log file, you can remove `one_line_left = ...` and just check whether `lines_match` is true." } ], "meta_data": { "CommentCount": "2", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-09-07T16:05:55.833", "Id": "30920", "ParentId": "30912", "Score": "1" } } ]
{ "AcceptedAnswerId": "30920", "CommentCount": "3", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-09-07T13:10:29.767", "Id": "30912", "Score": "2", "Tags": [ "python" ], "Title": "Compare File with ignore some line/last line" }
30912
<p>I have a class that stores the data related to all employees in a particular department. In this class, I am having a list of employees and other fields. Also, I am having a property which returns a <code>bool</code>, indicating whether an employee exists or not. I am a bit confused regarding the naming of this property.</p> <pre><code>class Employee_Details { #region Private Fields private List&lt;Employee&gt; employees; #endregion #region Fields // Gets a value indicating whether an employee exists public bool DoesEmployeeExists // what should be the name of this property? { get { return this.employees.Any(); } } #endregion } </code></pre> <p>Is the property name <code>DoesEmployeeExists</code> correct, or should I use any other name?</p>
[ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-09-07T18:47:04.377", "Id": "49227", "Score": "5", "body": "`DoesEmployeeExists` is grammatically incorrect. At least use `DoesEmployeeExist`. But +1 to `Has*`/`Is*`, guitar_freak beat me to it." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-09-07T19:35:57.860", "Id": "49236", "Score": "0", "body": "While at it - properties that do work other than input validation and potentially can take long time to run or throw exception on get should be methods." } ]
[ { "body": "<pre><code>class Employee_Details\n</code></pre>\n\n<p>This class is badly named. First, .Net naming conventions say you shouldn't use underscore for this, the class should be called <code>EmployeeDetails</code>. Second, the name seems to imply it contains details about a single employee. Better names would be <code>EmployeesDetails</code> or something like <code>EmployeeList</code>.</p>\n\n<pre><code>#region Private Fields\n</code></pre>\n\n<p>I don't see any reason to use <code>#region</code> here, especially since it's for a single field.</p>\n\n<pre><code>#region Fields\n</code></pre>\n\n<p>If you're going to have regions, at least don't lie in their descriptions. This <code>#region</code> contains properties, not fields.</p>\n\n<pre><code>// Gets a value indicating whether an employee exists\n</code></pre>\n\n<p>Consider using XML documentation comments. That way, the IDE (and other tools) can understand them.</p>\n\n<pre><code>public bool DoesEmployeeExists\n</code></pre>\n\n<p>I think a better name is indicated by the implementation: <code>AnyEmployees</code>. But probably even better name would be a negated one: something like <code>NoEmployees</code> or <code>Empty</code>.</p>\n\n<p>Also consider whether this property actually makes sense. I think a better option would be exposing the private list as something like <code>IEnumerable&lt;Employee&gt;</code> or <code>IReadOnlyList&lt;Employee&gt;</code>, which you probably have to do anyway. That way, any user of your class can run any query they want on the list, and you won't have to create separate properties or methods for each kind of query.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-09-07T17:12:57.023", "Id": "49220", "Score": "3", "body": "I'm not convinced about `AnyEmployees`, `NoEmployees` or `Empty`. I don't see any reason in using a negative name: if you want to check if any employees exist you'd have to use `if(!NoEmployees)` which isn't very fluent. `Empty` is ambigious because it might just as well refer to any other property in the class. `HasEmployees` follows conventions (`Has-a`, `Is-a` etc) and makes its purpose clear. Agree on everything else." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-09-07T19:17:08.243", "Id": "49234", "Score": "0", "body": "@ svick, this is not my actual code. I was just confused with the property name that's why I have given random name to other entities. For all the regions and all, I was just trying to make the code readable :). I do need to have properties like this in which I check for empty collection, for WPF bindings." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-09-07T22:17:17.113", "Id": "49241", "Score": "3", "body": "@MehaJain Well, [the rules of this site](http://codereview.stackexchange.com/help/on-topic) say that you should post your actual code. That way, you might get comments about thing that you didn't expect to be problematic too." } ], "meta_data": { "CommentCount": "3", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-09-07T15:32:08.820", "Id": "30917", "ParentId": "30914", "Score": "8" } }, { "body": "<p>I would use simply <code>HasEmployees</code>.</p>\n\n<p>In case of Boolean, I always try to use <code>hasSomething</code> or <code>isSomething</code>. In Java, many libraries use this strategy (it's just a convention). And I like it, because it's so easy to read when you see:</p>\n\n<pre><code>if(annoyingEmployee.isRemovable() &amp;&amp; !annoyingEmployee.hasBirthday()) {\n manager.fireEmployee(annoyingEmployee);\n} \n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-09-08T07:29:45.870", "Id": "49254", "Score": "7", "body": "Sometimes also other prefixes can be used for booleans: e.g. `if (employee.canFixBug(bug)) { manager.giveExtraHoursTo(employee); }`" } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-09-07T16:51:32.043", "Id": "30923", "ParentId": "30914", "Score": "23" } }, { "body": "<p>First, <a href=\"https://codereview.stackexchange.com/a/30917/2429\">@svick</a> is absolutely right about the class name, regions and xml comments.</p>\n\n<p>But to address your basic question, I would have the class implement either <code>ICollection</code> or <code>IList</code> depending upon how you use the rest of the class. If neither works for you, consider <code>Count</code>... but I wuld really go with IList, as that would allow them to get the answer without you doing much at all other than providing some wrappers around your private variable.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-09-07T22:19:12.183", "Id": "49242", "Score": "2", "body": "Most of the time, have a property of the appropriate collection type makes more sense over implementing a collection interface. Basically, composition over inheritance." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-09-08T02:25:10.867", "Id": "49247", "Score": "0", "body": "You're right, I was assuming that the OP had a good reason to make the list private instead of public, and if he does, he would probably want the `IReadOnlyList` instead." } ], "meta_data": { "CommentCount": "2", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-09-07T18:38:54.207", "Id": "30925", "ParentId": "30914", "Score": "2" } } ]
{ "AcceptedAnswerId": "30923", "CommentCount": "2", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-09-07T14:57:44.847", "Id": "30914", "Score": "10", "Tags": [ "c#" ], "Title": "Boolean naming convention" }
30914
A field-programmable gate array (FPGA) is an integrated circuit designed to be configured by a customer or a designer after manufacturing.
[]
[]
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-09-07T15:48:21.940", "Id": "30919", "Score": "0", "Tags": null, "Title": null }
30919
<p>I am creating a small app working on file system. The user can choose a directory and than, application get one of the possible result (examples):</p> <ul> <li>return number of lines in all *.java files</li> <li>return number of lines in all *.java files without comments</li> <li>return number of all classes</li> <li>return number of <code>i</code>fs etc...</li> </ul> <p>Because I want to follow the single responsibility principle, and because all these functionalities have something in common, I want to create one class for each functionality (using commons.io DirectoryWalker) under a common interface. That's why I find such an interface useful:</p> <pre><code>** * Common interface for counting classes (lines, words, classes, etc...) */ public interface Counter { /** * count required things starting from startDirectory, recursively or not, * and consider only specified extensions */ int count(File startDirectory, boolean recursive, List&lt;String&gt; fileExtensions); int count(File startDirectory, boolean recursive); } </code></pre> <p>Now, the user can simply create some collection with counters, create and add new counter easily, iterate etc.</p> <p>Questions:</p> <ol> <li>Of course it is just a simplification, but do you think that the main idea of using an interface here is reasonable?</li> <li><p>Maybe I will have some methods which will return something different than <code>int</code> - for example, <code>Map</code> with pairs, or a list of the ten longest files. In this case my interface is not correct. What should I do in such case? Maybe the interface's method should return Object like this:</p> <pre><code>Object count(File startDirectory, boolean recursive); </code></pre> <p>But this seems bad to me as it will lead to some unfriendly casting when parsing the returned value (Object). I can create some special DTO object like the below which will contain all possible "answers":</p> <pre><code>public class CounterDTO { public int numerOfLines; // used for counters counting lines public int numberOfIfs; // used for counters counting if statements public Map&lt;File, Integer&gt; linesInFiles; // ... File -&gt; number of lines public List&lt;File&gt; longestFiles; // used for indicating files with maximal number of lines // and so on... } </code></pre> <p>Then the interface method would look like:</p> <pre><code>CounterDTO count(File startDirectory, boolean recursive); </code></pre> <p>Is this OK or is there a better way?</p></li> </ol>
[ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-09-07T17:43:34.033", "Id": "49223", "Score": "0", "body": "The fact, that classes behave similarly doesn't mean they need to implement the same interface. You need an interface, if some code will have to work with any of those classes. How are you going to use this interface? Maybe you will call `count` only on concrete types and this interface will only get in your way." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-09-07T17:47:34.910", "Id": "49224", "Score": "2", "body": "`recursive` flag looks suspicious. It looks like every class will have to implement its own directory traversing. Maybe you should have a separate class for that. It would take any existing `Counter` and apply it to all files in specified directory." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-09-07T18:30:52.690", "Id": "49225", "Score": "0", "body": "@Banthar Usage will be probably like this: user have a checklist with many counter types (counting options). After user selects required counter, then it app will simply invoke all count methods from all counter via interface." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-09-07T18:32:01.930", "Id": "49226", "Score": "0", "body": "@Banthar Thanks for \" It looks like every class will have to implement its own directory traversing\". That's a very good point I've forgot to ask in post..." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-09-07T19:02:45.040", "Id": "49231", "Score": "0", "body": "Please consider editing your title to describe what your code does. This will help reduce the amount of \"is this code ok\" questions and contribute to make CR Google-discoverable :)" } ]
[ { "body": "<p><strong>Normally when you need \"different return types\"</strong>, you can use <a href=\"http://docs.oracle.com/javase/tutorial/java/generics/\" rel=\"nofollow\">generics</a>. However, since you want these <code>Counter</code>s to be in a List of some sort, using generics goes out the window since a List cannot be defined properly to contain both <code>Counter&lt;List&lt;File&gt;&gt;</code> and <code>Counter&lt;Integer&gt;</code>, so the only solution would be to have a <code>List&lt;Counter&lt;?&gt;&gt;</code> in which case the reason for using generics in the first place is lost.</p>\n\n<p>Your <code>CounterDTO</code> class makes sense if a <code>Counter</code> counts more than one of the things. If the counter is only meant to return an int <strong>or</strong> a list of files, then using a <code>CounterDTO</code> is quite useless since many fields will be <strong>null</strong>.</p>\n\n<p><strong>Regarding Banthar's comment</strong> to your question, you could modify your existing interface to</p>\n\n<pre><code>int count(List&lt;File&gt; files);\n</code></pre>\n\n<p>It would then be the job for <strong>a single utility method</strong> (or two) to create a list of files from these parameters: <code>File startDirectory, boolean recursive, List&lt;String&gt; fileExtensions</code>.</p>\n\n<p><strong>As for the question about return type</strong>... If you need an interface for this or not depends on how you are using these counters. And also: Which possible counters are there? If you have one counter for returning total line count and one for returning a <code>Map&lt;File, Integer&gt;</code> of line counts, then you don't need two different counters. Since you need to know all the line counts in all the files to know the total line count, using a <code>CounterDTO</code> makes perfect sense here.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-11-18T22:02:56.297", "Id": "35638", "ParentId": "30922", "Score": "2" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "5", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-09-07T16:46:55.570", "Id": "30922", "Score": "1", "Tags": [ "java", "interface" ], "Title": "Common interface with different return types" }
30922
<p>I have this function which is associated with a timer that I'm creating in AngualarJS. Should I be concerned about the function being able to execute quickly enough for the timer to be accurate.</p> <pre><code>$scope.start = function() { if($scope.counting === true) return false; $scope.counting = true; $scope.counter = $timeout(function updateCount() { $scope.count++; $scope.hh = Math.floor($scope.count / 360000); $scope.mm = Math.floor(($scope.count - ($scope.hh * 360000)) / 6000); $scope.ss = Math.floor(($scope.count - ($scope.hh * 360000) - ($scope.mm * 6000)) / 100); $scope.ms = Math.floor($scope.count - ($scope.hh * 360000) - ($scope.mm * 6000) - ($scope.ss * 100)); $scope.counter = $timeout(updateCount, 10); }, 10); }; </code></pre>
[ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-09-07T17:25:50.670", "Id": "49221", "Score": "1", "body": "Already creating one closure costs more than 10000 math functions and kills 13 kittens" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-09-07T17:31:17.077", "Id": "49222", "Score": "0", "body": "@Esailija In angular, I've been told that $timeout is generally preferred over setInterval so this is how the closure \"should\" be set up. And...I don't know if you're trying to be helpful or just interjecting some clever comment..." } ]
[ { "body": "<p>After digging around a bit, it seems the most appropriate approach for this is to create a kind of \"fix\" for latency resulting from CPU time that will quickly cause inaccuracies in a javascript timer. I wrote the below to demonstrate. As you can see, the <code>setTimeout</code> named <code>timer1</code> includes a check based on the difference between the <code>start</code> Date object and an updated Date object. Using this value, we can calculate (with better, not perfect, accuracy) how off our incrementing <code>time</code> is. The <code>setTimeout</code> named <code>timer2</code> does not include this check and, as you will see, the latency begins to accumulate.</p>\n\n<pre><code>&lt;!DOCTYPE html&gt;\n&lt;html&gt;\n&lt;head&gt;\n &lt;title&gt;Accurate Timer Test&lt;/title&gt;\n&lt;/head&gt;\n&lt;body&gt;\n&lt;p&gt;&lt;label&gt;Corrected Example:&lt;/label&gt;&lt;input type=\"text\" value=\"0\" name=\"correct\" id=\"correct\" /&gt;&lt;/p&gt;\n&lt;p&gt;&lt;label&gt;Latency Example:&lt;/label&gt;&lt;input type=\"text\" value=\"0\" name=\"latency\" id=\"latency\" /&gt;&lt;/p&gt;\n&lt;p&gt;&lt;a href=\"#\" id=\"start\"&gt;Start&lt;/a&gt;&lt;/p&gt;\n&lt;p&gt;&lt;a href=\"#\" id=\"stop\"&gt;Stop&lt;/a&gt;&lt;/p&gt;\n&lt;script type=\"text/javascript\"&gt;\n window.onload = function() {\n var timerTest = new TimerTest(),\n correct = document.getElementById(\"correct\"),\n latency = document.getElementById(\"latency\");\n\n document.getElementById(\"start\").addEventListener(\"click\", function(evt) {\n timerTest.start();\n return false;\n });\n\n document.getElementById(\"stop\").addEventListener(\"click\", function(evt) {\n timerTest.stop();\n return false;\n });\n };\n\n var TimerTest = function() {\n var _this = this,\n timer1 = false,\n timer2 = false,\n start = 0,\n time1 = 0,\n time2 = 0,\n elapsed1 = 0,\n elapsed2 = 0,\n diff = 0;\n\n _this.start = function() {\n start = new Date().getTime();\n timer1 = setTimeout(_this.updateTimer1, 100);\n timer2 = setTimeout(_this.updateTimer2, 100);\n };\n\n _this.stop = function() {\n clearTimeout(timer1);\n clearTimeout(timer2);\n timer1 = false;\n timer2 = false;\n\n }\n\n _this.updateTimer1 = function() {\n time1 += 100;\n elapsed1 = Math.floor(time1 / 100) / 10;\n if(Math.round(elapsed1) == elapsed1) elapsed1 += '.0';\n correct.value = elapsed1;\n diff = (new Date().getTime() - start) - time1;\n timer1 = setTimeout(_this.updateTimer1, 100 - diff);\n };\n\n _this.updateTimer2 = function() {\n time2 += 100;\n elapsed2 = Math.floor(time2 / 100) / 10;\n if(Math.round(elapsed2) == elapsed2) elapsed2 += '.0';\n latency.value = elapsed2;\n timer2 = setTimeout(_this.updateTimer2, 100);\n }\n\n return _this;\n };\n&lt;/script&gt;\n&lt;/body&gt;\n&lt;/html&gt;\n</code></pre>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-09-09T17:18:58.897", "Id": "31005", "ParentId": "30924", "Score": "1" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "2", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-09-07T17:24:02.527", "Id": "30924", "Score": "1", "Tags": [ "javascript", "performance", "angular.js" ], "Title": "Is it reasonable to expect this AngularJS function to perform well?" }
30924
<p>Very easy question for these who spend some time on analyzing code written by co-workers. </p> <p>When I write my code, I do my best to write it in a very, extremely readable way. But sometimes I have an impression, that I write it too easy... Simple example:</p> <p>When I see such a code:</p> <pre><code>public Category getCategoryType(Component components){ if(component.hasSensor() &amp;&amp; component.hasInputUnit &amp;&amp; component.isValid() &amp;&amp; !component.isSuspended()){ return Category.TYPE_A; } } </code></pre> <p>the first thing I do is changing it into:</p> <pre><code> public Category getCategoryType(Component components){ boolean hasSensor = component.hasSensor(); boolean hasInput = component.hasInputUnit(); boolean isValid = component.isValid(); boolean isNotSuspended = !component.isSuspended(); if(hasSensor &amp;&amp; hasInput &amp;&amp; isValid &amp;&amp; isNotSuspended){ return Category.TYPE_A; } } </code></pre> <p>One of my collegue told me politely, that it is not necessary, because people can read a little more complicated code. But I think, that someone who will read this ode after me, will have a easier task (despite the fact, that I make this function a little bit longer)</p> <p>Question for you: Do you think, that such changes in code are senseless?</p> <p>Maybe only formatting stuff is sufficient:</p> <pre><code>public Category getCategoryType(Component components){ if(component.hasSensor() &amp;&amp; component.hasInputUnit &amp;&amp; component.isValid() &amp;&amp; !component.isSuspended()){ return Category.TYPE_A; } } </code></pre>
[ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-09-08T15:05:33.210", "Id": "49265", "Score": "0", "body": "I like your idea of formatting every condition on a new line, but the automatic formatter (yours, or your co-workers') will probably destroy that at some point." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-09-08T17:30:12.703", "Id": "49270", "Score": "0", "body": "@toto2 Absolutely right : ) That's why I use code from the second listing and that's why in some companies each developer is obligated to use the same formatting rules ; )" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-09-09T20:02:48.543", "Id": "49351", "Score": "0", "body": "You'll never get consensus on this question, I think. Anyway, if you solve your [other problem](http://codereview.stackexchange.com/questions/30990), then you might not run into this issue." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-09-10T07:47:53.187", "Id": "49401", "Score": "0", "body": "_Iff_ you introduce variables make them `final`." } ]
[ { "body": "<p>Does the method <code>getCategoryType</code> need to know everything about a <code>Component</code>? Maybe its logic can be satisfied (and tested) with only this:</p>\n\n<pre><code>public Category getComponentCategoryType(boolean hasSensor, \n boolean hasInput, \n boolean isValid, \n boolean isSuspended)\n {\n if(hasSensor &amp;&amp; hasInput &amp;&amp; isValid &amp;&amp; !isSuspended)\n {\n return Category.TYPE_A;\n }\n } \n</code></pre>\n\n<p>I'm not really into java so maybe this is violating a convention I don't know about, but I find this signature makes the method/function self-documented as far as its inner logic is concerned.</p>\n\n<p>A bit like constructors that statically declare dependencies in <em>dependency injection</em>, a signature like this declares everything the method needs to know in order to give you a <em>category type</em> - by taking in a <em>Component</em>, all you know is that it takes a <em>Component</em> and spits out a <em>Category</em>.</p>\n\n<p>And you can test the logic without needing to instanciate a <em>Component</em> - if that object were a 3rd-party thing you had no control over, having it as a <em>depedency</em> could make the method very hard to test.</p>\n\n<p>Of course if the method is already in use in 2000 places and changing the signature would be a major breaking change, I see no problem with the last listing you provided.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-09-10T07:33:00.677", "Id": "49400", "Score": "1", "body": "I am all in favour of DI but I don't think that's the way to do it in this context. The signature contains 4 booleans which is confusing and you can bet that somebody is going to call the method with the arguments in the wrong order - and reading a statement like `getComponentCategoryType(true, false, false, true)` does not improve readability IMO." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-09-10T10:37:26.133", "Id": "49409", "Score": "0", "body": "This is not DI ..and first thing I thought when I read my answer was \"this looks like it needs something analogueous to EventArgs, an interface that wraps allthe args in a single param... but that would be overkill it seems. You're right, 4 bools isn't a very nice signature, I meant to say the method doesn't need to know everything about the component :)" } ], "meta_data": { "CommentCount": "2", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-09-07T19:16:22.737", "Id": "30927", "ParentId": "30926", "Score": "4" } }, { "body": "<p>If this is used in more than one place I would put validation logic either in Component, or some sort of ComponentRules class, so then your code will be something along the lines of</p>\n\n<pre><code>if (component.IsCategorizable())\n DoWork();\n</code></pre>\n\n<p>Or </p>\n\n<pre><code>if (ComponentRules.CanBeCategorized(component))\n DoWork();\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-09-11T00:38:46.863", "Id": "49478", "Score": "0", "body": "+1. The more I look at it, the more I find component should be able to determine its category. Looks like *feature envy*." } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-09-07T19:43:25.513", "Id": "30928", "ParentId": "30926", "Score": "1" } }, { "body": "<p>I think we can avoid using local variables if possible and can directly use the passed-in parameter</p>\n\n<pre><code>public Category GetCategoryType(Component component)\n{\n if((component.hasSensor())\n &amp;&amp; \n (component.hasInputUnit)\n &amp;&amp; \n (component.isValid())\n &amp;&amp;\n (!component.isSuspended()))\n {\n return Category.TYPE_A;\n }\n}\n</code></pre>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-09-07T19:47:08.563", "Id": "30929", "ParentId": "30926", "Score": "1" } }, { "body": "<p>Readability is extremely important, particularly in large projects with many programmers involved with the same code. What you do, using local Boolean variables to clarify potentially complex conditions, is a very good way of improving readability that I try to imprint on my co-workers.</p>\n\n<p>That said, in your example, if I wrote that method from scratch, I would do it similarly to your first re-write. However, if I just happened upon the existing code, I would do just about exactly as your second re-write. It is good enough, and I do not really like to change other peoples code unless it is either incorrect, or directly violates the coding standard (which it incidentally does two-fold: The conditional line is too long, and our standard also tells us to place sub-conditions on separate lines).</p>\n\n<p>So, in my humble opinion: You have it right - I like how you do it, and you should take pride in writing readable code. But do not waste time on re-<em>writing</em> working code when a simple re-<em>formatting</em> is good enough.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-09-09T02:00:04.213", "Id": "49282", "Score": "1", "body": "+1 \"... when a simple re-formatting is good enough.\" Ditto. Further: Re-written code must be tested - all testing phases in your development process - and ensure that functionality has not changed. And beware of \"but it's a simple change\" thinking; that is a \"famous last words\" kind of things. Professionalism is a harsh mistress." } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-09-08T07:56:42.243", "Id": "30944", "ParentId": "30926", "Score": "5" } }, { "body": "<p>Going against the grain of most answers, I am guessing that there are a lot of Component types . If there were more than say 20 types than I would either want to maintain</p>\n\n<ul>\n<li>Code like you have found</li>\n<li>Code that parses config file / database table with the rules</li>\n<li>Some kind of Map that contains the rules</li>\n</ul>\n\n<p>The last thing I would want to find is code diarrhea with hundreds or thousands of lines.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-09-09T12:44:39.083", "Id": "30981", "ParentId": "30926", "Score": "1" } }, { "body": "<p>I'm going to throw my hat in the ring and say the format of the last example is the easiest for me to read(like your colleague says). </p>\n\n<p>It's easy to see that everything is coming from <code>component</code> and I can read the conditions in a straight line: it has a sensor, it has an input unit, it is valid, and it is not suspended. And that's exactly how I would read it going through the code the first time. Someone who comes across this code in the future shouldn't have any trouble figuring out what is going on.</p>\n\n<p>With the local booleans, I have to verify that each boolean is coming from <code>component</code> and that the booleans created are the ones being used in the <code>if(...)</code>. In this example it's trivial to see that is the case, but in the case of multiple ifs, elses, or other logic in the function...it may not be so trivial.</p>\n\n<p>It also introduces another vector for producing bugs either in the creation of the function, or the function's maintenance in the future. Again, the example is trivial, but it's easy to imagine cases that aren't trivial.</p>\n\n<p>Having seen your other related post, I would also pair this with having a separate function for each category(x3ro suggested something like isCat24(), etc), and within that function following the format of the last example you gave(one condition per line, no locals created).</p>\n\n<p>Your conditionals then start to look like:</p>\n\n<pre><code>if(isCatA(component))\n return Category.TYPE_A;\nif(isCatB(component))\n return Category.TYPE_B;\n...\n\n//Based on x3ro's suggestion:\npublic boolean isCatA(Component c) {\n return c.hasSensor() &amp;&amp; \n c.hasInputUnit &amp;&amp; \n c.isValid() &amp;&amp;\n !c.isSuspended();\n}\n</code></pre>\n\n<p>And if I want to verify each set of conditions, I can just look up one function per category and see what they're doing.</p>\n\n<p>Finally, you might want to consider making a function in <code>Component</code> called <code>getCategory()</code>. All of the logic shown uses one <code>Component</code>, and uses no information from anything outside of that <code>Component</code>. It seems like it should be encapsulated by the <code>Component</code> class, and anyone who wants to know the category can call the getter for that information.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-09-09T19:46:06.570", "Id": "31013", "ParentId": "30926", "Score": "1" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "4", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-09-07T18:56:37.870", "Id": "30926", "Score": "6", "Tags": [ "java" ], "Title": "Long conditionals in ifs" }
30926
<p>For a simple project, I represent a two-dimensional grid as a one-dimensional array, with both row and column indices between <code>1</code> and <code>gridHeight</code>. When retrieving a cell from the grid, I first need to check if both row and column IDs are within allowed bounds.</p> <pre><code>public void checkIfAllowed(int row_or_column) { if ((row_or_column &lt; 1) || (row_or_column &gt; gridHeight)) { throw new IndexOutOfBoundsException("Row or column ID is not acceptable."); } } public boolean getCellById(int row, int column) { checkIfAllowed(row); checkIfAllowed(column); return grid[row * gridHeight + column]; } </code></pre> <p>Can it possibly be improved?</p> <p>There are two things about this code that I don't particularly like:</p> <ul> <li>Somewhat repetitive code in <code>getCellById</code>.</li> <li>It asks for permission instead of forgiveness: first checks everything, and then does the action. I would prefer a <code>try .. catch</code> construction (something like "try to return a value and then catch <code>IndexOutOfBoundsException</code>), but would it really work for Java? The array dimension is defined during run time, and initial declaration for my grid is just <code>private boolean[] grid;</code>.</li> </ul>
[ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-09-09T08:45:31.397", "Id": "49293", "Score": "1", "body": "throw out all your checkIfAllowed stuff - you'll still get IndexOutOfBoundsException, though without message (which is not informative anyway)" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-09-11T17:02:32.173", "Id": "49540", "Score": "0", "body": "You do in fact need the check as without you could, for example on a 25x25 grid, access (4,30). This would result in index (4*25)+30 = 130, which is a valid index, but invalid grid coordinate. I posed a way to overcome this below." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-09-27T13:38:41.660", "Id": "117078", "Score": "0", "body": "Why not use a two dimensional array and let Java take care of everything?" } ]
[ { "body": "<p>Not sure if I've understood yout question correctly, but I assume, that your grid is a square grid (you test both, maximal high and width, as a lower than grid's height).</p>\n\n<p>Referring to your first question:\nThere are many options. You can make a method which takes two parameters at a time:</p>\n\n<pre><code>public void checkIfAllowed(int row, int column){\n boolean areCorrect = checkIfRowAllowed(row) &amp;&amp; checkIfColAllowed(column);\n if(!areCorrect){\n throw new IndexOutOfBoundsException(\"Row or column ID is not acceptable.\");\n }\n}\n\nprivate boolean checkIfAllowed(int row_or_column) {\n return (row_or_column &lt; 1 || row_or_column &gt; gridHeight);\n} \n</code></pre>\n\n<p>Now, a client is not forced to check each row and column in separate lines. Just an example:</p>\n\n<pre><code>public boolean getCellById(int row, int column) {\n try{ \n checkIfAllowed(row, column);\n return grid[row * gridHeight + column];\n\n } catch (IndexOutOfBoundsException e) {\n // log an error, or do something else\n }\n}\n</code></pre>\n\n<p>But this exception handling seems strage for me. I would simply throw it in <code>getCellById(int row, int col)</code> and handle when this method is invoked.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-09-26T20:37:59.287", "Id": "117014", "Score": "0", "body": "I would edit the IndexOutOfBoundsException message with `IndexOutOfBoundsException(\"Row (\" + row + \") or column (\" + column + \") ID is not acceptable.\");` Without say nothing it's like \"Hey something is wrong and i know what, but i will not tell you anything put a breakpoint here if you want to know.\"" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-09-27T10:32:16.780", "Id": "117065", "Score": "0", "body": "@MarcoAcierno Yeah, you are certainly right... By \"// log an error, or do something else\" I meant exactly what you've said - some logging message in particular." } ], "meta_data": { "CommentCount": "2", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-09-08T07:03:59.230", "Id": "30943", "ParentId": "30937", "Score": "2" } }, { "body": "<p>A quick solution would be to use absolute value and mod on the input by the grid size. That way you could put in any numbers and never get an Out Of Bounds exception. </p>\n\n<pre><code>grid[Math.abs(row)%gridHeight*gridHeight + Math.abs(column)%gridHeight]\n</code></pre>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-09-11T16:59:55.367", "Id": "31116", "ParentId": "30937", "Score": "2" } }, { "body": "<p>I cannot see anything wrong, both with checking the arguments first and the little bit of repetitive code. However, there are two things that I think need fixing:</p>\n\n<ul>\n<li><p>The exception message is not helpful. It says \"row or column\" and neither mentions bounds nor actual value. That does not make debugging easy. Once you fix that, there will be no repetitive code anymore.</p></li>\n<li><p>More importantly: Your code seems to have a bug. You are disallowing row and column indexes of 0. That does not go well with the fact that your data is stored in <code>grid</code> which is an array. That effectively means the entire first row (<code>gridHeight</code> many elements in the array) are unused, but still need to be allocated. If you create the <code>grid</code> as <code>new boolean[gridHeight * gridHeight]</code> this would still lead to an <code>ArrayIndexOutOfBoundsException</code> although it is not detected by <code>checkIfAllowed()</code>. Rather subtract one from the indices and save on the array length.</p></li>\n</ul>\n\n<p>Finally, avoid underscores in Java identifiers, or at least don't mix them with camel case.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-09-26T21:44:30.900", "Id": "63994", "ParentId": "30937", "Score": "0" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "3", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-09-08T02:59:21.310", "Id": "30937", "Score": "2", "Tags": [ "java", "array", "exception-handling" ], "Title": "Checking if an index is out of bounds" }
30937
<p>This is a question about whether my coding style follows AngularJS best practices. </p> <p>One of the selling points to Angular is directives. Directives allow you to create custom DOM with elements or attributes you create. I've found myself creating lots of directives, thinking of each one as little controls to be placed on the page. Looking back, I'm wondering if I'm too directive focused and if Angular directives should only be used when you need a custom link method?</p> <p>What I find myself doing a lot is wrapping up some HTML in a directive with a simple controller that does one or two basic things. I have a lot of code that looks like <a href="http://www.opensourceconnections.com/2013/08/25/instant-search-with-solr-and-angular/">this code of mine from a blog post</a>:</p> <pre><code>'use strict'; angular.module('solrAngularDemoApp') .directive('searchResults', function () { return { scope: { solrUrl: '=', displayField: '=', query: '&amp;', results: '&amp;' }, restrict: 'E', controller: function($scope, $http) { console.log('Searching for ' + $scope.query + ' at ' + $scope.solrUrl); $scope.$watch('query', function() { $http( {method: 'JSONP', url: $scope.solrUrl, params:{'json.wrf': 'JSON_CALLBACK', 'q': $scope.query, 'fl': $scope.displayField} }) .success(function(data) { var docs = data.response.docs; console.log('search success!'); $scope.results.docs = docs; }).error(function() { console.log('Search failed!'); }); }); }, template: '&lt;input ng-model="query" name="Search"&gt;&lt;/input&gt;' + '&lt;h2&gt;Search Results for {{query}}&lt;/h2&gt;' + '&lt;span ng-repeat="doc in results.docs"&gt;' + ' &lt;p&gt;{{doc[displayField]}}&lt;/p&gt;' + '&lt;/span&gt;' }; }); </code></pre> <p>So now I can think of my search results as a little widget to embed on the page:</p> <pre><code> &lt;search-results solrUrl="..." etc&gt;&lt;/search-results&gt; </code></pre> <p>OK Let's say I take the next step in my application and want to display more information about the individual documents from the search results. My inclination up to this point has been to create a custom directive, like a little "widget" that handles all the functionality here. If I need to say wrap-up how a document from the search results gets displayed, I'll add a directive like lets say "docDisplay". Something like:</p> <pre><code>angular.module('solrAngularDemoApp') .directive('docDisplay', function() { // same pattern as above }); </code></pre> <p>Then in the template for search Results, I'll change out my template:</p> <pre><code> template: '&lt;input ng-model="query" name="Search"&gt;&lt;/input&gt;' + '&lt;h2&gt;Search Results for {{query}}&lt;/h2&gt;' + '&lt;span ng-repeat="doc in results.docs"&gt;' + ' &lt;doc-display&gt;&lt;/doc-display&gt;' + // THIS LINE CHANGED '&lt;/span&gt;' </code></pre> <p>I may or may not use prototypical inheritance of $scope or use an isolate $scope, depending on how strongly I feel this directive is tied to the parent.</p> <p>After writing a lot of code this way and learning more about Angular, I realized that I could just have</p> <ol> <li>Thrown all this HTML into my main HTML</li> <li>Used ng-controller on specific pieces of HTML</li> </ol> <p>As nothing here takes advantage of the link functionality of the directive (binding DOM events to create some custome functionality) and my directives are just a bunch of HTML and controller code I'm left wondering the following two questions:</p> <ol> <li><strong>Is it ok to use directives like this to break up my UI? or am I thinking too much in the directives==controls mindset</strong></li> <li><strong>Should I avoid directives when there's no link function? and just stick with plain-jane HTML with ng-controller?</strong></li> </ol>
[ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2015-11-13T10:17:24.720", "Id": "203899", "Score": "0", "body": "Old question, however.. avoid `ng-controller` (its not reusable), use custom directives and TDD those directives. You should use HTML as your vehicle of user state instead of relying on implicit scope hierarchy to help communicate your intent better, and its actually very rare to have a section of your code that *doesn't* need input that wouldn't be better as a filter." } ]
[ { "body": "<p>AngularJS encourages <strong>slim controllers</strong>. They'd rather you have fat directives and services than controllers.</p>\n\n<p>I think you are absolutely correct to have many directives.</p>\n\n<p>In my angular apps, I have some directives without <code>link</code> to make my templates clean and readable. <em>You can compress trees of HTML into their high-level meaning</em>. Plus, if things get more complex later on, you can add a link function and add functionality with relative ease, and you don't have to change code in multiple places. As a Rails developer, I believe in <em>DRY</em> (don't repeat yourself). The fewer places the same code is, the easier it is to maintain.</p>\n\n<p>So, <code>directive</code> or <code>ng-controller</code>?</p>\n\n<p>If you are going to reuse a \"widget\" in multiple places, directives are ideal!</p>\n\n<p>If it's a one-off or the main feature of the page, you're probably better off making it a <code>ng-controller</code>.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-01-04T00:28:03.783", "Id": "64283", "Score": "1", "body": "I do this same kind of thing all the time. The only other thing I'd add on is you move that $http request into a companion service. Then you can easily mock and test this directive and service." } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-09-30T11:42:54.287", "Id": "32029", "ParentId": "30938", "Score": "6" } }, { "body": "<p>One thing I would say is having a lot of directives can have an impact on the performance of your app.</p>\n\n<p>If your directive does not have a link or compile function then I would suggest it is better just to have it as an html file (partial or view) and use ng-include on the div you wish to inject it.</p>\n\n<p>this way you still have nice declarative html, but with better performance, and more clear coding conventions to follow.</p>\n\n<p>looking at that 1st code example there is no compile or link function so that directive is unnecessary. you could include the template as an html file with ng-include within the scope of a self contained controller with the same functionality as the controller above. Also create a factory which exposes your necessary http requests and inject that into the controller.</p>\n\n<p>then it will be nice and de-coupled, you will have an html template you can inject into any controller scope you like, like wise you can inject your controller anywhere you like, and you will have a factory for http requests which you can inject into any controller you like.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2015-11-13T10:16:30.237", "Id": "203898", "Score": "0", "body": "This doesn't make any sense. In order to include code - and/or actually use the controller - you need to use a directive. Might as well use a custom directive. Angular 2.0 will move towards components which will be directive + controller (react-style) and remove the separation of controller and directive" } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-08-12T02:17:09.300", "Id": "59756", "ParentId": "30938", "Score": "3" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "1", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-09-08T03:01:31.257", "Id": "30938", "Score": "7", "Tags": [ "javascript", "angular.js" ], "Title": "In AngularJS, create lots of directives or use ng-controller?" }
30938
<p>I'm not sure if this implementation is good enough. The function takes a vector of 1 million chars and creates a table of the sequences that pass before the next occurrence of itself.</p> <p>Some questions I have, though feel free to point other things out as well:</p> <ul> <li>Is the initialization of the hash-map done well?</li> <li>Am I using the correct / optimal data structures and algorithm?</li> <li>I think my code is more procedural than needs to be, having trouble thinking of folding this correctly.</li> </ul> <p></p> <pre><code>(define (get-reocc v) ;'(#\J #\S #\T #\I #\J #\I #\O #\Z #\T #\S ....) -&gt; ; '#hash((#\T . #(1 357 1661 1939 1759 1425 1240 985 890 716 556 483 392 335 268 1258)) ; (#\J . #(1 449 1613 1914 1725 1480 1266 1021 850 748 581 527 377 317 255 1223)) ; (#\S . #(1 379 1678 1995 1708 1397 1230 1006 860 714 605 489 378 318 323 1211)) ; (#\L . #(1 449 1671 1916 1663 1492 1256 1000 862 735 572 449 400 330 276 1259)) ; (#\O . #(1 396 1596 1854 1727 1491 1270 1109 873 743 584 473 371 315 273 1209)) ; (#\I . #(1 396 1625 1901 1758 1414 1229 1057 852 733 605 483 359 328 260 1249)) ; (#\Z . #(1 394 1529 1973 1657 1473 1309 1018 863 746 569 481 362 355 245 1256))) (define reocc-table2 (make-hash)) (for ([i pieces]) (hash-set! reocc-table2 i (make-vector 16 0))) (define (update-reocc key pos t) ; #\T 3 '#hash((#\T . #(1 357 1661 1939 1759 -&gt; '#hash((#\T . #(1 357 1661 1940 1759 (define v2 (hash-ref t key)) (vector-set! v2 pos (+ 1 (vector-ref v2 pos)))) ; (hash-set y key (vector-set! v2 pos (+ 1 (vector-ref v2 pos))))) same as above? (define (find-prev v piece pos i2) ; (#\J #\S #\T #\I #\J #\I #\O #\Z #\T #\S) #\T, #\T, 10, 0 -&gt; 8 ; (define x (vector-ref v (- pos i2))) (cond [(char=? piece x) i2] [(= 0 (- pos i2)) 0] [#t (find-prev v piece pos (+ i2 1))])) (define (f v t i) (define p (vector-ref v i)) (define stop (- 1 (vector-length v))) (if(&gt;= i stop) t (f v (lambda () (update-reocc p (find-prev v p i 0) t)) (+ i 1)))) (f v reocc-table2 0)) </code></pre>
[]
[]
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-09-08T08:32:52.817", "Id": "30945", "Score": "1", "Tags": [ "lisp", "scheme", "vectors", "hash-map", "racket" ], "Title": "Creating an updating hash table" }
30945
<p>I've been learning Java for about 3 weeks now, and I was hoping someone could check over my code for me, and let me know how to improve.</p> <p>I am aware that the maths class could be removed (I could've typed <code>answer = inputA * inputB</code> etc. within the switch statement) but this is just because I wanted to practice using multiple classes.</p> <pre><code>import java.util.Scanner; public class Calculator { public static void main(String[] args) { Scanner input = new Scanner(System.in); Maths Maths = new Maths(); double answer = 0; double inputA, inputB; char operator; boolean done = false; while (done == false) { System.out.print("Please enter your sum: "); inputA = input.nextDouble(); operator = input.next().charAt(0); inputB = input.nextDouble(); switch (operator) { case '+': answer = Maths.add(inputA, inputB); break; case '-': answer = Maths.subtract(inputA, inputB); break; case '*': answer = Maths.multiply(inputA, inputB); break; case '/': answer = Maths.divide(inputA, inputB); break; case '^': answer = Maths.power(inputA, inputB); break; } System.out.println(answer); } input.close(); } } </code></pre> <p>And my second class...</p> <pre><code>public class Maths { double add(double a, double b) { double answer = a+b; return answer; } double subtract(double a, double b) { double answer = a-b; return answer; } double multiply(double a, double b) { double answer = a*b; return answer; } double divide(double a, double b) { double answer = a/b; return answer; } double power(double a, double b){ double answer =a; for (int x=2; x&lt;=b; x++){ answer *= a; } return answer; } } </code></pre>
[ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-09-10T11:58:53.817", "Id": "49421", "Score": "0", "body": "rhetorical question: why does java use: `public static double sqrt(double a)` ? see the API http://docs.oracle.com/javase/7/docs/api/java/lang/Math.html#sqrt%28double%29. hint: good book, effective java, 2nd edition. Sometimes methods **should** be static." } ]
[ { "body": "<ul>\n<li><p><code>power</code> should probably be using <code>Math.pow()</code>. I'm picturing how slow your code would be at calculating 1.0000001<sup>5000000</sup>. Or how inaccurate it'll be when someone wants to raise to a non-integer power. If those are not intended to be allowed, then passing <code>double</code>s all over the place seems odd. But it'd be better to check beforehand and throw an error than return a blatantly incorrect result, in my opinion.</p></li>\n<li><p>You never set <code>done</code> to true, and thus have an infinite loop; take out the flag and say <code>while (true)</code> or <code>for (;;)</code>, so that that's apparent. Don't add the flag back til you're also adding the code that sets it.</p></li>\n<li><p>The fact that you use objects doesn't make your code object-oriented. <em>How</em> you use them is what makes the difference. In this case, you're using classes as namespaces for functions, which is not very object-oriented at all.</p>\n\n<p>In your case, <code>Maths</code> is entirely useless; everything it does would be better done in your own code. This is an example of gratuitous use of objects. If you wanted to practice your OOP, you might want to think about how you'd get rid of that <code>switch</code> statement. Hint:</p>\n\n<pre><code>public interface BinaryOperation {\n public double resultFor(double left, double right);\n}\n\n\nclass Multiplication implements BinaryOperation {\n public double resultFor(double left, double right) {\n return left * right;\n }\n}\n\nclass Addition implements BinaryOperation {\n public double resultFor(double left, double right) {\n return left + right;\n }\n}\n\nprivate Map&lt;Character, BinaryOperation&gt; operations;\n\n...\n\noperations.put('*', new Multiplication());\noperations.put('+', new Addition());\n\n...\n\nBinaryOperation op = operations.get(operator);\nif (op != null) {\n answer = op.resultFor(inputA, inputB);\n}\nelse {\n System.out.println(\"Error: Unknown operator\");\n]\n</code></pre></li>\n</ul>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-09-08T11:56:10.080", "Id": "49258", "Score": "1", "body": "Making a class for just multiplication is overkill. OP is just a beginner, he needs time to know about Map. Give him time to digest :P." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-09-08T12:01:30.230", "Id": "49259", "Score": "5", "body": "@tintinmj: He wanted to learn about OOP. OOP is about more than just saying `new` a lot. :P If he's not using polymorphism or encapsulating something, he's not using OOP. In such cases, he would be better off *not* using it just yet than using it wrong from the very start and getting the wrong ideas ingrained." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-09-08T12:05:41.060", "Id": "49260", "Score": "1", "body": "Thanks-- I'll take that on board. As you say, I don't want to get in any bad habits early on" } ], "meta_data": { "CommentCount": "3", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-09-08T11:42:49.613", "Id": "30952", "ParentId": "30950", "Score": "17" } }, { "body": "<p>For a beginner it's a good approach. You need to know about <a href=\"http://java.about.com/od/javasyntax/a/nameconventions.htm\">Java Naming Convention</a>. We use <strong>mixed case</strong> for naming any variable or instance of a class. So in your code <code>Maths Maths = new Maths();</code> should be <code>Maths maths = new Maths();</code>. </p>\n\n<p>Or even better make all the methods in <code>Maths</code> class <code>public static</code> as the instance of the class doesn't play any part in computation. Point to be noted in Java we make utility class's methods static as you can see in API's <a href=\"http://docs.oracle.com/javase/6/docs/api/java/lang/Math.html\">Math class</a>, <a href=\"http://docs.oracle.com/javase/6/docs/api/java/util/Arrays.html\">Array class</a>.</p>\n\n<p>Suggestions</p>\n\n<ul>\n<li>In <code>add</code>, <code>subtract</code> methods you don't need to introduce a new <code>answer</code> variable. Just return the result like <code>return (a+b);</code> or <code>return (a-b);</code>.</li>\n<li><code>while (done == false)</code> is yukkk. Just make it <code>while (!done)</code>.</li>\n</ul>\n\n<p>Thumbs up for closing the Scanner. Now read about <a href=\"http://docs.oracle.com/javase/tutorial/essential/exceptions/\">Exception handling</a>. Happy programming!!! :D</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2018-02-03T15:43:25.877", "Id": "356154", "Score": "0", "body": "Actually, when Scanner is opened to System.in, it should *not* be closed. You won't be able to use System.in after that." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2018-02-03T20:54:37.087", "Id": "356211", "Score": "0", "body": "@ksnortum Can you explain with an example or any source of this?" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2018-02-05T15:01:42.597", "Id": "356443", "Score": "0", "body": "@tintinmj, Here you go: https://gist.github.com/ksnortum/22eeae450122a1112d3e6c1a674359e2" } ], "meta_data": { "CommentCount": "3", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-09-08T11:51:51.407", "Id": "30953", "ParentId": "30950", "Score": "13" } } ]
{ "AcceptedAnswerId": "30953", "CommentCount": "1", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-09-08T11:02:31.660", "Id": "30950", "Score": "11", "Tags": [ "java", "beginner", "calculator" ], "Title": "Simple calculator in Java" }
30950
<p>------edit---------</p> <p>note: this is for a <a href="http://en.wikipedia.org/wiki/Mud_client" rel="nofollow">MUD client</a>, so the commands are issued to the MUD game server</p> <p>-----end edit--------</p> <p>For an overview, here's the structure of the project:</p> <pre><code>NetBeansProjects/TelnetConsole/src/ ├── connection.properties └── telnet ├── connection │   ├── CharacterDataQueueWorker.java │   ├── ConsoleReader.java │   ├── InputStreamWorker.java │   └── PropertiesReader.java ├── Controller.java └── game ├── Command.java ├── PlayerCharacter.java ├── PlayerFlags.java ├── PlayerLogic.java ├── PlayerStats.java └── RegexWorker.java 3 directories, 12 files </code></pre> <p>I'm fairly sure that <code>PlayerFlags</code> and <code>PlayerStats</code>, if not <code>PlayerCharacter</code> itself, deserve Builders. This, very basic, MUD client has <code>PlayerCharacter</code> as Singleton to ensure that the correct (the only) player character is referenced.</p> <p>I've resorted to making the other classes beans because I seem to have a sort of infinitite regression where <code>PlayerCharacter</code> has <code>PlayerFlags</code> (booleans) and <code>PlayerStats</code> (integers), as well as <code>PlayerLogic</code> and the <code>RegexWorker</code>. I would much rather use builders, or factories, to clarify and make explicit the state of the player character and the commands.</p> <p>Ideally, <code>PlayerLogic</code> and <code>RegexWorker</code> should, I think, strictly have static methods, but for now, these classes also are distorted beans, which is ok.</p> <p>The infinite, or too deep for me, at least, regression is that <code>PlayerLogic</code> and <code>RegexWorker</code> each have references to <code>PlayerStats</code> and <code>PlayerFlags</code>. <code>RegexWorker</code> sets flags on the <code>PlayerCharacter</code> Singleton, while <code>PlayerLogic</code> both sets and reads the flags. (Yes, the logic class shouldn't change the state of the `PlayerCharacter', but that's ok for now.) It seems to be circular composition, or at least flawed in some way.</p> <p>It becomes a problem of initialization. While <code>PlayerStats</code> and <code>PlayerFlags</code> have default settings, its never quite explicit, to me, which reference is being used at any given time. As a kludge, the utility type classes, <code>RegexWorker</code> and <code>PlayerLogic</code>, each get a fresh reference to the current state through the <code>PlayerCharacter</code> Singleton for each opportunity to do so, and similarly refresh the state of <code>PlayerCharacter</code> whenever possible.</p> <p>Without this kludge, the program refuses to run, generating, if I recall correctly, a null-pointer because <code>PlayerStats</code> and <code>PlayerFlags</code> each have null references, not having not initialized in the Singleton. (The regex worker actually initializes the state of the player character with data from the MUD server.) </p> <p>Because of the initialization paradox, these classes should have private constructors and at least a Builder each, if not a static factory method to create new instances, if only to make it easier for me to understand. I would rather that state be immutable, but then it's just awkward, and <em>very</em> verbose. However, each time I try to make these classes small and immutable it just gets more complex.</p> <p>The controller invokes <code>PlayerCharacter.processRemoteOutput</code> as necessary (when it receives a message from the <code>CharacterDataQueueWorker</code>).</p> <p>code:</p> <pre><code>package telnet.game; import java.util.Queue; import java.util.logging.Logger; public enum PlayerCharacter { INSTANCE; //only one player can play the client private final static Logger log = Logger.getLogger(PlayerCharacter.class.getName()); private PlayerStats stats = new PlayerStats(); private PlayerFlags flags = new PlayerFlags(); private PlayerCharacter() { } public Queue&lt;Command&gt; processRemoteOutput(String remoteOutputMessage) { log.fine("trying to process..."); RegexWorker regexWorker = new RegexWorker(); regexWorker.parseAndUpdatePlayerCharacter(remoteOutputMessage); PlayerLogic playerLogic = new PlayerLogic(); Queue&lt;Command&gt; newCommands = playerLogic.doLogic(); for (Command c : newCommands) { log.fine(c.toString()); } return newCommands; } public PlayerStats getStats() { return stats; } public void setStats(PlayerStats stats) { this.stats = stats; } public PlayerFlags getFlags() { log.fine(flags.toString()); return flags; } public void setFlags(PlayerFlags flags) { this.flags = flags; } }package telnet.game; import java.util.List; import java.util.Map.Entry; import java.util.Observable; import java.util.logging.Logger; public class PlayerFlags { private final static Logger log = Logger.getLogger(PlayerFlags.class.getName()); private boolean backstab = false; private boolean heartplunge = false; private boolean enervate = false; private boolean confuse = false; private boolean corpse = false; private boolean loggedIn = true; private boolean doping = false; private boolean healing = false; public PlayerFlags() { } PlayerFlags(List&lt;Entry&gt; flagsEntries) { String key = null; boolean val = false; switch (key) { case "loggedIn": loggedIn = val; break; case "confuse": confuse = val; break; } } public boolean isBackstab() { return backstab; } public void setBackstab(boolean backstab) { this.backstab = backstab; } public boolean isHeartplunge() { return heartplunge; } public void setHeartplunge(boolean heartplunge) { this.heartplunge = heartplunge; } public boolean isEnervate() { return enervate; } public void setEnervate(boolean enervate) { this.enervate = enervate; } public boolean isConfuse() { return confuse; } public void setConfuse(boolean confuse) { this.confuse = confuse; } public boolean isCorpse() { return corpse; } public void setCorpse(boolean corpse) { this.corpse = corpse; log.fine("corpse\t" + this.corpse); } public boolean isLoggedIn() { return loggedIn; } public void setLoggedIn(boolean loggedIn) { this.loggedIn = loggedIn; } public boolean isDoping() { return doping; } public void setDoping(boolean doping) { this.doping = doping; } public boolean isHealing() { return healing; } public void setHealing(boolean healing) { this.healing = healing; } public String toString() { return "corpse\t" + corpse; } } package telnet.game; import java.util.List; import java.util.Map.Entry; public class PlayerStats { private int hp = 0; private int cp = 0; private int adrenaline = 0; private int endorphine = 0; private int berserk = 0; private int none = 0; private int darts = 0; private int blood = 0; private int grafts = 0; public PlayerStats() { } public PlayerStats(List&lt;Entry&gt; stringEntries) { String key = null, val = null; for (Entry e : stringEntries) { key = e.getKey().toString(); key = key.toLowerCase(); val = e.getValue().toString(); if (key.contains("hp")) { key = "hp"; } if (key.contains("cp")) { key = "cp"; } if (key.contains("adrenaline")) { key = "adrenaline"; } if (key.contains("endorphine")) { key = "darts"; } if (key.contains("berserk")) { key = "darts"; } if (key.contains("none")) { key = "none"; } if (key.contains("blood")) { key = "blood"; } if (key.contains("grafts")) { key = "grafts"; } switch (key) { case "hp": hp = Integer.parseInt(val); break; case "cp": cp = Integer.parseInt(val); break; case "adrenaline": adrenaline = Integer.parseInt(val); break; case "endorphine": endorphine = Integer.parseInt(val); break; case "berserk": berserk = Integer.parseInt(val); break; case "none": none = Integer.parseInt(val); break; case "darts": darts = Integer.parseInt(val); break; case "blood": blood = Integer.parseInt(val); break; case "grafts": grafts=Integer.parseInt(val); break; } } } public int getHp() { return hp; } public void setHp(int hp) { this.hp = hp; } public int getCp() { return cp; } public void setCp(int cp) { this.cp = cp; } public int getAdrenaline() { return adrenaline; } public void setAdrenaline(int adrenaline) { this.adrenaline = adrenaline; } public int getEndorphine() { return endorphine; } public void setEndorphine(int endorphine) { this.endorphine = endorphine; } public int getBerserk() { return berserk; } public void setBerserk(int berserk) { this.berserk = berserk; } public int getNone() { return none; } public void setNone(int none) { this.none = none; } public int getDarts() { return darts; } public void setDarts(int darts) { this.darts = darts; } public int getBlood() { return blood; } public void setBlood(int blood) { this.blood = blood; } public int getGrafts() { return grafts; } public void setGrafts(int grafts) { this.grafts = grafts; } public String toString() { return "\n\nhp\t" + hp + "\tcp\t" + cp + "\tadrenaline\t" + adrenaline + "\nendorphine\t" + endorphine + "\t\tberserk\t" + berserk + "\nenemy\t" + none; } } package telnet.game; import java.util.LinkedList; import java.util.Queue; import java.util.logging.Logger; public class PlayerLogic { private final static Logger log = Logger.getLogger(PlayerLogic.class.getName()); private PlayerCharacter playerCharacter = PlayerCharacter.INSTANCE; private PlayerFlags flags = new PlayerFlags(); public PlayerLogic() { } private Queue&lt;Command&gt; confuse() { Queue&lt;Command&gt; commands = new LinkedList&lt;&gt;(); Command confuse = new Command("confuse"); Command backstab = new Command("backstab"); Command heartplunge = new Command("heartplung"); Command enervate = new Command("enervate"); commands.add(confuse); commands.add(heartplunge); commands.add(backstab); commands.add(enervate); commands.add(confuse); flags.setConfuse(false); return commands; } private Queue&lt;Command&gt; corpse() { Queue&lt;Command&gt; commands = new LinkedList&lt;&gt;(); Command draw = new Command("draw"); Command processCorpse = new Command("process corpse"); Command getAll = new Command("get all"); Command monitor = new Command("monitor"); Command glance = new Command("glance"); commands.add(draw); commands.add(processCorpse); commands.add(getAll); commands.add(monitor); commands.add(glance); flags.setCorpse(false); return commands; } private Queue&lt;Command&gt; healing() { log.fine(playerCharacter.toString()); Queue&lt;Command&gt; commands = new LinkedList&lt;&gt;(); if (playerCharacter.getStats().getEndorphine() &gt; 0) { Command e = new Command("endorphine 5"); commands.add(e); } if (playerCharacter.getStats().getBerserk() &gt; 0) { Command b = new Command("berserk 0"); commands.add(b); } Command m = new Command("monitor"); flags.setHealing(false); commands.add(m); return commands; } public Queue&lt;Command&gt; doLogic() { log.fine("should print..."); flags = playerCharacter.getFlags(); log.fine(flags.toString()); Queue&lt;Command&gt; commands = new LinkedList&lt;&gt;(); log.fine(playerCharacter.getFlags().toString()); if (playerCharacter.getFlags().isConfuse()) { commands.addAll(confuse()); } if (playerCharacter.getFlags().isCorpse()) { commands.addAll(corpse()); } if (playerCharacter.getFlags().isHealing()) { commands.addAll(healing()); } if (!playerCharacter.getFlags().isLoggedIn()) { commands = new LinkedList&lt;&gt;(); } playerCharacter.setFlags(flags); return commands; } } </code></pre>
[]
[ { "body": "<p>1) (Minor Detail) Don't make PlayerCharacter a singleton. I understand it only occurs once, but it seems overkill to make it a singleton, and making it an enum is even more confusing.</p>\n\n<p>2) PlayerFlags should instead be an <code>EnumMap&lt;Flag, Boolean&gt;</code> where Flag is a simple enum of all the flags. Similarly, PlayerStats should be <code>EnumMap&lt;Stat, Integer&gt;</code>. I would remove everything else from PlayerCharacter; it would just have two getter methods for the EnumMap's.</p>\n\n<p>3) (Minor Detail) I don't see why you would need the constructor <code>public PlayerStats(List&lt;Entry&gt; stringEntries)</code>. You should just create the stats initially with their default start values and they would just be updated as the game goes. Anyway, since this should be an EnumMap, it is not an issue.</p>\n\n<p>5) (Minor Detail) In PlayerLogic, you have members <code>playerCharacter</code> and <code>flags</code>. You initially define <code>flags</code> as something else then the flags member in <code>playerCharacter</code>, but they you do set it to the flags in <code>playerCharacter</code>. That is dangerous. You should not define a separate <code>flags</code> member but manipulate the flags in <code>playerCharacter</code>. Actually, you do <code>playerCharacter.setFlags(flags)</code> at the end of PlayerLogic.doLogic(), so I assume there are some bugs in your handling of the flags. Anyway, if you follow what I write below, you won't even have that method anymore.</p>\n\n<p>6) I would change the name PlayerLogic to CommandProcessor, or similar. It would have one public method to process the incoming command strings.</p>\n\n<p>7) Instead of having <code>Queue&lt;Command&gt;</code> make a subclass of Command called CommandSequence which contains a queue of commands. Command should be an interface with a single method called <code>modify(playerCharacter)</code>, or similar. Your methods confuse(), corpse(), healing(), etc. would just be subclasses of Command, or CommandSequence. </p>\n\n<p>8) In CommandProcessor, you will probably need a member <code>Map&lt;String, Command&gt;</code> to process the incoming text (instead of your RegexWorker). Note that the String's in that map would not include any numerical argument, ie. not \"endorphine 5\", but just the first word, \"endorphine\". </p>\n\n<p>9) (Minor Detail) For all the stats (hp, cp, adrenaline, ...), you can define a single Command sub-class to deal with all of them:</p>\n\n<pre><code>public BasicStatCommand implements Command {\n private Stat stat;\n private int newValue;\n\n public BasicStatCommand(Stat stat, int newValue) {\n this.stat = stat;\n this.newValue = newValue;\n }\n\n @Override\n public void modify(PlayerCharacter player) {\n player.stats.put(stat, newValue);\n }\n}\n</code></pre>\n\n<p>You could also define a BasicStatIncrementCommand where you could add or substract some given value to some stat. You would not to be careful about going below 0; either disallow it, or have some method later in the processing that checks for negative values and takes the appropriate actions (ie, terminate the game if the life value is negative). Also, if all Stat's have a minimum and maximum value, you could encode that information in the enum itself:</p>\n\n<pre><code>enum Stat {\n XP(10, 0, 10), CP(10, 0, 10), ADRENALINE(0, 0, 10), ...;\n\n public Stat(int defaultStartValue, int minimum, int maximum) {\n this.defaultStartValue = defaultStartValue;\n this.minimum = minimum;\n this.maximum = maximum;\n }\n\n private final int defaultStartValue;\n private final int minimum;\n private final int maximum;\n\n ... add the getters (no setters since those are constants)\n}\n</code></pre>\n\n<p><strong>Summary</strong><br>\nSo the Command's now contain no reference to the player. Instead the player is just an argument to <code>command.modify(player)</code>.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-09-08T23:14:13.797", "Id": "49277", "Score": "0", "body": "I'm going through everything, thank you. In particular point five is, I think, my main organizational problem." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-09-09T04:02:47.193", "Id": "49287", "Score": "0", "body": "This is great advice. I'll only add that `Player`--you can drop the `Character` suffix I think--should be responsible for modifying stats. The commands should call methods on `Player` to modify it. Don't let other classes reach in to access `PlayerStats` as it violates encapsulation." } ], "meta_data": { "CommentCount": "2", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-09-08T14:48:07.153", "Id": "30957", "ParentId": "30951", "Score": "2" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-09-08T11:15:57.107", "Id": "30951", "Score": "2", "Tags": [ "java", "design-patterns", "singleton" ], "Title": "Singleton has logic and state, and logic has state" }
30951
<p>I really need a review on the structure, and how things are done. I want to improve.</p> <p>Command.class:</p> <pre><code>&lt;?php /** * Command * Processing commands to the server, acting, receiving response. * * @author Jony &lt;driptonethemes@gmail.com&gt; */ class Command extends PrepareCommand { /** * Client * The command processor * @object Client */ private $client; /** * Annonymous constructor * Constructs the application. * * @param message ; Object Client */ public function __construct(Client $message) { $this-&gt;client = $message; if ($this-&gt;isUsingCommand()) { $this-&gt;_prepare(); } } /** * Protected _prepare * Preparing the command line. * * @return void */ protected function _prepare() { $this-&gt;_commander = $this-&gt;client; $this-&gt;_process(); $this-&gt;processCommand(); } /** * processCommand * Processing the given commmand, finds out * what command was used, and it's data. * * @var _commandLine ; The used command name. * @var _commandActions ; The data that comes after the command * @return void */ private function processCommand() { switch ($this-&gt;_commandLine[1]) { case "ban": echo "LOl you tried to ban " . $this-&gt;fullString(); break; case "yell": echo $this-&gt;fullString(); break; } } /** * isUsingCommand * Is the Client using a command at all? * Checks if line starts with the command sign " / ". * * @return boolean */ public function isUsingCommand() { return (substr($this-&gt;client-&gt;getMessage(), 0, 1) === "/") ? true : false; } /** * fullString * Gets all of the array elements of _commandActions and * converts it to one big String * * @var message ; The String message. * @var _commandActions ; The data that comes after the command. * @return String */ private function fullString() { $message = ""; for ($i = 1; $i &lt; count($this-&gt;_commandActions); $i++) { $message .= " " . $this-&gt;_commandActions[$i]; } return $message; } } ?&gt; </code></pre> <p>PrepareCommand.class:</p> <pre><code>&lt;?php abstract class PrepareCommand { /** * Properties */ private $command; protected $_commander; protected $_commandActions; protected $_commandLine; /** * Processing the command, and calling parse * to explore the commandline. * * @return void */ protected function _process() { $this-&gt;command = $this-&gt;_commander-&gt;getMessage(); $this-&gt;parse(); } /** * Parsing the command ; Exploring it ; * Getting the first command and actions. * * @var _commandActions ; Holding all of the words, between the entered spaces. * @var _commandLine ; Getting the entered command name after the " / " sign. * @return void */ private function parse() { $this-&gt;_commandActions = explode(" ", $this-&gt;command); $this-&gt;_commandLine = explode("/", $this-&gt;_commandActions[0]); } /** * Abstract prapre * * Activating the class, and preparing the command * through the class. * * @return void */ protected abstract function _prepare(); } ?&gt; </code></pre> <p>usage:</p> <pre><code>new Command(new Client($_POST['process'], date('time'), "guest")); </code></pre>
[]
[ { "body": "<ol>\n<li>Stop using underscore to indicate private/protected parts of a class.</li>\n<li>Do not put logic in the constructors</li>\n<li>It is pointless to have <code>... ? true : false;</code> in <code>isUsingCommand()</code>.</li>\n<li>Use <a href=\"http://uk3.php.net/manual/en/function.implode.php\" rel=\"nofollow\"><code>implode()</code></a> in <code>fullString()</code></li>\n</ol>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-09-14T19:53:09.050", "Id": "49794", "Score": "0", "body": "Any reason why is using underscore bad? I've been using it and helps me nicely to separate private and public methods." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-09-14T20:32:43.803", "Id": "49795", "Score": "0", "body": "@DmitriZaitsev that's what `private` and `protected` keywords are for. The underscore notation is a throwback from PHP4, when there were no options to set visibility of class members. The practice itself comes from Hungarian notation. So, to sum it up - unless you also use `$iCount` and `cPuppy`, and `iPrintable` or are stuck in PHP4, you should not use underscore for this purpose." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-09-14T20:42:53.110", "Id": "49796", "Score": "0", "body": "The keywords like `private` are only used in _declarations_. Everywhere else the variable is alone. By putting underscore I can easily see this variable's visibility without searching for its declaration. The hungarian `$iCount` is different - coming back after X months to my code I will ask - what's the hell is the `i`? But if I see `$_count` even after X years, I (and many developers) will still have the right guess about what underscore means. So the 1st notation was obscuring but the 2nd is helpful. So if that is the only reason, I am not convinced :)." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-09-14T21:06:47.150", "Id": "49799", "Score": "0", "body": "The `i` is for \"integer\". Look up the \"hungarian notation\"." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-09-14T21:31:32.757", "Id": "49800", "Score": "0", "body": "Not unless there is another type beginning with `i`. Anyhow, my point was that using underscore is helpful and suggestive and so improves my code readability imho. That is why I'm surprised to hear it is bad but I am ready to learn if there is any serious reason." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-09-15T17:53:27.247", "Id": "49863", "Score": "0", "body": "Just checked more sources on the subject and it is indeed not all black and white. Joel Spolsky has [fantastic article](http://www.joelonsoftware.com/articles/Wrong.html) going in depth about good use of Hungarian notation vs abuse and misunderstanding that lead people to declare them bad. Specifically `$iCount` and `cPuppy` are precisely examples of the misconception. Another in-depth analysis is http://stackoverflow.com/questions/5428/do-people-use-the-hungarian-naming-conventions-in-the-real-world where author of the top answer actually does use `_`." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-09-15T18:10:42.223", "Id": "49865", "Score": "0", "body": "Here is another nice advantage of `_` that I discovered. Whenever I decide to change my `$_privateVariable` from _private_ to _public_ (for testing or other purposes), I am forced to replace it everywhere by `$privateVariable`. A bad thing? The opposite! Being lazy as I am, and exactly because such a change is tedious, I rather write a _getter_ to expose the variable without making it public. If I didn't use the notation, I could too easily change _private_ to _public_. Making my laziness win over best practice. So the `_` forces me to use good practices. Not bad at all!" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-09-15T18:29:14.653", "Id": "49868", "Score": "0", "body": "I don't care for your excuses. Please stop trying to drag me into discussing the color of bike-shed." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-09-15T18:42:05.930", "Id": "49871", "Score": "0", "body": "I didn't mean to drag you into anything. I sincerely want to learn the exact meaning of your comment, and sincerely believe my comments can be of help to reader who wants to learn it too." } ], "meta_data": { "CommentCount": "9", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-09-08T13:41:23.880", "Id": "30955", "ParentId": "30954", "Score": "3" } }, { "body": "<p>Such comments are obvious and help very little to read the code:</p>\n\n<pre><code> /**\n * Annonymous constructor\n * Constructs the application.\n</code></pre>\n\n<p>Uncle Bob in his seminal <a href=\"http://rads.stackoverflow.com/amzn/click/0132350882\" rel=\"nofollow\">Book \"Clean Code\"</a> recommends to replace comments (that are often imprecise and tend to lie once code changes) as much as possible by expressive names of your methods.</p>\n\n<p>For instance call your method <code>_prepareCommandLine</code> instead of just <code>_prepare</code>, then you don't need to put in the comments.\nMoreover, should you decide to change this method, you much more likely to change its name to reflect the new function, but can easily forget to change the comment. </p>\n\n<hr>\n\n<p>This is well-known anti-pattern:</p>\n\n<pre><code>for ($i = 1; $i &lt; count($this-&gt;_commandActions); $i++)\n</code></pre>\n\n<p>This way the count function executes in every single loop. You can avoid this:</p>\n\n<pre><code>for ($i = 1, $max = count($this-&gt;_commandActions); $i &lt; $max; $i++)\n</code></pre>\n\n<p>However, if your loop only concatenates array, using <code>implode</code> is even better as suggested by tereško.</p>\n\n<hr>\n\n<p>Why underscore for protected but none for private?</p>\n\n<pre><code> private $command;\n protected $_commander;\n</code></pre>\n\n<p>That would make more sense:</p>\n\n<pre><code> private $__command;\n protected $_commander;\n</code></pre>\n\n<hr>\n\n<p>Again, the name says little about what's going on:</p>\n\n<pre><code>private function parse() \n</code></pre>\n\n<hr>\n\n<p>These comments are again obvious and worse, have misprints:</p>\n\n<pre><code> /**\n * Abstract prapre\n *\n</code></pre>\n\n<p>This type of line is way too concrete for an abstract class:</p>\n\n<pre><code> $this-&gt;_commandLine = explode(\"/\", $this-&gt;_commandActions[0]);\n</code></pre>\n\n<p>You may want to revise your abstractions :)</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-09-15T18:43:07.700", "Id": "49872", "Score": "0", "body": "Any comment why the downvote?" } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-09-14T20:20:30.763", "Id": "31281", "ParentId": "30954", "Score": "0" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-09-08T12:25:54.790", "Id": "30954", "Score": "2", "Tags": [ "php", "object-oriented" ], "Title": "Object-oriented command processor" }
30954
<p>I just finished a widget clock that displays the actual seconds and changes an <code>ImageView</code> each 15 minutes. I have used a <code>BroadcastReceiver</code> with <code>AlarmManager;</code>. I also have setup a click on an <code>ImageView</code> to change it for another image and play a sound, and this image is back to an original one after 5 seconds. I'm using a <code>ClickPendingIntent</code> to handle this and everything works fine, however my widget appears using 2% of the battery, which I think is too much for only displaying the actual time.</p> <p>Please let me know if this is normal or there is something that I can do to avoid use unnecessary battery.</p> <p>AppWidgetProvider:</p> <pre><code>@Override public void onUpdate(Context context, AppWidgetManager appWidgetManager, int[] appWidgetIds) { // TODO Auto-generated method stub //super.onUpdate(context, appWidgetManager, appWidgetIds); RemoteViews remoteViews = new RemoteViews(context.getPackageName(), R.layout.widget_demo); pushWidgetUpdate(context, remoteViews); } @SuppressWarnings("deprecation") @Override public void onEnabled(Context context) { // TODO Auto-generated method stub //super.onEnabled(context); RemoteViews remoteViews = new RemoteViews(context.getPackageName(), R.layout.widget_demo); remoteViews.setOnClickPendingIntent(R.id.imageView1, buildButtonPendingIntent(context)); AlarmManager alarmManager = (AlarmManager)context.getSystemService(Context.ALARM_SERVICE); alarmManager.setRepeating(AlarmManager.RTC, System.currentTimeMillis() + 1000, 1000, test(context)); pushWidgetUpdate(context, remoteViews); } @Override public void onDisabled(Context context) { // TODO Auto-generated method stub //super.onDisabled(context); Intent intent = new Intent(context, MyWidgetProvider.class); PendingIntent sender = PendingIntent.getBroadcast(context, 0, intent, 0); AlarmManager alarmManager = (AlarmManager) context.getSystemService(Context.ALARM_SERVICE); alarmManager.cancel(sender); } public static PendingIntent buildButtonPendingIntent(Context context){ Intent intent = new Intent(); intent.setAction("custom.intent.action.CHANGE_PICTURE"); return PendingIntent.getBroadcast(context, 0, intent, PendingIntent.FLAG_UPDATE_CURRENT); } public static PendingIntent test(Context context){ Intent intent = new Intent(); intent.setAction("custom.intent.action.HELLO"); return PendingIntent.getBroadcast(context, 0, intent, PendingIntent.FLAG_UPDATE_CURRENT); } public static void pushWidgetUpdate(Context context, RemoteViews remoteViews){ ComponentName myWidget = new ComponentName(context, MyWidgetProvider.class); AppWidgetManager manager = AppWidgetManager.getInstance(context); manager.updateAppWidget(myWidget, remoteViews); } </code></pre> <p>BroadcastReceiver:</p> <pre><code>@Override public void onReceive(Context context, Intent intent) { // TODO Auto-generated method stub if(intent.getAction().equals("custom.intent.action.CHANGE_PICTURE")){ updateWidgetPictureAndButtonListener(context, true); } else if(intent.getAction().equals("custom.intent.action.HELLO")){ updateWidgetPictureAndButtonListener(context, false); } } private void updateWidgetPictureAndButtonListener(Context context, boolean updateOnlyPicture){ RemoteViews remoteViews = new RemoteViews(context.getPackageName(), R.layout.widget_demo); java.text.DateFormat dateFormat = SimpleDateFormat.getTimeInstance(SimpleDateFormat.MEDIUM, Locale.getDefault()); if(updateOnlyPicture == true){ remoteViews.setImageViewResource(R.id.imageView1, getImageToSet()); MediaPlayer mPlayer = MediaPlayer.create(context, R.raw.alert); mPlayer.start(); } else if(updateOnlyPicture == false){ remoteViews.setTextViewText(R.id.textView1, dateFormat.format(new Date())); @SuppressWarnings("deprecation") int min = dateFormat.getCalendar().getTime().getMinutes(); @SuppressWarnings("deprecation") int sec = dateFormat.getCalendar().getTime().getSeconds(); //Refresh image to a normal state after being clicked if(isImageclicked == true){ if(sec == actualSeconds + 5){ remoteViews.setImageViewResource(R.id.imageView1, R.drawable.center); actualSeconds = 0; isImageclicked = false; } } if(min == 00){ remoteViews.setImageViewResource(R.id.imageView1, R.drawable.center); } else if(min == 15){ remoteViews.setImageViewResource(R.id.imageView1, R.drawable.left); } else if(min == 30){ remoteViews.setImageViewResource(R.id.imageView1, R.drawable.right); } else if(min == 45){ remoteViews.setImageViewResource(R.id.imageView1, R.drawable.down); } } remoteViews.setOnClickPendingIntent(R.id.imageView1, MyWidgetProvider.buildButtonPendingIntent(context)); MyWidgetProvider.pushWidgetUpdate(context, remoteViews); } @SuppressWarnings("deprecation") private int getImageToSet(){ java.text.DateFormat dateFormat = SimpleDateFormat.getTimeInstance(SimpleDateFormat.MEDIUM, Locale.getDefault()); clickCount++; isImageclicked = true; actualSeconds = dateFormat.getCalendar().getTime().getSeconds(); return R.drawable.alert; } </code></pre> <p>Do you think 2% - 3% is "good" for a clock widget? If not, what would you recommend to make it use less battery? It does consume any battery for at least a day, but then it appears in the battery analyzer app with 2% and then increases in 1% slowly, but it does it. I was using a service which seems to use less battery, but when a user clears the processes in memory, it stops working.</p>
[]
[ { "body": "<p>Well, after doing some research and testing, I think the BroadcastReceiver is the best way to create a clock, however the update each second can drain the battery, in some phones is not noticeable, but I prefered to update it each minute, I personally do not recommend using services or handler since these are killed by android in a regular basis and, if you go and release processes from the memory, the application stops working.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-09-06T20:49:34.160", "Id": "30959", "ParentId": "30958", "Score": "1" } } ]
{ "AcceptedAnswerId": "30959", "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-09-01T21:06:14.300", "Id": "30958", "Score": "2", "Tags": [ "java", "android", "datetime" ], "Title": "A Widget Clock with seconds" }
30958
<p>I've been doing a lot of searching on PHP, logins, forms, cookies, sessions, etc. And so, I've tried to gather all the info that I got from all over the place. But, I didn't find a place with all the info, and tried to do the best secure login I could do.</p> <p>This is what I have. If this ends up being good, others can use this. Otherwise, just ignore it. But I'd like to have opinions.</p> <p>First, every page makes sure you use <code>HTTPS</code>:</p> <pre><code>if($_SERVER["HTTPS"] != "on") { header("Location: https://" . $_SERVER["HTTP_HOST"] . $_SERVER["REQUEST_URI"]); exit(); } </code></pre> <p>Send <code>username</code> and <code>pass</code> using <code>POST</code> over the <code>https</code> should be safe enough?</p> <p>Using <code>XMLHttpRequest</code> to check password on <code>Check.php</code>:</p> <pre><code>function validate() { var un = document.form1.myusername.value; var pw = document.form1.mypassword.value; httpObject = getHTTPObject(); if (httpObject != null) { var params = "username="+un+"&amp;password="+pw; httpObject.open("POST","Check.php", true); httpObject.setRequestHeader("Content-type","application/x-www-form-urlencoded"); httpObject.setRequestHeader("Content-length",params.length); httpObject.setRequestHeader("Connection","close"); httpObject.onreadystatechange = setValid; httpObject.send(params); } } </code></pre> <p>On <code>Check.php</code>, upon confirming password (which was saved on server encrypted), I set up cookie and session creating unique IDs and session secrets:</p> <pre><code>if($u==$username &amp;&amp; $p==$password) { $valid=1; //Setting up session and cookie //if cookie stored secret does not meet session secret, session has been hijacked, the same for id //session is stored on server while cookie is stored on client session_start(); $sessionTime = time(); $unique_id = uniqid(sha1($_SERVER['HTTP_USER_AGENT'] . $username), true); //create a unique ID $sessionSecret = sha1($sessionTime . $unique_id); // Create a unique secret based on time and ID $_SESSION[$unique_id]['time'] = $sessionTime; $_SESSION[$unique_id]['user'] = $us; $_SESSION[$unique_id]['secret'] = $sessionSecret; // if user changes cookie Secret, it wont match any secret of any other session stored in server setcookie("LoginCookie_s", $sessionSecret); setcookie("LoginCookie_i", $unique_id); // inform user that login was successfull echo $valid; return; } </code></pre> <p>Back in login: if the return value is <code>1</code>, I can proceed to main page. On the main page and every other pages I validate cookie and session:</p> <pre><code>&lt;?php // Validate session and cookie //if cookie stored secret does not meet session secret, session has been hijacked, the same for id //session is stored on server while cookie is stored on client //is cookie set? if(!isset($_COOKIE["LoginCookie_s"]) || !isset($_COOKIE["LoginCookie_i"])) { //this guy did not pass by login! header("location:Login.php"); exit(); } session_start(); // was session started on login? if(!isset( $_SESSION[$_COOKIE["LoginCookie_i"]] )) { //this guy did not pass by login! header("location:Login.php"); exit(); } // even if a user forged an id matching another user's id he would need to change cookie secret // if user changes cookie id or secret, it wont match the session secret of that other user id if( $_COOKIE["LoginCookie_s"] != $_SESSION[$_COOKIE["LoginCookie_i"]]['secret'] ) { //cookie and\or session has been hijacked header("location:Login.php"); exit(); } //all is fine, proceed loading the rest of the page... ?&gt; </code></pre> <p>Am I missing something?</p>
[ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-09-08T19:19:26.860", "Id": "49273", "Score": "0", "body": "You might want to read this article: http://phpsec.org/projects/guide/4.html and place a session_destroy / session_regenerate_id in your Check.php code." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-09-08T19:36:53.290", "Id": "49275", "Score": "0", "body": "Why are you reinventing the wheel? Use OpenId." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-09-10T08:34:00.607", "Id": "49403", "Score": "3", "body": "By encrypted password you mean hashed, right? And by hashed, you would mean either scrypt or bcrypt right? :)" } ]
[ { "body": "<p>Some comments:</p>\n\n<pre><code>if($_SERVER[\"HTTPS\"] != \"on\")\n</code></pre>\n\n<p>See: <a href=\"https://stackoverflow.com/a/2886224/59087\">https://stackoverflow.com/a/2886224/59087</a></p>\n\n<p>Avoid calling <code>exit()</code> from more than one location.</p>\n\n<p>The following code is repeated many times:</p>\n\n<pre><code>//this guy did not pass by login!\nheader(\"location:Login.php\");\nexit();\n</code></pre>\n\n<p>You could write some functions to avoid the duplication:</p>\n\n<pre><code>function redirectLogin() {\n redirect( \"Login.php\" );\n}\n\nfunction redirect( $page ) {\n header( \"Location: $page\" );\n exit();\n}\n</code></pre>\n\n<p>This removes the duplication and ensures that you have only one place in the code to change if you wanted to rename <code>Login.php</code>, for example, to <code>login.php</code>, which is a bit more user-friendly (on Unix systems).</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-11-21T18:35:59.550", "Id": "35870", "ParentId": "30962", "Score": "3" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "3", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-09-08T18:59:27.573", "Id": "30962", "Score": "4", "Tags": [ "php", "security", "session" ], "Title": "Is this a safe Login?" }
30962
<p>I am trying to learn events and delegates in C#. To do that I am trying to create a hypothetical console project where when some user submits the orders in his/her shopping cart, I need the Billing department and mailing department to handle that event. Can someone please critique this code for doing the same?</p> <pre><code>using System; using System.Collections.Generic; namespace LearnEvents { class Program { static void Main(string[] args) { var shoppingCart = new ShoppingCart(10);//shopping cart for user number 10 var bd = new BillingDepartment(shoppingCart); var md = new MailingDepartment(shoppingCart); shoppingCart.Add(75458); shoppingCart.Add(54693); shoppingCart.Add(52145); shoppingCart.Submit(); } } public class ShoppingCart { private int _userId ; private List&lt;int&gt; _orders=new List&lt;int&gt;(); public delegate void OrderSubmitted(OrderDetails orderDetails); public event OrderSubmitted OrderSubmittedEvent; public ShoppingCart(int userId) { _userId = userId; } public void Add(int itemNumber) { _orders.Add(itemNumber); } public void Submit() { OrderSubmittedEvent.Invoke(new OrderDetails{ItemCodes = _orders,UserId = _userId}); } } public class OrderDetails { public List&lt;int&gt; ItemCodes { get; set; } public int UserId { get; set; } } public class BillingDepartment { public BillingDepartment(ShoppingCart sc) { sc.OrderSubmittedEvent+=OrderSubmittedHandler; } public void OrderSubmittedHandler(OrderDetails orderDetails) { foreach (var item in orderDetails.ItemCodes) { Console.WriteLine("Billing user "+orderDetails.UserId+" for the order "+item.ToString()); } } } public class MailingDepartment { public MailingDepartment(ShoppingCart sc) { sc.OrderSubmittedEvent += OrderSubmittedHandler; } public void OrderSubmittedHandler(OrderDetails orderDetails) { foreach (var item in orderDetails.ItemCodes) { Console.WriteLine("Mailing user " + orderDetails.UserId + " the order " + item.ToString()); } } } } </code></pre> <p>I would also like to know, why do I need an event? Why can't I just use multicast delegates instead as shown below?</p> <pre><code>using System; using System.Collections.Generic; namespace LearnEvents { class Program { static void Main(string[] args) { var shoppingCart = new ShoppingCart(10);//shopping cart for user number 10 var bd = new BillingDepartment(shoppingCart); var md = new MailingDepartment(shoppingCart); shoppingCart.Add(75458); shoppingCart.Add(54693); shoppingCart.Add(52145); shoppingCart.Submit(); } } public class ShoppingCart { private int _userId ; private List&lt;int&gt; _orders=new List&lt;int&gt;(); public delegate void OrderSubmitted(OrderDetails orderDetails); public OrderSubmitted os; public ShoppingCart(int userId) { _userId = userId; } public void Add(int itemNumber) { _orders.Add(itemNumber); } public void Submit() { os.Invoke(new OrderDetails { ItemCodes = _orders, UserId = _userId }); } } public class OrderDetails { public List&lt;int&gt; ItemCodes { get; set; } public int UserId { get; set; } } public class BillingDepartment { public BillingDepartment(ShoppingCart sc) { sc.os+=OrderSubmittedHandler; } public void OrderSubmittedHandler(OrderDetails orderDetails) { foreach (var item in orderDetails.ItemCodes) { Console.WriteLine("Billing user "+orderDetails.UserId+" for the order "+item.ToString()); } } } public class MailingDepartment { public MailingDepartment(ShoppingCart sc) { sc.os += OrderSubmittedHandler; } public void OrderSubmittedHandler(OrderDetails orderDetails) { foreach (var item in orderDetails.ItemCodes) { Console.WriteLine("Mailing user " + orderDetails.UserId + " the order " + item.ToString()); } } } } </code></pre>
[]
[ { "body": "<p>The standard signature for an event-handler delegate is</p>\n\n<pre><code>void HandlerName(object sender, HandlerArgs args)\n</code></pre>\n\n<p>Where <code>HandlerArgs</code> inherits from <code>System.EventArgs</code></p>\n\n<p>So to follow this convention, you should create a new class:</p>\n\n<pre><code> class OrderSubmittedEventArgs : EventArgs\n {\n OrderDetails { get; set; }\n }\n</code></pre>\n\n<p>And then you could theoretically define the event as:</p>\n\n<pre><code> //... \n public delegate void OrderSubmittedHandler(object sender, OrderSubmittedEventArgs eventArgs);\n public event OrderSubmittedHandler OrderSubmitted;\n</code></pre>\n\n<p>But that's more code than we need, now that we're following the convention.\n.NET provides a helper class:</p>\n\n<pre><code> //\n public event EventHandler&lt;OrderSubmittedEventArgs&gt; OrderSubmitted;\n</code></pre>\n\n<p><hr />\nYou also ask another question - why use an event rather than a multicast delegate?</p>\n\n<p>You can think of an event as a multicast delegate, but with restrictions. </p>\n\n<ul>\n<li>Only the object that owns the event can invoke it.</li>\n<li>Another object can add or remove a listener, but cannot modify it in any other way</li>\n</ul>\n\n<p>For example:</p>\n\n<pre><code>class TestClass\n{\n public EventHandler ThisDelegate;\n public event EventHandler ThisEvent;\n\n private void TryThis()\n {\n if (this.ThisEvent != null)\n {\n // I can fire my own event\n this.ThisEvent(this, EventArgs.Empty);\n }\n\n // I can clear my own event\n this.ThisEvent = null;\n }\n}\n\n\nclass OtherClass\n{\n void Test()\n {\n var test = new TestClass();\n // I can invoke test's delegate!\n test.ThisDelegate(this, EventArgs.Empty);\n // I can clear test's delegate!\n test.ThisDelegate = null;\n\n // But I can't do that to its event\n test.ThisEvent(this, EventArgs.Empty); // Compiler error\n test.ThisEvent = null; // Compiler error\n }\n}\n</code></pre>\n\n<p>So, by making the member an <code>Event</code> rather than a <code>Multicast Delegate</code>, you give it extra semantic meaning that is enforced by the compiler. You do this for similar reasons that you mark members as <code>private</code>.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-09-09T00:16:32.033", "Id": "49279", "Score": "0", "body": "@radarbob That doesn't make any sense, you seem to mixing up declaring a delegate type and invoking an event." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-09-09T00:20:35.080", "Id": "49280", "Score": "0", "body": "why, yes. yes I am. SO.. what I'm trying to say is, one may forego subclassing `EventArgs` and then pass `EventArgs.Empty`. If of course one does not need to pass data in the object. I'd argue that's conventional." } ], "meta_data": { "CommentCount": "2", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-09-08T23:57:22.230", "Id": "30966", "ParentId": "30965", "Score": "7" } }, { "body": "<p>I think you need another entity to delegate events, it makes no sense to pass shopping cart to your \"departments\" constructors.</p>\n\n<pre><code>class Shop\n{\n public ShoppingCart GetCart(int id)\n {\n var cart = new ShoppingCart(id);\n shoppingCart.OrderSubmittedEvent += OnOrderSubmitted;\n return cart;\n }\n\n private BillingDepartment _billingDepartment = new BillingDepartment(shoppingCart);\n private MailingDepartment _mailingDepartment = new MailingDepartment(shoppingCart);\n\n private void OnOrderSubmitted(OrderDetails orderDetails)\n {\n _billingDepartment.Bill(orderDetails);\n _mailingDepartment.Submit(orderDetails);\n\n //notice unsubsription, its a good style to do that \n //even if you dont really need to\n //your current event signature does not allow access to shopping cart tho.\n //it probably should\n\n //shoppingCart.OrderSubmittedEvent -= OnOrderSubmitted;\n }\n}\n</code></pre>\n\n<p>Usage:</p>\n\n<pre><code>var shop = new Shop();\nvar cart = shop.GetCart(10);\ncart.Add(75458);\ncart.Add(54693);\ncart.Add(52145);\ncart.Submit();\n</code></pre>\n\n<p>Also this:</p>\n\n<pre><code>public void Submit()\n{\n OrderSubmittedEvent.Invoke(new OrderDetails { ItemCodes = _orders, UserId = _userId });\n}\n</code></pre>\n\n<p>is bad code. The proper way do invoke events is:</p>\n\n<pre><code>public void Submit()\n{\n //copy to local variable to avoid racing i multithreading environment\n var ev = OrderSubmittedEvent;\n //check for null\n if (ev != null)\n {\n //only then invoke\n ev(new OrderDetails { ItemCodes = _orders, UserId = _userId });\n }\n}\n</code></pre>\n\n<p>Andrew also makes valid point about common conventions when it comes to events, check his answer. In my inner modules, i would probably break it and use <code>Action&lt;T&gt;</code> as event type though, but in code availible to others you should use <code>EventHandler&lt;T&gt;</code>.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-09-09T05:54:45.577", "Id": "30974", "ParentId": "30965", "Score": "0" } } ]
{ "AcceptedAnswerId": "30966", "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-09-08T23:46:53.153", "Id": "30965", "Score": "6", "Tags": [ "c#", "event-handling", "delegates", "e-commerce" ], "Title": "Shopping cart using events and delegates" }
30965
Vectors are sequence containers representing arrays that can change in size. For questions about geometric or algebraic vectors, use [coordinate-system] instead.
[]
[]
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-09-09T00:43:53.157", "Id": "30969", "Score": "0", "Tags": null, "Title": null }
30969
<ul> <li>the asterisk (*) typically represents zero or more characters in a string of characters</li> <li>the question mark (?) typically represents any one character</li> </ul>
[]
[]
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-09-09T01:00:16.100", "Id": "30970", "Score": "0", "Tags": null, "Title": null }
30970
A wildcard character is a special character that represents one or more other characters.
[]
[]
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-09-09T01:00:16.100", "Id": "30971", "Score": "0", "Tags": null, "Title": null }
30971
<p>This is a simple jQuery script that I use to vertically center elements on pages. It's quite simple, but I would love to know if there is room for improvement.</p> <pre><code>(function( $ ){ $.fn.flexVerticalCenter = function( onAttribute, verticalOffset, parentSelector ) { return this.each(function() { var $this = $(this); // store the object var attribute = onAttribute || 'margin-top'; // the attribute to put the calculated value on var offset = parseInt(verticalOffset) || 0; // the number of pixels to offset the vertical alignment by var parent_selector = parentSelector || null; // a selector representing the parent to vertically center this element within // recalculate the distance to the top of the element to keep it centered var resizer = function () { var parent_height = (parent_selector) ? $this.parents(parent_selector).first().height() : $this.parent().height(); $this.css( attribute, ( ( ( parent_height - $this.height() ) / 2 ) + offset ) ); }; // Call once to set. resizer(); // Call on resize. Opera debounces their resize by default. $(window).resize(resizer); // Apply a load event to images within the element so it fires again after an image is loaded $this.find('img').load(resizer); }); }; })( jQuery ); </code></pre>
[ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-09-09T02:38:34.857", "Id": "49283", "Score": "1", "body": "This is well written code, I don't think you will find any improvements here, congrats :)" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-09-09T02:44:41.377", "Id": "49284", "Score": "0", "body": "Sorry, I didn't put the header. It's not my script. It's from https://github.com/PaulSpr/jQuery-Flex-Vertical-Center. I just want to learn from it." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-09-09T02:45:08.410", "Id": "49285", "Score": "0", "body": "This is good code :)" } ]
[ { "body": "<p>From the comments above, I think the code is ok :)</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-09-11T15:49:40.183", "Id": "31110", "ParentId": "30972", "Score": "1" } } ]
{ "AcceptedAnswerId": "31110", "CommentCount": "3", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-09-09T02:13:39.347", "Id": "30972", "Score": "5", "Tags": [ "javascript", "jquery", "optimization" ], "Title": "Optimising this simple jQuery script that vertically centers elements on pages" }
30972
<p>Currently, the code below looks awful because of all the callbacks involved. How can I reduce the amount of nesting? Also, would you recommend the use of q or Async.js?</p> <pre><code>var mongoose = require('mongoose'); var User = require('../models/user.js'); var Genre = require('../models/genre.js'); var Album = require('../models/album.js'); var Band = require('../models/band.js'); exports.populate = function (req, res) { var bandNames = [ 'The Cool Group', 'The Peeps', 'Music Creation', 'Number and Wumbers', 'Testing For You', 'What What', 'Alrightly Then', 'Is this the way it is?', 'It hurts to know who you are', 'There has been one or two of you', 'Please and eyond' ]; var userNames = [ 'syte', 'koumarianos', 'ericStas', 'bloodCobia' ]; albumId = Album.create({ name: 'Test Album', biography: 'example' }, function (err, album) { if (!err) { var albumId = album._id; Genre.create({ name: 'Rock' }, function (err, genre) { if (!err) { var genreId = genre._id; var users = []; for (var i = 0; i &lt; userNames.length; i++) { users.push({ username: userNames[i] }); } User.create(users, function (err) { var bands = []; var users = Array.prototype.slice.call(arguments, 1); var userIds = [] for (var i = 0; i &lt; users.length; i++) { userIds.push(users[i]._id); } res.send(userIds); if (!err) { for (var i = 0; i &lt; bandNames.length; i++) { bands.push({ name: bandNames[i], biography: 'Lorem ipsum dolor sit amet, consectetur adipiscing elit. Aenean ac iaculis dui. Duis dignissim est ut ante cursus sodales. Duis et turpis ac nisl dictum mollis. Ut vel tempus metus. Vestibulum ante ipsum primis in faucibus orci luctus et ultrices posuere cubilia Curae; Duis eu risus aliquet, mattis est vitae, tempus sem. In eget ante semper, adipiscing arcu eu, fringilla lectus. Sed non tortor vulputate magna sodales varius eu quis nulla. Sed dignissim sed magna sit amet sodales. Ut nisi tortor, dapibus quis nulla eu, consectetur ornare dolor. Morbi mollis diam ut vulputate consectetur. In tincidunt, elit quis ultricies auctor, dolor odio condimentum ligula, quis sodales magna dui at est. Integer a orci rutrum, fermentum sapien quis, facilisis purus.', albums: [albumId], genres: [genreId], members: userIds }); } // save all bands Band.create(bands, function (err) { if (!err) { res.send("Successfully made all test data"); } else { res.send(err); } }); } }); } else { res.send(err); } }); } else { res.send(err); } }); }; </code></pre>
[ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-09-09T14:11:33.957", "Id": "49307", "Score": "0", "body": "Just to be clear: all those `create` methods take a callback because they create the item on the server and they execute the callback when it is done?" } ]
[ { "body": "<ol>\n<li>The code does not look awful. It is normal async JavaScript.</li>\n<li>No, in this case I would not recommend to to use Async, step or sth. else.</li>\n<li>When you have got used to async programming, you will understand 1. and 2.</li>\n</ol>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-09-09T13:04:30.537", "Id": "49303", "Score": "3", "body": "I disagree with that first statement. Any code with so many indentation levels needs refactoring." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-09-10T14:29:59.297", "Id": "49446", "Score": "0", "body": "I disagree with your statement @Changaco. The quality of code has no relation to the amount of indentation levels." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-09-10T14:41:26.167", "Id": "49448", "Score": "1", "body": "\"It is normal async JavaScript\" that doesn't mean it isn't awful looking. Promise objects are probably the best the asker is going to get without switching languages." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-03-10T15:23:00.040", "Id": "76035", "Score": "0", "body": "@JonnySooter Except when you decide that you need to add some steps, change the order in which they happen, or make any change which would be trivial if callback nesting didn't tangle everything up and make things difficult to modify and easy to break :P" } ], "meta_data": { "CommentCount": "4", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-09-09T12:58:57.283", "Id": "30983", "ParentId": "30973", "Score": "0" } }, { "body": "<p>My 2 cents are:</p>\n\n<ul>\n<li>This code is understandable, but I would still rewrite it since it is cookie cutter, and you will surely move on to more complex stuff </li>\n<li>Q uses a Promise object, Mongoose does not, so that would not work without some overhauling ( I personally like Q better though )</li>\n<li>Async works with 'last parameter must be a callback' which is exactly how Mongoose works, so use that </li>\n</ul>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-09-10T13:25:54.230", "Id": "31054", "ParentId": "30973", "Score": "1" } }, { "body": "<p>I went ahead and refactored the code to use the async library. Apologies for it not being the exact same example above. This one included error handling, and the population of more test data, but the idea should be conveyed the same. :)</p>\n\n<pre><code>var mongoose = require('mongoose');\nvar User = require('../models/user.js');\nvar Genre = require('../models/genre.js');\nvar Album = require('../models/album.js');\nvar Song = require('../models/song.js');\nvar Band = require('../models/band.js');\nvar async = require('async');\n\nexports.insertDummyData = function(req, res) {\nmongoose.connect('mongodb://localhost/yourMusic');\n\nvar bandNames = [\n 'The Cool Group',\n 'The Peeps',\n 'Music Creation',\n 'Number and Wumbers',\n 'Testing For You',\n 'What What',\n 'Alrightly Then',\n 'Is this the way it is?',\n 'It hurts to know who you are',\n 'There has been one or two of you',\n 'Please and eyond'\n];\n\nvar songNames = [\n 'stomy winds',\n 'another one writes the series',\n 'async breakdown',\n 'dust in the php'\n];\n\nvar userNames = [\n 'syte',\n 'koumarianos',\n 'ericStas',\n 'bloodCobia'\n];\n\nvar genreNames = [\n 'rap',\n 'rock',\n 'dance',\n 'trance',\n 'techno',\n 'country'\n];\n\nvar albumNames = [\n 'Milk Money',\n 'Rhyming No Dancing',\n 'Touch Your Face',\n 'A Sexual Reproduction',\n 'The Spackle of the Wolf'\n ];\n\n var slice = Array.prototype.slice;\n\n async.auto({\n genres: function(callback) {\n var genres = [];\n\n for(var i = 0; i &lt; genreNames.length; i++) {\n genres.push({ name: genreNames[i] });\n };\n\n Genre.create(genres, function(err) {\n var savedGenres = slice.call(arguments, 1);\n callback(err, savedGenres);\n });\n },\n users: function(callback) {\n var users = [];\n\n for (var i = 0; i &lt; userNames.length; i++) {\n users.push({\n username: userNames[i]\n });\n }\n\n User.create(users, function(err) {\n var savedUsers = slice.call(arguments, 1);\n callback(null, savedUsers);\n });\n },\n songs: ['genres', function(callback, results) {\n var users = [];\n var songs = [];\n var genres = results.genres;\n var genre = genres[0];\n\n for (var i = 0; i &lt; songNames.length; i++) {\n songs.push({\n name: songNames[i],\n genres: [genre]\n });\n }\n\n Song.create(songs, function(err) {\n var savedSongs = slice.call(arguments, 1);\n callback(err, savedSongs);\n });\n }],\n albums: ['songs', function(callback, results) {\n var albums = [];\n var songIds = [];\n var songs = results.songs;\n\n for(var i = 0; i &lt; albumNames.length; i++) {\n albums.push({ name: albumNames[i], songs: songs });\n }\n\n Album.create(albums, function(err) {\n var savedAlbums = slice.call(arguments, 1);\n callback(null, savedAlbums);\n });\n }],\n bands: ['albums', 'users', function(callback, results) {\n var members = results.users;\n var songs = results.songs;\n var albums = results.albums;\n var bands = [];\n\n var bio = \"this is a simple bio\\\n that i came up with.\\\n i hope it's good enough.\";\n\n for(var i = 0; i &lt; bandNames.length; i++) {\n bands.push({\n members: members,\n songs: songs,\n biography: bio,\n genres: [songs[0].genres],\n albums: albums\n })\n }\n\n Band.create(bands, function(err) {\n var savedBands = slice.call(arguments, 1);\n callback(null, savedBands);\n });\n }] \n }, function(err, results) {\n if(err) {\n console.log(err);\n res.send(err)\n }\n else {\n res.send(results);\n }\n });\n};\n</code></pre>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-09-20T01:47:35.493", "Id": "31569", "ParentId": "30973", "Score": "1" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "1", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-09-09T04:09:04.163", "Id": "30973", "Score": "6", "Tags": [ "javascript", "node.js" ], "Title": "Avoiding callback hell" }
30973
<p>I append the DOM elements dynamically, and when the data gets changed i use to hide and show lots of DOM elements. How do I improve my code?</p> <pre><code>str_user_details += '&lt;tr &gt;&lt;td class="td_edu td_pad" colspan="2"&gt;&lt;div class="div_edu"&gt;&lt;span class="headings"&gt;Education &lt;/span&gt; &lt;span class="user_details_desc" id="alma_span'+key+'"&gt;'+alma_mater+'&lt;/span&gt;&lt;/div&gt;&lt;div&gt;&lt;span class="headings"&gt;Speciality &lt;/span&gt; &lt;span class="user_details_desc" id="speciality_span'+key+'"&gt;'+str_speciality+'&lt;/span&gt;&lt;/div&gt;'; $jq('.container').css('overflow-y','auto'); $jq('#create_account').css('display','none'); $jq('#wrong_user').css('display','none'); if(details_length ==1) { $jq('.details_right_arrow').css('display','none'); } else { $jq('.details_right_arrow').css('display','block'); } </code></pre> <p>Its taking lots of 'if' and 'else' loops. how should i manage my code. </p>
[ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-09-09T09:19:32.147", "Id": "49295", "Score": "6", "body": "There's not enough info here to really answer the question. A decently sized sample of the actual code would probably help." } ]
[ { "body": "<p>Well for one thing I know you can replace this...</p>\n\n<pre><code>$jq('#create_account').css('display','none');\n$jq('#wrong_user').css('display','none'); \n</code></pre>\n\n<p>With...</p>\n\n<pre><code>$jq('#create_account').hide();\n$jq('#wrong_user').hide()\n</code></pre>\n\n<p>Same with...</p>\n\n<pre><code>if(details_length ==1) {\n $jq('.details_right_arrow').hide();\n} else {\n $jq('.details_right_arrow').show()\n}\n</code></pre>\n\n<p>As for the long str_user_details... there are _underscore templates you can use... </p>\n\n<p>If you have more chains of if/else statements where you are doing similar operations maybe you can pull them out and have one method that applies to them all? I would need to see more to comment further.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-09-09T09:17:35.420", "Id": "49294", "Score": "2", "body": "The last one can probably be done with `$jq('.details_right_arrow').toggle(details_length != 1);`" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-10-09T10:18:03.737", "Id": "51844", "Score": "0", "body": "Thanks for your comments. I will attach further code.\nAlso i'm loading a html page inside a div and animating that div, since the html page is heavy the animation looks choppy. Is there way to make it smoother ?" } ], "meta_data": { "CommentCount": "2", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-09-09T09:15:56.133", "Id": "30977", "ParentId": "30976", "Score": "1" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "1", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-09-09T08:51:16.573", "Id": "30976", "Score": "-1", "Tags": [ "javascript", "jquery" ], "Title": "Hiding and showing DOM elements dynamically" }
30976
<p>I'd really appreciate if any of you could do a code review of my Sopping cart demo. I was wondering whether this could be improved? I'm honestly trying to improve myself too!</p> <p>There's a small problem on the product list! looks like doest work if has more than 1 product. Demo: <a href="http://plnkr.co/edit/jLk0VdSgGYPwLhNKkcs7" rel="nofollow">http://plnkr.co/edit/jLk0VdSgGYPwLhNKkcs7</a></p> <pre><code>var module = { init: function () { this.shoppingCart(); }, shoppingCart: function () { numberIncrementer(this); updateQuantity(this); recalculateCart(); /* Set rates + misc */ var taxRate = 0.20; var fadeTime = 300; /* Assign actions */ $('.product-quantity input').change( function() { updateQuantity(this); }); $('.product-removal button').click( function() { removeItem(this); }); /* Recalculate cart */ function recalculateCart() { var subtotal = 0; /* Sum up row totals */ $('.product').each(function () { subtotal += parseFloat($(this).children('.product-line-price').text()); }); /* Calculate totals */ var tax = subtotal * taxRate; var total = subtotal + tax; /* Update totals display */ $('.totals-value').fadeOut(fadeTime, function() { $('#cart-subtotal').html(subtotal.toFixed(2)); $('#cart-tax').html(tax.toFixed(2)); $('#cart-total').html(total.toFixed(2)); if(total == 0){ $('.checkout').fadeOut(fadeTime); }else{ $('.checkout').fadeIn(fadeTime); } $('.totals-value').fadeIn(fadeTime); }); } /* Update quantity */ function updateQuantity(quantityInput) { /* Calculate line price */ var quantityInput = $('.product-quantity input'); var productRow = $(quantityInput).parent().parent(); var price = parseFloat(productRow.children('.product-price').text()); var quantity = $(quantityInput).val(); var linePrice = price * quantity; /* Update line price display and recalc cart totals */ productRow.children('.product-line-price').each(function () { $(this).fadeOut(fadeTime, function() { $(this).text(linePrice.toFixed(2)); recalculateCart(); $(this).fadeIn(fadeTime); }); }); } /* Remove item from cart */ function removeItem(removeButton) { /* Remove row from DOM and recalc cart total */ var productRow = $(removeButton).parent().parent(); productRow.slideUp(fadeTime, function() { productRow.remove(); recalculateCart(); }); } function numberIncrementer(){ $("div.product-quantity").append('&lt;div class="inc button"&gt;+&lt;/div&gt;&lt;div class="dec button"&gt;-&lt;/div&gt;'); $(".button").on("click", function() { var $button = $(this); var oldValue = $button.parent().find("input").val(); if ($button.text() == "+") { var newVal = parseFloat(oldValue) + 1; } else { // Don't allow decrementing below zero if (oldValue &gt; 0) { var newVal = parseFloat(oldValue) - 1; } else { newVal = 0; } } $button.parent().find("input").val(newVal); updateQuantity(); }); } } } $(document).ready(function () { module.init(); }); </code></pre>
[]
[ { "body": "<p>This code style is not very good, becouse u declare functions inside a function. The problem with this is that you recreate all this functions every time u run \"shoppingCart\" function.</p>\n\n<p>Instead try using this pattern;</p>\n\n<pre><code>(function(){\n\n //my private functions delare\n\n function recalculateCart(){\n ...\n }\n\n\n // my module public methods\n var myModule = {\n init: ...,\n shoppingCart: ...\n }\n\n return myModule;\n\n})()\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-09-09T17:36:48.523", "Id": "49337", "Score": "0", "body": "would u be able to put together a fiddle or a demo please?" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-09-10T09:16:26.563", "Id": "49404", "Score": "0", "body": "np i need few hours to do that... going out for launch ^^" } ], "meta_data": { "CommentCount": "2", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-09-09T13:23:22.347", "Id": "30986", "ParentId": "30982", "Score": "1" } } ]
{ "AcceptedAnswerId": "30986", "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-09-09T12:51:20.220", "Id": "30982", "Score": "1", "Tags": [ "javascript", "jquery" ], "Title": "Jquery shopping cart code review" }
30982
<p>I use two lists of objects invoices, original list and a new modified list. I would insert in db invoices presents in the new modified list but not presents in the original list.</p> <p>For delete, I would remove from db invoices presents in the original list but absent in the new modified list.</p> <p>This is what I did and that works, but I am not satisfied with the algorithm used, someone would have a way to do this more simply and clearly?</p> <pre><code>public void updateCustomerInvoicesCouple(List&lt;CustomerInvoicesDto&gt; originalCouplesListDto, List&lt;CustomerInvoicesDto&gt; newCoupleListDto){ // 1 - Insert Iterator&lt;CustomerInvoicesDto&gt; itFinal = newCoupleListDto.iterator(); // Browse all couples (customer-invoice) from final list // Insert couples of final list not in original list while(itFinal.hasNext()){ CustomerInvoicesDto finalCoupleDto = (CustomerInvoicesDto) itFinal.next(); Integer idCustomerFinal = finalCoupleDto.getCustomer().getId(); Integer idInvoiceFinal = finalCoupleDto.getInvoice().getId(); boolean coupleFind = false; for(CustomerInvoicesDto itemInitialCouple : originalCouplesListDto) { if(idCustomerFinal == itemInitialCouple.getCustomer().getId() &amp;&amp; idInvoiceFinal == itemInitialCouple.getInvoice().getId()) { coupleFind = true; } } if(!coupleFind){ // dto -&gt; entity CustomerInvoicesEntity finalCoupleEntity = new CustomerInvoicesEntity(); finalCoupleEntity = mapper.map(finalCoupleDto, CustomerInvoicesEntity.class); // Save in db CustomerInvoicesDao.save(finalCoupleEntity); } } // 2 - Delete Iterator&lt;CustomerInvoicesDto&gt; itInit = originalCouplesListDto.iterator(); // Browse all couples (customer-invoice) from original list // Insert couples of final list not in final list while(itInit.hasNext()){ CustomerInvoicesDto initialCoupleDto = (CustomerInvoicesDto) itInit.next(); Integer idCustomerInitial = initialCoupleDto.getCustomer().getId(); Integer idInvoiceInitial = initialCoupleDto.getInvoice().getId(); boolean coupleFind = false; for(CustomerInvoicesDto itemFinalCouple : newCoupleListDto) { if(idCustomerInitial == itemFinalCouple.getCustomer().getId() &amp;&amp; idInvoiceInitial == itemFinalCouple.getInvoice().getId()) { coupleFind = true; } } if(!coupleFind){ CustomerInvoicesDao.remove(initialCoupleDto.getId()); } } } </code></pre>
[]
[ { "body": "<p>1) In your <code>for</code>-loop, when the <code>if</code> is true, you should not only set <code>coupleFind = true</code>, but also add a <code>break</code> since you keep looping for nothing otherwise.</p>\n\n<p>2) I'm not sure why the customerId is not already part of the invoice.</p>\n\n<p>3) Instead of looping over the lists, you could just create a HashSet and check if the invoice is already present. There is some extra complexity if you take this approach, but if you call that method often, it will definitely be cheaper computationally. You should define some class InvoiceIncludingCustomerId if you don't want to put the customerId within the invoice. And you should override (carefully) the <code>hashCode()</code> and <code>equals()</code> of that class so that the hash is unique, but quick to compute: invoiceId and customerId should be sufficient.</p>\n\n<p>You then just need a <code>HashSet&lt;InvoiceIncludingCustomerId&gt; knownInvoices</code> and you just check if an invoice exists with <code>knownInvoices.contains(invoice)</code>. If it is missing, you add it to the DB and <code>knownInvoices.add(invoice)</code>. </p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-09-09T14:02:11.093", "Id": "30988", "ParentId": "30984", "Score": "1" } }, { "body": "<p>Here's how I would personally do it :</p>\n\n<pre><code>public void updateCustomerInvoicesCouple(List&lt;CustomerInvoicesDto&gt; originalCouplesListDto, List&lt;CustomerInvoicesDto&gt; newCoupleListDto){\n Map&lt;Pair&lt;Integer, Integer&gt;, CustomerInvoicesDto&gt; originalCouplesByIds = new HashMap&lt;&gt;();\n List&lt;CustomerInvoicesDto&gt; addedCouples = new ArrayList&lt;CustomerInvoicesDto&gt;();\n\n for (CustomerInvoicesDto originalCouple : originalCouplesListDto) {\n originalCouplesByIds.put(new Pair&lt;Integer, Integer&gt;(originalCouple.getCustomer().getId(), originalCouple.getInvoice().getId()), originalCouple);\n }\n\n // at the end of this loop, the originalList will contain list that have been deleted.\n for (CustomerInvoicesDto newCouple : newCoupleListDto) {\n if (null == originalCouplesByIds.remove(new Pair&lt;&gt;(newCouple.getCustomer().getId(), newCouple.getInvoice().getId()))) {\n // if the original list contains the Ids, then it's not an insert nor a delete. If it doesn't, it's an insert\n addedCouples.add(newCouple);\n }\n }\n\n insertAll(addedCouples);\n deleteAll(originalCouplesByIds.values());\n }\n</code></pre>\n\n<p>I would also suggest to not use integers as Ids. Create your own Id class and use this instead. Or worst case, use a String.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-09-10T10:48:28.917", "Id": "49411", "Score": "0", "body": "Why do you think that `String` is better for ids than `Integer`?" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-09-10T13:18:12.057", "Id": "49433", "Score": "0", "body": "It's more flexible. If you want to make your IDs unique across types (tables), integer won't do the trick. A String can always change in DB without needing to change most of the code" } ], "meta_data": { "CommentCount": "2", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-09-10T08:19:44.520", "Id": "31039", "ParentId": "30984", "Score": "0" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-09-09T13:20:00.703", "Id": "30984", "Score": "1", "Tags": [ "java", "algorithm" ], "Title": "Algorithm for comparing two lists of objects, to insert added items, and delete removed items" }
30984
<p>I've written a vocabulary trainer which does a lot of passing state around, as I have an ACID-database and a temporary state.</p> <p>In my experience with Haskell I've learnt that overusing <code>IO ()</code> is a code smell, I think that this is also true for state.</p> <p>Please have a look at the following <code>Main.hs</code>, which is improvable in my opinion. The whole project is available at GitHub; feel free to clone it. <a href="https://github.com/epsilonhalbe/VocabuLambda.git" rel="nofollow">git clone</a></p> <pre><code>module Main (main) where import VocabularyData import Database import FreqTable import Trainer import Control.Exception (bracket) import Control.Lens import Control.Monad.Trans.State import Data.Acid import Data.Maybe (listToMaybe) import Data.Char (toUpper) import System.Exit (exitSuccess) import System.IO (hFlush, stdout) main :: IO () main = do let test = initTestState lang &lt;- getSourceOrTarget "from" test' &lt;- execStateT (source.=lang) test lang' &lt;- getSourceOrTarget "to" test'' &lt;- execStateT (target.=lang') test' bracket (openLocalState emptyLearntList) (closeAcidState) (\db -&gt; command db test'') command :: AcidState LearntList -&gt; TestState -&gt; IO () command db test = do putStrLn "+===================================================+" putStrLn "| |" putStrLn "| what to do next? (type: \"help\" for help screen) |" putStrLn "| |" putStrLn "+===================================================+" cmd &lt;- getLine control db test cmd control :: AcidState LearntList -&gt; TestState -&gt; String -&gt; IO () control db test "help" = do print_help command db test control db test "next" = do len &lt;- query db LengthVocabulary if (len &lt;=0) then do putStrLn "No vocabulary in list." putStrLn "Use \"add word\" to insert." command db test else do idx &lt;- randomListIndex (fromIntegral len) f &lt;- query db (LookupFrequency idx) test' &lt;- execStateT (currentWord.=freqTable!!(f-1)) test -- putStrLn $ "vocabulary list len: "++show len -- _ _ _ _ -- -- putStrLn $ "random index: "++show idx -- | \ |_ |_⟩ | | | _ -- -- putStrLn $ "frequency to the index: "++show -- |_/ |_ |_⟩ |_| |_| -- -- print test' -- -- guess db test' control db test "change source" = do lang &lt;- getSourceOrTarget "from" test' &lt;- execStateT (source.=lang) test -- print test' command db test' control db test "change target" = do lang &lt;- getSourceOrTarget "to" test' &lt;- execStateT (target.=lang) test -- print test' command db test' control db test ('a':'d':'d':' ':'w':'o':'r':'d':xs) = do let times = maybeRead xs :: Maybe Int _repeat db test times control db test "clear all" = do putStrLn "Are you sure to delete all learnt vocabularies?" putStrLn "Type \"yes\" or \"no\" to confirm." yesNo &lt;- getLine yesNoElse db test yesNo control db _ "exit" = do closeAcidState db exitSuccess control db test "print db" = do frqKnowList &lt;- query db ViewAllVocabulary print frqKnowList command db test control db test _ = do putStrLn "Invalid Input" command db test guess :: AcidState LearntList -&gt; TestState -&gt; IO () guess db test = do putStr $ "What is ("++show (test^.source)++"): " putStrLn $ vocab (test^.currentWord) (test^.source) putStr $ "Your answer ("++show (test^.target)++") is: " hFlush stdout answer &lt;- getLine let is_hinted = (test^.hinted) is_correct = correct (test^.currentWord) (test^.target) answer f = test^.currentWord.frq if is_hinted then if is_correct then do _ &lt;- update db (UpdateKnowledge f 3) putStrLn "Correct, +3 Knowledge!" putStr "Full Answer: " putStrLn (vocab (test^.currentWord) (test^.target)) command db test else do _ &lt;- update db (UpdateKnowledge f (-2)) putStrLn "Wrong, -2 Knowledge!" putStr "Correct Answer: " putStrLn (vocab (test^.currentWord) (test^.target)) test' &lt;- execStateT (hinted.=False) test command db test' else if is_correct then do _ &lt;- update db (UpdateKnowledge f 5) putStrLn "Correct, +5 Knowledge!" putStr "Full Answer: " putStrLn (vocab (test^.currentWord) (test^.target)) command db test else do test' &lt;- execStateT (hinted.=True) test putStr "Hint: " putStrLn (hint (test'^.currentWord) (test'^.source)) guess db test' _repeat :: AcidState LearntList -&gt; TestState -&gt; Maybe Int -&gt; IO () _repeat db test (Just n)| n&lt;=0 = command db test | otherwise = do _ &lt;- update db AddVocabulary _repeat db test (Just (n-1)) _repeat db test Nothing = do _ &lt;- update db AddVocabulary command db test yesNoElse :: AcidState LearntList -&gt; TestState -&gt; String -&gt; IO () yesNoElse db test "yes" = do _ &lt;- update db ClearVocabulary;command db test yesNoElse db test "no" = command db test yesNoElse db test _ = control db test "clear all" print_help :: IO () print_help = do putStrLn "" putStr "| |_| |" ; putStrLn "help -&gt; prints this text" putStr "| | | |" ; putStrLn "" putStr "| _ |" ; putStrLn "next -&gt; next random vocabulary" putStr "| |_ |" ; putStrLn "add word -&gt; adds a new vocabulary to the list of learnt words" putStr "| |_ |" ; putStrLn "clear all -&gt; clears all vocabulary from the list of learnt words" putStr "| |" ; putStrLn "" putStr "| | |" ; putStrLn "change source -&gt; changes the source language" putStr "| |_ |" ; putStrLn "change target -&gt; changes the target language" putStr "| _ |" ; putStrLn "" putStr "| |_| |" ; putStrLn "print db -&gt; prints the database" putStr "| | |" ; putStrLn "exit -&gt; guess what \"exits the program\"" -- putStrLn "print test -&gt; prints the current test" initTestState :: TestState initTestState = TestState { _currentWord = freqTable!!0 , _source = F , _target = D , _hinted = False } langOptions :: IO () langOptions = do putStrLn "\tF/f for Français/French/Französisch" putStrLn "\tD/d for Allemande/German/Deutsch" putStrLn "\tE/e for Anglais/English/Englisch" getSourceOrTarget :: String -&gt; IO Language getSourceOrTarget toOrFrom = do putStrLn $ "Which language do you want to translate "++toOrFrom++"?" langOptions lang &lt;- getLine case (maybeRead . map toUpper . take 1) lang of Just l -&gt; return l Nothing -&gt; do putStrLn "Invalid Input" getSourceOrTarget toOrFrom maybeRead :: Read a =&gt; String -&gt; Maybe a maybeRead = fmap fst . listToMaybe . reads hint :: Word -&gt; Language -&gt; String hint w F = w^.phrase hint w D = w^.satz hint w E = w^.sentence vocab :: Word-&gt; Language -&gt; String vocab w F = w^.fra vocab w D = w^.deu vocab w E = w^.eng correct :: Word-&gt; Language -&gt; String -&gt; Bool correct w F str = elem str $ (subst2 . words . subst) (w^.fra) correct w D str = elem str $ (subst2 . words . subst) (w^.deu) correct w E str = elem str $ (subst2 . words . subst) (w^.eng) subst ::String -&gt; String subst = map subst_ where subst_ :: Char -&gt; Char subst_ ';' = ' ' subst_ '.' = ' ' subst_ ',' = ' ' subst_ '/' = ' ' subst_ a = a subst2 :: [String] -&gt; [String] subst2 = map (map subst_) where subst_ :: Char -&gt; Char subst_ '_' = ' ' subst_ a = a </code></pre>
[ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-09-10T12:28:05.377", "Id": "49428", "Score": "1", "body": "I believe the _prompt_ monad would be an answer to your problem. See [this post](https://groups.google.com/forum/#!topic/fa.haskell/XfX6LKlpheA) and [this paper](http://web.mit.edu/~ezyang/Public/threemonads.pdf)." } ]
[ { "body": "<p>I have a few suggestions:</p>\n\n<ol>\n<li>Instead of functions recursively call each other, have a single master dispatching function that calls <code>command</code>, <code>control</code>, <code>guess</code> etc. This will give a central overview how the whole process works. Otherwise it's very difficult to comprehend the flow of the program.</li>\n<li><p>Pattern matching on <code>String</code>s is very error prone and you can't give meaningful error messages if a user types a wrong command. So instead I'd suggest to introduce a data type that holds all possible user commands and create a parser that parses user input into commands (for example using <em>parsec</em>). Something like</p>\n\n<pre><code>data Command = Help | Next | AddWords Int | ...\n</code></pre></li>\n<li><p>There are many options how to avoid having everything inside <code>IO</code>. One possibility is to use the prompt monad (see my comment). As an example, let's modify <code>guess</code> using <code>MonadPrompt</code>. First, we'll create a data type that represents all possible actions <code>guess</code> can perform:</p>\n\n<pre><code>data GuessPrompt a where\n AskWord :: String -&gt; GuessPrompt String\n Say :: String -&gt; GuessPrompt ()\n DbUpdateKnowledge :: Int -&gt; Int -&gt; GuessPrompt ()\n AltTestState :: State TestState a -&gt; GuessPrompt a\n</code></pre>\n\n<p>(we'll need <a href=\"http://www.haskell.org/haskellwiki/Generalised_algebraic_datatype\" rel=\"nofollow\">GADTs</a> for this). Each constructor represents an action that takes a given set of parameters and returns some result to the caller. It will be convenient to have corresponding helper functions so that we don't have to write <code>prompt . ...</code> everywhere:</p>\n\n<pre><code>askWord = prompt . AskWord\nsay = prompt . Say\ndbUpdateKnowledge f n = prompt (DbUpdateKnowledge f n)\naltTestState = prompt . AltTestState\n</code></pre>\n\n<p>Now we can rewrite <code>guess</code> as follows. It doesn't carry around any state nor database and runs in any monad that is an instance of <code>MonadPrompt GuessPrompt</code> (this signature requires <a href=\"http://ghc.haskell.org/trac/haskell-prime/wiki/FlexibleContexts\" rel=\"nofollow\">FlexibleContexts</a>).</p>\n\n<pre><code>import Control.Monad.State as S (MonadState(..))\n-- ...\n\nguess' :: (MonadPrompt GuessPrompt m) =&gt; m ()\nguess' = do\n test &lt;- altTestState S.get\n answer &lt;- askWord $ \"What is (\"++show (test^.source)++\"): \" ++\n vocab (test^.currentWord) (test^.source) ++ \"\\n\" ++\n \"Your answer (\"++show (test^.target)++\") is: \"\n let is_hinted = (test^.hinted)\n is_correct = correct (test^.currentWord) (test^.target) answer\n f = test^.currentWord.frq\n if is_hinted\n then if is_correct\n then do\n dbUpdateKnowledge f 3\n say $ \"Correct, +3 Knowledge!\\n\" ++\n \"Full Answer: \" ++\n (vocab (test^.currentWord) (test^.target)) ++ \"\\n\" ++\n \"Translated Hint: \" ++\n hint (test^.currentWord) (test^.target)\n altTestState $ hinted.=False\n else do\n dbUpdateKnowledge f (-2)\n say $ \"Wrong, -2 Knowledge!\\n\" ++\n \"Correct Answer: \" ++\n vocab (test^.currentWord) (test^.target) ++ \"\\n\" ++\n \"Translated Hint: \" ++\n hint (test^.currentWord) (test^.target)\n altTestState $ hinted.=False\n else if is_correct\n then do\n dbUpdateKnowledge f 5\n say $ \"Correct, +5 Knowledge!\\n\" ++\n \"Full Answer: \" ++\n vocab (test^.currentWord) (test^.target)\n else do\n test' &lt;- altTestState $ hinted.=True &gt;&gt; S.get\n say $ \"Hint: \" ++\n hint (test'^.currentWord) (test'^.source)\n guess'\n</code></pre>\n\n<p>Now <code>guess'</code> has no reference to <code>IO</code> or other particular monad, it only uses our given set of actions. For example, we could create a testing instance that simulates user input, checks that it returns (<code>Say</code>s) the correct reply, checks how <code>guess'</code> updates the database etc.</p>\n\n<p>If we converted the whole <code>Main</code> module, we'd most likely add all the actions our functions need and we'd let the main dispatcher provide the correct implementations. Since we converted only <code>guess</code>, we could implement the old <code>guess</code> type as</p>\n\n<pre><code>guess :: AcidState LearntList -&gt; TestState -&gt; IO ()\nguess db test = evalStateT (runPromptM actions guess') test\n where\n actions :: GuessPrompt a -&gt; StateT TestState IO a\n actions (AskWord msg) = lift $ putStrLn msg &gt;&gt; getLine\n actions (Say msg) = lift $ putStrLn msg\n actions (DbUpdateKnowledge f n) = lift $ update db (UpdateKnowledge f n)\n actions (AltTestState s) = mapStateT (return . runIdentity) s\n</code></pre>\n\n<p>which describes in one place how the actions are actually executed inside <code>IO</code> and <code>TestState</code>.</p></li>\n</ol>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-09-11T08:29:05.473", "Id": "31083", "ParentId": "30989", "Score": "2" } } ]
{ "AcceptedAnswerId": "31083", "CommentCount": "1", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-09-09T14:32:32.047", "Id": "30989", "Score": "2", "Tags": [ "haskell", "io", "quiz", "state" ], "Title": "Vocabulary trainer passing around too much IO/State" }
30989
<p>Yesterday I found some nice video from some IT conference about removing if statements from code. I saw a very nice example of refactoring. I am curious what do you think about it, especially what weak points do you see in such approach.</p> <p>1) We have a class with very "nice" method:</p> <pre><code>public int inferCategoryID(Component c) { if(c.hasOneChannel() &amp;&amp; c.hasValidCertificate() &amp;&amp; c.isTested() &amp;&amp; c.frequentlyUsed()) { return 24; } if(c.hasOneChannel() &amp;&amp; c.hasValidCertificate() &amp;&amp; !c.isTested() &amp;&amp; c.frequentlyUsed()) { return 95; } if(c.hasOneChannel() &amp;&amp; !c.hasValidCertificate() &amp;&amp; c.isTested() &amp;&amp; c.frequentlyUsed()) { return 221; } if(c.hasTwoChannels() &amp;&amp; c.hasValidCertificate() &amp;&amp; c.isTested() &amp;&amp; c.frequentlyUsed()) { return 2004; } if(c.hasTwoChannels() &amp;&amp; c.hasValidCertificate() &amp;&amp; !c.isTested() &amp;&amp; c.frequentlyUsed()) { return 20044; } if(c.hasTwoChannels() &amp;&amp; c.hasValidCertificate() &amp;&amp; !c.isTested() &amp;&amp; !c.frequentlyUsed()) { return 2003; } // etc... } </code></pre> <p>As you can see all conditions are mutually exclusive. </p> <p>2) The idea was, to create a separate class for each condition - under a common interface:</p> <pre><code>interface CategoryIDCondition { public boolean isTrue(Component c); public int getID(); } class Cat24Condition implements CategoryIDCondition { public boolean isTrue(Component c){ return c.hasOneChannel() &amp;&amp; c.hasValidCertificate() &amp;&amp; c.isTested() &amp;&amp; c.frequentlyUsed(); } public int getID(){ return 24; } } </code></pre> <p>// etc...</p> <p>3) Usage example: </p> <pre><code>public int inferCategoryID(Component c) { List&lt;CategoryIDCondition&gt; conditions = new ArrayList&lt;&gt;(); conditions.add(new Cat24Condition); conditions.add(new Cat95Condition); // etc... (btw. not a good place for list init but never mind...) for (CategoryIDCondition cond : conditions) { if(cond.isTrue(c)){ return cond.getID(); } } } </code></pre> <p>What weak points do you see in such approach apart from that, that conditions have to be mutually exclusive, or have to be added to conditions list in a very specific order? Would you decide to use such strategy in your code?</p>
[ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-09-10T12:25:05.980", "Id": "49426", "Score": "0", "body": "is the code for `Component` available? I think there-in lies your problem. Shouldn't this logic be right in that class?" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-09-11T16:46:16.883", "Id": "49538", "Score": "0", "body": "Can you prove that these are mutually exclusive? Not all statements include hasOneChannel, and hasTwoChannels." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2015-07-22T01:34:57.057", "Id": "178707", "Score": "0", "body": "i think is good to reduce duplicate code,but Cat24Condition is not readable.you should think a domain name" } ]
[ { "body": "<p>Personally, I wouldn't use that approach, because of the amount of boilerplate code and complexity it introduces. Adding N+1 classes, where N is the number of conditions, just seems like overkill to me.</p>\n\n<p>First off, I don't think that the method at hand must necessarily be refactored. I agree that is not a terribly \"nice\" method from a aesthetic point of view, but the amount of complexity it contains might not justify a refactor. Often, a bit of reformatting is already a good approach:</p>\n\n<pre><code>public int inferCategoryID(Component c) {\n if( c.hasOneChannel() &amp;&amp;\n c.hasValidCertificate() &amp;&amp;\n c.isTested() &amp;&amp;\n c.frequentlyUsed()) {\n return 24;\n }\n\n [...]\n}\n</code></pre>\n\n<p>If that is not satisfactory, my next approach would've been to simply used separate methods for the conditions. This doesn't imply creating lots of classes, but still clean up the <code>inferCategoryID</code> substantially. While I'm not a fan of giving names like <code>isCat24</code>, I will use it here since the example refactoring technique using classes does so too and I can't infer more useful naming from the conditions:</p>\n\n<pre><code>public int inferCategoryID(Component c) {\n if(isCat24(c)) {\n return 24;\n }\n\n [...]\n}\n\npublic boolean isCat24(Component c) {\n return c.hasOneChannel() &amp;&amp;\n c.hasValidCertificate() &amp;&amp;\n c.isTested() &amp;&amp;\n c.frequentlyUsed();\n}\n</code></pre>\n\n<p>Last but not least, in cases where lots of boolean conditions are used, bit-lists are often applicable. The following code isn't tested, but it should give an idea of what I mean:</p>\n\n<pre><code>const int CATEGORY_24 = 15;\nconst int CATEGORY_95 = 13;\n\npublic int inferCategoryID(Component c) {\n int properties = componentProperties(c);\n\n if(properties == CATEGORY_24) {\n return 24;\n }\n\n if(properties == CATEGORY_95) {\n return 95;\n }\n\n [...]\n}\n\npublic int componentProperties(Component c) {\n return ((int) c.hasOneChannel() &lt;&lt; 3) &amp;&amp;\n ((int) c.hasValidCertificate() &lt;&lt; 2) &amp;&amp;\n ((int) c.isTested() &lt;&lt; 1) &amp;&amp;\n ((int) c.frequentlyUsed());\n}\n</code></pre>\n\n<p>The integer returned from <code>componentProperties</code> is a dense representation of the components properties in form of a bit list, that is each bit represents one boolean property. For example, if all properties are true, the resulting integer (in binary) would be <code>1111</code>, if only <code>hasOneChannel</code> was true, the integer would be <code>1000</code> and so on. This has the advantage that you don't have to create a large amount of methods or classes, but still cleans up the <code>inferCategoryID</code> method quite nicely. The downside of this method is that it is arguably the most cryptic (while I also find the multiple-class approach relatively cryptic :D).</p>\n\n<p>Since I said that adding lots of classes introduces too much complexity to be really worth it (in this case), I can't say that the last solution is any different in terms of adding unnecessary complexity, so I probably wouldn't use either of them for the use case at hand. I just wanted to give you an idea of a different approach that, in my opinion, is preferable to creating a class per condition :)</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-09-09T20:49:30.740", "Id": "49358", "Score": "2", "body": "+1, if encapsulating complexity is the goal. However if the set of conditions is changing dynamically at runtime then separate objects may be the way to go." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-09-09T21:56:20.573", "Id": "49367", "Score": "1", "body": "@radarbob Agreed, in that case my approach is a little \"static\". However, one could e.g. create a `Map<Int, Int>` mapping a properties identifier to a category id, which would also be more dynamic." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-06-02T22:08:45.563", "Id": "91581", "Score": "1", "body": "Agree with the progression, but just wanted to point out that bit lists and bit wise storing of booleans are very cryptic. Use sparingly if at all. Future maintainers might hate you. :)" } ], "meta_data": { "CommentCount": "3", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-09-09T16:23:27.650", "Id": "31002", "ParentId": "30990", "Score": "5" } }, { "body": "<p>This doesn't seem like an improvement - there is still an if per case, and an extra jump for the for loop. It might be better to factor out parts of the ifs that are in common, giving something more like:</p>\n\n<pre><code>if(condA()) {\n if(condB()) {\n //foo\n } else { //!condB\n //bar\n} else { //!condA\n //etc\n}\n</code></pre>\n\n<p>It doesn't remove any ifs, but the number of them that will be tested is now O(log n) instead of O(n), which is an improvement! The major downside is that this is a pain to read and mentally track the flow of, not to mention being more idiomatic of C-style programming.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-09-09T16:30:16.167", "Id": "31003", "ParentId": "30990", "Score": "1" } }, { "body": "<p>There are 4 boolean state-returning methods, but my solution is probably more relevant when there are more states. Instead of having 4 boolean state members, the Component class would have an <code>EnumSet&lt;State&gt;</code>.</p>\n\n<pre><code>public enum State {\n HAS_ONE_CHANNEL, HAS_VALID_CERTIFICATE, IS_TESTED, IS_FREQUENTLY_USED;\n}\n\npublic enum Category {\n C24(EnumSet.of(States.HAS_ONE_CHANNEL, ...)),\n C95(EnumSet.of(...)),\n ...;\n\n private EnumSet&lt;State&gt; enumSet;\n\n private Category(EnumSet&lt;State&gt; enumSet) {\n this.enumSet = enumSet;\n }\n\n public boolean equals(EnumSet&lt;State&gt; otherEnumSet) {\n return enumSet.equals(otherEnumSet);\n }\n\n // returns null if not found\n public static Category find(EnumSet&lt;State&gt; otherEnumSet) {\n // TODO instead of looping, it would be more efficient to build a HashMap&lt;EnumSet&lt;State&gt;, Category&gt;&gt; once\n for (Category category : Category.values()) {\n if (category.equals(otherEnumSet)) \n return category;\n }\n return null;\n }\n }\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-09-10T00:51:08.453", "Id": "49381", "Score": "1", "body": "I think that using the EnumSets is very good idea (so +1), however I would argue that creating the `Category` enum is unnecessary. Directly filling a `Map` with the mapping of your sets to return value instead of creating the `Category` enum would strike me as a cleaner solution (as your TODO comment alludes to)." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-09-10T01:12:30.493", "Id": "49385", "Score": "0", "body": "I was not too keen myself on making Category an enum. I did it as such because there might be more information that could be added to each category on top of just the active flag. For example, the int id for each category." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-09-10T10:43:17.933", "Id": "49410", "Score": "0", "body": "can you go further and add logic to the enum itself?" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-09-10T12:09:05.127", "Id": "49423", "Score": "0", "body": "@Thufir I'm not sure what you mean. But it is possible to add logic to enums. I don't enough about this particular code sample to suggest something useful to add." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-09-10T12:24:06.757", "Id": "49425", "Score": "0", "body": "it just seems like there's some insanity with this `Component` class, and either in an Enum or `Component` itself, there should be logic so that the object **itself** returns this desired output..?" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-09-10T17:04:27.973", "Id": "49453", "Score": "0", "body": "You mean it should return the category id? It would be trivial to add an `int categoryId` member to the enum and set it in the constructor. But it actually should be avoided and the enum itself should be used instead of \"magic\" numbers." } ], "meta_data": { "CommentCount": "6", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-09-09T18:26:34.927", "Id": "31006", "ParentId": "30990", "Score": "5" } }, { "body": "<p>Here's my solution.</p>\n\n<h1>Advantages</h1>\n\n<ul>\n<li>The <code>.hasOneChannel()</code> methods are called just once.</li>\n<li>No runtime setup, and no data structures. Everything is compiled in.</li>\n<li>The <code>switch</code> statement is <a href=\"https://stackoverflow.com/questions/6860525\">fast</a>.</li>\n</ul>\n\n<h1>Disadvantages</h1>\n\n<ul>\n<li>You have to manually maintain the mapping of bitmap values to constant names. (Well, you <em>could</em> dispense with the named constants and just hard-code the bitmap values as switch cases, but that would just be too cryptic, I think.)</li>\n<li>The definition of the category IDs happens far from the definition of the constant names. It would be nicer to be able to say <code>final Properties FOVT(15, 24)</code>.</li>\n<li>Using enums would be more elegant (but more complicated).</li>\n</ul>\n\n<p>‍</p>\n\n<pre><code>/**\n * F = Frequently used f = Rarely used\n * O = One channel o = Two channels\n * V = Valid certificate v = Invalid certificate\n * T = Tested t = Untested\n */\nprivate static final int\n FOVT = 15, FOVt = 14, FOvT = 13, FOvt = 12,\n FoVT = 11, FoVt = 10, FovT = 9, Fovt = 8,\n fOVT = 7, fOVt = 6, fOvT = 5, fOvt = 4,\n foVT = 3, foVt = 2, fovT = 1, fovt = 0;\n\npublic static int inferCategoryID(Component c) {\n int properties = (c.frequentlyUsed() ? 1 &lt;&lt; 3 : 0) |\n (c.hasOneChannel() ? 1 &lt;&lt; 2 : 0) |\n (c.hasValidCertificate() ? 1 &lt;&lt; 1 : 0) |\n (c.isTested() ? 1 &lt;&lt; 0 : 0);\n switch (properties) {\n case FOVT: return 24;\n case FOVt: return 95;\n case FOvT: return 221;\n case FOvt: return ...;\n case FoVT: return 2004;\n case FoVt: return 20044;\n // etc...\n default:\n assert false; // All 16 cases should be covered\n throw new UnsupportedOperationException(\"Unrecognized Component\");\n }\n}\n</code></pre>\n\n<p><strong>Edit:</strong> On second thought, dispensing with the named constants isn't so bad, especially if you use comments and binary literals (Java 7).</p>\n\n<pre><code>public static int inferCategoryID(Component c) {\n int properties = (c.frequentlyUsed() ? 1 &lt;&lt; 3 : 0) |\n (c.hasOneChannel() ? 1 &lt;&lt; 2 : 0) |\n (c.hasValidCertificate() ? 1 &lt;&lt; 1 : 0) |\n (c.isTested() ? 1 &lt;&lt; 0 : 0);\n switch (properties) {\n /**\n * F = Frequently used f = Rarely used\n * O = One channel o = Two channels\n * V = Valid certificate v = Invalid certificate\n * T = Tested t = Untested\n */\n\n case 0b1111 /* FOVT */: return 24;\n case 0b1110 /* FOVt */: return 95;\n case 0b1101 /* FOvT */: return 221;\n case 0b1100 /* FOvt */: return ...;\n case 0b1011 /* FoVT */: return 2004;\n case 0b1010 /* FoVt */: return 20044;\n // etc...\n default:\n assert false; // All 16 cases should be covered\n throw new UnsupportedOperationException(\"Unrecognized Component\");\n }\n}\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-09-11T08:16:33.767", "Id": "49495", "Score": "0", "body": "You might as well put the binary properties into a map and pair them with the integers to return. Then you could simply use `return map.get(properties);`˙." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-09-11T20:30:26.653", "Id": "49548", "Score": "0", "body": "@DrH Creating a Map would be missing the point of this solution, which is that the compiler does all the setup. `private static final Map<Integer,Integer> propsToCat = new HashMap<Integer,Integer>(); static { propsToCat.put(pppp, nnnn); /* etc */ }` would be static initialization overhead. And for what? To take information that is already embedded in the bytecode and load it into a HashMap that probably won't perform any better than a super-efficient `tableswitch` opcode." } ], "meta_data": { "CommentCount": "2", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-09-09T19:42:53.497", "Id": "31011", "ParentId": "30990", "Score": "2" } }, { "body": "<p>You basically have two values, that have a one to one coorespondences. I would take advantage of that.</p>\n\n<p>One value is what you want to return, the other value is the distinct value you get by using your 4 (5?) booleans as a bit pattern.</p>\n\n<p><a href=\"http://ideone.com/8hLB0v\" rel=\"nofollow\">Here's an example</a> of creating the mapping programatically. It is for illustration purposes only, I don't recommend using it -- better to either put the map into a config file or a database.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-09-10T03:08:49.830", "Id": "31034", "ParentId": "30990", "Score": "2" } }, { "body": "<p>I would do it just the way the video presented it. It gives very loose coupling to the classes and it provides extensibility without needing to later open a class and modify it. The 'single responsibility principle' is a great guideline for building robust and easy to maintain code and this methodology lends itself to the SRP well.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-09-10T14:12:03.687", "Id": "31055", "ParentId": "30990", "Score": "1" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "3", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-09-09T14:52:54.087", "Id": "30990", "Score": "9", "Tags": [ "java" ], "Title": "Many if statements - refactoring" }
30990
<p>Is there a way to simplify the code below? I want to simplify it, but I don't know if it is possible.</p> <p>In the table below, I insert data which will end up in a MySQL table.</p> <p>HTML</p> <pre><code>&lt;table border="0"&gt; &lt;tr&gt; &lt;td align="center"&gt;Dată / Interval orar&lt;/td&gt; &lt;td align="center"&gt;Denumire&lt;/td&gt; &lt;td align="center"&gt;Moderatori&lt;/td&gt; &lt;td align="center"&gt;Detalii&lt;/td&gt; &lt;/tr&gt; &lt;tr&gt; &lt;td align="center"&gt;&lt;input name="DataInterval1" type="text" id="DataInterval1"&gt;&lt;/td&gt; &lt;td align="center"&gt;&lt;input name="Denumire1" type="text" id="Denumire1"&gt;&lt;/td&gt; &lt;td align="center"&gt;&lt;input name="Moderatori1" type="text" id="Moderatori1"&gt;&lt;/td&gt; &lt;td align="center"&gt;&lt;input name="Detalii1" type="text" id="Detalii1"&gt;&lt;/td&gt; &lt;/tr&gt; &lt;tr&gt; &lt;td align="center"&gt;&lt;input name="DataInterval2" type="text" id="DataInterval2"&gt;&lt;/td&gt; &lt;td align="center"&gt;&lt;input name="Denumire2" type="text" id="Denumire2"&gt;&lt;/td&gt; &lt;td align="center"&gt;&lt;input name="Moderatori2" type="text" id="Moderatori2"&gt;&lt;/td&gt; &lt;td align="center"&gt;&lt;input name="Detalii2" type="text" id="Detalii2"&gt;&lt;/td&gt; &lt;/tr&gt; ... &lt;tr&gt; &lt;td align="center"&gt;&lt;input name="DataIntervaln" type="text" id="DataIntervaln"&gt;&lt;/td&gt; &lt;td align="center"&gt;&lt;input name="Denumiren" type="text" id="Denumiren"&gt;&lt;/td&gt; &lt;td align="center"&gt;&lt;input name="Moderatorin" type="text" id="Moderatorin"&gt;&lt;/td&gt; &lt;td align="center"&gt;&lt;input name="Detaliin" type="text" id="Detaliin"&gt;&lt;/td&gt; &lt;/tr&gt; &lt;/table&gt; </code></pre> <p>Part of the PHP code that I want to simplify:</p> <pre><code>$DataInterval1=$_POST['DataInterval1']; $Denumire1=$_POST['Denumire1']; $Moderatori1=$_POST['Moderatori1']; $Detalii1=$_POST['Detalii1']; $DataInterval2=$_POST['DataInterval2']; $Denumire2=$_POST['Denumire2']; $Moderatori2=$_POST['Moderatori2']; $Detalii2=$_POST['Detalii2']; ... $DataIntervaln=$_POST['DataIntervaln']; $Denumiren=$_POST['Denumiren']; $Moderatorin=$_POST['Moderatorin']; $Detaliin=$_POST['Detaliin']; // Insert data into mysql $sql="INSERT INTO tabel (DataInterval, Denumire, Moderatori, Detalii)VALUES ('".$DataInterval1."', '".$Denumire1."', '".$Moderatori1."', '".$Detalii1."'), ('".$DataInterval2."', '".$Denumire2."', '".$Moderatori2."', '".$Detalii2."'), ... ('".$DataIntervaln."', '".$Denumiren."', '".$Moderatorin."', '".$Detaliin."')"; $result=mysql_query($sql); </code></pre>
[ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-09-15T18:51:52.750", "Id": "58052", "Score": "0", "body": "The mysql extension has been deprecated; no longer in active development, and no longer supported in php5.5x. Using the old mysql extension will make your code less future proof. Look into PDO and mysqli (-mysql \"improved\" extension) and also take advantage of their support for OOP." } ]
[ { "body": "<h2>Use indexing in HTML name attributes</h2>\n\n<pre><code>&lt;table&gt;\n &lt;tr&gt;\n &lt;td&gt;Dată / Interval orar&lt;/td&gt;\n &lt;td&gt;Denumire&lt;/td&gt;\n &lt;td&gt;Moderatori&lt;/td&gt;\n &lt;td&gt;Detalii&lt;/td&gt;\n &lt;/tr&gt;\n &lt;tr&gt;\n &lt;td&gt;&lt;input name=\"DataInterval[0]\" type=\"text\" id=\"DataInterval1\"&gt;&lt;/td&gt;\n &lt;td&gt;&lt;input name=\"Denumire[0]\" type=\"text\" id=\"Denumire1\"&gt;&lt;/td&gt;\n &lt;td&gt;&lt;input name=\"Moderatori[0]\" type=\"text\" id=\"Moderatori1\"&gt;&lt;/td&gt;\n &lt;td&gt;&lt;input name=\"Detalii[0]\" type=\"text\" id=\"Detalii1\"&gt;&lt;/td&gt;\n &lt;/tr&gt;\n ...\n &lt;tr&gt;\n &lt;td&gt;&lt;input name=\"DataInterval[n]\" type=\"text\" id=\"DataIntervaln\"&gt;&lt;/td&gt;\n &lt;td&gt;&lt;input name=\"Denumire[n]\" type=\"text\" id=\"Denumiren\"&gt;&lt;/td&gt;\n &lt;td&gt;&lt;input name=\"Moderatori[n]\" type=\"text\" id=\"Moderatorin\"&gt;&lt;/td&gt;\n &lt;td&gt;&lt;input name=\"Detalii[n]\" type=\"text\" id=\"Detaliin\"&gt;&lt;/td&gt;\n &lt;/tr&gt;\n&lt;/table&gt;\n</code></pre>\n\n<h2>Use the indexing on the server side</h2>\n\n<pre><code>&lt;?php\n$data = array();\nforeach ($_POST[\"DataInterval\"] as $index =&gt; $value) {\n $data[] = array(\n \"DataInterval\" =&gt; $_POST[\"DataInterval\"][$index],\n \"Denumire\" =&gt; $_POST[\"Denumire\"][$index],\n \"Moderatori\" =&gt; $_POST[\"Moderatori\"][$index],\n \"Detalii\" =&gt; $_POST[\"Detalii\"][$index],\n );\n}\n</code></pre>\n\n<p>After this you only have to iterate throught the $data array and execute paramtrized INSERT SQL commands.</p>\n\n<ul>\n<li>do not use old mysql lib</li>\n<li>learn about PDO and prepared statements</li>\n</ul>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-09-09T16:12:15.743", "Id": "49327", "Score": "0", "body": "no i don't know the rest..." } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-09-09T15:49:58.250", "Id": "30997", "ParentId": "30991", "Score": "1" } }, { "body": "<p>I use this function:</p>\n\n<pre><code> function InsertToTable($table, $data) {\n $total = count($data);\n\n $sql = \"INSERT INTO `$table` (\";\n\n $runs = 0;\n foreach($data as $name =&gt; $value) {\n $runs++;\n $sql .= \"`$name`\";\n\n if($runs != $total) {\n $sql .= ',';\n }\n }\n\n\n $sql .= ') VALUES(';\n\n $runs = 0;\n foreach($data as $name =&gt; $value) {\n $runs++;\n $sql .= \"'$value'\";\n\n if($runs != $total) {\n $sql .= ',';\n }\n }\n\n $sql .= ')';\n\n if(mysql_query($sql)) {\n return true;\n } else {\n return false;\n }\n }\n</code></pre>\n\n<p>And then you have an array with the data, like so:</p>\n\n<pre><code> // columns to insert (array)\n // like this:\n // 'NAME_OF_FIELD_IN_TABLE' =&gt; 'CONTENT (i.e. the $_POST['field'] value)'\n $columnsToInsert = array(\n $DataInterval1 =&gt; $_POST['DataInterval1'],\n $Denumire1 =&gt; $_POST['Denumire1'],\n $Moderatori1 =&gt; $_POST['Moderatori1'],\n );\n\n if(InsertToTable('tabel', $columnsToInsert)) {\n echo 'Hurray! Success';\n } else {\n echo 'An error happend :(';\n }\n</code></pre>\n\n<p>Hope it solves your question.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-09-11T08:38:31.247", "Id": "49498", "Score": "0", "body": "This is in conjunction with what Peter Kiss wrote?" } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-09-10T17:19:32.813", "Id": "31062", "ParentId": "30991", "Score": "0" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "1", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-09-09T14:58:28.987", "Id": "30991", "Score": "1", "Tags": [ "php", "mysql" ], "Title": "Simplify MySQL INSERT query" }
30991
<p>I have written a script using Beautiful Soup to scrape some HTML and do some stuff and produce HTML back. However, I am not convinced with my code and I am looking for some improvements.</p> <p>Structure of my source HTML file:</p> <pre class="lang-html prettyprint-override"><code>&lt;!DOCTYPE html&gt; &lt;html&gt; ... &lt;body&gt; ... &lt;section id="article-section-1"&gt; &lt;div id="article-section-1-icon" class="icon"&gt; &lt;img src="../images/introduction.jpg" /&gt; &lt;/div&gt; &lt;div id="article-section-1-heading" class="heading"&gt; Some Heading 1 &lt;/div&gt; &lt;div id="article-section-1-content" class="content"&gt; This section can have p, img, or even div tags &lt;/div&gt; &lt;/section&gt; ... ... &lt;section id="article-section-8"&gt; &lt;div id="article-section-8-icon" class="icon"&gt; &lt;img src="../images/introduction.jpg" /&gt; &lt;/div&gt; &lt;div id="article-section-8-heading" class="heading"&gt; Some Heading &lt;/div&gt; &lt;div id="article-section-8-content" class="content"&gt; This section can have p, img, or even div tags &lt;/div&gt; &lt;/section&gt; ... &lt;/body&gt; &lt;/html&gt; </code></pre> <p>My code:</p> <pre class="lang-python prettyprint-override"><code>import re from bs4 import BeautifulSoup soup = BeautifulSoup(myhtml) all_sections = soup.find_all('section',id=re.compile("article-section-[0-9]")) for section in all_sections: heading = str(section.find_all('div',class_="heading")[0].text).strip() contents_list = section.find_all('div',class_="content")[0].contents content = '' for i in contents_list: if i != '\n': content = content+str(i) print '&lt;html&gt;&lt;body&gt;&lt;h1&gt;'+heading+'&lt;/h1&gt;&lt;hr&gt;'+content+'&lt;/body&gt;&lt;/html&gt;' </code></pre> <p>My code works perfectly without any issues so far, however, I don't find it pythonic. I believe that it could be done in a much better/simpler way. </p> <ol> <li><code>Content_list</code> is a list which has items like <code>'\n'</code>. With a loop running over this list, I am removing it. Is there any better way?</li> <li>I am not interested in article icon, so I am ignoring it in my script.</li> <li>I am using <code>strip</code> method to remove extra white spaces in the heading. Is there any better way? </li> <li>Other than new lines, the <code>div</code> element within content can have anything, even nested <code>div</code>s. So far, I have run my script over a few pages I have and it seems to work. Anything here I need to take care of?</li> <li>Lastly, is there any better way to generate HTML files? Once I scraped data, I will work on generating HTML files. These files will have same structure (CSS, JavaScript, etc) and I have to do is put scraped data into it. Can the above method I used (build a string and put content and headings) be improved in any way?</li> </ol> <p>I am not looking for full code in answers; just give me subtle hints or point me in some direction.</p>
[]
[ { "body": "<p>regarding 1 you can:</p>\n\n<pre><code>new_content = [c for c in old_content if c != '\\n']\n</code></pre>\n\n<p>or simply</p>\n\n<pre><code>new_content = old_content.replace('\\n', '')\n</code></pre>\n\n<p>Regarding 5, if your are generating anything that is nontrivial, then it will pay off to learn some template engines like <a href=\"http://jinja.pocoo.org/docs/\" rel=\"nofollow\">Jinja2</a>. If that is too much, then you can make a simple template in text file and use <a href=\"http://docs.python.org/2/library/re.html\" rel=\"nofollow\">regex</a> or even <code>replace()</code> to substitute generic parts:</p>\n\n<pre><code># template\n&lt;div class=\"some value\"&gt;%FOO%&lt;/div&gt;\n&lt;div class=\"some value\"&gt;%BAR%&lt;/div&gt;\n</code></pre>\n\n<p>and on the python side:</p>\n\n<pre><code>values = {\"%FOO%\": \"the foos\", \"%BAR%\": \"the bars\"} \ntemplate = open('template').read()\nfor k, v in values.iteritems():\n template = template.replace(k, v)\nprint template\n</code></pre>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-09-09T12:10:09.493", "Id": "30993", "ParentId": "30992", "Score": "4" } }, { "body": "<p>You can use <code>find</code> instead of <code>findAll</code> as <code>findAll</code> searches every element, thus taking more time. If only the first element matters, using <code>find</code> can save a lot of time.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-09-13T19:03:50.550", "Id": "31251", "ParentId": "30992", "Score": "2" } } ]
{ "AcceptedAnswerId": "30993", "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-09-09T12:05:18.880", "Id": "30992", "Score": "4", "Tags": [ "python", "html", "web-scraping", "beautifulsoup" ], "Title": "Scraping HTML using Beautiful Soup" }
30992
<p>I've just started looking at Zend Framework 2 and Doctrine ORM, with a view to possibly using it in one of my future products. So far I have a very simple application which allows the user to select data from a 'configuration' table. This table has just one row and several columns with settings that the application will use at some point.</p> <p>So far this is what I have come up with:</p> <p>ConfigController.php (my Zend controller)</p> <pre><code>&lt;?php /** * A restful controller that retrieves and updates configuration information */ namespace Application\Controller; use Zend\Mvc\Controller\AbstractRestfulController; use Zend\View\Model\JsonModel; class ConfigController extends AbstractRestfulController { /** * Retrieves the configuration from the database */ public function getList(){ //locate the doctrine entity manager $em = $this-&gt;getServiceLocator() -&gt;get('Doctrine\ORM\EntityManager'); //there should only ever be one row in the configuration table, so I use findAll $config = $em-&gt;getRepository("\Application\Entity\Config")-&gt;findAll(); //return a JsonModel to the user. I use my toArray function to convert the doctrine //entity into an array - the JsonModel can't handle a doctrine entity itself. return new JsonModel(array( 'data' =&gt; $config[0]-&gt;toArray(), )); } /** * Updates the configuration */ public function replaceList($data){ //locate the doctrine entity manager $em = $this-&gt;getServiceLocator() -&gt;get('Doctrine\ORM\EntityManager'); //there should only ever be one row in the configuration table, so I use findAll $config = $em-&gt;getRepository("\Application\Entity\Config")-&gt;findAll(); //loop through each submitted field foreach($data as $column=&gt;$value){ //work out the name of the setter function for each field $func = "set".ucfirst($column); $config[0]-&gt;$func($value); } //save the entity to the database $em-&gt;persist($config[0]); $em-&gt;flush(); //return a JsonModel to the user. I use my toArray function to convert the doctrine //entity into an array - the JsonModel can't handle a doctrine entity itself. return new JsonModel(array( 'data' =&gt; $config[0]-&gt;toArray(), )); } } </code></pre> <p>Config.php (my Doctrine entity)</p> <pre><code>&lt;?php namespace Application\Entity; use Doctrine\ORM\Mapping as ORM; /** * @ORM\Entity * @ORM\HasLifecycleCallbacks */ class Config { /** * @ORM\Id * @ORM\Column(type="integer") */ protected $minLengthUserId; /** * @ORM\Id * @ORM\Column(type="integer") */ protected $minLengthUserName; /** * @ORM\Id * @ORM\Column(type="integer") */ protected $minLengthUserPassword; /** * @ORM\Id * @ORM\Column(type="integer") */ protected $daysPasswordReuse; /** * @ORM\Id * @ORM\Column(type="boolean") */ protected $passwordLettersAndNumbers; /** * @ORM\Id * @ORM\Column(type="boolean") */ protected $passwordUpperLower; /** * @ORM\Id * @ORM\Column(type="integer") */ protected $maxFailedLogins; /** * @ORM\Id * @ORM\Column(type="integer") */ protected $passwordValidity; /** * @ORM\Id * @ORM\Column(type="integer") */ protected $passwordExpiryDays; /** * @ORM\Id * @ORM\Column(type="integer") */ protected $timeout; // getters/setters /** * Get the minimum length of the user ID * @return int */ public function getMinLengthUserId(){ return $this-&gt;minLengthUserId; } /** * Set the minmum length of the user ID * @param int $minLengthUserId * @return \Application\Entity\Config This object */ public function setMinLengthUserId($minLengthUserId){ $this-&gt;minLengthUserId = $minLengthUserId; return $this; } /** * Get the minimum length of the user name * @return int */ public function getminLengthUserName(){ return $this-&gt;getminLengthUserName; } /** * Set the minimum length of the user name * @param int $minLengthUserName * @return \Application\Entity\Config */ public function setMinLengthUserName($minLengthUserName){ $this-&gt;minLengthUserName = $minLengthUserName; return $this; } /** * Get the minimum length of the user password * @return int */ public function getMinLengthUserPassword(){ return $this-&gt;minLengthUserPassword; } /** * Set the minimum length of the user password * @param int $minLengthUserPassword * @return \Application\Entity\Config */ public function setMinLengthUserPassword($minLengthUserPassword){ $this-&gt;minLengthUserPassword = $minLengthUserPassword; return $this; } /** * Get the number of days before passwords can be reused * @return int */ public function getDaysPasswordReuse(){ return $this-&gt;daysPasswordReuse; } /** * Set the number of days before passwords can be reused * @param int $daysPasswordReuse * @return \Application\Entity\Config */ public function setDaysPasswordReuse($daysPasswordReuse){ $this-&gt;daysPasswordReuse = $daysPasswordReuse; return $this; } /** * Get whether the passwords must contain letters and numbers * @return boolean */ public function getPasswordLettersAndNumbers(){ return $this-&gt;passwordLettersAndNumbers; } /** * Set whether passwords must contain letters and numbers * @param int $passwordLettersAndNumbers * @return \Application\Entity\Config */ public function setPasswordLettersAndNumbers($passwordLettersAndNumbers){ $this-&gt;passwordLettersAndNumbers = $passwordLettersAndNumbers; return $this; } /** * Get whether password must contain upper and lower case characters * @return type */ public function getPasswordUpperLower(){ return $this-&gt;passwordUpperLower; } /** * Set whether password must contain upper and lower case characters * @param type $passwordUpperLower * @return \Application\Entity\Config */ public function setPasswordUpperLower($passwordUpperLower){ $this-&gt;passwordUpperLower = $passwordUpperLower; return $this; } /** * Get the number of failed logins before user is locked out * @return int */ public function getMaxFailedLogins(){ return $this-&gt;maxFailedLogins; } /** * Set the number of failed logins before user is locked out * @param int $maxFailedLogins * @return \Application\Entity\Config */ public function setMaxFailedLogins($maxFailedLogins){ $this-&gt;maxFailedLogins = $maxFailedLogins; return $this; } /** * Get the password validity period in days * @return int */ public function getPasswordValidity(){ return $this-&gt;passwordValidity; } /** * Set the password validity in days * @param int $passwordValidity * @return \Application\Entity\Config */ public function setPasswordValidity($passwordValidity){ $this-&gt;passwordValidity = $passwordValidity; return $this; } /** * Get the number of days prior to expiry that the user starts getting * warning messages * @return int */ public function getPasswordExpiryDays(){ return $this-&gt;passwordExpiryDays; } /** * Get the number of days prior to expiry that the user starts getting * warning messages * @param int $passwordExpiryDays * @return \Application\Entity\Config */ public function setPasswordExpiryDays($passwordExpiryDays){ $this-&gt;passwordExpiryDays = $passwordExpiryDays; return $this; } /** * Get the timeout period of the application * @return int */ public function getTimeout(){ return $this-&gt;timeout; } /** * Get the timeout period of the application * @param int $timeout * @return \Application\Entity\Config */ public function setTimeout($timeout){ $this-&gt;timeout = $timeout; return $this; } /** * Returns the properties of this object as an array for ease of use * @return array */ public function toArray(){ return get_object_vars($this); } /** * Before persisting this entity, check that the minimum * length of the user ID is not less than 1 * @ORM\PrePersist * @ORM\PreUpdate */ public function assertMinLengthUserIdNotLessThan1(){ if($this-&gt;minLengthUserId &lt; 1){ throw new \Exception('Minimum length of user ID cannot be less than 1.'); } } } </code></pre> <p>One of my goals is to make the application 'testable'. The applications we have written so far do not include any automated testing whatsoever, which has proved to be very time consuming.</p> <p>I have several questions regarding what I've done so far:</p> <ul> <li>Is this easily testable at the moment? How could I improve it in this regard? </li> <li>Do I really need all the getters and setters or could I use a generic 'magic methods' __get and __set to do this job? </li> <li>Should I be validating input in the setter functions or is it fine to validate before persisting (like in my assertMinLengthUserIdNotLessThan1 function)? </li> <li>Is there any better way of getting the Doctrine entity into an array? I have a simple toArray() function so far but I there may be better ways of doing it for more complicated objects.</li> </ul> <p>Any general comments/advice would be much appreciated also!</p> <p>Thanks in advance!</p>
[]
[ { "body": "<p>Quick answers:</p>\n\n<ul>\n<li>Is it easy to test? AFAICT, with the code provided it's quite easy to test. If you follow the docs (and it looks like you did follow them rather closely) then it should be easy to test.</li>\n<li>Could I use magic-methods: In theory, you can, but I wouldn't. More on this later (there's a lot to be said on this matter)</li>\n<li>Should I be validating input in the setter: <em>YES</em> definitly. When some snippet of code passes the wrong value to your entity, that could mean there's a bug. If your setter just blindly accepts whatever value it gets, the line that actually sets the value won't throw up errors. If you later check if everything is as it should be, then you'll have to track back to see where the wrong value was passed... have fun debugging. Adding additional validation methods is fine, but the setter should at least check the type of the value.</li>\n<li>entity 2 array: The easiest (And dirtiest) approach would be <code>(array) $entity</code>. All in all, I feel as if this is a bad idea. If you miss your arrays that much use <code>getArrayResult</code> on the query object</li>\n</ul>\n\n<hr>\n\n<p>On the setters and getters. First off, all magic-methods are <em>slow</em>, they cause way to much overhead. I've linked to an answer I gave on SO that goes into this a bit more, but basically, using the magic methods boils down to this:<br/>\nAsumme you have an instance, with some private/protected properties, and a magic getter:</p>\n\n<pre><code>class Foo\n{\n private $bar = null;\n public function __get($name)\n {\n if (property_exists($this, $name))\n {\n return $this-&gt;{name};\n }\n return null;\n }\n public function __set($name, $val)\n {\n return $this-&gt;{$name} = $val;\n }\n}\n</code></pre>\n\n<p>You may think that this is very handy (and it can be) because now you can simply write <code>$instance-&gt;bar = 123;</code> and <code>echo $instance-&gt;bar;</code>. What happens internally in PHP is a different matter, though. First, the object's <code>properties_info</code> HashTable is searched, to get the offset of a given <em>public</em> property in the <code>properties_table</code> HashTable. If this fails (which it will), PHP performs another lookup for the <code>__get</code> or <code>__set</code> method. In this case, that will work. The function is called, and the corresponding parameters are passed as arguments. Inside the method's body, the property-lookup is repeated.<br/>\nSo: more work is done == more time taken == slow.<br/>\nUsing getter methods is faster, because the a getter method lookup is an <em>O(1)</em> operation. The method will access a property, that should be predefined, so that the property-lookup is <em>O(1)</em>, too. Adding properties on-the-fly (and then getting too their respective values), on the other hand is <em>O(n)</em> (the more you do this, the slower it gets).</p>\n\n<p>Furthermore, magic methods, essentially <em>expose</em> private or protected properties. Why bother using access modifiers, if you're going to allow the users of your code to mess with every property your object has to offer anyway? Simple example:</p>\n\n<pre><code>class Wrapper\n{\n protected $conn = null;\n private $params = array(/*default settings here*/);\n public function __construct($wsdl)\n {\n $this-&gt;conn = SoapClient($wsdl, $this-&gt;params);\n }\n public function getData(array $params)\n {//get something, no worries\n return $this-&gt;conn($params);\n }\n public function deleteAll()\n {\n throw new RuntimeExcpetion('Delte is disabled, are you insane');\n }\n public function __get($name)\n {\n return $this-&gt;{$name};\n }\n}\n</code></pre>\n\n<p>What is preventing me from doing this:</p>\n\n<pre><code>$soap = new Wrapper();\ntry\n{\n $soap-&gt;deleteAll();\n}\ncatch(RuntimeExcpetion $e)\n{//I can't delete via wrapper, ok: use client directly, then...\n $soap = $soap-&gt;conn;//magic getter returns client!\n $soap-&gt;deleteAll();\n}\n</code></pre>\n\n<p>Of course, you might think that adding some simple checks in the magic getter will prevent me from doing this (and it will), but the more logic you add to <code>__get</code>, the slower it becomes.<br/>\nThen think of inheritance:</p>\n\n<pre><code>class ExposeWrapper extends Wrapper\n{\n public function __get($n)\n {\n return $this-&gt;{$n};\n }\n}\n</code></pre>\n\n<p>All I had to do was extend your class, and overwrite the getter, to regain access to the protected properties. Defining the magic methods as <code>final</code> might seem like an option, but it'll severly limit <em>your</em> ability to extend from your own classes (and thus your abilities to reuse your code later on). If all objects have one or 2 properties they want to prevent from being exposed, they all have a <code>final</code> getter defined, and can't extend from each other. Does that sound like proper OO code to you? Of course not</p>\n\n<p>As if that weren't bad enough, consider what a mess this would leave you with, when you consider typo's (very, if not _the _most, common cause of bugs):</p>\n\n<pre><code>protected $id, $foo, $bar;//three fields in entity\npublic function __set($name, $val)\n{\n $this-&gt;{$name} = $val;\n return $this;\n}\n//on the instance:\n$entity-&gt;baz = 'typo';//!!\n</code></pre>\n\n<p>I've <em>added</em> a fourth property. That doesn't make sense. I might then go on to assume I've set the <code>bar</code> property, and then spent ages tracking down a silly typo. Still, I, too, often implement <code>__get</code> and <code>__set</code>, with a difference:</p>\n\n<pre><code>public function setBar($val)\n{\n if ($val != (string) $val)\n {\n throw new InvalidArgumentException(__FUNCTION__ .' expects string (or string-like argument not '. typeof $val);\n }\n $this-&gt;bar = (string) $val;\n return $this;\n}\npublic function __set($name, $val)\n{\n $name = 'set'.ucfirst(strtolower(trim($name)));\n if (!method_exists($this, $name))\n {\n throw new RuntimeException(get_class($this).' cannot be overloaded no method: '.$name);\n }\n return $this-&gt;{$name}($val);\n}\n</code></pre>\n\n<p>And the same for the getter. This allows you to do something like:</p>\n\n<pre><code>$entity-&gt;id = 123;\n</code></pre>\n\n<p>But avoids things like:</p>\n\n<pre><code>$entity-&gt;idd = 123;//typo\n$entity-&gt;idd = new stdClass;//check int||numeric in setter of course\n</code></pre>\n\n<p>Another reason to implement individual getters/setters is to <em>program by interface</em>. Suppose you have a dozen of data models (which isn't a lot). A couple of these models share some data (like <code>Client</code> and <code>CurrentUser</code> or something). Let's, for example, assume they both have a property that contains the email address. Since these models are linked to a particular table, it's not unlikely that the properties have different names (eg <code>email</code> and <code>mailAddress</code>).<br/>\nWhen using type-hints, which I hope you do, you can't just hint to the abstract model type (some models don't have the required property/method). Enter <code>Interface</code>:</p>\n\n<pre><code>interface HasEmail\n{\n public function getEmail();\n public function setEmail($email);\n}\n\nclass Client extends AbsctractModel implements HasEmail\n{\n private $email = null;\n public function getEmail()\n {\n return $this-&gt;email;\n }\n public function setEmail($email)\n {\n $this-&gt;email = $email;\n return $this;\n }\n}\n\nclass CurrentUser extends AbsctractModel implements HasEmail\n{\n private $mailAddress = null;//no email property\n public function getMailAddress()\n {\n return $this-&gt;mailAddress;\n }\n public function setMailAddress($mail)\n {\n if (!filter_var($mail, FILTER_VALIDATE_EMAIL))\n {\n throw new InvalidArgumentExcetion('invalid email address: '.$mail)\n }\n $this-&gt;mailAddress = $mail;\n return $this;\n }\n public function getEmail()\n {\n return $this-&gt;mailAddress;\n }\n public function setEmail($email)\n {\n return $this-&gt;setMailAddress($email);\n }\n}\n</code></pre>\n\n<p>With this code, you can use a type-hint that assures you the argument has specific methods, that will return you the expected data:</p>\n\n<pre><code>public function updateEmail(HasEmail $instance)\n{\n $newAddress = $instance-&gt;getEmail();\n}\n</code></pre>\n\n<p>A since a class can implement multiple Interfaces, and interfaces can extend eachother, they offer a very flexible, and solid way of assuring the correct objects are being passed to the right methods, at the right time.</p>\n\n<p>Lastly, I've said that magic methods are slower... properties that are added using <code>__set</code> (ie properties that are not part of the class definition) are slower, too. That's another reason to disable PHP's object overloading. <a href=\"https://stackoverflow.com/questions/17696289/pre-declare-all-private-local-variables/17696356#17696356\">See here for more details</a></p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-09-12T13:28:49.340", "Id": "49587", "Score": "0", "body": "Thank you for this very detailed answer. I think I will stick to the getters and setters then! In terms of testing my project, how do you think I should go about it? Various examples I have seen only write unit tests to check if you can access the controller methods, and do most unit tests on the model/entity. Is this the correct way?" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-09-12T13:38:19.990", "Id": "49588", "Score": "1", "body": "@user1578653: Good choice, glad I could clear things up. In terms of testing: testing teh controllers is something that is, indeed, covered more than just test for data-models, but [have a look here](https://github.com/FriendsOfSymfony/FOSUserBundle/blob/master/Tests/Doctrine/UserManagerTest.php), I know it's symfony, but it gives you some idea of how to set about writing test for your Doctrine entities. Browse the entire test dir of this repo... there's a lot of examples to be found. PS: If this answer was what you're looking for, would you mind accepting it (it's ok to wait some more, too)" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-09-12T13:55:24.840", "Id": "49591", "Score": "0", "body": "Thanks for the extra information, I've had a look at the link you posted. If I implement many tests on the models as in that example, do I still need to test for those things through the controller also? E.g. If I test the model to make sure it throws an exception when you update it with value 'x', do I still need to test what happens if I submit value 'x' to my controller which will simply try to update the model? I hope this makes sense?" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-09-12T13:58:55.933", "Id": "49592", "Score": "1", "body": "@user1578653: You don't have to check what exception is being thrown, no. You will have to write a test, if you want to make sure the exception is dealt with correctly. For example: is it caught, is it rethrown, does the controller switch to the default error view... all that sort of stuff. But if the model throws an error when a setter is abused, then it shouldn't matter where the invalid data is comming from: the model contains the checks and throw statements..." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-09-12T14:03:45.533", "Id": "49593", "Score": "0", "body": "OK, thanks. So I will probably write most tests on the model, since this is the thing doing the hard work. For the controllers I will just make sure certain URLs map to the correct function, and that they return valid JsonModel, unless the controller happens to be doing something more complicated. Does that sound right? If I work on writing some unit tests and post them on this site later, could you have a look at them and let me know what you think? Thanks!" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-09-12T14:44:10.173", "Id": "49595", "Score": "1", "body": "@user1578653: Sounds exactly right. The controller needn't contain too much logic, so the model layer needs to be tested the most. Most test use the controller because that's how the client will interact with the model layer, so controller tests are as close as you get to _real-life_ scenario's. If I see a follow-up, I'll take a look at it (but I've got a lot of work ATM, so I've not been all that active on StackExchange-sites lately)" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-09-13T15:06:48.827", "Id": "49721", "Score": "0", "body": "Hi, I have posted my new unit tests here: http://stackoverflow.com/questions/18789468/zend-framework-and-doctrine-2-are-my-unit-tests-sufficient I would be very grateful if you could cast your eye over them and let me know what you think!" } ], "meta_data": { "CommentCount": "7", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-09-11T09:31:39.257", "Id": "31088", "ParentId": "30994", "Score": "2" } } ]
{ "AcceptedAnswerId": "31088", "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-09-09T15:35:08.670", "Id": "30994", "Score": "2", "Tags": [ "php", "unit-testing", "zend-framework", "doctrine" ], "Title": "Advice on Zend Framework 2 and Doctrine" }
30994
<pre><code>char* Migrated[]={"026","109"}; int isMigrated(char* codeB) { int i; int n=sizeof(Migrated)/sizeof(*Migrated); for(i=0;i&lt;n;i++) { if(strcmp(Migrated[i],codeB)==0) return 0; } return -1; } </code></pre> <p>is this function optimised from execution time perspective ?</p> <p>Migrated should contain at maximum 200 value all of them are 4 byte .</p>
[ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-09-09T15:40:30.067", "Id": "49316", "Score": "0", "body": "You should use a hash table." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-09-09T15:40:52.423", "Id": "49317", "Score": "4", "body": "If there are only two items in `Migrated` array they yes, it is optimized, but if there are thousands of items then there are better ways to code it." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-09-09T15:42:45.867", "Id": "49318", "Score": "1", "body": "Actually, if there are only two items in the array it would be better to check for the first character in `codeB` and based on it compare the string with only one viable item in the array." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-09-09T15:43:43.660", "Id": "49319", "Score": "1", "body": "Get a profiler and find out." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-09-09T15:45:02.913", "Id": "49320", "Score": "0", "body": "Dialecticus: Actually `strcmp` will scan through characters, and if the first one does not match, it will stop immediately." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-09-09T15:45:42.937", "Id": "49321", "Score": "0", "body": "Dunno -- what compiler optimization option did you use?" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-09-09T15:46:57.580", "Id": "49322", "Score": "1", "body": "@Kip9000 - For *two elements*?? Any decent compiler will unroll the loop and have it done before you've figured your first hash value." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-09-09T15:48:34.897", "Id": "49323", "Score": "1", "body": "The key to optimising is usually to *not optimise* unless you have empirical evidence that it is necessary. In saying that, understanding the complexity and memory consumption of various types of containers is very worthwhile. For instance, the using a hash-table here with 2 items is a massive overhead." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-09-09T17:09:58.260", "Id": "49336", "Score": "0", "body": "In some embedded systems, testing against 0 is marginally faster than testing against a constant, so reverse the `for` loop: `for(i=n; --i >= 0; )`" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-09-13T15:46:06.467", "Id": "49729", "Score": "0", "body": "Migrated should contain at maximum 200 value all of them are 4 byte ." } ]
[ { "body": "<p>You could assert that any code has to come from the <code>Migrated</code> array and thus only compare the addresses, i.e. omit the <code>strcmp</code> call and just test for <code>Migrated[i] == codeB</code>.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-09-09T15:52:20.543", "Id": "49324", "Score": "1", "body": "THe more assumptions you make, the better it gets. If we assume all of the strings are 3 characters long - so 4 with terminating NULL, they be compared as `int`s - and possibly stored in this way too. Probably not practical solution though." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-09-09T15:59:31.173", "Id": "49325", "Score": "0", "body": "@Marko: Sure, and if you assume that no given string matches, you could return `-1` right away. ;-) You have to draw a line somewhere. I just picked a more or less random assumption to illustrate that the best potential for optimization is by considering the domain of values fed to the function." } ], "meta_data": { "CommentCount": "2", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-09-09T15:41:38.357", "Id": "30996", "ParentId": "30995", "Score": "0" } }, { "body": "<p>I am not sure how far you intend to expand <code>Migrated</code>, but something like this could be an optimisation:</p>\n\n<pre><code>char* Migrated[]={\"026\",\"109\"};\n\nint isMigrated(char* codeB)\n{ \n int i;\n // since we know that all strings in Migrated are 4 bytes long\n int32_t _codeB_as_int32 = *(int32_t *)codeB; \n int32_t * Migrated_as_int32 = Migrated;\n\n for(i=0;\n i&lt;sizeof(Migrated)/sizeof(*Migrated); // sizeof is a compile time constant, better to put it here\n i++)\n { \n if(codeB == Migrated_as_int32[i])\n return 0;\n }\n return -1;\n}\n</code></pre>\n\n<p>it all really depends on what you intend to have in <code>Migrated</code>.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-09-09T16:35:21.747", "Id": "49329", "Score": "0", "body": "Right now `Migrated` is an array of pointers, so this won't work. You need to redefine it as an array of 4 character arrays. Also, you should probably make sure `codeB` is 4 bytes long before converting it to an integer." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-09-09T16:38:44.023", "Id": "49331", "Score": "0", "body": "Don't do this. The compiler will do this for for itself. You just need to write the code such that the compiler can see that that's a valid thing to do." } ], "meta_data": { "CommentCount": "2", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-09-09T15:52:17.977", "Id": "30998", "ParentId": "30995", "Score": "1" } }, { "body": "<p>If <code>Migrated</code> is a unchanging list that really is as short as you show then you should just hard-code the strings into the code (or use a macro, or declare them <code>const</code> (make sure they're const pointers as well as pointers to const)). That way the compiler can optimise the <code>strcmp</code> calls away to almost nothing; short strings like you show might even be done via a numeric comparison (a four byte string is the same length as a number), but don't do it manually - let the compiler sort that out. The key point is that the compiler cannot optimize this to the maximum if it can't prove that <code>Migrated</code> is constant.</p>\n\n<p>If <code>Migrated</code> is unchanging, but much larger than shown, then you should use \"perfect hashing\". There is a tool called <code>gperf</code> that, given a list of names, will generate C code to do the lookup in an optimal way.</p>\n\n<p>If <code>Migrated</code> can change at run-time and is small then you're probably just about optimal already.</p>\n\n<p>If <code>Migrated</code> can change at run-time, but can be very large then a hash table is the best option. Failing that a sorted, balanced tree would be better than a list.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-09-09T16:40:35.647", "Id": "49333", "Score": "0", "body": "Does perfect hashing do better than, say, a trie table or an Aho-Corsack automaton for matching a string against other strings? The constant factor of a hash function can be quite high (sometimes linear in the length of the string)." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-09-10T09:35:09.230", "Id": "49406", "Score": "0", "body": "@sfstewman: Given [this input](http://gitweb.samba.org/?p=ccache.git;a=blob;f=confitems.gperf;h=ae48d2b4b9724de975eb22fbc03d57182410481e;hb=HEAD), `gperf` produces [this output](http://gitweb.samba.org/?p=ccache.git;a=blob;f=confitems_lookup.c;h=d5d1c22a2ee18c527937b779b12549dc912d3668;hb=HEAD). There's not too much computational complexity there." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-09-10T09:45:05.593", "Id": "49407", "Score": "0", "body": "@sfstewman: perfect hashing is for finding one word in a moderate sized dictionary. It's not for finding dictionary words in a corpus of text, like Aho-Corsack seems to be. Trie tables can outperform imperfect hashing, but only in the worst case, and can never outperform a perfect hash table." } ], "meta_data": { "CommentCount": "3", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-09-09T16:36:42.377", "Id": "31004", "ParentId": "30995", "Score": "0" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "10", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-09-09T15:37:39.320", "Id": "30995", "Score": "1", "Tags": [ "c", "performance" ], "Title": "Optimization for C isMigrated function" }
30995
<p>I'm running this code with the FastMD5 library. Could it lead to memory leaks, or does it seem OK?</p> <pre><code>File[] directory = new File("/PATH/TO/FOLDER/WITH/LOTS/OF/FILES").listFiles(); for(int i = 0; i &lt; directory.length;i++){ System.out.println(MD5.asHex(MD5.getHash(directory[i]))); } </code></pre>
[ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-09-09T18:38:54.130", "Id": "49339", "Score": "1", "body": "Do you have a reason to suspect a memory leak? There are many tools in Java that interact with the virtual machine and can show you a graph of memory usage in real-time." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-09-09T20:52:59.367", "Id": "49360", "Score": "0", "body": "@toto2 It's really weird. About 2.5GB of free memory turns into inactive in the run of the program." } ]
[ { "body": "<p>In Java you have to do so much hard work to leak memory (someone will say not closing stream, but that's another story). </p>\n\n<p>I think you have a C programming background. So you are thinking of <code>memory leak</code>. Forget it there is JVM for you.</p>\n\n<p>And use enhanced for loop in Java as much as you can...</p>\n\n<pre><code>for(File file : directory) {\n System.out.println(MD5.asHex(MD5.getHash(file)));\n}\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-09-09T16:33:02.800", "Id": "49328", "Score": "0", "body": "For some reason I lose memory when I run my program. It's like the files are being saved to memory.\nYou're wrong :) I'm a pretty new developer. I'm losing my mind over this bug." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-09-09T18:48:15.560", "Id": "49340", "Score": "0", "body": "@ItaiHay: Java will likely grab a bunch of memory anyway. GC typically doesn't run immediately, and you're reading in mass amounts of data (probably to a new array each time) and even the list of files might be huge. Unless you're actually running into OOMEs, don't worry about it; the memory usage will level off." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-09-09T20:49:54.103", "Id": "49359", "Score": "0", "body": "@cHao It's segnificant. 2.5GB of free memory turnes into inactive in a matter of 1 minute (the programs run time)" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-09-09T21:41:48.633", "Id": "49366", "Score": "0", "body": "@ItaiHay: And your app crashes at that point?" } ], "meta_data": { "CommentCount": "4", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-09-09T16:22:19.490", "Id": "31001", "ParentId": "30999", "Score": "1" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "2", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-09-09T16:08:19.010", "Id": "30999", "Score": "1", "Tags": [ "java" ], "Title": "Can MD5ing all the files in a table cause a memory leak?" }
30999
<p>I'm working on a project for an Intro to C/Python class and am looking to improve the efficiency of the program. The program is a lottery simulation where the user inputs the number of tickets they want to buy, then generates tickets, and finally outputs the total winnings and net gain (usually loss). </p> <p>This is my code (in Python, as required):</p> <pre><code>def main(): numb_tickets = int(input("How many tickets would you like to buy?\n")) #Calculate Winnings winnings = 0 for i in range(numb_tickets): #For testing only, gives feedback progress of program print(i," ",winnings) #Creating winning ticket/your ticket, find number of matches win_tic = getRandomTicket(MAX_VALUE, TIX_SIZE) my_tic = getRandomTicket(MAX_VALUE, TIX_SIZE) numb_win = numMatches(win_tic, my_tic) #Add appropriate payout for number of matches if numb_win == 6: winnings += WIN_SIX elif numb_win == 5: winnings += WIN_FIVE elif numb_win == 4: winnings += WIN_FOUR elif numb_win == 3: winnings += WIN_THREE #Calculate cost of purchasing tickets cost_tics = numb_tickets * COST_TIC if winnings &gt;= cost_tics: profit = winnings - cost_tics print("You won $",winnings,", for a net earnings of $",profit,".", sep="") elif winnings &lt; cost_tics: loss = cost_tics - winnings print("You won $",winnings,", for a net loss of $",loss,".", sep="") main() </code></pre> <p>Note: the getRandomTicket() and numMatches() functions were provided by the professor to generate a lottery ticket and check the number of matches it has, respectively.</p> <p>My program works fine for smaller numbers of tickets, but when testing the required 1,000,000 tickets, takes a massive amount of time. It makes sense that the time increases rapidly as the range of the loop increases, but I don't know of a better way to loop this yet. Any input or suggestions are greatly appreciated.</p>
[ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-09-09T19:36:47.437", "Id": "49342", "Score": "4", "body": "Remove the `print(i,\" \",winnings)` and see if the performance improves. Or you could print every 10000 by `if i % 10000 == 0:`" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-09-09T19:36:54.547", "Id": "49343", "Score": "3", "body": "In your program, for every ticket you buy, you generate NEW winning ticket. Is this supposed to work this way? Oh, and yes, printing to console on windows platform is very slow." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-09-09T19:38:16.893", "Id": "49344", "Score": "1", "body": "Printing is really slow on any platform. It's almost certainly your bottleneck." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-09-09T19:40:09.623", "Id": "49345", "Score": "0", "body": "On an unrelated note, I'd recommend string formatting to clean up those print statements. `print('You won ${}, for a net loss of ${}.'.format(winnings, loss))`." } ]
[ { "body": "<p>Doing this in a loop means <code>O(N)</code> time, where <code>N = # of tickets</code>.</p>\n\n<p>If tickets are independent of each other, you can break this into chunks and process them in parallel. But threading is an advanced topic that you aren't likely to deal with in an intro class.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-09-09T19:27:25.517", "Id": "31008", "ParentId": "31007", "Score": "0" } }, { "body": "<p>If this is python 2, try using xrange instead of range in your for loop. This will allow the for loop to generate the next iteration value on demand rather than generating and storing them all in memory upon the initial call to range.</p>\n\n<p>See <a href=\"http://docs.python.org/2/library/functions.html#xrange\" rel=\"nofollow\">http://docs.python.org/2/library/functions.html#xrange</a></p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-09-09T19:40:58.937", "Id": "49346", "Score": "4", "body": "It's not. You can see the use of Python 3-style `input` and `print`." } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-09-09T19:40:29.770", "Id": "31009", "ParentId": "31007", "Score": "0" } }, { "body": "<p>A major optimization that you could do is to define a dictionary for <code>WIN_SIX</code>, <code>WIN_FIVE</code> etc. This will return the value to add in <code>O(1)</code> rather than going into nested if else every time. Other than that you could combine all your statements like <code>winnings += numb_win_dict[numMatches(getRandomTicket(MAX_VALUE, TIX_SIZE), getRandomTicket(MAX_VALUE, TIX_SIZE))]</code> but it will result in loss of readability of your code.\nFinal code would be like this:</p>\n\n<pre><code>numb_win_dict = { 3: WIN_SIX, 4: WIN_FOUR, 5: WIN_FIVE, 6: WIN_SIX}\n\ndef main():\n\n numb_tickets = int(input(\"How many tickets would you like to buy?\\n\"))\n\n #Calculate Winnings\n winnings = 0\n\n for i in range(numb_tickets):\n\n #For testing only, gives feedback progress of program\n print(i,\" \",winnings)\n\n #Add appropriate payout for number of matches \n winnings += numb_win_dict[numMatches(getRandomTicket(MAX_VALUE, TIX_SIZE), getRandomTicket(MAX_VALUE, TIX_SIZE))]\n #Calculate cost of purchasing tickets\n cost_tics = numb_tickets * COST_TIC\n\n if winnings &gt;= cost_tics:\n profit = winnings - cost_tics\n print(\"You won $\",winnings,\", for a net earnings of $\",profit,\".\", sep=\"\")\n elif winnings &lt; cost_tics:\n loss = cost_tics - winnings\n print(\"You won $\",winnings,\", for a net loss of $\",loss,\".\", sep=\"\") \n\nmain()\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-09-09T19:44:00.387", "Id": "49348", "Score": "0", "body": "Your code fails for <= 2 matches." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-09-09T19:49:35.673", "Id": "49350", "Score": "0", "body": "@user2357112: I haven't checked the code whether it's working or not. I have just rewritten the exact same code in the question in a compact form and have replaced the nested if-else with a dictionary." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-09-09T20:19:19.637", "Id": "49355", "Score": "0", "body": "I've fixed some bugs (for `numMatches` <= 3) (pending acceptance of edits). For small non-negative integers, just use an array instead of a dict. Also, I've restored the `win_tic` and `my_tic` variables because the variable names self-document the functionality of `numMatches()`, and it keeps lines shorter, and doesn't hurt efficiency." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-09-09T20:39:08.623", "Id": "49356", "Score": "0", "body": "@200_success: I agree that having the variables `win_tic` and `my_tic` improves the readability of the code but it does hurt efficiency a bit." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-09-09T20:44:47.343", "Id": "49357", "Score": "0", "body": "@AnkurAnkan this is not the exact same code as in the question, because dictionary throws a KeyError if the number of matches is not defined whereas the original `if...` sequence does not. I suggest using `winnings += numb_win_dict.get(..., 0)`" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-09-10T02:35:04.670", "Id": "49393", "Score": "0", "body": "@Stuart: I just wanted to give an idea what things could be done to optimize the code." } ], "meta_data": { "CommentCount": "6", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-09-09T19:41:45.633", "Id": "31010", "ParentId": "31007", "Score": "0" } }, { "body": "<p>It's more of a style preference, but instead of the paragraph with if and elif's, I would do</p>\n\n<pre><code>winnings += payouts_dictionary[numb_wins]\n</code></pre>\n\n<p>where</p>\n\n<pre><code>payouts_dictionary = {6: WIN_SIX, 5: WIN_FIVE, 4: WIN_FOUR, 3: WIN_THREE, 2: 0, 1: 0, 0: 0}\n</code></pre>\n\n<p>is defined as a constant before the loop.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-09-09T19:49:16.687", "Id": "49349", "Score": "0", "body": "I noticed Ankur has the same answer. However, I doubt using a dict will increase performance over a 4-deep if statement. I would be glad if someone could do a performance comparison." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-09-09T20:06:11.383", "Id": "49353", "Score": "0", "body": "Just did a profiling on both the ways and it's strange that the nested if-else ran faster than dictionary. Any idea why this is happening?" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-09-09T20:11:47.787", "Id": "49354", "Score": "0", "body": "It might be O(1) to fetch a dictionary entry, but there is some processing for transformimg the given key to an array index. The big-O notation only gives the asymptotic behavior. I'm not surprised that it is slower." } ], "meta_data": { "CommentCount": "3", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-09-09T19:45:50.263", "Id": "31012", "ParentId": "31007", "Score": "1" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "4", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-09-09T19:24:12.003", "Id": "31007", "Score": "1", "Tags": [ "python", "performance", "simulation" ], "Title": "Improving Lottery Simulation" }
31007
<p>I was tasked with writing a method which would take in an <code>int</code> (for amount in coins) and then convert the coins, accordingly, by counting how many quarters, dimes, nickels, and pennies were located in the amount. Afterwards, it would return a <code>String</code> which stated each count of individual coin.</p> <pre><code>public class Coins { private static final int QUARTER_VALUE = 25; private static final int DIME_VALUE = 10; private static final int NICKEL_VALUE = 5; private static final int PENNY_VALUE = 1; public static String convert(int amount) { int currentAmount = amount; int quarters = 0; int dimes = 0; int nickels = 0; int pennies = 0; String quarterUnit = new String(); String dimeUnit = new String(); String nickelUnit = new String(); String pennyUnit = new String(); if (amount != 0) { quarters = amount / QUARTER_VALUE; currentAmount = amount - (quarters * QUARTER_VALUE); dimes = currentAmount / DIME_VALUE; currentAmount = amount - (quarters * QUARTER_VALUE) - (dimes * DIME_VALUE); nickels = currentAmount / NICKEL_VALUE; currentAmount = amount - (quarters * QUARTER_VALUE) - (dimes * DIME_VALUE) - (nickels * NICKEL_VALUE); pennies = currentAmount / PENNY_VALUE; } if (quarters == 1) { quarterUnit = " quarter"; } else if (quarters &gt; 1 || quarters == 0){ quarterUnit = " quarters"; } if (dimes == 1) { dimeUnit = " dime"; } else if (dimes &gt; 1 || dimes == 0) { dimeUnit = " dimes"; } if (nickels == 1) { nickelUnit = " nickel"; } else if (nickels &gt; 1 || nickels == 0) { nickelUnit = " nickels"; } if (pennies == 1) { pennyUnit = " penny"; } else if (pennies &gt; 1 || pennies == 0) { pennyUnit = " pennies"; } StringBuilder conversion = new StringBuilder(); return conversion.append(quarters) .append(quarterUnit) .append("\n") .append(dimes) .append(dimeUnit) .append("\n") .append(nickels) .append(nickelUnit) .append("\n") .append(pennies) .append(pennyUnit) .append("\n") .toString(); } public static void main(String[] args) { String conversionString = convert(89); System.out.println( new StringBuilder().append("Converted amount equates to: ") .append("\n")); System.out.println(conversionString); } } </code></pre> <p>Here's the output:</p> <blockquote> <pre class="lang-none prettyprint-override"><code>Converted amount equates to: 3 quarters 1 dime 0 nickels 4 pennies </code></pre> </blockquote> <p>Is there a more efficient (fewer lines of code or a better OO style) way to implement this?</p>
[ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-09-09T21:08:29.600", "Id": "49363", "Score": "0", "body": "Hmm the unit names could be abbreviated to something like `nickelUnit = nickels==1 ? \" nickel\" : (nickels==0||nickels>1 ? \" nickels\" : \"ERROR - negative amount of nickels!\");` but I'm not sure you'd really gain much from that." } ]
[ { "body": "<p>Highlighting what a few helper classes can do : </p>\n\n<p>Imagine this enum </p>\n\n<pre><code>private enum Coin {\n QUARTER(25, \"quarter\"), DIME(10, \"dime\"), NICKEL(5, \"nickel\"), PENNY(1, \"penny\", \"pennies\");\n ...\n</code></pre>\n\n<p>and a tuple of quotient and remainder :</p>\n\n<pre><code>private static class QuotientAndRemainder {\n private final int quotient;\n private final int remainder;\n</code></pre>\n\n<p>so the enum can sport this method :</p>\n\n<pre><code>public QuotientAndRemainder divide(int pennies) {\n return QuotientAndRemainder.quotient(pennies / pennyValue).withRemainder(pennies % pennyValue);\n}\n</code></pre>\n\n<p>and this one :</p>\n\n<pre><code>public String format(int amount) {\n return Integer.toString(amount) + ' ' + (amount == 1 ? singular : multiple);\n}\n</code></pre>\n\n<p>then the convert method simply becomes :</p>\n\n<pre><code>public static String convert(int amount) {\n return print(minimalChange(amount));\n}\n\nprivate static String print(Map&lt;Coin, Integer&gt; amounts) {\n StringBuilder builder = new StringBuilder();\n for (Coin coin : amounts.keySet()) {\n builder.append(coin.format(amounts.get(coin))).append('\\n');\n }\n return builder.toString();\n}\n\nprivate static Map&lt;Coin, Integer&gt; minimalChange(int amount) {\n int penniesLeft = amount;\n Map&lt;Coin, Integer&gt; amounts = new EnumMap&lt;Coin, Integer&gt;(Coin.class);\n for (Coin coin : Coin.values()) {\n QuotientAndRemainder quotientAndRemainder = coin.divide(penniesLeft);\n amounts.put(coin, quotientAndRemainder.quotient());\n penniesLeft = quotientAndRemainder.remainder();\n }\n return amounts;\n}\n</code></pre>\n\n<p>Adding larger units of currency now simply comes down to adding them to the enum.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-09-09T23:47:14.347", "Id": "49375", "Score": "0", "body": "bowmore - Thank you for the valuable feedback! Your divide method inside the QuotientAndRemainder static class only pertains to pennies as does the minimalChange() method. How can I use this for other types of coins? Also, can you show me an example of how I can use these helper classes inside perhaps a main() method?" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-09-10T04:47:40.570", "Id": "49395", "Score": "0", "body": "QuotientAndRemainder is a static class because I made it an inner class, which is not strictly necessary. `divide()` and `minimalChange()` pertain to an amount of pennies just as your original `convert()` method does. If your input would be an amount of coins then the `Coin` enum could also be given an 'int toPennies()' method. For my full code see http://ideone.com/jD666U" } ], "meta_data": { "CommentCount": "2", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-09-09T21:31:45.327", "Id": "31019", "ParentId": "31014", "Score": "5" } }, { "body": "<p>Your solution is not very Object Oriented, but it works. This is a fine solution. There are many ways you could make the code less verbose, or more Object Oriented, but that is besides the point. I see nothing wrong with the way you implemented it.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-09-11T16:41:31.003", "Id": "31113", "ParentId": "31014", "Score": "0" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "1", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-09-09T20:40:47.603", "Id": "31014", "Score": "3", "Tags": [ "java" ], "Title": "Converting Java int-based amount to Coin metrics" }
31014
<p>Long story short, I would like to use OOP for my new PHP project. It has a "login" requirement (i.e. user will first need to enter the username and password (login.php), if it's correct, it will be redirected to index.php and then fetch some products information). Also there will be a settings page that allows user to change the password, and email if necessary.</p> <p>In summary:</p> <ul> <li>When user attempts to login, the program will check if the username, password entered is correct or not. If it's correct, username (or maybe the whole <code>User</code> object) will be saved in the <code>$_SESSION</code>.</li> <li>When the user settings page is loaded, it will display all user related fields on screen (i.e. by using <code>$_SESSION</code>).</li> <li>The user can make changes in the user settings pages and data should be saved to the database.</li> </ul> <p>I have this <code>User</code> class:</p> <pre><code>class User { private $username; private $email; private $hashed_password; private $dob; ... public __construct($user) { $this-&gt;username = $user; } public function isPasswordCorrect($userenteredpassword) { $this-&gt;loadFromDatabase(); //hashed userenteredpassword, compare it against $this-&gt;hashed_password //if it matches, return true, otherwise return false. } public function saveToDatabase() { //save info to database } public function loadFromDatabase() { $row = select fields from user table where username = $this-&gt;username limit 1 if ($row is found) { $this-&gt;hashed_password = $row['hashed_password']; $this-&gt;dob = $row['dob']; ... } } }//class </code></pre> <p>However, I was told that the function <code>isPasswordCorrect</code> shouldn't be implemented inside class <code>User</code>, as it is not its job to determine whether the login is valid or not. Instead, I should create an <code>authService</code> helper and use it to determine whether the login is good or not.</p> <p>Now, this makes me wonder if the rest of my <code>User</code> class design is okay or not. If I shouldn't put the password checking function in the <code>User</code> class, then is it okay to implement the database related functions in <code>User</code>? How do I determine which function should be implemented in the class? Should I follow Single Responsibility principle? Wouldn't it be too extreme?</p>
[]
[ { "body": "<p>The <strong>Single Responsibility Principle</strong> is a good thing to aim for, for many classes. It doesn't always mean that each class only does one thing (though it can), but that it is responsible for a small amount of tightly-related functionality.</p>\n\n<p>That said, the job of some classes <strong>is</strong> to collect together a number of responsibilities. <code>User</code> may well be one of these, but the individual responsibilities can still be delegated to other classes - e.g. you could always give <code>User</code> an instance of a Credentials class that deals with the password checking.</p>\n\n<p>You almost certainly don't want your database-related functions in <code>User</code> as if you write any tests for <code>User</code>, many of them are likely to have a need to hit the database when they run.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-09-09T21:20:27.273", "Id": "31017", "ParentId": "31015", "Score": "2" } }, { "body": "<blockquote>\n <p>Now, this makes me wonder if the rest of my User class design is okay or not. </p>\n</blockquote>\n\n<p>That depends entirely on your viewpoint. You certainly don't have to have a UserEntity, UserRepository, UserFactory, UserFinder, Email, Username and Password Value Objects, AuthenticationService AuthenticationAdapter and implementations. But you could have.</p>\n\n<p>Also, we could (no, we should) argue, whether storing the password hash in the user is a good idea. You'll only need it to authenticate and then never again, so that's one time in the application. After that, you can use a token or set a flag in the Session. There is no need to store the password then, regardless of where you do the authentication (a separate component sounds fine to me. You could inject that to the User and then delegate the call).</p>\n\n<p>The most important thing is that the code does what the enduser thinks it should do. However, it should also be implemented in a way that won't come back to haunt you, should your ever need to change the application. So whether it's \"okay\" or not pretty much depends on the scope of your project. Ask yourself: \"is it good enough?\"</p>\n\n<blockquote>\n <p>If I shouldn't put the password checking function in User class, then I wonder if it's okay to implement the database related functions in User??? </p>\n</blockquote>\n\n<p>That gets us right back to the first question. If we assume User to be a class holding business logic, then technically, putting the db access into the User is a violation of SRP. However, when the impedance mismatch is small or doesn't exist, then using an <a href=\"http://www.martinfowler.com/eaaCatalog/activeRecord.html\" rel=\"nofollow\">ActiveRecord</a>'ish pattern might be practical. So check how much impedance mismatch you have. When you notice your User to turn into a ORM, consider using an ORM instead.</p>\n\n<p>The other option would be that your User doesnt have any business logic and is really just a Gateway to the storage engine. Then it's okay to have db logic in it. It just shouldn't be called a User then though.</p>\n\n<blockquote>\n <p>How do I determine which function should be implemented in the class? </p>\n</blockquote>\n\n<p>A good general set of rules to follow is <a href=\"http://en.wikipedia.org/wiki/GRASP_%28Object_Oriented_Design%29\" rel=\"nofollow\">GRASP</a>.</p>\n\n<p>Another easy test is to look at what the class does and then check that the name matches that what it does. Your User apparently loads things from the database and checks passwords. Not exactly what I'd expect from a User.</p>\n\n<blockquote>\n <p>should I follow Single Responsibility principle? </p>\n</blockquote>\n\n<p>Yes, always. Except for when you can reasonably justify not to. Following SRP will make your code easier to maintain in the long run and will increase reuse possibilities. Once you assign multiple responsibilities, you will have to have the same set of responsibilities in another project if you want to reuse the class. And the chances for that are smaller than for single responsibilities.</p>\n\n<blockquote>\n <p>Wouldn't it be too extreme??</p>\n</blockquote>\n\n<p>No. Having many small classes is perfectly fine. It's a matter of appropriateness though again. I found it helps to keep things separated and small. However, it also gets harder to visualize the code flow in your head then the more classes you add.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-09-12T20:38:53.180", "Id": "49639", "Score": "0", "body": "*\"whether storing the password hash in the user is a good idea\"* .. emm ... it's not whether having hash in `User` instance is a good idea, but whether the rest of `Profile` has to be there too." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2015-08-19T19:47:08.703", "Id": "185403", "Score": "0", "body": "Hello! I am looking for some indications about this subject too. Could you, please, describe the classes mentioned in your answer's first paragraph? (`UserRepository`, `UserFactory`, `AuthentificationService`, `AuthentificationAdapter`). Please, mention their purpose, perhaps some of their members." } ], "meta_data": { "CommentCount": "2", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-09-09T21:37:55.687", "Id": "31020", "ParentId": "31015", "Score": "2" } }, { "body": "<p>The reason why you were told, that <code>isPasswordCorrect()</code> should not be implemented in <code>User</code> class is because someone is pretty bad at explaining stuff.</p>\n\n<p>It's OK for <code>User</code> instance to validate the provided credentials. The <strong>real</strong> problem there is the SQL. Your <code>User</code> instance should not care about the existence of database or even be aware that such a thing exists.</p>\n\n<p>A much better API would be:</p>\n\n<pre><code>$user = new User;\n$user-&gt;setUsername( $username );\n$mapper = new UserMapper( $pdo );\n\n$mapper-&gt;fetch( $user );\nif ( $user-&gt;isPasswordCorrect($password) )\n{\n // blah blah .. \n}\n</code></pre>\n\n<p>The terms that cover this are <a href=\"http://c2.com/cgi/wiki?DomainObject\" rel=\"nofollow\">domain object</a> and <a href=\"http://martinfowler.com/eaaCatalog/dataMapper.html\" rel=\"nofollow\">data mapper</a>.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-09-12T18:49:49.020", "Id": "49627", "Score": "0", "body": "I do agree that the statement \" *\"isPasswordCorrect\" shouldn't be implemented inside class User* \" is a little bold, as there are always various pros and cons to weigh up. But there are definitely some reasons to consider it - e.g. if we want another class (Administrator) to re-use the password-checking logic, or if we want to be able to write unit tests for our password-checking logic without needing to construct a User object. Or what if we later decide that we want to allow guest Users that don't have a password at all?" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-09-12T18:52:43.297", "Id": "49628", "Score": "0", "body": "BTW I am not contradicting you, just agreeing with Gordon's statement that we should argue about these things! :)" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-09-12T20:42:17.617", "Id": "49640", "Score": "0", "body": "None of those \"IFs\" made any sense." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-09-12T23:37:01.807", "Id": "49654", "Score": "0", "body": "Care to expand?" } ], "meta_data": { "CommentCount": "4", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-09-09T23:15:56.370", "Id": "31025", "ParentId": "31015", "Score": "0" } }, { "body": "<p>When situations like this come up, it's a good idea to step away from the code and think about how the real-world operates. Objects in programming mimic those in the real-world, so it can be useful to just look at a use case you see elsewhere.</p>\n\n<p>For example, let's say you're a US Citizen, and you went to another country for vacation. On your way back into the US, you must prove who you are so that they know you're not on some black list somewhere. You, the user, provide your credentials: primarily your passport, but you might also be asked for your drivers license or any other identifying documents. You hand those documents over, and then it's someone else who determines whether your papers are a forgery or not. It is <em>not</em> your responsibility to tell the officers that you're not a threat. It is <em>their</em> responsibility to determine that.</p>\n\n<p>Taking this back to computer authentication: The user provides their username and password, and then someone else(the system) determines if they are authorized to access the system or not.</p>\n\n<p>Taking this to the coding level: it doesn't make much sense to have a user authenticate themselves. The code can be written to do that, but it really isn't the user's job to say he's authorized to have access. Someone else in the system needs to determine that - like the authService your colleague mentioned.</p>\n\n<p>On the topic of database access...like others have said: that's somewhat up to you. I always like to have one object that provides access to data resources(not necessarily to mean one thread, but one object that determines which operations are allowed concurrently and when to lock the resource for writes/updates). Alternatively, many objects can access a data resource but they're synchronized in some way(mutex, semaphore, etc).</p>\n\n<p>This way, the concurrency issues will be located within that object(s) instead of scattered in mysterious locations that make debugging harder. So, if my program is running and I'm noticing wonky things going to/from the database, it's pretty straight forward to drill down to where the problem exists. If I had a bunch of users who were in their own thread and doing whatever they wanted with the database, it might not be immediately obvious that the users are the problem. The symptom is the database looks wrong, and the reason it's wrong is because users are changing the database without respecting the changes the others are making.</p>\n\n<p>An example of that case would be source control, which is a tool used to allow multiple developers to work on the same project at the same time without worrying about who is writing in which file. Now, take away the source control. If two developers write to the same file without knowledge of the other, one of the developer's code is going to get erased completely, and when that developer tries to watch his functionality work...it simply won't be there because someone wrote over it. Then the question becomes...who wrote over it, when, and is there a copy of the feature that was implemented, or does it need to be done again? These kinds of things happen on the order of minutes, hours, or even days...but in a program that uses a database...this will be happening hundreds of times a second. It's better to give control of a resource like that to someone who can safely manage it(source control, database handler, etc).</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-09-12T19:48:04.520", "Id": "31161", "ParentId": "31015", "Score": "-1" } } ]
{ "AcceptedAnswerId": "31020", "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-09-09T20:57:32.977", "Id": "31015", "Score": "7", "Tags": [ "php", "object-oriented", "authentication" ], "Title": "Determining what functions should be implemented in this user-authentication class" }
31015
<pre><code>def fib_m_through_n(m, n): """(number, number) -&gt; list A function which returns a list containing the mth through the nth fibonacci numbers. SHOULD BE MODIFIED IN THE FUTURE so it will remember values already computed, so when it is called again it reuses that information """ fib_list = [0, 1, 1] a, b, c = 1, 1, 0 #why can I do three variable assignments here... count = 0 while count &lt;= n: c = a + b; a = b; b = c #...but not here? fib_list.append(c) count += 1 print(fib_list[m : n]) fib_m_through_n(0, 17) </code></pre> <p>I have a few questions about this:</p> <p>The first is general: are there any clear pythonic violations here, any obvious improvements to style? </p> <p>The second is included in some of the comments. Why can I get away with assigning three variables in one line here: <code>a, b, c = 1, 1, 0</code></p> <p>but not here: <code>c = a + b; a = b; b = c</code></p> <p>If I try to do this: <code>c, a, b = a + b, b, c</code></p> <p>Then I get an incorrect output.</p> <p>After analyzing the mistake and trying to imagine how things look from the function's POV, it still seems to me like doing three variable assignments in a row should work, assuming that when the function runs it just reads this line from left to right. </p> <p>Finally, as noted in the section just after the docstring, I want to turn this into a generator. I have read about generators and understand them a bit, but I don't know how to implement one here. </p>
[]
[ { "body": "<p>Of course not.</p>\n\n<p>If you do <code>c, a, b = a + b, b, c</code>, this is what you get</p>\n\n<pre><code>a, b, c = a0, b0, c0\nc, a, b = a + b, b, c \n## c become a0 + b0\n## a becomes b0\n## b becomes c0\n</code></pre>\n\n<p>I'm pretty sure this is not your intention.</p>\n\n<p>In tuple assignment, the right tuple is evaluated first and then assigned to the left tuple. I'm guessing you thought it's done in order. Sorry, but no.</p>\n\n<p>You can instead eliminate the variable <code>c</code> and do this </p>\n\n<pre><code>a, b = a0, b0\na, b = b, a + b\n## a becomes b0\n## b becomes a0 + b0\n</code></pre>\n\n<p><strong>UPDATE</strong></p>\n\n<p>This is what is done by the machine, imagine the left values as an array of variables waiting to be assigned values that are on the left. Like this </p>\n\n<pre><code>[c, a, b] = [a + b, b, c] \n</code></pre>\n\n<p>Imagine the right values as an array of expression waiting to be evaluated. <strong>The right one gets evaluated first</strong>, then one by one the left variables takes the right values. No assignment is done until the left expressions are evaluated.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-09-11T00:43:03.367", "Id": "49479", "Score": "0", "body": "Thanks for your reply. As I understand it, that actually was my intention. I want c to be a + b, then I want a to equal b and b to equal c. This may not be pretty, but it will shuffle through the Fibonacci sequence. And if the right tuple evaluates first, doesn't that just mean that a + b will evaluate and assign to c, then b will assign to a, then c will assign to b?" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-09-11T01:22:49.730", "Id": "49484", "Score": "0", "body": "@TrentFowler read my update" } ], "meta_data": { "CommentCount": "2", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-09-10T00:36:18.150", "Id": "31026", "ParentId": "31024", "Score": "4" } }, { "body": "<p>Rather than looping with <code>while</code> and a count variable, it is more pythonic to write <code>for _ in range(n + 1)</code>. Also worth commenting that you are storing the same values in two places - in <code>fib_list</code> and in <code>a</code>, <code>b</code>, <code>c</code>.</p>\n\n<pre><code>fibonacci = [0, 1]\nfor _ in range(n + 1):\n fibonacci.append(fibonacci[-2] + fibonacci[-1])\nprint (fibonacci[m:n])\n</code></pre>\n\n<p>To convert this into a generator is fairly straightforward:</p>\n\n<pre><code>def fibonacci(m, n):\n a, b = 0, 1\n for _ in xrange(m):\n a, b = b, a + b\n for _ in xrange(n - m):\n yield a\n a, b = b, a + b\nprint (list(fibonacci(0, 17)))\n</code></pre>\n\n<p>If, as you say in your docstring, you want to hold values that have already been calculated, then making a generator does not particularly help you; instead you need to make a class in which you can store the values. In this case it will be handy to <a href=\"http://docs.python.org/2/reference/datamodel.html#emulating-container-types\" rel=\"nofollow\">overload the slice operators</a> so you can treat Fibonacci objects as if they were lists.</p>\n\n<pre><code>class Fibonacci:\n def __init__(self):\n self.sequence = [0, 1]\n def __getitem__(self, key):\n if isinstance(key, int):\n stop = key + 1\n elif isinstance(key, slice):\n stop = key.stop\n while len(self.sequence) &lt; stop:\n self.sequence.append(self.sequence[-2] + self.sequence[-1])\n return self.sequence[key]\nf = Fibonacci()\nprint f[7:17]\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-09-11T00:50:11.130", "Id": "49482", "Score": "0", "body": "Thanks very much, I will study this code carefully. If you didn't know, I think xrange was replaced in python 3, because I had to change it to 'range' when I ran the code you gave me. The output was still correct, though." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-09-11T01:01:38.087", "Id": "49483", "Score": "0", "body": "Also, you say that if I want the function to remember values then a generator won't be much help. My understanding of generators was that they could remember where they stopped when they passed control to something else. How is that different from storing values?" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-09-11T07:19:49.110", "Id": "49492", "Score": "0", "body": "Yes, actually the generator does store values too. But with the class, you could call `f[0:17]` and it will calculate and store the first 17 values of the sequence; and then later write `f[0:25]` and it will use the 17 values it has already calculated. With the generator you could write `f = fibonacci(0, 100)` and get values of the sequence with `f.next()`, so you could end up being able to use it in a similar way." } ], "meta_data": { "CommentCount": "3", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-09-10T01:38:18.107", "Id": "31031", "ParentId": "31024", "Score": "1" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-09-09T22:56:01.340", "Id": "31024", "Score": "2", "Tags": [ "python", "fibonacci-sequence" ], "Title": "Returning a Fibonacci list" }
31024
<p>You guess heads or tails by clicking one of the buttons on easyGUI. If it's right, you will get a "good job" message. If it's wrong, you will get a "wrong" message! After that, there is an option to play again.</p> <p>Please give me some feedback on how I can make my code better, if there is room for improvement.</p> <pre><code>import random import time import easygui import sys while True: rand = random.choice(["Heads", "Tails"]) firstguess = easygui.buttonbox("Pick one", choices= ["Heads", "Tails"]) if firstguess == rand: easygui.msgbox("Wow you win!") else: easygui.msgbox("Sorry you guessed wrong!") time.sleep(2) answer = easygui.buttonbox("Play again?", choices=["Yes","No"]) if answer == "Yes": pass else: break easygui.msgbox("Ok, see you later!") sys.exit(0) </code></pre>
[ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-09-10T01:06:46.203", "Id": "49384", "Score": "2", "body": "please, correct your indentation" } ]
[ { "body": "<p>Top-level code in a module should generally be definitions only, not \"executable\" code. In other words, you should be able to import your module without running your program. This makes it easier to read and easier to debug. My preferred style for a script (as opposed to library) module is something like:</p>\n\n<pre><code>\"\"\"This docstring explains the program's purpose.\n\nHere's some more details, including descriptions of any command-line arguments.\n\"\"\"\n\n# Keep imports in sorted order\nimport bar\nimport foo\nimport sys\n\n# Define helper functions, classes, etc\ndef baz(...):\n \"\"\"Functions and classes get docstrings too.\"\"\"\n ...\n\ndef main(argv):\n ...\n\nif __name__ == '__main__':\n main(sys.argv) # This passes commandline arguments to your main function\n</code></pre>\n\n<p>From a UX point of view, even keeping in mind that this is meant to be a simple program, you could stand to improve. For example, you can always print the last \"You guessed correctly\" / \"You guessed wrong\" answer over your dialog box, and make your dialog \"Heads\"/\"Tails\"/\"Quit\", taking away the 2-second delay, and allowing you to quit at any time, not just when the \"play again\" dialog is up.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-09-10T05:04:27.520", "Id": "49397", "Score": "0", "body": "I have absolutely no idea how to use the def function correctly. I just don't understand the use for it..would you mind explaining it more?" } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-09-10T01:30:04.477", "Id": "31030", "ParentId": "31027", "Score": "1" } }, { "body": "<p>Your script isn't bad. But there is always room for improvement:</p>\n\n<ul>\n<li><p>It's bad to mix tabs and spaces. The fact that your code broke when you pasted it here shows why. Good editors have a setting that will help you with this. (<a href=\"http://www.python.org/dev/peps/pep-0008/#tabs-or-spaces\">It is recommended</a> that you use spaces only.)</p></li>\n<li><p>You don't need <code>sys.exit(0)</code> at the end of your script, since Python will exit automatically when it reaches the end.</p></li>\n<li><p>Choose your variable names carefully. <code>rand</code> is not very descriptive and <code>firstguess</code> is plain incorrect (every guess, not just the first, gets assigned to this variable).</p></li>\n<li><p>Don't repeat yourself. Don't write <code>[\"Heads\", \"Tails\"]</code> twice, because if you have to change it for whatever reason, you have to remember to change it in two places. Store it in a variable.</p></li>\n<li><p>You can simplify this:</p>\n\n<pre><code>if answer == \"Yes\":\n pass\nelse:\n break\n</code></pre>\n\n<p>To this:</p>\n\n<pre><code>if answer != \"Yes\":\n break\n</code></pre></li>\n<li><p>I don't know easygui, but it seems you should use a\n<a href=\"http://easygui.sourceforge.net/tutorial/index.html#contents_item_8.3\"><code>ynbox</code></a>\nwhen you're asking \"yes or no?\". So you can change this:</p>\n\n<pre><code>answer = easygui.buttonbox(\"Play again?\", choices=[\"Yes\",\"No\"])\nif answer != \"Yes\":\n break\n</code></pre>\n\n<p>To this:</p>\n\n<pre><code>play_again = easygui.ynbox(\"Play again?\")\nif not play_again:\n break\n</code></pre>\n\n<p>Or simply:</p>\n\n<pre><code>if not easygui.ynbox(\"Play again?\"):\n break\n</code></pre></li>\n</ul>\n\n<p>With all the changes made and after applying the rules from the the Python style guide <a href=\"http://www.python.org/dev/peps/pep-0008/\">PEP8</a>, your code looks like this:</p>\n\n<pre><code>import random # alphabetic order\nimport time\n\nimport easygui # third-party modules after standard-library modules\n\nCHOICES = [\"Heads\", \"Tails\"] # ALL_CAPS for variables whose value never changes\n\nwhile True:\n result = random.choice(CHOICES)\n guess = easygui.buttonbox(\"Pick one\", choices=CHOICES)\n if guess == result:\n easygui.msgbox(\"Wow you win!\")\n else:\n easygui.msgbox(\"Sorry you guessed wrong!\")\n time.sleep(2)\n if not easygui.ynbox(\"Play again?\"):\n break\n\neasygui.msgbox(\"Ok, see you later!\")\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-09-10T05:02:37.090", "Id": "49396", "Score": "0", "body": "Thanks so much for the feedback. I have never used \"if not\" in my code yet so I will try that out. Also I see why I should make the [\"Heads, \"Tails\"] a variable. Thank you!" } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-09-10T02:03:19.140", "Id": "31033", "ParentId": "31027", "Score": "5" } } ]
{ "AcceptedAnswerId": "31033", "CommentCount": "1", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-09-10T01:02:42.953", "Id": "31027", "Score": "2", "Tags": [ "python", "beginner", "game" ], "Title": "Guessing Game (Heads or Tails)" }
31027
<p>I have a <code>move</code> function in this game that I'm making. It works fine, but I'd like to reduce its size a bit.</p> <pre><code>function move(moveTo, direction) { switch (direction) { case "right": $('#player').animate({ left: "+=" + scale }, "slow", function () { $("#player").appendTo("#" + moveTo);$('#player').attr("style", ""); });break; case "left": $('#player').animate({ left: "-=" + scale }, "slow", function () { $("#player").appendTo("#" + moveTo);$('#player').attr("style", ""); });break; case "up": $('#player').animate({ top: "-=" + (9 * (scale / 10)) }, "slow", function () { $("#player").appendTo("#" + moveTo);$('#player').attr("style", ""); });break; case "down": $('#player').animate({ top: "+=" + (9 * (scale / 10)) }, "slow", function () { $("#player").appendTo("#" + moveTo);$('#player').attr("style", ""); });break; } } </code></pre> <p>I always execute the same commands:</p> <pre><code>$("#player").appendTo("#" + moveTo); </code></pre> <p>and</p> <pre><code>$('#player').attr("style", ""); </code></pre> <p>I can't put it after the <code>switch</code> statement because I want to wait until the <code>animate</code> is finished. Is there a way to do this other than making a function? I also want this type of thing for some other code, so a bit less case specific would be better.</p>
[ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-09-13T00:54:02.900", "Id": "49660", "Score": "0", "body": "what do you mean by backwards coding?" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-09-13T01:01:34.477", "Id": "49661", "Score": "0", "body": "also known as a \"hack\", kinda like the famous change the drop-down arrow, the point is code that works, but isnt meant to do what its doing. its a common term..." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-09-13T01:08:51.207", "Id": "49666", "Score": "0", "body": "it doesn't look like a hack. You're using `animate` to do animation. Can you maybe explain what you're trying to do and what the problem is with your current approach?" } ]
[ { "body": "<p>I would abstract the animation logic into a high order function and the possible directions in an object, then just lookup the corresponding function for each direction, in other words:</p>\n\n<pre><code>function move(to, dir) {\n\n function animate(props) {\n return function() {\n $('#player').animate(props, 'slow', function() {\n $(this).attr('style', '').appendTo('#'+ to);\n });\n }\n }\n\n var dirs = {\n right: animate({ left: '+='+ scale }),\n left: animate({ left: '-='+ scale }),\n up: animate({ top: '-='+ (9*scale/10) }),\n down: animate({ top: '+=' + (9*scale/10) })\n };\n\n if (dir in dirs) dirs[dir]();\n}\n</code></pre>\n\n<p>I fixed a few other things. You can use <code>$(this)</code> to refer to the element being animated in the callback and chain those methods.</p>\n\n<p>Then <code>(9*(scale/10))</code> is effectively the same as <code>9*scale/10</code>; associative operators.</p>\n\n<p>You probably need to abstract even more if you add more code; ideally you'd want separate all your logic from your DOM manipulation and create a clear data structure that you can reuse. Also think about using classes instead of IDs. Classes are more reusable and lead to simpler code.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-09-10T02:01:43.803", "Id": "49389", "Score": "0", "body": "This is just a basic DRY abstraction of your current code. The `scale` comes from wherever it comes in your actual code, a higher scope I suppose. This should be a drop-in replacement if I took everything into account... A dictionary lookup is a common alternative to a switch statement." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-09-10T02:25:01.643", "Id": "49391", "Score": "0", "body": "your right i thought you came up with `scale`, i still dont want to use a object, even if its common, im asking if you can make a block of code wait till the animate finishes without using `.animate(.. , .. , function(){/*code here*/})`." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-09-10T16:59:27.697", "Id": "49452", "Score": "0", "body": "Just DRYing up the code a bit more: Replace `9*scale/10` with `scale*0.9`. You can also skip the `op` argument as well by making `scale` a negative number when appropriate." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-09-13T00:51:16.700", "Id": "49658", "Score": "1", "body": "I think this won't work because you are adjusting the `left` property even when the movement is supposed to be up or down." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-09-13T01:06:58.840", "Id": "49663", "Score": "0", "body": "i cant `-1` but i think evryone should, this code simply doesnt work." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-09-13T01:08:38.440", "Id": "49665", "Score": "0", "body": "I overlooked the `top` property, it's a matter of understanding the abstraction, more than the code itself." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-09-13T01:13:03.097", "Id": "49670", "Score": "0", "body": "Edited, that should do, hope I didn't overlook anything else, but again, it's about understanding the abstraction, and why it matters." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-09-13T01:14:33.980", "Id": "49671", "Score": "0", "body": "u sure u can do that? i mean thats only passing 3 arguments to animate, your supposed to pass 4." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-09-13T01:17:24.380", "Id": "49674", "Score": "1", "body": "What is this fourth argument? You have the properties, the speed, and the callback. I don't see any other argument in your code..." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-09-13T05:29:32.810", "Id": "49684", "Score": "0", "body": "the properties are supposed to be as arguments, i think. are you sure that a comma from inside the variable works?" } ], "meta_data": { "CommentCount": "10", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-09-10T01:44:24.240", "Id": "31032", "ParentId": "31028", "Score": "11" } }, { "body": "<p>You are concerned about the repeated calls to <code>.appendTo()</code> and <code>.attr()</code> but you should also be concerned about your calls <code>.animate()</code> which are very repetitive as well.</p>\n\n<p>Basically you are mapping the four directions to modifications of <code>top</code> and <code>right</code>.</p>\n\n<p>To keep that mapping simple I propose this:</p>\n\n<pre><code>directionMap = \n{\n right : { attribute : \"left\" , operator: \"+=\" , scaleMultiplier : 1 },\n left : { attribute : \"left\" , operator: \"-=\" , scaleMultiplier : 1 },\n up : { attribute : \"top\" , operator: \"-=\" , scaleMultiplier : 0.9 },\n down : { attribute : \"top\" , operator: \"+=\" , scaleMultiplier : 0.9 }\n}\n</code></pre>\n\n<p>This mapping should be done once, without knowing your code, I cannot tell you where.</p>\n\n<p>Then, in the move function, you can retrieve the details for the given direction, construct the properties object with the proper css name/value pair.</p>\n\n<pre><code>function move(moveTo, direction) \n{\n var approach = directionMap[direction];\n if( approach )\n {\n var properties = {};\n properties[approach.attribute] = approach.operator + ( scale * approach.scaleMultiplier );\n $('#player').animate( properties , \"slow\", function () \n {\n $(this).appendTo(\"#\" + moveTo).attr(\"style\", \"\");\n }); \n }\n}\n</code></pre>\n\n<p>The only other thing to note is that <code>this</code> in the callback function is the animated DOM element, and constructing a jQuery selector from an element is faster than constructing it from an ID.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-09-13T01:05:56.180", "Id": "49662", "Score": "0", "body": "it isnt multiple calls, js is lazy. the thing is those two are always exactly the same while the `.animate` changes, your answer is still good." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-09-13T01:11:53.750", "Id": "49668", "Score": "0", "body": "i dont want to create a object. i stated that pretty clearly, i want another method, i rather it this way then create a object for this." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-09-13T01:16:03.080", "Id": "49673", "Score": "0", "body": "...but objects are your friends :)" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-09-13T05:27:52.130", "Id": "49682", "Score": "0", "body": "ooh yes they are... really i love them (if you check my page -its in my profile- you will c that), its just thati like using them as **objects** as in real life, a object that is there to be interacted with, not as a place to temporarily store some code, to be used as a switch, to me thats backwards coding, and im trying to make mine straightforward." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-09-13T05:51:00.610", "Id": "49688", "Score": "0", "body": "An object is just another data structure. Don't think of objects as classes in JavaScript. People here are trying to give you good advice. Again, an object (or dictionary) look-up is a common alternative to a switch statement, specially in functional programming languages like JavaScript. You can program in JS without `if,else,while,for,switch` so no side effects." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-09-16T20:15:59.443", "Id": "49967", "Score": "0", "body": "i use objects, to store **properties**, of a *object*, simple if there is no other way, i will use the switch." } ], "meta_data": { "CommentCount": "6", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-09-13T00:57:16.473", "Id": "31211", "ParentId": "31028", "Score": "1" } }, { "body": "<p>I'm not sure why you are set against creating an object to use here. It is really the best option for you here. </p>\n\n<p>But since you asked for this specifically.</p>\n\n<pre><code>function move(moveTo, direction) {\n\n var doAfter = function() {\n $(\"#player\").appendTo(\"#\" + moveTo);$('#player').attr(\"style\", \"\");\n }\n\n switch (direction) {\n case \"right\":\n $('#player').animate({ left: \"+=\" + scale }, \"slow\", doAfter);\n break;\n case \"left\":\n $('#player').animate({ left: \"-=\" + scale }, \"slow\", doAfter);\n break;\n case \"up\":\n $('#player').animate({ top: \"-=\" + (9 * (scale / 10)) }, \"slow\", doAfter);\n break;\n case \"down\":\n $('#player').animate({ top: \"+=\" + (9 * (scale / 10)) }, \"slow\", doAfter);\n break;\n }\n}\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-09-13T05:23:27.130", "Id": "49681", "Score": "0", "body": "thats simple... why in the world didnt i c that?" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-09-13T05:29:16.117", "Id": "49683", "Score": "0", "body": "forest for the trees..." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-09-13T05:30:37.047", "Id": "49685", "Score": "0", "body": "yup yup, (im a virgo)... happens all the time to me." } ], "meta_data": { "CommentCount": "3", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-09-13T05:20:58.290", "Id": "31222", "ParentId": "31028", "Score": "1" } }, { "body": "<h1>$('#player')$('#player')$('#player')</h1>\n\n<pre><code>$('#player')$('#player')$('#player')$('#player')\n$('#player')$('#player')$('#player')$('#player')\n</code></pre>\n\n<p>Do not use <code>$('#player')</code> more than once in your code if you intend on fetching data or setting data to the DOM element more than once. Instead save your element to a javascript variable so you can quickly access it. If not, then your jQuery will search through the DOM over and over again.</p>\n\n<pre><code>var playerNode = $('#player');\nplayerNode.animate(stuff);\n</code></pre>\n\n<h1>Anonymous Functions Are Evil</h1>\n\n<p>Notice how </p>\n\n<pre><code>function() {\n $(\"#player\").appendTo(\"#\" + moveTo);\n $('#player').attr(\"style\", \"\");\n}\n</code></pre>\n\n<p>is exactly the same as</p>\n\n<pre><code>function() {\n $(\"#player\").appendTo(\"#\" + moveTo);\n $('#player').attr(\"style\", \"\");\n}\n</code></pre>\n\n<p>That means you don't need to write the same line twice. Just create one function object and call itself for each method.</p>\n\n<pre><code>var animCallback = function() {\n $(\"#player\").appendTo(\"#\" + moveTo);\n $('#player').attr(\"style\", \"\");\n};\n</code></pre>\n\n<p>But wait! There's more! We can clean up that nasty callback because jQuery supports <em>chaining</em>, which allows you to just write one-liners with ease. In fact, while we're at it, we may as well use that variable that holds the player DOM node instead of searching for it again.</p>\n\n<pre><code>var animCallback = function() {\n playerNode.appendTo(\"#\" + moveTo).attr(\"style\", \"\")\n};\n\nplayerNode.animate({ left: \"+=\" + scale }, \"slow\", animCallback);\n</code></pre>\n\n<h1>If V.S. Case</h1>\n\n<p>Now here's a discrepancy. Some people say that <code>switch case</code> is faster than <code>if else</code>. However, you'll notice that newer browsers are focusing on improving the speed of <code>if else</code> by very large amounts. Some browsers are even faster with <code>if else</code> than <code>switch case</code>. Speed isn't the problem here, it's readability. Use an <code>if else</code> statement if there's only 4 possibilities because it makes more sense.</p>\n\n<pre><code>if(direction === 'left') {\n playerNode.animate({ left: \"+=\" + scale }, \"slow\", animCallback);\n} else if(direction === 'right') {\n playerNode.animate({ right: \"+=\" + scale }, \"slow\", animCallback);\n} ...\n</code></pre>\n\n<h1>jQuery</h1>\n\n<p>You can make a game in your web browser, it'll just be slower than a C++ program. Likewise, you can make a game with jQuery, but it'll be slower than raw Javascript or your own custom libraries. I'm personally okay with jQuery being a setup for a game because it can normalize values that would appear different from browsers. Keep in mind, though, that <code>document.getElementById('player')</code> is about 10 times faster than <code>$('#player')</code>.</p>\n\n<h1>All Together Now</h1>\n\n<pre><code>var playerNode = $(document.getElementById('player'));\n\nfunction move(moveTo, direction) {\n var animCallback = function() {\n playerNode.appendTo(\"#\" + moveTo).attr(\"style\", \"\")\n };\n\n if(direction === 'left') {\n playerNode.animate({ left: \"-=\" + scale }, \"slow\", animCallback)\n } else if(direction === 'right') {\n playerNode.animate({ left: \"+=\" + scale }, \"slow\", animCallback)\n } else if(direction === 'up') {\n playerNode.animate({ top: \"-=\" + (9 * (scale / 10)) }, \"slow\", animCallback)\n } else {\n playerNode.animate({ top: \"+=\" + (9 * (scale / 10)) }, \"slow\", animCallback)\n }\n}\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-09-17T19:43:53.927", "Id": "50101", "Score": "0", "body": "1) `document.getElementById('player').animate` returns `TypeError: document.getElementById(...).animate is not a function [Break On This Error]` (its faster because it includes less) 2) i see no reason to use `if/else` over `switch` 3) you are right about Anonymous Functions, and next time read the question first - `Is there a way to do this other than making a function?` 4) i do repeat player, i should replace with `playerNode`.... but im looking for more then that, i want to have the whole `.animate({ left: \"+=\" + scale }, \"slow\",` also not repeat itself." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-09-17T21:07:24.047", "Id": "50112", "Score": "0", "body": "(1) Getting an element by its ID gives you a DOM element. Getting it with jQuery returns an array of DOM elements normalized with jQuery. You can wrap `document.getElementById('player')` inside the jQuery function to get the animate method on it like this: `$(document.getElementById('player'))`. (2) `if/else` statements make code more readable for other people. It might not be for you, but if somebody has to come up behind your code, then they'll easily understand it. (3) Trust me ;) your code will run faster without the anonymous functions. (4) The only way might be editing jQuery itself." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-09-17T21:55:58.837", "Id": "50115", "Score": "0", "body": "(1) show a source that `$(document.getElementById('player'))` is faster then `$(\"$player\")` please (2) i dont see how `if/else` is easier to read then `switch` (3) what i meant was i know how to do it with function's is there a even better way without multiple function calls (4) ok so not the whole `.animate({ left: \"+=\" + scale }, \"slow\",` but i want to not have to write all of it 4 times, how much can i eliminate and how? also adding a block of sample finished code at the end would be better." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-09-17T22:09:15.273", "Id": "50117", "Score": "0", "body": "(1) The way you're doing it is [3 times faster](http://jsperf.com/jquery-sharp-vs-getelementbyid/31) than what you were before. (2) It's called [syntactic sugar](http://en.wikipedia.org/wiki/Syntactic_sugar) and it's the reason why you use camelCase for your variables. It's just a standard for the programming language. (3) Putting the callback function in the `$().animate` method doesn't call it. It just references it like an object the same way you reference `playerNode`. (4) The only way I can think of is to make it default to that within jQuery itself. Not much you can do." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-09-17T22:20:12.797", "Id": "50119", "Score": "0", "body": "(1) 230,783 ops/sec will have to do for now... (2) i know what syntactic sugar is, i just dont think `if/else` is more \"sugary\" then `switch`, and i see certain advantages in clarity for `switch` (3) you are right, but it is defiantly clearer if i could write (the following is pseudo-code) `switch(..){case:...case:...} $(\"#player\").done().appendTo(\"#\" + moveTo).attr(\"style\", \"\");` (4) again i would want something that replaces at least part i.e. `.animate({ dir, amount }, \"slow\",` and similar ideas. oh and i `+1` for putting so much time in thanks, i hope you solve this and earn the bounty." } ], "meta_data": { "CommentCount": "5", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-09-17T16:14:20.783", "Id": "31433", "ParentId": "31028", "Score": "3" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "3", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-09-10T01:02:44.970", "Id": "31028", "Score": "5", "Tags": [ "javascript", "jquery" ], "Title": "Move function for a game" }
31028